:::: MENU ::::

Robotlegs Gotcha #2 – Using Interfaces for your services and models

One of the common practices suggested by the Robotlegs team (and one I have personally grown to love) is the user of Interfaces for your services and data models. What this allows you to do is type-cast all of your injections and other references to these classes using the name of the Interface, then, when mapping these classes, you map the Interace to the either the concrete class or a seperate “mock” class that can be used for testing. This gives you the ability to quickly swap between mock data and live data by simply changing the injection mappings in your context file (or startup command or wherever you handle your mappings).

A quick example of this would be if I had a service called MyService that went out and requested some data. Now let’s say that (as usual) the backend services weren’t quite ready yet, but I need to move forward and begin testing my code. Enter the Mock Service. To accomplish this, I would create three classes: IMyService, MockMyService, and MyService. IMyservice is a simple interface class that lays out the rules that all the classes that implement it must adhere to. MockMyService implements IMyservice and creates all the required methods, but instead of reaching out and pulling data from some webservice, it simply returns dummy data (either by directly returning the data, or dispatching an event containing the data, this will depend on how your app is set up). The final class MyService implements IMyservice and looks exactly like MockMyService, except it reaches out to the real webservices to pull it’s data.

Now For the magic! Anywhere in your application that references MyService via injection should type-case the injection variable as “IMyService”. Then, when you will tell your injection mapping to map any references to IMyService to either MockMyService or MyService (depending on whether you need to work with your dummy data or live data). The mapping would look something like this:

Then when you were ready to go live, you would simply change out the reference to point to MyService and all of your application would automatically be updated via the sexyness of inject:

OK, so that’s all well and good and awesome! Now time for the GOTCHA: If you accidentally type-cast one of your injections to one of the concrete classes such as this:

instead of your interface:

you get a big nasty error when you try to compile that will read something along the lines of:

MORAL OF THE STORY: If you are going to use this very handy pattern, make sure that you always type-cast to the Interface. And if you see this type of error, look to the class listed as target [object MyObject] to find the reference to the concrete class and updated it to use the Interface!

More Robotlegs Gotcha’s:

One Comment

So, what do you think ?