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 bothFooUtil
and its client classes. - I cannot create an instance of
FooUtil
at 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.
import
statement makes an external name a part of the context. – 9000 Jan 05 '15 at 21:04static
? Normally a utility class of this kind usesstatic
methods, so that you can callFooUtility.SomeMethod()
without having to instantiate the class or pass around an instance. – Robert Harvey Jan 05 '15 at 21:04FooUtil
methods should be put intoFooSomething
, maybe there are properties ofFooSomething
that should be changed/extended so that theFooUtil
methods are not needed anymore. Please give us a more concrete example of whatFooSomething
to help us providing a good answer to this questions. – valenterry Jan 05 '15 at 21:28@9000, if the answers to these questions don't apply to you, could you tell us what's different about your situation?
– Ixrec Jan 05 '15 at 21:34StringUtils
classes in several popular libraries. Now ifFoo
is a class that you control, then RobertHarvery's comment is more appropriate. – Jan 05 '15 at 22:00FooSomething
's private fields, I don't see why they ought to be instance methods. – Doval Jan 05 '15 at 22:17