VOOZH about

URL: https://www.javacodegeeks.com/2014/10/legacy-code-to-testable-code-6-add-overload.html

⇱ Legacy Code to Testable Code #6: Add Overload


πŸ‘ 55686844_zps86380239

This post is part of the β€œLegacy Code to Testable Code” series. In the series we’ll talk about making refactoring steps before writing tests for legacy code, and how they make our life easier.

In the last post, I’ve talked about Extract Class, 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 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 injecting 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();
}

We do the actual comparison on the new overload. The new overload should be accessible to the test, depending on language (so it doesn’t have to be completely public). In the original method, we delegate the call to the new implementation.

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?

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.

Reference: Legacy Code to Testable Code #6: Add Overload from our JCG partner Gil Zilberfeld at the Geek Out of Water blog.
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

Tags
Testing
πŸ‘ Photo of Gil Zilberfeld
Gil Zilberfeld
October 30th, 2014Last Updated: October 29th, 2014
0 84 1 minute read
Back to top button
Close
wpDiscuz