TDD as if you Meant It: Refactoring to Builder (Episode 5)
Cost of Change during evolution
There are some language structures that make Evolutionary Design difficult. One of them is the constructor. When I evolve the code, I often understand that one more parameter is needed for the constructor. Because of this I need to minimize the cost of change of the constructor. The best way I know to do that is by creating a builder. In this way I will call the constructor only once, in the builder. So my cost of change is really small.
If I need to introduce a new design concept, I make sure before that I minimized the duplication connected to that new design concept. Calling new Board(…) many times is a clear sign of duplication. This duplication would make the code evolution considerably slower.
Testing becomes easier when state does not change during the life cycle of the object. Or, there are no setters on any object. That is why I use constructors and private fields.
A builder is called fluent when it looks like playerBuilder.withName(“Adi”).withAge(7).withColor(“Red”).build(). If let’s say I need to introduce a new characteristic to my player, I can always add a new method to the PlayerBuilder. And I would have something like playerBuilder.withName(“Adi”).withAge(7).withColor(“Red”).withExperienceLevel(“Beginner”).build().
Focused Tests with Idempotence
Having this type of builder also lets me have focused tests. I don’t want my test that needs only Age to contain Name. So I want to be able to have playerBuilder.withAge(34).build(). In this case all the values for all the other fields of Player will have a default value that is not generating any side-effects in the system. We could call this characteristic an idempotence of the builder.
Check the video below with the codecast:
Check the next episode on TDD as if you Meant it here: http://blog.adrianbolboaca.ro/evolutionary-design
On the same page you can find more ideas on Evolutionary Design.
Many thanks to Keith Braithwaite for creating the concept of TDD as if you Meant It
Teddy bear thanks to Erik Talboom for all the pairing, discussions that lead to so many twists we discovered together with TDD as if you Meant It.
Special regards to JB Rainsberger for the fun pairing we did using TDD as if you Meant It