This post is part of the “Legacy Code to Testable Code” series. In the series we’ll talk about making refactoring steps before writing unit tests for legacy code, and how they make our life easier. Other posts include:
The Legacy Code To Testable Code Series
General patterns | Accessibility | Dealing with dependencies | Advanced patterns |
---|---|---|---|
Introduction | Add setters | Extract method | Static constructors (initializers) |
Renaming | More accessors | Extract class | More static constructors |
Add overload | Introduce parameter | Instance constructors | |
Testable object | Conditionals to guard blocks |
In the last post, I’ve talked about Extract Class refactoring pattern, and that sometimes in order to do that, we might want to change the signature of a method.
Turns out adding an overload helps in other cases as well.
We used a “setter” to expose to the unit test and inject internal state before. Another option is to add a controllable overload to bypass the internal state.
Let’s look at this code:
public Bool isSameStreet(String newStreet) { return newStreet == this.currentAddress.getStreet(); }
In this example, we compare an external value to an internal state. As we saw before, the option we could use is add a “setter” accessor, to allow the unit test to inject the internal value from outside. Instead, we can also add an overload:
public Bool isSameStreet(String newStreet) { return isSameStreet(newStreet, this.currentAddress.getStreet()); } public Bool isSameStreet(String newStreet, String currentStreet) { return newStreet == currentStreet(); }
The new overload is more controllable. We can stop there, but if our logic code does not rely on state anymore, why not use Extract Class refactoring pattern?
public Bool isSameStreet(String newStreet) { return StreetValidator.areEqual(newStreet, this.currentAddress.getStreet()); }
The StreetValidator class can now be controlled and tested easily.
Time to wrap up the series. So next time, in the last chapter – using dependency injection framework.
2 Comments
Daniel Rosales · October 29, 2014 at 2:04 pm
Isn’t StreetValidator a static class. I thought static classes were ANATHEMA in testable design.
Gil Zilberfeld · October 29, 2014 at 6:57 pm
Danny,
I think that static classes, with static methods and no state, have gotten a bad rap. They are easy to test as is.
Otherwise, it’s just an example, you can create an instance if you like 🙂
Gil