Should a utility class be static? [closed]
Solution 1:
My utility classes look like this:
// final, because it's not supposed to be subclassed
public final class FooUtil {
// private constructor to avoid unnecessary instantiation of the class
private FooUtil() {
}
public static int doSomethingUseful() {
}
// ...
}
Note that, although this makes the utility methods easily testable, and easily accessible from the outside, it also makes the classes using them hard to unit-test, because it's not easy to mock these utility methods. Having too many of such utility classes can be a sign of a lack of OO design (procedural programming), and can really make the code hard to test.
If you're using a dependency injection framework (Spring, Guice, whatever), it might be a good idea to just make the utility class instantiatable, with non-static methods, and make it an injectable singleton. This way, classes using these utility methods can be tested by mocking the utility object.
Solution 2:
If it is a general purpose utility, static is IMO better. You stated that you will not have any states to store, so I don't see why should you make it non-static. Declaring it to be static will save memory too.
Solution 3:
Just because something can be static, doesn't mean it should be static.
There is another consideration to all this: mocking. It's harder to mock static methods in your tests than it is to mock the behaviour of an instance of a class.
Talk of unnecessary heap allocations and GCing of objects smacks of premature optimisation to me. The JVM will do a pretty good job at optimising away this sort of issue.
Solution 4:
The simplest way to define a Utility class is as an enum with no instances
public enum Utility {;
public static int utilityMethod(int x) { /* ... */ }
}
A utility class shouldn't have any state or have minimal state so you shouldn't worrying about GCs.
You can have other stateful classes for specific purposes like Builder, Factory, you can create the object as desired and discard it when you have finished.
Solution 5:
Its good to make the class as non-static with a private constructor:
- if we make the class static then class will be loaded when the application is deployed, if it is non-static then the class will be loaded when there is a call to one of its static methods
- creating a private constructor will avoid instantiating the class