If a change is too difficult to make in existing method, then create a new method which performs additional work and call it from existing method. Unit test the new method, even if it requires to make it static and pass all dependencies in it.
Similar to sprout method, but if creating instance of class is too difficult to do in limited time, or maybe it will require separating a lot of dependencies. Create another class to hold changes and use from original difficult to test class. Unit test sprouted class properly. This may seem like making the code worse, and sometimes is, but many times it helps in figuring out commanality between sprouted class and some new class in future and improves chances of carving out interfaces or resusable classes.
If new functionality is cleanly separable, then rather than adding more stuff to existing method, we can make original method as private and rename it to give apt name, make wrap method of same name and call two methods from it. One of them is new method and other is the one we made private.
Before
public void method() {
...
...
}
After
public void method() {
renamedMethod();
newMethod();
}
private void renamedMethod() {
// was previously called method, but renamed and wrapped inside new wrap method
}
private void newMethod() {
// New functionality implemented in this method
}
Just like wrap method, Wrap class performs the additional functionality and delegates to original class to perform the old function. A decorator pattern implementation. A wrapper on top of existing class.
- Extract Interface refactoring
- Make existing class implement it and the new wrapping class as well.