How your 'Mother' can help you 'Build' cleaner unit tests - Part III

We ended Part II with an inner Builder for Address, which forced us to revert to specifying seemingly arbitrary values in each test that needed to build an Address.

What I’ve usually seen at this point is pulling the Address objects into constants in each test class. As the test suite grows, the number of private static final Address WHATEVER_ADDRESS = ...; grows and grows. Doing that makes it hard to keep control over your test data, especially in a large codebase. A minor change to Address, such as a new invariant or an added field, could cause cascading changes to keep all those objects valid.

To avoid that, the next step is actually a very simple one, and boils down to centralizing the definition and creation of an Address with an Object Mother.

How your 'Mother' can help you 'Build' cleaner unit tests - Part II

In Part I, we created a separate Builder class in an attempt to move away from a constructor with too many parameters. In the process, the separate Builder ended up taking on the additional responsibility of supplying default values, blurring the line between a Builder and Factory.

Though a step in the right direction, it didn’t actually fix any of the Address constructor’s original problems, unfortunately. Oops. Other classes can still call it directly, meaning all of the risks of having a method with multiple parameters of the same type are still there, and we have another class in our system to maintain.

What we need is a strictly controlled way of creating Address objects that can be accessed by test code and prod code that is decoupled from the current constructor and it’s baggage.

How your 'Mother' can help you 'Build' cleaner unit tests - Part I

Over the past few months on my project, a pattern emerged for using Builders and Object Mothers to build-up objects for unit testing. We were able to keep our tests minimal and clean, decouple test code from production code, and solve some design issues such as constructors with too many parameters. In this multi-part series, I will take you through the evolution of the pattern over a series of refactorings.

YAGNI a'int a Design Principle

You Ain’t Gonna Need It is an XP practice that encourages developers to focus on the requirements at hand right now. It warns against the tendency to over-engineer by developing features based on what you think you will need later. Easy in theory. Hard in practice.

YAGNI Blinders

I’ve noticed that developers, especially those just starting out, tend to apply YAGNI narrow-sightedly. I often see it being strictly adhered to at face-value only, by developers always choosing to do what seems to be the most obvious and straightforward thing at the time, without putting any thought into the design implications of their choices. When suggesting other options that seem to be less simple on the surface, they YAGNI argument gets used. “Oh, that’s YAGNI.”