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 bothFooUtiland its client classes. - I cannot create an instance of
FooUtilat the place of consumption with anew, 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?
Update: since the utility classes are stateless, I could probably add a static singleton INSTANCE member, or a static getInstance() method, while retaining the ability to update the underlying static field of the class for testing. Does not seem super-clean, too.