Should a utility class be static? [closed]

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)