Coding Together: Developing Apps for iPhone and iPad

Wow this is a really great course! Thank you Paul Hegarty you are a great teacher.

I’ll be writing this series of posts following the iTunesU course you’ll be able to get working examples of the assignments implemented using TDD. All the code is available on github.

Test Driven Development

For myself and many professional developers TDD is something we practice daily. I am a practioner and an advocate. Your code will be better. You will be better. When you working on your old code, you’ll appreciate it. When others are working on your code, they’ll appreciate it.

Objective C

I don’t have much to say here, I’ve never used it before doing this course. I can advise that you get AppCode. JetBrains IDE’s are awesome and make TDD natural.

Red, Green, Refactor

Say what? Its the TDD workflow:

  1. Add a test
  2. Run the tests and see the new test fail
  3. Write the code to make the test pass
  4. Run the tests and see they all succeed
  5. Refactor


To get this working on you with your own project install the latest Xcode and AppCode followed by OCMock. Create a new Empty Application for iOS and follow the OCMock instructions or just clone my repository and open it in Xcode or AppCode, OSMock is already setup.

A little tip for AppCode, if you get an error saying Code Sign error: The identity ‘iPhone Developer’ doesn’t match any valid, non-expired certificate/private key pair in your keychains while running the app or tests choose the Run option from the Run menu and make sure you have the iPhone or iPad emulator selected.

First thing we need to do is write our failing test.

If you run this test your build should fail because we don’t even have a Card class. Compilation failures count as red. Now we’ll write the code to make the test pass. Hint if you’re using AppCode and you’re not familiar with JetBrains IDE’s hit ALT + Enter over the red Card it will prompt you to create the class, do the same with the match method!

If you’ve never practiced TDD before you’re might be saying something like: You’re just returning zero, thats ignorant, the match method does more than that… What I’ve done is the simplest way to pass the test. The tests are the documentation of our code, right now we’ve documented that match should return 0, so that is all our code should be doing. I agree that we probably want our match method to be more useful… so its time to write another test.

Pseudo randomness in tests can be useful, remember to seed your random number and give the seed as part of the feedback, that way if the test ever fails you can repeat the randomness. The randomness means we need to think a little be more about how we make the above test pass. We could not perform a naive lookup on the array index based on the ordering in the test. Randomness excercises our code better. Time to make it Green.

Okay great now the match method is useful. After many more Test classes and Model class I realize I need to override isEqual on Card below are the tests interspersed with the evolving implementation.

Okay now we have isEqual there is a good oppurtunity for a bit of refactoring. Our previous match method had a for loop and an if statement it would be nice to get rid of those.

The benefit of testing really shines now, we can have confidence that our objects are working as we documented (with our tests) even thought we have made a fairly large change to our code (the match method is now 87% smaller).


Being able to mock out dependencies is an important for TDD. It allows us to test the behaviour of our objects, when we either don’t want to or are unable to, expose the results of our interaction with dependencies. As an example lets look at the tests for the addCard method of the Deck class.

Here we’re validating that we are infact adding the card to the backing NSMutableArray *cards. When it comes to mocking I believe you have to be pragmatic, its really powerful but can also couple your tests to your implementations. You can read all about mocks in this post by Martin Fowler.

You have no comments…

Tests are better documentation than any comment, unlike tests, comments never get updated or even validated.

What now?

Well if you’ve implemented the homework yourself why don’t you compare you implementation with mine and ask yourself?

  1. Which is easier to understand.
  2. Which would you feel more comfortable refactoring.

For a far more detailed explanation by Kent Beck read Test Driven Development: By Example. I also recommend that you read Refactoring: Improving the Design of Existing Code by Martin Fowler.

I strongly recommend you participate in a Code Retreat whether you’re a TDD novice or expert. Pairing with other practioners is the best way you can learn and improve!

Next time

We’ll spend time looking at how we can write functional tests for our UI of our application.

The story so far

In part 1 we covered getting our SE app started and the Jetty and Weld containers started to provide us with a servlet and CDI capabilities. In part 2 we added support for RESTful webservices with the Jersey implementation of JAX-RS. In part 3 we added JSF support using Mojarra 2.1.

This time we’re going to be adding JPA 2 support using Hibernate we will also be making our EntityManager injectable and implemented container transations using our own CDI interceptor.

As always a fully working project to go along with this post is available here.


JPA 2 is probably one of the best JCP and JSR success stories. I really love this specification and every implementation I have used has done a really great job.

The implementation I have chosen to use is Hibernate but you can switch this out if you wish!

We’re going to implement our own EntityManager which will simply wrap a delegate, this gives us two things:

  1. An EntityManager we can @Inject
  2. It gives us fine grained control of the lifecycle of our delegate EntityManager.

We will also create an @ApplicationScoped CDI producer which will produce the delegate for our wrapper.

Lastly we will be creating a transaction interceptor to automatically begin/commit/rollback our transactions.

We add hibernate and h2 database as dependencies.

Next we setup our persistence.xml

And our entity

Now for the exciting stuff first up the producer

The producer looks after our delegate EntityManager lifecycle, creating a new one when required and more importantly allowing the TransactionInterceptor to destroy it when a transaction ends.

Next we implement our EntityManager to wrap our delegate, because we are in a CDI container the our wrapper also lets us @Inject a @Dependent scoped EntityManager into any CDI bean.

As you see the wrapper is very straight forward, but with a CDI container at work the wrapper plays an important role.

The final piece of the puzzle is our TransactionInterceptor, it knits our wrapper and delegate producer together and makes our JPA transactions automatic.

The logic is fairly straight forward the important part is that we unregister the delegate with our producer when a transaction goes out of scope.

We also need the interceptor binding…

… and remember to enable our interceptor in the beans.xml

We can now @Inject our EntityManager and transactions are taken care of automatically if we annotate our bean or method @Transactional.

Thats it for now in this series of blog posts. You can fork the master branch of the example project and have a solid start for your application. If you have any ideas for more topics in this series or questions about the topics covered so far let me know on Twitter or Google+!

Blogger was okay, but working with code snippets is really painful. With that is mind I’ve moved over to Octopress hosted on Github Pages!

It took me about 2 hours to move, but I probably spent 10 hours researching and deciding what to move to, however I am VERY happy with my choice.

The story so far

In part 1 we covered getting our SE app started and the Jetty and Weld containers started to provide us with a servlet and CDI capabilities. In part 2 we added support for RESTful webservices with the Jersey implementation of JAX-RS.

Now its time for some UI, for this we’re going to setup setup JSF using the Mojarra 2.1 implementation.

As always a fully working project to go along with this post is available here.

Java Server Faces

Lots of people love JSF and a lot of people don’t. In general I am not a frontend hacker, and to be honest when I have to do it (and I am usually forced to use a UI framework) I find myself wishing for plain old HTML or that new cool term POH5. Now whether this is the fault of Java, the UI framework or GASP a failing deep within myself I am not sure.

My experience is that JSF makes writing web applications in Java feel the least like trying to parallel park an articulated bus.

Remember the real problem with web development is that some always mentions wanting support for some version of Internet Explorer ;)

So all of that said how do we go about doing this? Well its really pretty simple at this point. We have most of the environment in place already, all we need now are a few extra dependencies, a bit in the web.xml and a faces-config.xml.

The four dependencies that we need are the Mojarra JSF API and implementation, JSTL and lastly a EL implementation (we added the API in part 2).

Above we ask Mojarra to configure JSF for us and we setup the EL implementation.

If you check out the example there is also a DeedController bean, and an index.xhtml you can build and run the example and point your browser at http://localhost:8080/faces/index.xhtml.

In part 4 we’ll setup JPA and using CDI make our EntityManager injectable and setup container transactions.

The story so far

In part 1 we covered getting our SE app started and the Jetty and Weld containers started to provide us with a servlet and CDI capabilities. Now we are going to setup JAX RS.

RESTful services

Do you want to add restful services to our application? Of course you do!

A fully working project to go along with this post is available here.

JAX RS Provider

I chose Jersey however it should be just as easy to get RESTeasy integrated. First off we need to tell Jetty about Jersey.

So in the above we setup our Jersey servlet and we set the parameter, the value is a class that we need to implement which returns a list of all the JAX RS resources in our application.

Our Service

Its also good idea to actually write the RESTful service.

So go ahead and POST to http://localhost:8080/rest/deed/good and you should receive a 201 Created response

You can also see the CDI lifecycle taking place on stdout.

In part 3 we will get JSF 2.0 working as well.

What is the problem?

You want to write a Java app, that has all the good stuff in it?

By good stuff I mean:

  • CDI (who doesn’t want awesome DI and interceptors)
  • JAX RS
  • JSF
  • JPA 2.0 (with container managed transactions)

Of course you do, why wouldn’t you? I love an app server as much as the next guy or gal, but it is another piece of the stack which needs to be monitored and patched, it can also have its own bag of issues you need to look out for.

So we recently wrote a product and I wanted to use all the “good stuff”. Since the product is to be widely deployed I veto’d the use of an app server after all less moving parts means less support calls.

So I went about getting all these goodies working in Java SE and here is how I did it.

A fully working project to go along with this post is available here.

Servlet Container

You’re going to need one of these, I picked Jetty 8 its really easy to get running in embedded mode and it has JNDI. That said you could probably use Tomcat 7 without too much modification.

The above is some pretty standard stuff to get embedded jetty going.

CDI Container

You’ll also be needing one of these, I chose Weld for the job. Your web.xml would need to look something like the snippet below.

The Weld servlet listener will start our CDI container and the init() method of AppServlet is our entry point into our application after the containers have loaded, so you can go ahead and put any initialization you want in here with the CDI container available!

Next we have our CDI bean.

Our CDI interceptor implementation…

… and the interceptor annotation.

We even have an Arquillian unit test.

In part 2 we will get JAX RS working as well.