Friday, May 20, 2011

Refactoring Code with Static Dependencies for Testability

Methods that have dependencies on static methods can be difficult to test. In this example we have a dependency that we obtain via a static method that we do not have control over and we want to test the surrounding code.

public void myMethod(Long id) {
// ...
Dependency dependency = DependencyUtil.getDependency();
// ...
}

We can refactor this to:

public void myMethod(Long id) {
Dependency dependency = DependencyUtil.getDependency();
myMethod(dependency);
}

void myMethod(Long id, Dependency dependency) {
// ...
doSomething(dependency);
// ...
}

We overload the method signature and preserve the public API. We make the new method have default access to make it testable. We can now mock Dependency however we like.

Thursday, May 19, 2011

Bad Comments

Over the years I've found some 'interesting' comments in legacy code. One recent one is a seventeen line screed / excuse for how bad a particular piece of code is that ends with 'This makes me feel really dirty, fortunately, the Client/Server conversions have lowered the users expectations to the point where this seems inconsequential'.

A version history on this file shows that the commenter is the same person who wrote another comment that 'explains' why something is wrong because '... we are RETARDED' (referring to the organization). Supposedly this guy now works for Google. Amazing.