lundi 5 janvier 2015

Taming the 'utility functions' classes


In our Java codebase I keep seeing the following pattern:



/**
This is a stateless utility class
that groups useful foo-related operations, often with side effects.
*/
public class FooUtil {
public int foo(...) {...}
public void bar(...) {...}
}

/**
This class does applied foo-related things.
*/
class FooSomething {
int DoBusinessWithFoo(FooUtil fooUtil, ...) {
if (fooUtil.foo(...)) fooUtil.bar(...);
}
}


What bothers me is that I have to pass an instance of FooUtil everywhere, because testing.



  • I cannot make FooUtil's methods static, because I won't be able to mock them for testing of both FooUtil and its client classes.

  • I cannot create an instance of FooUtil at the place of consumption with a new, again because I won't be able to mock it for testing.


I suppose that my best bet is to use injection (and I do), but it adds its own set of hassles. Also, passing several util instances inflates the size of method parameter lists.


Is there a way to handle this better that I'm not seeing?





Aucun commentaire:

Enregistrer un commentaire