What is Inversion of Control?

A Non-Inverted Control Scheme
Your control lacks inversion

When I first encountered the concepts of inversion of control and dependency injection, I found the available explanations on the internet to be written in impenetrable “nerd speak.”

This is the dependency injection and inversion control explanation I wish I could have read at that time.

A Simple Analogy

Let’s begin by comparing the operations of two restaurants: HamburgerTown and Mel’s Diner.

At HamburgerTown, hungry customers stand in line at the counter, order, pick up their food and then sit down to eat. The customer in this situation needs to know a number or things…where the counter is, where the kitchen is, where to get food and where to sit afterwards.

The customer is entirely in charge of knowing, identifying and fulfilling their own needs.

The Injection Process In Action
The Injection Process In Action

At Mel’s Diner, customers enter the restaurant, sit down and are given menus. When the customer is ready for food, they signal  their desires to the waitress, who scans their orders and then fetches their order from the kitchen automatically.

The customer is only in charge of  communicating their needs. An external entity does the leg work of detecting and resolving those needs automatically.

An Example Mobile Application

Let’s use the example of a Yelp-like application which gets a list of nearby restaurants.

In the “HamburgerTown” version of this application, the logic for fetching and populating the list of restaurants is owned entirely by the list’s view controller.

Some pseudo-code of a simple “View Controller” construct.

Class RestaurantListViewController: TableViewController{

     // Array of restaurants to be fetched from our remote service
     private Array restaurants;
     // Service for fetching restaurants
     private Service restaurantsService;

     // Psuedo-code initialization
     public void init(){
        self.restaurants = new Array();
	self.restaurantsService = new restaurantsService();

	// Fetch the restaurants.
	self.restaurantsService.fetchRestaurants(onRestaurantsFetched);
     }

     // Method for handling restaurants fetched events
     private void onRestaurantsFetched(Array fetchedResults){
	self.restaurants = fetchedResults;
        self.tableView.dataSource = restaurants;
        self.tableView.reloadData();
     }
}

In this situation, the view controller is in charge of identifying and fulfilling it’s own data needs. 

Notice that no external opportunities are provided here to influence how this table view controller fetches data. The view controller depends on some service internally in order to do it’s own job. Lets talk about why this is potentially an anti-pattern.

HamburgerTown: It Isn’t Testable

Automated testing is widely recognized as a good way to help ensure that large complex systems continue to perform reliably and don’t break down unexpectedly due to subtle bugs introduced during regular coding work.

A key requirement of automated testing is that it should be possible to remove individual software components from the overall system and verify their behavior.

The problem with having each view controller entirely in charge of it’s own data fetching is that all of this logic is now hidden inside that view controller.

We have also introduced an internal dependency which makes it difficult to extract our view controller from the system: The view controller depends on some service object internally in order to do it’s own job properly.

This problem may be solved by introducing a “dependency injector” and “inverting control” over where the data fetching logic sits. We must completely remove the dependency the view controller has on any external service.

Note: Another solution might be to introduce something called a “Service Locator.” The service locator pattern works by having some mechanism of “injecting” a service (or otherwise dynamically resolving this dependency) into your class dynamically. Many believe the service locator pattern to be an “anti-pattern” because the view controller still depends on another object (the service) in order to do it’s own job.

The Injector Intelligently Identifies and Fills Dependencies

Mel’s Diner represents the “Inversion of Control” pattern: The view controller is solely responsible for exposing it’s own needs and some external entity will read these and then inject them automatically.

Here is an example in pseudo-code of what an inverted view controller would look like.

Class RestaurantListViewController: TableViewController{

     // Array of restaurants fetched from our remote service
     private Array restaurants;

     // Psuedo-code initialization
     public void init(){
        self.restaurants = new Array();
     }

     // All we do here is expose what dependency we require filled.
     public Array getDependencies(){
	return (Array:"restaurants");
     }

     // React when the restaurants dependency is injected.
     public void setRestaurants(Array _restaurants){
        self.tableView.dataSource = restaurants;
        self.tableView.reloadData();
     } 
} 

// Time to load the restaurants list! 
RestaurantListViewController restaurantsController = new restaurantListViewController(); 
Injector injector = new Injector(); 
injector.inject(restaurantsController);

 

The above example is purposefully very sparse and ultra-basic, but the core tenets are there: The injector scans the view controller (often using a technique known as reflection) for it’s dependencies and automatically resolves them. Control is said to be “inverted” because it is now someone else’s job to resolve dependencies.

Some Mobile IOC Frameworks

RoboGuice for Android
Dagger for Android
Objection for iOS

AT&T Hackathon @ Reactor: Wearable Technology

photo (5) There has been a strong showing of “internet of things” technology at the Reactor Accelerator this weekend for AT&T’s pre-Seattle Interactive Conference hackathon.

The space of wearable computing has clearly come a long way and still has a long way to go. The number one demand from participants I am seeing is a desire for tiny, self powered devices which can communicate with other devices via cellular networks, Wifi or Bluetooth. Such devices are clearly possible with current generation Arduino parts and components…

The smallest options I have seen are Arduinos like the Femtoduino, which in theory could be combined with an Arduino Cellular Shield or low powered Bluetooth shield to provide the desired connectivity and small size.

urlAnother fun option I have seen people experimenting  is the Arduino Lilypad. A nice sized device by itself which can be sewn into clothing and then updated with software to communicate with other components via a conductive thread.

There are several types of Lilypad, but they all share a common round form factor with various outlets where conducting thread can be looped and then subsequently tied to related hardware such as tri-color LED boards or other sensors. Earlier Lilypads require a FTDI component plug in order to upload software onto the board which can then provide the board with logic while the newer ones may be plugged directly into a computer via a Micro USB cable.

Aside from that I have seen brain-controlled electronic bunny-ears which twitch as the user’s brain patterns change, wearable headsets by Plantronics which contain an accelerometer and can be used to track user’s head movements and relay this information to a bound mobile phone. 

 

 

PubNub & Rasberry Pi: Up and Running

photo credit: CNETWhat follows is a tutorial outlining how to get up and running with PubNub on a Rasberry Pi running Rasbian. I have created this tutorial for the purpose of connected device / embedded device demonstrations at the upcoming Wearable Computing AT&T Hackathon.

Step 1: Have a Rasberry Pi configured and running Rasbian

This should be relatively straightforward, your OS does not honestly have to be Rasbian but that is what I am using to go through this process. More than likely any common Linux distribution will be fine.

In my case I ordered a basic Rasberry Pi development kit which comes complete with an HDMI cable, an SD card, a mini-usb power supply and a plastic shell to keep you from shorting out the motherboard.

You will need to have a PubNub account…logged in and activated as a developer (free!): www.pubnub.com

Also make sure you have (obviously) some type of internet connection whether it be a WiFi Nub or ethernet cable. Assuming your Pi is plugged in, turned on and connected to the internet…proceed from there.

Step 2: Clone into the PubNub C-Library GitHub Account

Create and navigate to a folder on your Desktop or other such desired location in the terminal. Much of this information can already be found on the GitHub page for the Rasberry Pi C client for PubNub here: https://github.com/pubnub/c.

On your standard command line run:

git clone https://github.com/pubnub/c.git
  • You will also need to run the following commands to install the libraries necessary to “make” or build the PubNub C libary
sudo apt-get update (just in case you are out of date)
sudo apt-get install libevent-dev libjson0-dev libcurl4-openssl-dev libssl-dev
  • Next, browse to your “C” folder which you just cloned from GitHub where the PubNub C libraries now should reside
sudo make (to make the library)
sudo make install (to install it)

 Step 3: Test Your Pub / Sub Connection

Time to try a publish / subscribe communication between your Pi and PubNub.

cd examples/sync-demo (from the Git directory of your PubNub folder)
  • Open example-sync-demo.c with your favorite editor

Now change the following lines to match your PubNub pub / sub credentials. These credentials should be on your PubNub API dashboard:

pn
Replace the demo publish and subscribe tags below with your actual credentials in the example-sync-demo.c file.

struct pubnub_sync *sync = pubnub_sync_init();
struct pubnub *p = pubnub_init(
/* publish_key */ "demo",
/* subscribe_key */ "demo",
/* pubnub_callbacks */ &pubnub_sync_callbacks,
/* pubnub_callbacks data */ sync);
json_object *msg;
  • Next, customize your message which you are publishing to something you will recognize (line 27):
json_object_object_add(msg, "str", json_object_new_string("\"Hello, AT&T Hackers!\" she said."));
  • Next, you will need to build a “.o” file by running “make” while in the examples directory. The result should be example-sync-demo.o.
  • Run this file in the terminal with: ./example-sync-demo
  • You should see the following:
pubnub subscribe ok, no news
pubnub subscribe [my_channel]: {"num":42, "str": "\\"Hello, AT&T Hackers!\" she said.}

 

Data Science: The Revolution Lacks Useability

37193508I spent the week in San Francisco at GraphLab, a data science and machine learning summit.

The interest in the field of data science is simply amazing,  growing rapidly (last year’s GraphLab had ~300 attendees, this year’s GraphLab had something like 500+)…and well justified. Companies like Pandora and Netflix who have made Machine Learning and Data Science techniques work have conquered the world…but capturing and recreating their magic remains an elusive task. The field is fraught with problems.

Data Science is a field which is deeply entrenched in it’s academic roots and the number of people who can claim any sort of expertise are few and far between (and often already rich/highly valued and therefore impossible to hire). Even rarer are large enterprises willing to invest in obtaining data science expertise.

The problem is part supply and demand. A Data Scientist is basically a software engineer who can do statistics. Most tech companies have a difficult enough time finding normal software types, now they have to find ones who dig stats. Such a person will be as rare as the mythical “Developer-Designer-corn” or hybrid developer / designer.  Such a person would be so intelligent and talented that they would likely not bother working for your company and be off starting their own.

The next part of the problem is communication: How do you actually get this mythical Software Engineering Statistician Unicorn to both turn up useful business insights and then convince management types to act on these insights?

In my experience, having business insights is often much, much easier than actually getting bandwidth to implement any insights outside of the realm of critical path tasks. An organization which is willing to proceed through the use of Data Science probably can’t exist unless the founder built the company around such an approach.

In short: Most current existing companies are very unlikely to suddenly sprout machine learning competencies where they had none before and the supply of people able to claim the expertise is nearly non existant. Therefore, most large enterprises are going to be better off getting some serious external help in that department. Otherwise, the only way I see data science becoming a focus is by starting your tech company with it as a cornerstone and proceeding from there.

The final hope for Data Science finding its way into main stream technology companies is to expose functionality in a way that BI, data analysts and online marketers can actually run exotic Graph based queries with simple interfaces (see: Google Analytics). Such interfaces have not been invented yet…will they ever be?

Graph based data does not really lend itself to analysis via traditional Microsoft Excel spreadsheets, a new set of tools will be needed.

 

Game Over, Man

img-16

Like a silent anaconda slowly wrapping it’s coils around a sleeping jungle wildebeest, Apple is slowly dropping the last pieces of it’s all-conquering gaming strategy into place.

Apple is not rushing to market….this is slow, methodical and almost sinister in it’s measured progression.

The first steps involved iOS, the iPad, the iPhone, the iPod, the App Store and then software features like Game Center and then micro transactions for games. At this week’s WWDC, we saw a few new glimpses of the freight train that is coming: SpriteKit and SceneKit….two brand new game centric tool sets for 2D and 3D games. Possibly of equal importance will be updates to OSX which allow for completely independent windows to be spawned on Apple TV’s using AirPlay…just like the Wii-U!

The strings are all in place but loosely tied…if Apple is half as intelligent and methodical as they appear to be, all of these elements will be strung together and suddenly yanked into a tight noose around the entire game and console market which will leave little room for escape….But something is missing.

Where is the final piece?

Changing topics for a moment, lets examine the new Mac Pro:

2013_mac_pro

Just look at this thing. Have you ever seen anything like it? Me neither. Just imagine walking into a pristine, white Apple store filled with airy, ultra thin silver and white devices and then coming across this monstrosity…it sticks out like a sore thumb.

There are only a couple market niches where black, powerful devices for sophisticated high-end users abounds: High end work stations and game consoles.

If Apple can produce a Mac Pro that looks like this thing and is 1/8th the size of the original Mac Pro…imagine what they could do with an Apple TV Extreme…perhaps controlled, via AirPlay or Mifi game controller.

 

Part II: Mobile Software Is Eating Game Consoles

logo_liongazelle

It’s easy to forget watching the celebrations going on at E3 around the launch of new game consoles that the console market has sprung a leak.

Mobile gaming is the elephant in the room…not used game sales, not DRM, not services and certainly not new console hardware.

The Nintendo was the first to fall…the broad casual market which Apple dominates through their app store turned out to be low hanging fruit. No one wants to pay $50 for a game when the alternative is either a free download game or a $0.99 game from the app store.

Microsoft and Sony will be next. It is likely that mobile may not, by itself, ultimately kill the console market…but downloadable, cheap games will likely be the most important factor controlling for all other variables.

Congratulations Sony, you have won the distinction of being king of the sand castle.  Just hope the wave takes two more years to arrive.