Twitter GitHub Facebook Instagram dirv.me

Daniel Irvine on building software

Wrong way round (part 2)

8 June 2014

In part 1 I discussed how using TDD I’d ended up with a wrong way round design in which the controller depended on my view. Since the view must at some point notify the controller of user input, a cyclic dependency results.

Wrong way round Wrong way round: Controller depends on View, but View must still depend on Controller

In the diagram above, the application immediately passes control to the Controller which then drives both the View and changes to the Model.

Simplifying the design

The UML class diagram above makes it easy to see what the issue is and how to fix it: let control flow out from the View and into the Controller instead. That way, the callback can be removed entirely.

The traditional MVC pattern The traditional MVC pattern

This is the Model-View-Controller pattern that we all know and love.

How did TDD end up with the wrong design?

Interestingly, TDD (and emergent design) doesn’t help with discovering well-known design principles. By building without regard to design, the wrong design resulted. That’s not to say I couldn’t have found the right design, but in this particular case I didn’t.

However...

How did TDD help with fixing the issue?

TDD has this wonderful thing: the red-green-refactor cycle. The refactor stage is that when you’ve got an all-passing test suite, you can take a step back and refactor.

And this is exactly what happened. At some point, the code started smelling bad--it was just too complicated--and I was able to refactor quickly and without fear. The tests helped me ensure that I was doing the right thing at all stages.

After a few hours work, this particularly nasty smell had been eliminated from my code.

The moral of the story is...

... use TDD! It will save your ass when you walk down the wrong path. When you realise you’ve made a mistake, you’ll take the right choice and refactor. Without tests, fear of your own codebase will mean you’ll never have the guts to make the required fixes.

About the author

Daniel Irvine is a software craftsman at 8th Light, based in London. These days he prefers to code in Clojure and Ruby, despite having been a C++ and C# developer for the majority of his career.

For a longer bio please see danielirvine.com. To contact Daniel, send a tweet to @d_ir or use the comments section below.

Twitter GitHub Facebook Instagram dirv.me