Articles Feed

Authors

Categories

We're Busy!

by: eric | August 23rd, 2009 | 0 comments »

Agile2009_webbadges_speaker
SCNA Graphic

This week is a big one for the 8th Light team. Let’s head through the highlights:

Agile 2009

As usual a large number of 8th Lighters will be participating at Agile 2009. This is always a fun and educational experience for us, and this year it’s in our hometown. Let’s go through the talks we’re giving:

Mission Impossible: TDD and Javascript In the New Orleans room on Tuesday at 11:00 Jim Suchy will be giving a talk on doing TDD in Javascript. Javascript is a language that people tend to claim is “untestable” or “not worth it” but Jim will be showing that testing is not only possible, but worthwhile. In addition he demonstrates some of the neat features that make Javascript a cool language.

Ruby Kata and Sparring Back in the New Orleans room on Thursday at 9:45, Micah Martin will be talking about Ruby Kata and Sparring. Everybody wants to be a great developer, but how do you do it? Micah will show two different practice techniques, kata’s and sparring. If you go to this talk you get to judge the speaker and tell him how well he codes. How often do you get to do that?

TDD on iPhone The Eric’s are giving their legendary talk on practicing TDD on the iPhone on Thursday from 2:00 - 3:30 in Grand Ballroom F. This time we have a special surprise for those who attend - a Randori coding session where you will code functioning iPhone application. Please wash your hands before attending, as you’ll be using my keyboard. Head to my github page to see a sneak preview of what we’ll be working on.

Live Aid Once again some 8th Light guys will be helping out with Live Aid, including our newest Craftsman Colin Jones. Come to the stage, write some Rails, help charity. 10 minutes or 10 hours it doesn’t matter. Experience in Rails or even web development are unnecessary - that’s what the mentors are there for.

chiPhone

The second meeting of chiPhone, the Chicago iPhone developer group, will be held at a special location this week: the Obtiva offices! Thursday night if you’d like to do some hacking head to the chiPhone website to register - or just show up. I only need to count so I order the right amount of pizza.

SCNA America

I saved the best for last. Software Craftsmanship North America is a joint effort by 8th Light and Obtiva and frankly it has the best speaker lineup I’ve ever seen. Registrations are still available and cheap! If I could take credit for this I would - but it really goes to the organizers, who did a fantastic job. The entire 8th Light staff well be there and available for discussion, questions, and to accept free beer from the attendees. Meanwhile two of us will be speaking:

The Business of Craftsmanship “Craftsmanship sounds expensive!” If you’ve heard similar comments from your supervisors or clients, then join Micah, Kevin Taylor and Carl Erickson, three experienced craftsmen-turned-entrepreneurs for this 30 minute panel discussion. All three panelists come from technical backgrounds and have built successful software development companies that are built on craftsmanship values, such as quality, learning, and community, and use Extreme Programming practices to develop software.

Apprenticing to Mastery Listen to Paul and Obtiva’s Dave Hoover discuss how an Apprenticeship program can benefit your company and your career. Software companies are always looking for ways to develop skilled developers. Formal software apprenticeship is the approach taken by more and more companies, including Obtiva and 8th Light. Over the past 2 years we have observed almost a dozen apprenticeships and come to recognize certain apprenticeships of developers that are themed by their aspiration to mastery.

This might be the biggest week in 8th Light history - hope to see you there!

Announcing chiPhone

by: eric | July 9th, 2009 | 0 comments »

skitched-20090709-234004.jpg
Uploaded with plasq’s Skitch!

It’s with great pleasure that I announce the creation of chiPhone, the Chicago iPhone developer’s group, with our first meeting on July 23rd at 6:30. The fourth Thursday of every month should feature interesting presentations, hackfests, and everything else you’d expect from a quality developer group.

The group website is now up and running at www.chiphonegroup.org where you can register there to attend the first meetup. In addition you’ll find directions to the 8th Light offices, where most of our meetings will take place, and the announcement of the topic for the next meeting. As the official site website all further information will be posted there, including video recording of the talks.

The first meeting will feature a presentation by “the Eric’s” on Test Driven Development for the iPhone. We’ll be starting with the basics of setup and work all the way through Dependency Injection using Interface Builder. Bring your Macs so you can grab our github project for experimenting. Get to the 8th Light offices early for pizza and refreshments.

8th Light is located just off of Route 45 in Libertyville, and detailed directions are available on the chiPhone website. In addition we are near the Libertyville train station, just email me if you need to arrange to be picked up.

I’m looking forward to a lot of great meetups, and I’ll be asking you to provide some topics in the near future.

TDD and iPhone - NSTimer

by: eric | May 11th, 2009 | 3 comments »

TDD on the iPhone is a challenging experience, especially when you’ve been spoiled by Ruby like I have been, but it can be done. I have a tutorial in the works for getting started, but in the meantime I’ll be writing bits and pieces about my experience. The first was here and this is the second. Test cases are written using the Google Toolbox for Mac. This particular example is about the NSTimer.

It keeps going and going

The app to your right is a simple app for experimentation purposes that runs Conway’s Game of Life. It has two buttons: advance and start. Advance moves one generation ahead each time you press it, whereas Start keeps advancing generations until you touch Stop. To implement that we use an NSTimer object which is programmed to call advance on the game object. The design is simple, shown here:

TinyUML Version 0.13_02
Uploaded with plasq’s Skitch!

The GameRunner creates an NSTimer, the NSTimer sends the message to Game. Great but how do we test it? The less I know about something the more I tend to test it, which means I tend to write smaller and smaller tests. Let’s look at my first few tests of the GameRunner object:

  1. -(void) testSetsAndGetsTimeInterval {
  2. runner.interval = 0.30;
  3. STAssertEquals(0.30, runner.interval, nil);
  4. }
  5. -(void) testCreatesNSTimerObject {
  6. [runner start];
  7. STAssertNotNil(runner.timer, @"The timer was not created");
  8. STAssertTrue([runner.timer isValid], nil);
  9. }
  10. -(void) testNSTimerFields {
  11. runner.interval = (NSTimeInterval) 0.26;
  12. [runner start];
  13. STAssertEquals([runner.timer timeInterval], 0.26, nil);
  14. }

We’ve got some basic tests of creation. At this point I was stumped. I couldn’t check the other parameters of the timer, because they weren’t public variables, so at this point the code that actually created the timer looked like this:

  1. -(void) start {
  2. timer = [[NSTimer timerWithTimeInterval: interval
  3. target:nil
  4. selector:nil
  5. userInfo:nil
  6. repeats:true] retain];
  7. }

That doesn’t really help me does it? I have a timer with an interval, but it won’t call anything when it’s triggered. This is about the time I got to pair with Jake Scruggs during the Craftsman Swap, which he’s written about here. It went badly, somewhat embarrassingly for me since I’m supposed to be the expert, however we learn from failure. Let’s look at some of the steps Jake and I took that didn’t quite get us there.

The first pass on the test was simple. We needed a mock game, and it needed to have its advanceGeneration method called (Ed. note: I realize they aren’t called methods in Obj-C, to which I say: bite me.) each turn. Let’s try the brute force approach:

  1. -(void) testTimerCallsGameAdvance {
  2. MockGame *mockGame = [[MockGame alloc] init];
  3. runner.game = mockGame;
  4. [runner start];
  5. sleep(.30);
  6. STAssertTrue([mockGame advanceGenerationCalled], nil);
  7. }

I’m writing the original tests from memory, so I make the occasional error here, but it doesn’t matter since we got this wrong. This test here seemed the most logical. We ran the test and it failed, yea! Then we updated the code:

  1. -(void) start {
  2. timer = [[NSTimer timerWithTimeInterval: interval
  3. target:game
  4. selector:@selector(advanceGeneration)
  5. userInfo:nil
  6. repeats:true] retain];
  7. }

Experienced Cocoa developer’s have already discovered our error, please don’t ruin it for the rest of the readers. So after changing the code we run the test and…we fail. So from here Jake and I figured it out. Sleep won’t work because it stops the entire application, including the run loop that calls our timer, so we’ll just have to get the info out of the timer another way. We’re interested in testing that we’ve setup the timer correctly, and can trust that the timer just works. After a loooong time browsing documentation we figured it out. We could call this:

  1. -(void) testTimerCallsGameAdvance {
  2. MockGame *mockGame = [[MockGame alloc] init];
  3. runner.game = mockGame;
  4. [runner start];
  5. [runner.timer fire];
  6. STAssertTrue([mockGame advanceGenerationCalled], nil);
  7. }

This will fire the timer and validate that it is setup correctly. So we did this, our test passed, we ran the app and it….failed. We knew the timer was executing because our test was passing, but when we ran the real app it just didn’t do it. Stumped and frustrated we stopped for the day. Then time passed…..

Yesterday I had a candidate in for an apprenticeship position, and we attempted to solve the same problem. We re-evaluated the test and decided calling fire directly was cheating. We looked into a half-dozen other ways to test this and learned about the NSRunLoop. Too much coding in Windows had rotted my brain, the run loop in Objective-C is not the same as the one in Windows. Specifically the current run loop is accessible as an object. We wrote a new test:

  1. -(void) testTimerCallsGameAdvance {
  2. MockGame *mockGame = [[MockGame alloc] init];
  3. runner.game = mockGame;
  4. [runner start];
  5. [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow: 0.30]];
  6. STAssertTrue([mockGame advanceGenerationCalled], nil);
  7. }

It’s not perfect - the 0.30 relies on the hard coded default interval of 0.25, and that is too long, but it failed! In the process of learning about NSRunLoop we also realized I used the wrong method. The working code is this:

  1. -(void) start {
  2. timer = [[NSTimer scheduledTimerWithTimeInterval: interval
  3. target:game
  4. selector:@selector(advanceGeneration)
  5. userInfo:nil
  6. repeats:true] retain];
  7. }

See the word “scheduled” in front of Timer? That actually adds the timer to the default run loop. Now we ran our spec, ran our actual code, and it works! The moral of the story? Well if you’re persistent enough you can get your code under test, and if your test is correct then your code will work.

Dependency Inversion Principle and iPhone

by: eric | April 16th, 2009 | 0 comments »

skitched-20090403-075826.jpg

Vertical Dependency

While working on the slides for our upcoming* talk on TDD for iPhone I asked Eric Meyer why we need the Dependency Inversion Principle. He eagerly answered, “Testing!” which made me laugh because I wasn’t giving him a trivia quiz, and I love Eric’s enthusiasm. He’s right, but the answer is circular. TDD is great because it gives us better designs that correspond to the DIP which enables TDD. Ha! I win, would you like to buy my consulting services? I have plenty of three letter acronyms where those came from.

Fortunately this isn’t the case, as the DIP existed well before TDD was popularized, but recently there was a bit of a dust-up over the SOLID principles. Many developers don’t understand why dependency inversion is important, so let’s demonstrate the usefulness in the Objective-C language on the iPhone.

The Dependency Inversion Principle (DIP) reads as follows:

A. High level modules should not depend upon low level modules. Both should depend upon abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.

So your code should depend on interfaces not on concrete classes, but why? Let’s look at a useful example in the Objective-C built in classes.

  1. [NSString stringWithFormat:@"Object is: %@", object];

Do you see the DIP at work? It’s subtle here, but look at the method stringWithFormat, which takes a format string and then a list of parameters to fill in the format specifiers. The format specifier here is “%@” which takes any Objective-C object and calls descriptionWithLocale on it, or description otherwise. The object that is passed in here could be anything because all the stringWithFormat method cares about is that the object provides at least one of the two methods above. It’s depending on the interface, and not the concrete class. Let’s imagine a world where this didn’t exist, and the NSString method could only be composed of other strings. Suddenly you’d have something like:

  1. return [NSString stringWithFormat:@"Object is %s", [object toString]];

That’s not bad at all is it? Well what if there are different objects.

  1. return [NSString stringWithFormat:@"Object is %s %s %s", [object1 toString],
  2. [object2 toS],
  3. [object3 stringify]];

Are you starting to see the problem? Suddenly I can’t use this method without being cognizant of the specifics of the object I passed in. The minute one of these interfaces changes I have to change my code. I stole this method from some real code, so let’s look at it with some context. Once upon a time I was writing a mock object for an iPhone application. Now iPhone doesn’t have a good mock object framework, at least that I’m aware of, so I was rolling my own mock. The mock logged calls to it which I then queried. To construct the string I used this method:

  1. +(NSString *) createStringFrom: (id) cell at: (CGPoint) point
  2. sizeOf: (CGRect) rect
  3. {
  4. return [NSString stringWithFormat:@"%@ %f %f %f %f", cell,
  5. point.x,
  6. point.y,
  7. rect.size.width,
  8. rect.size.height];
  9. }

Don’t sweat the details right now, they’re not important. Instead look at how you can see the DIP succeeding and failing in the same code here. The first parameter to createStringFrom is a cell object, but it’s of type id, so it could really be anything. That’s good because I wasn’t sure when I wrote this mock what type the cell would be and I’d generally prefer that my mock object not have to know the details. In fact the cell did change type several times which is why insulating yourself from change is so important. There’s an assumption by many developers that you should only worry about the things you’ll be changing in the future, but the best gauge of future changes is present changes, and if you’re changing a module frequently during development as you get it right you’ve found a likely change point. Even if you haven’t, you’ll make your life simpler in the present by insulating yourself from that change, speeding up your development cycles. I digress.

The rest of this method isn’t so lucky. You see CGPoint and CGRect are C structures, and I am left to write these as floats in the string (%f). If I was to change the parameter types frequently I would probably introduce some way to insulate myself from that change as well, possibly by wrapping them in objects. Since those parameters have not changed I haven’t done that, although I’m thinking about it.

Our current apprentice Colin has given a first-hand account of refactoring to DIP here as well.

How do I do it?

skitched-20090403-102851.jpg
Uploaded with plasq’s Skitch!

Eric and I are working on a program to run Conway’s Game of Life. On the iPhone screen you see Rounded Rect Buttons that change color based on whether a cell is alive or dead. The problem is that we don’t really want to drag and drop 300+ tiny buttons on the screen with interface builder. Instead we want to create them programatically, when the GameOfLifeViewController is loaded. Again I don’t want to overload you with extraneous details, so just take my word for it that there is a GameOfLifeViewController, and it needs to generate buttons. Here’s what my first pass at a test looked like in rough pseudocode:

  1. for (int row = 0; row < 15; row++)
  2. {
  3. for (int column = 0; column < 15; column++)
  4. {
  5. button = GetButtonViewAt(row, column)
  6. STAssertEquals(expectedSize, button.size)
  7. STAssertEquals(expectedLocation, button.location)
  8. STAssertAction(expectedAction, button.action)
  9. }
  10. }

There’s a lot wrong with this test. The most obvious is the hard coded 15. What happens when we want to change the number of rows and columns? Now we have to change code in multiple places. Naturally we did in fact change this, so I would have paid for this decision quickly if I hadn’t already refactored it away. The second is that there’s going to be more than one test for creation, each of which will have to perform the same 15x15 loop. The annoyance of constantly changing this will reveal the root the problem, the GameOfLifeViewController should really only be in charge of GameOfLifeView and really doesn’t need to know the details of the creation of its subviews. It’s violating the Single Responsibility Principle. We can fix that with a factory object, and will do so, but that will violate the Dependency Inversion Principle. So we’ve got one DIP violation, an SRP violation, and a potential second DIP violation, all demonstrated in 6 lines of test code.

Fortunately we’re going to introduce some interfaces to clean that up. The first is an interface to the board object. Why the board? Well the board should know the number of rows and columns it has, and if we can inject a fake version of the board we can actually set those to be 1 and 1. That’s will make our test focus on what we are truly concerned about. The second thing we’re going to do is introduce the Abstract Factory pattern to create our button views. It’s a bit of a heavyweight solution but its going to pay off by cleaning up our client code dramatically. We’ll have a View Controller concerned with controlling the view, and a creation factory concerned with creation, as well as a board that keeps track of rows. Let’s take a look at the test now, again in rough pseudocode.

  1. -(void) setUp
  2. {
  3. controller = [[GameOfLifeViewController alloc] init];
  4. controller.board = [[MockBoard alloc] init];
  5. controller.buttonControllerFactory = [[MockButtonFactory alloc] init];
  6. }
  7. -(void) testCreationOfButtons
  8. {
  9. [controller viewDidLoad];
  10. bool called = [controller.board calledWith: params that: I want: true];
  11. STAssertTrue(called);
  12. }

So what’s going on here? In the setup we load up the board with a fake board, one that returns 1 for its rows and columns, and we load up its buttonControllerFactory with a fake buttonController Factory. In our test we call the viewDidLoad method, which is called on controllers after their view is loaded. Duh. That’s the method where we use the buttonControllerFactory. Then we call a method on the mock factory calledWith: that takes the parameters I expected the creation factory to receive. Finally we check that it was called with the assertion. So far I’ve only been showing test code, because I wanted to demonstrate just how much cleaner our tests have become. Now there’s no loop, no hard coded constants, and no testing the internals of the creation factory in the view controller. That isn’t to say we don’t test the creation, we just do that in a different test case, the one that corresponds to the ConcreteButtonFactory class. As a rule if our test code is cleaner, our implemenation code is cleaner, and that’s the case here as well.

Let’s now look at the real class, and how to enable Dependency Inversion on it. We have to start with Objective-C protocols. Protocols are very similar to Java interfaces, and just as useful, but are strangely underrepresented in XCode. As best I can tell** just create an NSObject subclass and remove the .m file and any imports from the .h. Here’s the protocol from the unfortunately named ButtonControllerFactoryProtocol.h:

  1. #import "ButtonController.h"
  2. @protocol ButtonControllerFactoryProtocol
  3. -(ButtonController*) createButtonControllerForCell: (id) cell
  4. at: (CGPoint) point
  5. sizeOf: (CGRect) rect;
  6. @end

As you can see the interface only defines one message, createButtonControllerForCell. It returns the ButtonController object, although it could return an object conforming to a protocol. Indeed one could argue it should, as that would streamline my mock object. Hmmm… I see a refactoring in my future. Now let’s look at the class definition for the ConcreteButtonControllerFactory, which is the object that is actually used when the real app is running.

  1. #import <uikit />
  2. #import "ButtonController.h"
  3. #import "ButtonControllerFactoryProtocol.h"
  4. @interface ConcreteButtonControllerFactory :
  5. NSObject<buttoncontrollerfactoryprotocol> {
  6. }
  7. @end

Not much here is there. The important part to look at is NSObject. ConcreteButtonControllerFactory inherits from NSObject, as all Cocoa objects do, and conforms to the ButtonControllerFactoryProtocol. Like a Java interface this is a contract to later implement createButtonControllerForCell in my implementation file and that’s exactly what I’ve done.

  1. #import "ConcreteButtonControllerFactory.h"
  2. @implementation ConcreteButtonControllerFactory
  3. -(ButtonController*) createButtonControllerForCell: (id) cell
  4. at: (CGPoint) point
  5. sizeOf: (CGRect) rect;
  6. {
  7. ButtonController *controller =
  8. [[ButtonController alloc] initWithCell:cell];
  9. UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  10. [button setFrame:rect];
  11. [button setCenter:point];
  12. [button setImage:[UIImage imageNamed:@"dead_cell.png"]
  13. forState:UIControlStateNormal];
  14. [button addTarget:controller
  15. action:@selector(bringToLife:)
  16. forControlEvents:UIControlEventTouchUpInside];
  17. controller.view = button;
  18. return controller;
  19. }
  20. @end

This isn’t an article on UIKit so I’m not going to get into the details of creating the button. You can see again that I’ve ignored the DIP for creating the UIButton and the ButtonController. Since this is a factory I’m okay with this violation. I could have created abstract factories for the UIButton and ButtonController and passed them in here but I don’t believe I’d gain any benefit from that implementation. That’s verified by my testing, as writing tests for the creation of these objects was hard before I introduced this factory but isn’t any longer. If it becomes difficult then I’ll consider making the change to two factories. Now we need to inject the concrete dependency. In a Java project you could do this in a main method or with a DI framework like Spring. We’re going to be using my favorite DI framework of all time: Interface Builder!*

It’s a common misconception that IB is just a GUI builder. What’s great about it is that it doesn’t just generate a bunch of code, but instead “freeze dries” real objects to be instantiated when the program loads the NIB file. Furthermore while the most common Outlets are UI elements there’s no reason other objects can’t be used. Let’s take a look at my NIB document window for the GameOfLifeViewController:

GameOfLifeViewController.xib-3
Uploaded with plasq’s Skitch!

As you can see I’ve got objects for the Game, ConcreteButtonControllerFactory, and the Board. That’s because all three of the objects are injected at runtime, while the code depends on protocols. To add your own objects to a NIB file simply by selecting it from the Library:

Activity Monitor
Uploaded with plasq’s Skitch!

It’s inspector window will have a class drop down, so set this object’s object to your class. Finally you need to connect the outlets to actual outlets in your code. Let’s look at the Outlets tab in IB for my controller (the File’s Owner):

Game Of Life View Controller Identity
Uploaded with plasq’s Skitch!

Notice how the controller still thinks of them all as NSObject? So if I change the objects it doesn’t care, as long as I conform to the interface? Finally let’s take a peek at the controller interface file:

  1. #import "BoardProtocol.h"
  2. #import "ButtonControllerFactoryProtocol.h"
  3. #import "GameProtocol.h"
  4. @interface GameOfLifeViewController : UIViewController {
  5. IBOutlet NSObject<boardprotocol> *board;
  6. IBOutlet NSObject<buttoncontrollerfactoryprotocol> *buttonFactory;
  7. IBOutlet NSObject<gameprotocol> *game;
  8. }
  9. @property(nonatomic, retain) NSObject<boardprotocol> *board;
  10. @property(nonatomic, retain) NSObject<buttoncontrollerfactoryprotocol> *buttonFactory;
  11. @property(nonatomic, retain) NSObject<gameprotocol> *game;

See any dependencies on the actual objects? Nope - just protocols. There are properties for the objects so that I can inject the dependencies through the tests, all of which pass in fake versions as various times depending on how it suits the test. It may be unhealthy - but I find this incredibly cool.

Summary

What I love about Interface Builder is setting this up is extremely simple. Writing tests for the controller that is based on these dependencies is also extremely simple, far simpler than just depending on the concrete objects. It’s funny how developers often complain about the time wasted writing tests or “over-engineering” in this way, but once I broke these dependencies I got things done a lot faster. I’m writing working code without loading the actual simulator. I write my tests first, making progress, and when I’m done for the session I run the app once or twice just to verify I haven’t done anything like forgotten to inject the dependency. Compare that to running the simulator constantly, each time hoping your code is functional. Who’s wasting their time now?

FootNotes:
* Uh yeah we gave that talk already. These take a while!
** I’m 99% positive there’s a better way, and that I haven’t found it. Tell me if there is!
*** To be fair it’s the only one I’ve actually used.

####