Mark Needham

Thoughts on Software Development

Archive for the ‘Coding Dojo’ Category

Coding Dojo #13: TDD as if you meant it

with 9 comments

We decided to follow Keith Braithwaite’s ‘TDD as if you meant it‘ exercise which he led at the Software Craftsmanship Conference and which I originally read about on Gojko Adzic’s blog.

We worked on implementing a Flash Message interceptor, to hook into the Spring framework, that one of my colleague’s has been working on – the idea is to show a flash method to the user, that message being stored in the session on a Post and then removed on a Get in the ‘Post-Redirect-Get‘ cycle. It’s similar to the ‘:flash’ messages that get passed around in Rails.

The Format

We used the Randori approach with five people participating for the whole session.

What We Learnt

  • We were following these rules for coding :
    1. write exactly ONE failing test
    2. make the test from (1) pass by first writing implementation code IN THE TEST
    3. create a new implementation method/function by:
      1. doing extract method on implementation code created as per (2), or
      2. moving implementation code as per (2) into an existing implementation method
    4. only ever create new methods IN THE TEST CLASS
    5. only ever create implementation classes to provide a destination for extracting a method created as per (4).
    6. populate implementation classes by doing move method from a test class into them
    7. refactor as required
    8. go to (1)

    Despite having read about Gojko’s experiences of this exercise I still found it amazingly frustrating early on taking such small steps and the others pointed out a couple of times that the steps we were taking were too big. The most difficult thing for me was the idea of writing the implementation in the test and working out what counts as implementation code and what counts as test setup. The line seemed to be a little bit blurred at times.

  • We worked out after writing 5 or 6 tests that we had overcomplicated things – we originally started out using a map to represent the session and then called the get and put methods on that to represent putting the flash message into and taking it out from the session. We decided to redo these tests so that the flash message was just represented as a string which we manipulated. This second approach guided us towards the idea of having a FlashMessageStore object with a much simpler API than a Map.
  • We started off only extracting methods when there was duplication in our tests which forced us to do so. As a result of doing this I think we ended up having the implementation details in the test for longer than the exercise intended. We didn’t introduce a class to hold our methods for quite a while either – the idea we were following was that we wouldn’t create a class unless we had three methods to put on it. Once we got the hang of the exercise we started creating those methods and classes much earlier.
  • Dave pointed out an interesting way of writing guard blocks which I hadn’t seen before – the idea is that if you want to exit from a method it’s fine not to have the {} on the if statement as long as you keep the whole statement on one line. Roughly something like this:
    public void clearFlashMessageIfRequestTypeIsGet(Request request) {
    	if(!"get".equalsIgnoreCase(request.GetType()) return;
    	// do other stuff
    }
  • It seemed like following these rules guided us towards tiny/micro types in our code and the methods we extracted were really small compared to the ones we would have written if we’d started off writing the test and implementation separately.
  • We had an interesting discussion towards the end of the dojo about the merits of wrapping framework libraries with our own types. For example we might choose to wrap the HttpServletRequest in our own Request object so that we can control the API in our code. Although I think this might initially be a bit confusing to people who expect to see a certain set of methods available when they see they are using a Request object, this approach seems to be following Steve McConnell’s advice in Code Complete of ‘coding into a language’ rather than in a language – we are moulding the framework to our system’s needs.

For next time

  • I really enjoy the dojos where we experiment with an approach which is slightly different than what you do on projects. Although the language (Java) was familiar to everyone it was still challenging to code a very different way than what we’re used to. We’ll probably try this exercise again the next time with another problem.

Written by Mark Needham

April 30th, 2009 at 6:12 am

Posted in Coding Dojo

Tagged with

Coding Dojo #12: F#

with one comment

In our latest coding dojo we worked on trying to port some of the functionality of some C# 1.0 brain models, and in particular one around simulating chaos behaviour, that Dave worked on at university.

The Format

This was more of an experimental dojo since everyone was fairly new to F# so we didn’t rotate the pair at the keyboard as frequently as possible.

What We Learnt

  • The aim of the session was to try and put some unit tests around the C# code and then try and replace that code with an F# version of it piece by piece. We created an F# project in the same solution as the C# one and then managed to hook up the C# and F# projects, referencing the C# one from the F# one, with some success although the references did seem to get slightly confused at times. The support from the IDE isn’t really there yet so it can be a bit tricky at times.
  • We were using the XUnit.NET framework to unit test our code – this seems like a useful framework for testing F# code since it doesn’t require so much setup to get a simple test working. We can just annotate a function with the ‘Fact’ annotation and we’re good to go. One thing to be careful about is to make sure that you are actually creating functions to be evaluated by the test runner and not having the tests evaluated immediately and therefore not being picked up by the runner. For a while I had written a test similar to this and it wasn’t being picked up:
    [<Fact>] let should_do_something = Assert.AreEqual(2,2)

    The type of ‘should_do_something” is ‘unit’ and as I understand it gets evaluated immediately. What we really want to do though is create a function (with type ‘unit -> unit’) which can be evaluated later on:

    [<Fact>] let should_do_something() = Assert.AreEqual(2,2)

    The brackets are important, something that I hadn’t appreciated. We were generally running the test by directly calling the test runner from the command line – we couldn’t quite work out how to hook everything up inside Visual Studio.

  • I’m not sure if we went exactly to the book with our refactoring of the code to make it testable – the method on the class doing the work was private so we made it public – but it helped to get us moving. We were able to then replace this with an F# function while verifying that the output was still the same. As I mentioned on my post about the little twitter application I’m working on, I’m intrigued as to how we should structure code in F#. Apparently the answer is as objects but I’m interested how the design would differ from one done in a predominantly OO as opposed to functional language.

For next time

  • I’m really enjoying playing around with F# – it’s definitely interesting learning a different approach to programming than I’m used to – so we might continue working on that next time around. If not then we need to find another game to model!

Written by Mark Needham

April 16th, 2009 at 6:20 pm

Posted in Coding Dojo,F#

Tagged with ,

Coding Dojo #11: Javascript Isola

with one comment

In our latest coding dojo we attempted to code Isola in Javascript but instead of coding from the board inwards we decided to try and take the approach of coding from the cells outwards to keep it interesting.

My colleague brought in his copy of the game and it made it much easier to imagine how we should be modeling it by having the game in front of us.

The Format

We used the Randori approach with four people participating for the whole session.

What We Learnt

  • We tried out a couple of Javascript frameworks during the session – JSUnit and another one which is the testing framework used by the Prototype library. I’ve been using screw-unit on my current project and neither of the frameworks made test writing seem as fluent as it does when using screw-unit.
  • IntelliJ is a way better editor for writing Javascript than Visual Studio is at the moment. It was really cool that we got auto completion when writing the code (although the auto complete function does currently give you the opportunity to call any method within the project’s Javascript files even if it’s not valid!)
  • We had a copy of Javascript: The Good Parts with us which proved useful for showing us the right way to go when it comes to coding in javascript. Certainly trying to understand the meaning of the keyword ‘this’ was something that we didn’t find easy and I still don’t really understand what the ‘with‘ keyword does despite reading the definition several times.
  • Modeling wise the approach we took provided a a much more interesting problem to solve – we were keen to avoid ending up doing a lot of string manipulation as we had on our java attempts at solving this problem. We got as far as telling a cell to remove itself from the board and were implementing the functionality for the cell to inform adjacent cells that it no longer existed.
  • I hadn’t realised quite how easy jQuery has made it to do javascript work until this dojo. We were writing pure javascript which proved to be quite arduous although the code did read quite nicely once we got going. We’re planning to investigate whether jQuery would be useful for this type of coding or not.

For next time

  • I won’t be able to make the next couple of dojos but the plan is to keep working on the Isola problem in the next session.
  • I am also keen to try out Keith Braithwaite’s TDD exercise in one of our dojos, an idea which I came across from reading Gojko Adzic’s blog entry about the Software Craftsmanship Conference held in London last week.

    Briefly, the idea is to try to keep things simple – implement everything inside our test and then extract it out into classes and methods when necessary. Small steps is the order of the day.

Written by Mark Needham

March 6th, 2009 at 6:38 am

Posted in Coding Dojo

Tagged with

Coding Dojo #10: Isola III

without comments

In our latest coding dojo we continued working on Isola with a focus on adding functionality following on from last week’s refactoring effort.

The Format

We used the Randori approach with four people participating for the whole session.

What We Learnt

  • Our real aim for this session was to try and get the code into a state where we could reject an invalid move i.e. a move to a square that wasn’t adjacent to the one the player was currently on. As we still had the whole board represented as a string this proved to be quite tricky but we eventually came up with an approach which calculated the difference between the last and current moves and was able to tell us whether or not it was valid. This didn’t cover diagonal moves, however. We found it pretty difficult to drive this functionality due to the way the board was represented.
  • What I’ve found surprising is how long we’ve been able to get away with having the board represented like this. Ideally we would have it represented in a structure that made it easy for us to make changes. This would require quite a big refactoring effort which we shied away from, I think due to the fact that we would be working without a green bar for quite a while during the refactoring. It wasn’t obvious to me how we could refactor the code in small steps.
  • Halvard pointed out that while we don’t want to do Big Design Up Front, what we did in the first week of Isola was No Design Up Front which was equally harmful. Finding a happy medium i.e. Enough Design Up Front is necessary to avoid the problems we have run into here.

For next time

  • We’re planning to try and implement Isola in Javascript next week. Most of the Dojo regulars are working with Javascript on their projects so it makes sense to give it a go.

Written by Mark Needham

February 19th, 2009 at 11:09 pm

Posted in Coding Dojo

Tagged with

Coding Dojo #9: Refactoring Isola

with 2 comments

Our latest coding dojo involved refactoring the code we wrote a couple of weeks ago for the board game Isola.

We started a repository on Bit Bucket to store our code from these sessions.

The Format

We used the Randori approach again with four people participating for the whole session.

What We Learnt

  • Last time we had spent most of our time purely making the code functional so all the objects were completely mutable. We decided to start by removing that mutability to allow us to add additional functionality more easily. We came up with a rough idea of where we were aiming for and then started refactoring towards that.
  • The tests were really useful for this as they provided feedback after every small refactoring with respect to whether or not it had broken the original functionality. In some cases we had to redesign the tests a bit to cater for the fact that we were no longer mutating the original Isola class so some our assertions were incorrect.
  • It was quite surprising to me how much time it took to refactor the code. On the first session we didn’t spend any time refactoring the code so it made it difficult to change bits of the code without other bits being affected, several times leading into a bit of a yak shaving exercise. Luckily we backed out of these refactorings without spending too much time on them. It pretty much drilled into us how we shouldn’t forget the Refactor part of ‘Red, Green, Refactor’ or we will suffer!
  • While trying to implement what I have previously heard referred to as a slug but which may in fact be a variance of the flyweight pattern we realised that our IsolaPlayer object was mutable meaning that our tests were now dependent on each other! This was the code that led us into trouble:
    public class IsolaPlayer {
    	public IsolaPlayer playerOne = new IsolaPlayer("-1");
    	public IsolaPlayer playerTwo = new IsolaPlayer("-2");
     
        private final String playerRepresentation;private final String HOME_POSITION = "[]";
        private String stomach;
     
        public IsolaPlayer(String playerRepresentation) {
            this.playerRepresentation = playerRepresentation;
            this.stomach = HOME_POSITION;
        }
     
        public String toBoardRepresentation() {
            return playerRepresentation;
        }
     
        public String poop() {
            return stomach;
        }
     
        public void eat(String boardPosition) {
            stomach = boardPosition;
        }
    }

    As you can see the class is mutable but being referenced by a static instance. We quickly backed that change out and refactored to that pattern later on when IsolaPlayer was immutable.

  • We used a combination of the techniques from Working Effectively With Legacy Code to allow us to extract an IsolaBoard from the original Isola class. IsolaBoard was kept completely inside Isola while we refactored the code so that it could exist on its own. This approach allowed us to continually validate that we hadn’t broken any tests while we gradually put more and more of the board logic into the appropriate class.
  • When we write mutable code the order of operations makes a big difference and the application doesn’t work correctly if we change the order. We learnt this with an early refactoring to inline some variables – an innocuous enough change, but one which led to 50% of our tests breaking.
  • We had an interesting discussion around how we can have code which is mutable but in a non dangerous way. On our way to creating value objects at one stage we had the code in a state where we were returning a new Isola object evey time but we were passing the same instance of our coveredSquares queue around. The queue was mutable meaning that we had references between difference instances of Isola to the same queue. In this case we were throwing away old Isolas but this might have been a problem if we had multiple games running at the same time. The next step was to refactor Isola to be completely immutable.

For next time

  • Since we spent the whole of this weeks session refactoring the code the plan for next week is to add some more functionality to the application. There is still quite a bit of logic left before we have a working game.

Written by Mark Needham

February 12th, 2009 at 9:46 pm

Posted in Coding Dojo

Tagged with

Coding Dojo #8: Isola

with one comment

Our latest coding dojo involved writing the board game Isola in Java.

The Format

We used the Randori approach again with around 8 or 9 people participating for the majority of the session, our biggest turnout yet. I think the majority of people had the opportunity to drive a couple of times over the evening.

We had the pair driving at the front of the room and everyone else further back to stop the tendency of observers to whiteboard stuff.

What We Learnt

  • We took the approach of trying to get a useable front end for the game working as quickly as possible this time which was a bit different to our normal approach where we tend to focus more heavily on the modeling side of the problem. We therefore decided to do the simplest thing that could possibly work and hardcoded the representation of the board as a string, which surprisingly (to me at least) proved adequate for the whole time we were coding and it was only towards the end that we felt we needed to put in a more robust data structure. Certainly a lesson for me of the value of not over engineering a solution.
  • This led to a discussion around what sort of situation this would represent on a real project. The closest we came up with was that of using an in memory repository early on until a real database is actually needed. We need to trade off the complexity we are adding in by doing this integration versus the gains we get from integrating early.
  • An cool approach which Nick showed us was to always implement code inline, make the test pass and then extract it into methods or classes as part of a refactoring step. This is similar to the idea of sprouting inner classes which Pat Kua wrote about a couple of months ago. This takes the idea of taking small steps even further which can only be a good thing.
  • It was interesting to see that without a domain expert we ending up changing the ubiquitous language in the code quite frequently but never really came up with one that made sense to everyone – when talking about the code we ended up with people doing translation between their understanding of various concepts.

For next time

  • The plan for next week is to continue working on Isola – it turned out to be quite an interesting game to try and model, simple enough that we could understand the rules quickly but complicated enough that it takes a while to implement.

Written by Mark Needham

January 30th, 2009 at 11:17 am

Posted in Coding Dojo

Tagged with

Coding Dojo #7: Retlang/Hamcrest .NET attempt

with 4 comments

We ran a sort of coding dojo/playing around session which started with us looking at the .NET concurrency library, Retlang, and ended with an attempt to write Hamcrest style assertions in C#.

The Format

We had the same setup as for our normal coding dojos with two people at the keyboard although we didn’t rotate as aggressively as normal.

What We Learnt

  • We started off having a look at a concurrency problem in Cruise Control .NET which Dave Cameron recently fixed. The intention was to try and take one of the cases of multi threading and replace it with a message based approach using the Retlang library.
  • As I understand it, you can have any number of subscribers subscribe to any channel using Retlang which is different to the Erlang approach whereby only one subscriber would be allowed. A bit of experimentation also suggests that subscribers need to be subscribed to a channel at the time a message is published in order to receive it.
  • We started off with an initial test case but got sidetracked in trying to work out how to make the assertion syntax a bit nicer. The original assertion read like the examples on the website in that we check the state of a ManualResetEvent so that we know whether or not a message was received by a subscriber.

    The assertion read like this:

    var gotMessage = new ManualResetEvent(false);
    ...
    Assert.IsTrue(gotMessage.WaitOne(2000, false));

    We initially worked this to read like so:

    AssertThat(gotMessage, HasTrippedWithin(2.Seconds());

    AssertThat and HasTrippedWithin were local methods and Seconds was an extension method. It’s pretty nice but the problem is that we can’t reuse this code easily in other test classes and keep the readability.

    C#¬†doesn’t have Java’s ability to import static methods so we would need to reference the class which the AssertThat method and HasTrippedWithin methods reside on directly either by having every test case extend it or by explicitly referencing it when we use the methods.

  • A bit more playing around with extension methods and trying to work out a good way to write Matchers led us to the following syntax:
    gotMessage.Should(Be.TrippedWithin(2.Seconds());

    We also considered putting a Verify extension method on object so that a test case could have a series of different matchers to be evaluated.

    this.Verify(
    	gotMessage.Is().TrippedWithin(2.Seconds())
    );

    For some reason we need to use the ‘this’ keyword in order to access an extension method defined on object – I don’t really understand why as I thought classes implicitly extended object, meaning the following should be possible:

    Verify(gotMessage.Is().TrippedWithin(2.Seconds()));
  • I think the way that our tests fail and the way that they report this failure is vital for getting the most out of TDD so I’d be interested to know of any ideas people have with regards to this. The thing that makes Hamcrest so good is not just the fluent syntax but the error messages that you receive when tests fail – it’s very clear where the problem lies when a test fails, there is rarely a need to get out the debugger in complete confusion as to why the test failed.

Next Time

  • I think we may make a return to coding some OO problems again next week – I’m not convinced that we are getting the most out of the Dojo sessions learning something which is new to the majority of people taking part.

Written by Mark Needham

January 22nd, 2009 at 11:02 pm

Posted in Coding Dojo

Tagged with

Coding Dojo #6: Web Driver

with one comment

We ran a sort of coding dojo/more playing around with web driver learning session this evening, coding some tests in Java driving Planet TW from the code.

The Format

We had the same setup as for our normal coding dojos but only one person was driving at a time and the others were watching from around them offering tips on different approaches. I think only a couple of us drove during the session.

What We Learnt

  • This was an interesting way to start learning about a tool that I hadn’t previously used. Two of my colleagues had used it before and they were able to provide knowledge of best practices, such as the Page Object pattern. I finally got the value in this pattern today after seeing the way that we can use the PageFactory to help cut out a lot of the boiler plate code usually needed to get the elements on each page into a class.
  • Web Driver seems to be simpler to setup than Selenium from my experiences tonight. We don’t have to worry about the reverse proxy like we do when using Selenium which makes things much easier. The tests, especially when using the Html Unit driver, ran fairly rapidly.
  • We worked with the Safari driver for most of the time but had to put in a lot of sleeps because the calls to pages didn’t seem to wait for that page to load before going onto the next step. A quick browse of the mailing list suggests that this is an area that will be worked on soon. The Html Unit Driver worked really well though.
  • I learnt about the idea of LiFT style APIs – we can write web driver tests in this style by using the correct context wrapper. Effectively an acceptance testing DSL:

    LiFT allows writing automated tests in a style that makes them very readable, even for non-programmers. Using the LiFT API, we can write tests that read almost like natural language, allowing business requirements to be expressed very clearly. This aids communication amongst developers and customers, helping give all stakeholders confidence that the right things are being tested.

  • Liz mentioned an earlier discussion she had been having around the creation of strings using literals (“string”) or by using the constructor (new String(“string)). The latter is not encouraged as those strings are not put into the string pool and therefore cannot be reused. There is more discussion of the two approaches to creating strings on the Code Ranch forums and on Ethan Nicholas’ blog.

Next Time

  • Next week we are going to explore the Retlang concurrency library. I think the plan is to take a concurrency problem and try to solve it with the library.
  • I’m still not sure how well the Dojo format works for learning or exploring things that are new to most of the group. This week’s one certainly wasn’t as intense as last week’s although I still learnt about things that I previously didn’t know about.

Written by Mark Needham

January 15th, 2009 at 12:37 am

Posted in Coding Dojo

Tagged with

Coding Dojo #5: Uno

without comments

We ran our 5th coding dojo on Thursday night, writing the card game Uno in Java. We didn’t all know the rules so this video explained it – surely a parody but you never know!

The Format

We used the Randori approach again with 6 people participating for the majority of the session. Everyone paired with everyone else at least once and sometimes a couple of times.

We had the pair driving at the front of the room and everyone else further back to stop the tendency of observers to whiteboard stuff.

What We Learnt

  • Modeling games is really good for practicing design skills. Most people had played the game so we had domain experts who could use their knowledge to help drive out the API of the various classes. We didn’t get to the scoring part of the game in the time available but it was quite cool to see our code with all the terms detailed in Wikipedia’s entry on the term.
  • We managed to drive the design much more effectively than we have done on previous sessions. The flexibility to move between classes depending on where it made most sense to test from next was finally there and we didn’t end up with the problem we’ve had on previous sessions where we ended up with coarsely grained tests and then tried to code the whole application in one go.
  • It was quite painful for me personally having to manually perform operations on collections in Java rather than having the selection of functional operators that are available in C# 3.0.
  • It wasn’t a new learning but I’ve noticed in my project work that I’ve become a lot more keen to keep the steps really small – there is a bit of pressure on you to do this in a dojo situation and I think it’s just continued over from there. Every time I try to be too clever and take a big step something inevitably doesn’t work and I end up doing the small steps anyway. It’s also a lot of fun coding in this type of environment and watching how others approach problems and how they pair with each other. If you get a chance to attend a dojo I think it’d definitely be worthwhile.

Other Dojo Thoughts

  • Some ideas for future coding dojos that we discussed were:
    • Concurrency – using the Retlang/Jetlang libraries
    • Do some stuff with Web Driver
    • Modeling games
    • Taking an open source project and refactoring it
  • I notice there are a couple of sessions of coding/coding dojos planned for Jason Gorman’s Software Craftsmanship conference. It will be interesting to see how those work out, especially if there are high numbers of participants. We’ve always had a fairly small number of people involved which I think has helped to keep everyone involved. I’m not convinced it would be effective with many more participants.

Written by Mark Needham

January 8th, 2009 at 11:41 pm

Posted in Coding Dojo,Java

Tagged with

Coding Dojo #4: Roman Numerals

with one comment

We ran our 4th coding dojo on Thursday night, attempting to solve the Roman Numerals problem from the TDD Problems website.

The Format

We ran with the Randori approach again with between 4-6 participants taking part. We coded for about an hour and a half.

The pair coding were sat at the front of the room this time in an attempt to keep the focus on the code, a problem identified last week.

What We Learnt

  • I had worked on this problem myself a couple of weeks ago but it was interesting to note how many more of the edge cases we managed to cover when working as a group. We had an discussion around where the validation of what constitutes a valid roman numeral should go. We ended up validating when the roman numeral object was converted into an integer, the other option being to do constructor validation. I’m not sure exactly when each approach is applicable – I would tend to do constructor validation when data is coming in from the user interface otherwise validating when the object is used.
  • Having the pair at sit at the front of the room worked much better in terms of stopping others drawing on the white board and we seemed to achieve greater focus on the problem than in the previous weeks although I’m not sure whether or not this is directly linked to the positioning of the coding pair.
  • The idea of keeping minimal state in the code was an interesting idea that was suggested early on and one which we kept to. I’ve not considered this as part of my approach to solving problems before but it makes sense in helping to drive simplicity of design.
  • The drive for the green bar was again in evidence – on one occasion I tried to refactor and make the test pass in one go, forgetting that this would keep us away from the green bar for longer. This was pointed out by my pair and I backtracked the refactoring and just made the bar green.

Written by Mark Needham

November 30th, 2008 at 5:58 pm

Posted in Coding Dojo

Tagged with