If I have to design a Utility class( such as ByteUtils or StreamUtils or StringUtils), what is the best design choice for them.
PS: By static class, I meant a class with static methods(and not the inner static class)
Please give advice on design choices for this ?
Utility Classes are classes that have only static methods that perform some operation on the objects passed as parameters. Such classes typically have no state. Utility Class is usually declared final, so it cannot be subclassed.
Utility class methods MUST NOT have dependencies to non static methods like other class instances or global variables.
A class can be declared static only if it is a nested class. It does not require any reference of the outer class. The property of the static class is that it does not allows us to access the non-static members of the outer class.
In Java programming, the main motivation for making a method static is convenience. You can call a static method without creating any object, just by using its class name. So if you need a method, which you want to call directly by class name, make that method static. Utility classes e.g. java.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With