Mark Needham

Thoughts on Software Development

Coding Dojo #22: Scala, lamdaj, Project Euler

In our latest coding dojo we played around with Scala and lambdaj while attempting to solve some of the problems on the Project Euler website.

The Format

We started off on two different machines with two of us having a look at solving the first Project Euler problem in Scala and the other two trying to solve it in Java while using the lambdaj library.

What did we learn?

• Fabio and I worked on the Scala solution to the problem and we were pretty much playing around with different ways to aggregate all the values in the list:
```1.to(999).filter(x => x%3 == 0 || x%5 == 0).foldLeft(0)((acc,x) => acc + x) 1.to(999).filter(x => x%3 == 0 || x%5 == 0)./:(0)((x,y) => x+y) 1.to(999).filter(x => x%3 == 0 || x%5 == 0).foldRight(0)(_+_) 1.to(999).filter(x => x%3 == 0 || x%5 == 0).reduceLeft(_+_) 1.to(999).filter(x => x%3 == 0 || x%5 == 0)./:(0)(_+_)```

We decided to work through how ‘foldLeft’ and ‘foldRight’ work for summing a simpler collection of data, the numbers 1-5, which goes something like this:

fold_left

`(((((0 + 1) + 2) + 3) + 4) + 5) = 15`

fold_right

`(1 + (2 + (3 + (4 + (5 + 0))))) = 15`

When adding the numbers together it doesn’t make any different whether we fold the collection from the left or from the right.

If we do subtraction we do get different answers though:

fold_left

`(((((0 - 1) - 2) - 3) - 4) - 5) = -15`

fold_right

```(1 - (2 - (3 - (4 - (5 - 0))))) = 3   -> 5 - 0 = 5 -> 4 - 5 = -1 -> 3 - -1 = 4 -> 2 - 4 = -2 -> 1 - -2 = 3```

The other way of doing fold_left, ‘/:’, is quite interesting although perhaps unintuitive when you first come across it. Liz showed me an interesting post by Ricky Clarkson where he talks about this method and the reason why it’s in the language.

Liz and Dave Yeung worked on doing a solution to lambdaj to the problem but it ended up being quite verbose so we decided to play around with Scala for the rest of the session.

• We spent a bit of time playing around with traits via a nice introductory article which effectively acts as a a cut down version of the Programming in Scala book.

I particularly like the way that you can add a trait to an instance of an object and you get access to all the methods defined on that trait which seems quite similar to Ruby mixins.

Liz and I were discussing an article written by Michael Norton comparing technical debt and making a mess so that’s where the trait name came from!

```trait Mess { def makeMess = print("tech debt is so funny") }   class Liz {   }```

If you try to make use of the trait like this:

`val liz : Liz = new Liz with Mess`

You don’t have access to the ‘makeMess’ method since you explicitly defined the type to be ‘Liz’ which doesn’t have the method:

```liz.makeMess > error: value makeMess is not a member of Liz liz.makeMess```

If we let the compiler do its thing without trying to explicitly type the value it works much better:

```val liz = new Liz with Mess > Liz with Mess```
```liz.makeMess > tech debt is so funny```

I really like having the ability to do this although I think I need to code a bit more Scala before I’ll appreciate where we really gain by having this feature.

The conciseness of the language and the lack of ‘{}’ while keeping the same expressiveness in the code is something which reminds me a lot of F# and from what I’ve seen so far I imagine it would be much more fun to code in Scala than in Java.

It also seems more clear to me that when a static language has really good type inference then one of the main reasons that people prefer dynamic languages – you get to write less code for the same amount of features – is actually much less valid.

• This was a very experimental dojo in nature although Liz has been playing around with Scala a bit so she was able to guide us a bit when we got stuck.

I’m finding that sessions where everyone is fairly new to the language or technology aren’t necessarily as fruitless as I had previously imagined that they would be – I find that learning something together makes it more interesting as you can then draw on other people’s ideas and understanding of the language as well as your own.

I think in the cases where everyone is a novice people need to be prepared to get involved and write some code despite that. If that’s the case then I think it’s certainly possible to gain a lot from these sessions.

Written by Mark Needham

September 4th, 2009 at 12:26 am

Posted in Coding Dojo,Scala

Tagged with , ,

Coding Dojo #21: TDD as if you meant it revisited

In this weeks dojo we decided to revisit the “TDD as if you meant it’ exercise originally invented by Keith Braithwaite for the Software Craftsmanship Conference but recently tried out at the Alt.NET UK Conference in London.

The idea was to write code for ‘tic tac toe’ or ‘naughts and crosses’ and we were following these requirements:

• a game is over when all fields are taken
• a game is over when all fields in a column are taken by a player
• a game is over when all fields in a row are taken by a player
• a game is over when all fields in a diagonal are taken by a player
• a player can take a field if not already taken
• players take turns taking fields until the game is over

The code from Alt.NET UK is available on Google Code and what I found quite interesting is that the solutions are really quite different to each other.

Our code is up on bitbucket and again it is quite different to the other approaches.

The Format

For most of this week’s dojo Dave and I just worked together on the problem although a colleague did come and join us for the last half an hour or so. We were just pairing on a Mac.

What We Learnt

• We coded in Java in eclipse which I haven’t used for about a year and I was really surprised at how rapid the feedback cycle was. We seemed to be able to write a test and have it failing within seconds which is brilliant and just the way it should be whereas I’ve got used to a much slower feedback loop when using Visual Studio.
• We noticed as we did the previous times when we did this exercise that you notice objects in the code that you wouldn’t normally have noticed if we hadn’t been writing all the implementation details in the test first.

The ‘Square’ object was one which neither I nor Dave had expected to exist. We had imagined that code would end up on the ‘Game’ object and interestingly just before our colleague joined us we had drifted from the rules of the exercise and actually written the outline of a method on the game object to satisfy the 5th acceptance criteria ‘a player can take a field if not already taken’.

Luckily we undid that and it became obvious that the new code should be on an object of its own so that’s what we did.

• The code we have at the moment has everything implemented just using booleans which felt really weird when we were writing the code but seemed to be the simplest thing to do to meet the acceptance criteria.

We discussed this at the time and it seemed that any alternative approach where we didn’t do this would end up with us writing a really big test (perhaps with players making moves), therefore meaning the feedback cycle would be really slow.

For next time

• I think it would probably be quite interesting to try out this type of exercise and commit to either Git or Mercurial after each of the small steps so that we could see the story of the code more clearly afterwards.
• During our discussion on Continuous Integration a few weeks ago it was suggested that we could some sessions on parallelising tests and writing impersonators during one of our coding dojos so we might look at doing that next time around.

Written by Mark Needham

August 8th, 2009 at 11:50 pm

Posted in Coding Dojo

Tagged with

Coding Dojo #20: Groovy Sales Tax Problem

Continuing with the Groovy theme, this week we worked on the ThoughtWorks code review tax problem which involved modeling different items that a customer could buy and the associated tax rules that different types of goods had.

The Format

We had 3 people this week so most of the time we had all 3 of us involved in driving the code, which was projected onto the television screen again, while rotating every 10 minutes or so.

What We Learnt

• Although we weren’t intentionally following the ideas laid out in object calisthenics we actually ended up with code which fairly closely followed those ideas. We had very small classes, didn’t have any getter or setter methods and also wrapped the collection (Basket) which we had in our code.
• We ended up writing tests in classes which were quite context sensitive – normally when I write tests we would have one test class for each object under test but this time we created different classes depending on the way that we were making use of that object in the test. For example we ended up with ‘BasketWithOneItem’ and ‘BasketWithMultipleItems’ test classes by the end.

This seems pretty much like the Context-Spec approach to testing that I’ve read about previously in Scott Bellware’s framework. I’m noticing on the project I’m currently working on that our tests are drifting in that way almost naturally due to the different ways that objects are typically used.

• Dave took the lead in driving out a fluent interface which worked out quite well – we were able to chain together different items by including an ‘and’ method on objects which created a ‘Basket’ containing both items and then returned the Basket, therefore allowing us to add other items too. I was initially against this approach as I felt we should just create a basket with all the items that it held rather than adding them one at a time.

Objects needed to define an ‘and’ method and a ‘totalCost’ method in order for them to be chained. Due to the dynamic nature of Groovy we could just pass in objects and assume they would respond to the appropriate methods.

We therefore ended up with code that looked a bit like this:

`new Book(12.49).and(new Chocolate(1.89)).totalCost()`

If we were working in a static language then we would have needed to create a small interface with the two methods on and then have our objects implement that. This seemed to fit in quite nicely with the Interface Segregation Principle where the idea is to define thin cohesive interfaces which don’t inadvertently couple their different clients together.

In a discussion with a few colleagues recently it seems that one way of looking at methods on objects in dynamic languages is that each method would be the equivalent in a static language of a one method interface which our object implements.

For next time

• I’ve found the dojos we’ve done using Groovy to be quite fun – everyone who participates has worked with Java so it doesn’t seem to be too much of a jump to use Groovy. Writing less code to achieve the same goal is also nice. We may well continue with Groovy next time!

Written by Mark Needham

July 31st, 2009 at 9:07 am

Posted in Coding Dojo

Tagged with

Coding Dojo #19: Groovy Traveling salesman variation

with one comment

Our latest coding dojo involved working on a variation of the traveling salesman problem in Groovy again.

The Format

We had 8 people participating this week so we returned to the Randori format, rotating the pair at the keyboard every 7 minutes.

Give the number of people it might have actually been better to have a couple of machines and use the UberDojo format.

What We Learnt

• The importance of just getting started stood out a lot for me in this dojo – there have been quite a few times when we’ve met intending to do some coding and spent so long talking about coding that we didn’t end up writing anything. Luckily Dave took the lead in this dojo and got the ball rolling. The code we wrote originally wasn’t perfect but it helped create the momentum to keep the session going so it was valuable in that way.
• Another interesting feature of dojos for me is that it really doesn’t matter if you make mistakes – if you write really terrible code in a dojo it’s probably a good thing since you’ll probably not go and repeat the same mistake on a real project. I learnt a lot about the perils of not refactoring early enough and having too much state in our code from our Isola Dojo a few months ago.
• We refactored much earlier than we normally do in this dojo and I think it worked really well for allowing us to progress later on. Often we fall into the trap of just chasing the green bar a bit too much and we forget to clean up the code after each cycle but we had that a bit better in this one.

We also backed up a bit after around 3 cycles after realising that the code was becoming a bit horrific and spent 1 cycle working it into shape for the next one.

• We fell into the trap of going several cycles with broken tests while trying to do some redesign on the code – the steps were clearly not small enough!

Later on we corrected this when refactoring the code into a more functional style by taking very small steps and running the tests after each small change – this was a far more effective approach.

• Although we were working in a dynamic language it didn’t feel that the conversations were that different when discussing the code – we were still talking about types when working out what to do. I’m not sure whether this means we haven’t quite got the idea of dynamic languages or whether there isn’t such a big difference between the way you talk about your code in them.

For next time

• We might continue with another problem in Groovy – it’s been quite fun working in a language that runs on the JVM without the verbosity you sometimes get when writing Java code.

Written by Mark Needham

July 4th, 2009 at 9:36 am

Posted in Coding Dojo

Tagged with

Coding Dojo #18: Groovy Bowling Game

This week’s dojo involved coding a familiar problem – the bowling game – in a different language, Groovy.

The code we wrote is available on bitbucket.

The Format

Cam, Dean and I took turns pairing with each other with the code projected onto a TV. As there were only a few of us the discussion on where we were taking the code tended to included everyone rather than just the two at the keyboard.

What We Learnt

• I’ve sometimes wondered about the wisdom of running dojos in newer languages but this one worked quite well because Cam has been learning Groovy and he was able to point us in the right direction when we started writing Java-esque Groovy code. The particular syntax that I didn’t know about was that you can define and put items into a list in a much simpler way than in Java:

I was starting to write code like this:

```def frames = new List<Frame>() frames.Add(frame)```

Which Cam simplified down to:

```def frames = [] frames << frame```

I didn’t feel that I missed the static typing you get in Java although IntelliJ wasn’t quite as useful when it came to suggesting which methods you could call on a particular object.

• I’m even more convinced that using various languages functional equivalent of the ‘for each’ loop, in this case ‘eachWith’ and ‘eachWithIndex’ is not the way to go and we could see our code becoming very complicated when trying to work out how to score strikes thanks to our use of it!
• I think we actually got further this time in terms of the implementation although we did slow down when it came to scoring strikes to try and work out exactly how we wanted to do it.

Prior to this we had been following the idea of just getting the tests to pass and driving the design of the code that way but we at this stage it seemed foolish to keep doing that as the code would increased dramatically in complexity by doing so.

The two approaches we were thinking of involved using the state pattern to determine what the current frame outcome was and then work out the cumulative score based on that by looking forward to future frames or an approach that would make use of functional collection parameters (not sure exactly which ones!) to calculate the score in a more function rather than OO way.

For next time

• We’ll probably keep going with some more Groovy as it’s actually more interesting than I thought it would be. I’m also keen to do a coding dojo where we never make use of the if statement.

Written by Mark Needham

June 26th, 2009 at 6:15 pm

Posted in Coding Dojo

Tagged with , , ,

Coding Dojo #17: Refactoring Cruise Control .NET

After a couple of weeks of more experimental coding dojos this week we decided to get back to some pure coding with the session being focused around doing some refactoring of the continuous integration server Cruise Control .NET.

The overall intention of the refactoring we worked on is to try and introduce the concept of a ‘ChangeSet’ into the code base to represent the revisions that come in from source control systems that CC.NET integrates with.

The Format

We had 6 people for the majority of the dojo so we resorted to the Randori style with each pair at the keyboard for 10 minutes before rotating.

Dave and I have been reading/trying out the Pomodoro technique in our spare time recently so we decided to use Pomodoro’s idea of reflecting on our work by stopping every 3 pairing sessions and discussing what we’d done and whether we wanted to vary the approach or keep going the same way.

What We Learnt

• The most obvious place in the code where the ‘ChangeSet’ concept made sense was in the RssFeedPublisher which was taking a collection of modifications and then converting them back into the same revision format that the data was in when it came from the source control system.

The ISourceControl.GetModifications() method was the one that we needed to change if we wanted to introduce the changes which we started doing by changing the return type from being a modification array to an IEnumerable<Modificatiion>.

The goal was to drive towards a place where we could create a ChangeSet and have that extend an IEnumerable<Modificatiion> so that we could easily get that into the code before working out how to remove the concept of a Modification.

We wanted it to extend a more generic type than array since we didn’t want to tie the ChangeSet class to something as concrete as an array.

Even with seemingly minor change we still ended up taking around 40 minutes to get the code compiling again – we were very much leaning on the compiler to guide us on what to fix, a technique Michael Feathers talks about in Working Effectively with Legacy Code.

It would be interesting to see how a refactoring like this would work in a dynamic language like Ruby where you would lose the compiler support but still have the ability to run your tests to help guide you to the places that need fixing.

• There were 963 usages of Modification in the code so we didn’t have the option of just deleting it straight away! I’ve not yet worked on a code base this size so it was interesting for me to see how we were forced into a smaller steps approach by the code.
• After 3 pairing sessions we discussed the approach that we were taking which had led us to a situation where the code still wasn’t compiling.

The alternative approach was to go in even smaller steps and make another method on ISourceControl for ‘GetModfications’ with a different signature and then delegate from the new method to the existing one.

The problem with this was that there were 20 classes which implemented ISourceControl so we would have had to implement the delegation in all of these or create an abstract base class which did the delegation and then get all the existing implementors to extend the case class instead.

We decided to keep going with our original approach for 3 more pairs as it seems like we were quite close and it wasn’t clear whether changing the approach would give us significant benefits.

• The main compilation errors in the code were actually tests which no longer compiled due to the fact that IEnumerable doesn’t have a ‘Length’ property on it whereas array does.

CC.NET is a .NET 2.0 code base so we weren’t able to introduce LINQ into the code which would have made it really easy to just make use of the ‘Count’ extension method instead of casting the results from ‘GetModification’ back to an array in the tests for the time being.

We accidentally came across the ICollection interface towards the end which perhaps would have been a better choice than IEnumerable as it would have allowed us to avoid the nasty casting and just make use of the Count property on ICollection instead.

For next time

• The pace this week was a bit slower but it definitely seemed to keep people more involved so we’re going to try and keep it more focused on the coding rather than experimentation. Possibly a refactoring exercise on some Java code as we have more people using that on their projects.

Written by Mark Needham

June 12th, 2009 at 5:07 pm

Posted in Coding Dojo

Tagged with

Coding Dojo #16: Reading SUnit code

Continuing on from last week’s look at Smalltalk, in our latest coding dojo we spent some time investigating the SUnit testing framework, how we would use it to write some tests and looking at how it actually works.

The Format

We had 3 people for the dojo this week and the majority was spent looking at the code on a big screen and trying to understand between us what was going on. We only had the dojo for about 90 minutes this week. Normally we go for around 3 hours.

What We Learnt

• An interesting thing which I noticed during this session was the idea of protocols which are used to organise a set of methods that a class’ instance respond to. I think these are intended more for humans than for the computer which I think is a really cool idea – I am strongly of the belief that programming languages provide a mechanism for communicating our intent with ourselves and with the other people on our team.
• As a result of looking at the description of the ‘initialize-release’ protocol for Object I became intrigued about the way that objects are removed by the garbage collection. We weren’t able to find out exactly how Visual Works does garbage collection but I learnt a little bit about the way that garbage collection works in general using three different approaches – mark and sweep, copying collector and reference count.
• Another thing which I found interesting was the way that Smalltalk handles exceptions – we came across this when looking at how XUnit handles passing and failing test cases. Since Smalltalk only has messages and objects there is no explicit of an exception so as I understand it objects have the ability to respond to an error signal being sent to them.

(TestResult runCase:aTestCase)

``` | testCasePassed | testCasePassed := [[aTestCase runCase. true] sunitOn: self class failure do: [:signal | self failures add: aTestCase. signal sunitExitWith: false]] sunitOn: self class error do: [:signal | self errors add: aTestCase. signal sunitExitWith: false]. testCasePassed ifTrue: [self passed add: aTestCase]```

The above is the code block we spent a bit of time looking at which I think in C# world would look a bit like this:

```try { aTestCase.runCase() } catch(FailureException) { this.Failures.Add(aTestCase); } catch(ErrorException) { this.Errors.Add(aTestCase); } this.Passed.Add(aTestCase);```

It seems easier to understand to me having exceptions as a language construct but I haven’t done much Smalltalk so maybe that’s just a preference for what’s familiar.

• It took us a bit of Googling to work out how to start the SUnit TestRunner in VisualWorks but the way to do it eventually turned out to be quite simple. Typing the following code into the workspace window does it:
`TestRunner open`

For next time

• If we continue in Smalltalk world for another week then we’ll probably play around with SUnit a bit more and perhaps get onto seaside. If not then we’ll be back to the Java modeling I imagine.

Written by Mark Needham

May 29th, 2009 at 9:23 am

Posted in Coding Dojo

Tagged with , ,

Coding Dojo #15: Smalltalk

We decided to play around with Smalltalk a bit in our latest coding dojo.

A lot of the ideas that I value the most in terms of writing software effectively seem to have originally come from the Smalltalk community and a colleague of mine has been reading Kent Beck’s TDD by Example book and was really keen to try out the language to see where Kent’s original ideas came from.

The Format

We only had 2/3 people for the dojo this week so we all spent a bit of time at the keyboard getting familiar with the way things worked. We projected to a wide screen television so the other guys could track what was doing on.

What We Learnt

• One interesting thing for me was that the Smalltalk syntax reminded me a little bit of Ruby. We spent a little bit of time with irb open as well as the Smalltalk environment and compared what the code would look like for a few simple expressions in the different languages. Ruby seemed a little bit easier to understand for some of the expressions but I guess it has probably been influenced syntax wise by Smalltalk.

To give a simple example that we tried out, this is how you’d print the values 1-10 to the screen:

In Smalltalk:

`1 to: 10 do: [:i | Transcript cr; show: (i printString)].`

In Ruby:

`(1..10).each { |i| puts i }`
• We were following a simple introduction to Squeak, an open source implementation of Smalltalk. We were actually using Visual Works/Cincom Smalltalk which seems to differ a little bit. For example there was no ‘asString’ method on integer when we tried to execute the following bit of code:
`Transcript show: (1 asString)`

`Unhandled exception: Message not understood: #asString`

Instead we needed to use ‘printString like this:

`Transcript show: (1 printString)`

I’m sure there are probably some other differences but we only tried a few examples at the dojo.

• The idea of the development environment being the same as the environment where the code runs was quite strange for me but we saw some benefits of it even in the small amount of code we wrote. On making one of our many syntax errors the IDE popped up with a message asking whether we wanted to debug that piece of code on the fly. Pretty cool if we’d understood the stack trace that followed a bit better!
• I haven’t looked into the type systems of other languages that closely but I was quite surprised that looking the type of the value ‘1’ was ‘SmallInteger’ – it was much more strongly typed than I had expected. The ability to delve into the code of objects within the environment is really cool and we came across quite a bit of code which intrigued us to want to learn more.
• The intention for this session wasn’t actually to learn Smalltalk the language, as I don’t think dojos are great for doing that, but rather to try and understand the concepts behind all expressions being about sending a message to an object which for me is what object orientation is all about.

Chatting with Dave about object oriented design he spoke highly of Smalltalk as being the language where he learnt a lot about this and a couple of colleagues have said the same thing as well.

For next time

• We just about got started with writing a little bit of Smalltalk code this week but next week I’d quite like to see if we can write a little application using Smalltalk. We’re particularly keen on working out how unit testing fits into the picture and it’d be quite cool to play around with seaside a bit as well.
• Smalltalk is quite renowned for its refactoring browser so we’re quite keen to play around with that a bit and see what its like compared to some of the features available in IDEs nowadays

Written by Mark Needham

May 21st, 2009 at 7:05 pm

Posted in Coding Dojo

Tagged with ,

Coding Dojo #14: Rock, Scissors, Paper – TDD as if you meant it

We decided to have a second week of following Keith Braithwaite’s ‘TDD as if you meant it‘ exercise which he led at the Software Craftsmanship Conference.

Our attempt a fortnight ago was around implementing a Flash Message interceptor, to hook into the Spring framework but this week was focused more around modeling, the goal being to model a game of Rock, Paper, Scissors.

The code is available on our bitbucket repository.

The Format

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

What We Learnt

• It was interesting trying to work out what should be the first test that we should write – the instinct for me was to think about about the different objects that we would need to model a game but Halvard suggested it would be simpler to start off with a test where rock should beat scissors. What I also found interesting was that we edited and then ran this test at least 3 times, adding more test setup and then implementation details each time. It felt much more iterative than the normal TDD approach where much more time would be spent up front writing the test before writing the code to make it past.
• One thing Nick was helping us to drive was ‘safe refactoring’ when refactoring various parts of the code. The idea here was to try and drive the refactorings from the IDE without having to do too much of it manually which can lead to mistakes. We also tried to keep the code compiling the whole time while keeping the time that the tests were failing to a minimum.

For example we started off with rock as a string and our goal was to get it to be Throw.ROCK as it is on the repository.

• We started off by making “rock” a constant.
• We then introduced the enums by converting from the strings to enums using Throw.valueOf(“rock”)
• Then the twoPlayerRsp method that took an enum was called from the old one that took a string
• Finally we updated the tests to call the enum method directly and removed the old twoPlayerRsp that took the string.

This type of refactoring proved to be a bit harder when trying to refactor the return result of the twoPlayerRsp method since you cannot overload on return types in Java. There was therefore a little bit of time when we couldn’t compile the code while doing this refactoring.

It felt quite slow refactoring this way but I think this style of refactoring was new to most people so we would probably get quicker at it from doing it a few times. The fact that we are more certain that we haven’t broken anything while refactoring this way makes it a useful approach from my point of view.

For next time

• An idea that Phil and I were discussing was running an open dojo where anyone who wants to come is welcome. At the moment we’ve had it as an internal dojo but if anyone is interested in coming to code with us then let me know by replying to this post or messaging me on twitter. We normally run the dojo on Wednesday nights for a couple of hours in the ThoughtWorks Sydney office.
• We’ve used the Randori approach for the majority of our dojos so far and while I think it works really well I’m interested in seeing what other setups we can try. I’ve been reading about the Uber/Ultra Dojo on Hugo Corbucci’s blog so either of those might be something that we try out in one session.
• Another quite interesting idea that was suggested to me by Dan North is to make a commit to Mercurial after each pair’s go at the computer so that you have a history of how the code has progressed through the session – I think this would probably be quite interesting to read and maybe more useful than just having the code as it was when the session finished.

Written by Mark Needham

May 15th, 2009 at 7:39 am

Posted in Coding Dojo

Tagged with

Coding Dojo #13: TDD as if you meant it

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