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: 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
Simplifying the designThe UML class diagram above makes it easy to see what the issue is and how to fix it: let control flow out from the
Viewand into the
Controllerinstead. That way, the callback can be removed entirely.
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.
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.