Gilded Rose Clojure

I recently read Mike Jansen's 8th Light blog post on The Gilded Rose kata in Clojure and thought I'd give it a crack myself.

First was to get a set of tests setup. The kata is already setup to use the speclj testing library. I'd only used the very fine Midje library for testing in Clojure before, but I thought I'd stick with what was already in the project.

Both allow for very easy and straightforward testing, and both support automatic test running when files change. This makes for a really tight feedback loop when making any changes.

I tried as much as possible to just translate the requirements into a suite of tests without getting bogged down in implementation details. Here it is after the refactoring.

Not very much changed between initially writing the tests and refactoring the main code, just a few bits here and there to match changes made in the core file.

Refactoring the main code basically comprised of splitting each of the different behaviours spread around update-quality into their own functions which could be associated with different items in a declarative fashion. The update-quality function then just became a matter of mapping these functions over the items.

The restriction on being unable to change the item function made this approach a little more convoluted, but best not to enrage the goblin.

Here's the refactored core file.

There's bits I'd like to tweak, but I also wanted to time box it within a reasonable range. One thing I would like to do would be to try core.match on some of the functions; particularly the one relating to concert ticket quality.

Roboguice Assisted Injection on Android

Google-guice's assisted injection extension is useful when you need to inject a contructor or method, but need to manually provide some of the parameters.

Now that Roboguice is at version 2 I thought it time to try out the assisted injection extension on Android.

The assisted inject jar comes with the guice-3.0 zip file available from http://code.google.com/p/google-guice/downloads/.

As I'm using Maven it's a case of adding the following to the dependencies in my pom:

You need the exclusions section to prevent the with aop version of guice being added (you should already have the no-aop version of guice 3.0 added). Otherwise there'll be all manner of errors.

Using it is fairly well documented on the Google-guice wiki: http://code.google.com/p/google-guice/wiki/AssistedInject

It basically comes down to 3 steps. 

  1. Create a factory interface that defines a create method, accepting the manual parameters as arguments.
  2. Use the install method in your custom module to setup the factory for injection.
  3. Annotate the constructor/method in need of assisted injection.

To use it inject an instance of the factory interface and call create on it.

The following markdown brings together an example of the four previously mentioned elements from a project (https://github.com/davespanton/Nutbar)

Upgrading to Roboguice 2.0 beta 3.

Last Tuesday night I was feeling brave and decided it was time to upgrade a my current pet Android project to Roboguice 2.0b3. 

To get it all working I needed to...

Upgrade Dependancies

As the project uses Maven I firstly upgraded the Roboguice dependancy in my pom. This also entails upgrading the Google Guice dependancy as well. They now look like this:

 
<dependency>     
    <groupId>org.roboguice</groupId>     
    <artifactId>roboguice</artifactId>     
    <version>2.0b3</version>     
</dependency> <dependency>         

<groupId>com.google.inject</groupId>     
    <artifactId>guice</artifactId>    
     <version>3.0</version>    
     <classifier>no_aop</classifier>
 </dependency> 

This created quite a few errors.

Remove custom application, update modules.

Next step was to remove the custom application class, test and references from the project. The new version of Roboguice doesn't need an application extending RoboApplication.

Once this was gone l needed to let Roboguice know where my custom module is. The simplest way to do this is create a new resource file in res/values called roboguice.xml. Here's my new one https://github.com/davespanton/Nutbar/blob/master/res/values/roboguice.xml

Any custom modules need to be changed to inherit from AbstractModule instead of AbsractAndroidModule. I had to change this for my main custom module and my test module. 

I also had to refactor the main module to no longer take any constructor parameters. It previously took a reference to my application, but this was easily refactored.

Injected Test Runner.

I use Robolectric for unit testing and have an InjectedTestRunner which extends their RobolectricTestRunner. The prepareTest method was updated to:

Preferences Activity.

The only problems I had once the above was done was with my preferences activity injecting a shared preference instance. 

For the time being I simply reverted to manually retrieving the shared preferences rather than injecting them. 

I really need to upgrade the preferences to fragments at some point anyway, which will be a good time to look into getting the injection working once again.

 

Overall a fairly painless upgrade.

Have a browse on https://github.com/davespanton/Nutbar to see it in more detail.

 

 

Spying on Titanium; Titanium Appcelerator and Jasmine.

I've now worked small parts in a couple of Appcelerator projects for iOS. Both times I have been tasked with improving the unit testing.

Jasmine from Pivotal is a great Javascript unit testing framework, (https://github.com/pivotal/jasmine/wiki), and has been modified to work with with the Titanium framework (https://github.com/guilhermechapiewski/titanium-jasmine).

It mostly works excellently with all of Jasmine's features are available. The only issue I had was not being able spy on objects and methods that are a part of the Titanium API.

One way to get around this is to replace the part of the API you intend to use with a stubbed version. Say for example that you wish to spy on Titanium.Network.createHTTPClient. Before exercising any production code that uses it do something like:

It is then possible to call spyOn(Titanium.Network, "createHTTPClient") and subsequently expect this to have been called. Once done Titanium.Network can be set back to originalTiNet if required.

The same can be done for objects returned by Titanium's create methods. Either get your stubbed API (Titanium.Network in this case) to return a stubbed object, or use a spy to do it as in the below example. 

In this case we want to be able to verify that send and open were called on an HttpClient object. By setting up the above (in addition to the first gist) every subsequent call to Titanium.Network.createHTTPClient in our production code will be given stubClient, and we can verify calls made to send and open.

If anyone is interested I can post up a more complete example.

Switching my Android environment from Eclipse to Intellij IDEA

I've been using Eclipe for Android development pretty much since Android's release. I'm generally pretty happy using Eclipse; finding it always works well for small Android projects. 

More recently I've been using Maven with Android to better co-ordinate working with different libraries. Setting up Maven to work with Android in Eclipse was a bit of a pain, but not too difficult. 

Earlier this week I upgraded my Android SDK to r15; which promptly broke my project in Eclipse with a cryptic "Conversion to Dalvik format failed with error 1". Google reveals a number of people experiencing similar issues, but none of the suggested solutions seemed to work.

Another tack was to move from my old Galileo installation to a shiny new Indigo one and see if that helped. Got it all set up okay, and the old error went away; to be replaced with an out of memory error whenever I tried to launch.

Strangely enough everything still worked fine using Maven from the command line.

At this point I decided maybe Eclipse and it's various plugins were the weak link. Intellij IDEA seemed like it would be worth trying and the setup process was suprisingly straightforward. 

Beyond downloading and unzipping the community edition I had to setup the Sun JDK and JRE (https://help.ubuntu.com/community/Java) instead of using the OpenJDK. I also had to setup an M2_HOME environment variable to point to my Maven install. Both of steps tasks were spelled out by the IDE. 

Within about 15 minutes of downloading I had the project error free, building and running on a device. 

So for developing in the new environment has been good. I'll post an update once I've done a bit more with it.

New Home

Having not blogged for a few months I've finally got round to moving from as3offcuts.com to somewhere I can babble about a broader range of software development related topics including Android, Google Go, Haskell, bearded squid, embedded device shenanigans etc.

Wrapping Array indexes.

A quick post to note a method for wrapping Array indexes around if they are out of bounds. A good example use case for this would be for data displayed by a list component that cycles round endlessly.

It works for positive and negative inputs and returns the same index for inputs which are within the range of the length.

Strategies for decoupling views and mediators in PureMVC.

Keeping views and mediators nicely decoupled when using pureMVC can sometimes be a bit tricky. Declaring and using a concrete view within its corresponding mediator often seems the easiest way to accomplish things; but lands you with a very tightly coupled pair. Even though the view probably has no knowledge of the mediator it is the view that is most likely to change, meaning the mediator also requires modification.

Object oriented design advises against using concrete implementations for these very reasons. This article goes through a few ideas of ways to put this into practise.

Using the event model for two way communication.

Events are probably the most common way of achieving view to mediator communication. A mediator that knows its view component implements IEventDispatcher can add listeners and handle events dispatched by the component. Custom event classes can be used to pass data around.

This can work the other way round as well. A mediator that knows its view component implements IEventDispatcher can dispatch events on the view component for the component to handle itself. Custom events can be used once again to pass data from the mediator to the view.

The mediator now only needs to type its view component to IEventDispatcher or some high level implementation of (such as DisplayObject or UIComponent). This way views and mediators can fully communicate their intentions and the data that goes with them without any explicit knowledge of their concrete implementations.

Downsides to this: the code becomes a little harder to follow and you may need to add custom event classes (and the accompanying boilerplate) to pass the necessary data around.

Another similar approach would be to use a different messaging system instead. The Actionscript event model is perhaps a bit over complicated for a straightforward two way communication like the one described above.

Something along the lines of AS3 Signals could be used to create a lighter weight means of mediator-view communication in the same mould.

Using multiple interfaces.

Instead of a mediator having one view component reference - capable of handling all of the responsibilities inherent in their relationship - it could have several. Even if these references all point to the same object this is a way of dividing up the responsibilities the mediator has to the view into simpler, less strongly tied parts.

A mediator could be supplied an IEventDispatcher for event handling, a DisplayObject for positioning and several other interfaces/abstract classes to handle other aspects of the view.

This allows the view to be changed around without touching the mediator. Certain aspects could also be made to be optional in the mediator. For example supply an optional text component reference. If it is set then set its text, otherwise leave it. It also makes extending the mediator easier. To add on another responsibility is as easy as extending the mediator and adding another reference to another interface or class.

On the downside this also adds complexity and more interfaces. It also begs the question "how far do you break things down?". Do you need an IEventDispatcher for events when you've got a DisplayObjectContainer for adding and removing children? Ultimately it will depend whether the first is ever going to be needed without the second. Probably not in this case but the more complex the example the more likely it would be worth doing.

Another issue with this approach is when there is lack of common interfaces defined. A Flex Button has a label property, and a Label has a text property. Both accomplish the same thing, but as there's no common interface for setting their text this method is of no use.

Let the view decide.

Instead of making updating the responsibility of the mediator, make it the responsibility of the view. Then view components only have to implement an updating interface to achieve mediator to view communication.

When a notification is received by the mediator it's body is just passed straight into a call to the view's update method. The view can then check its content (for example check its type) before actioning the necessary update.

The biggest downside to this approach is the loss of compile time type checking. While using value objects can give good runtime checking, it adds processing overhead and invites errors that may not be found for some time.

Finally...

I will add some examples and any more thoughts I have on this subject soon.

UPDATE: A brief Flex example. http://db.tt/PRXGzvaX