81

I want to create a class with utility methods, for example

public class Util {

   public static void f (int i) {...}

   public static int g (int i, int j) {...}

}

Which is the best method to create an utility class?

Should I use a private constructor?

Should I make the utility class for abstract class?

Should I do nothing?

6

4 Answers 4

147

For a completely stateless utility class in Java, I suggest the class be declared public and final, and have a private constructor to prevent instantiation. The final keyword prevents sub-classing and can improve efficiency at runtime.

The class should contain all static methods and should not be declared abstract (as that would imply the class is not concrete and has to be implemented in some way).

The class should be given a name that corresponds to its set of provided utilities (or "Util" if the class is to provide a wide range of uncategorized utilities).

The class should not contain a nested class unless the nested class is to be a utility class as well (though this practice is potentially complex and hurts readability).

Methods in the class should have appropriate names.

Methods only used by the class itself should be private.

The class should not have any non-final/non-static class fields.

The class can also be statically imported by other classes to improve code readability (this depends on the complexity of the project however).

Example:

public final class ExampleUtilities {
    // Example Utility method
    public static int foo(int i, int j) {
        int val;

        //Do stuff

        return val;
    }

    // Example Utility method overloaded
    public static float foo(float i, float j) {
        float val;

        //Do stuff

        return val;
    }

    // Example Utility method calling private method
    public static long bar(int p) {
        return hid(p) * hid(p);
    }

    // Example private method
    private static long hid(int i) {
        return i * 2 + 1;
    }
}

Perhaps most importantly of all, the documentation for each method should be precise and descriptive. Chances are methods from this class will be used very often and its good to have high quality documentation to complement the code.

3
  • 6
    I would stress that quality documentation means complete JavaDoc comments, not code comments. May 3, 2017 at 16:48
  • 3
    @initramfs this is a nice answer but could you please adapt your example according to what you write to make it consistent!?
    – karlihnos
    Dec 21, 2017 at 8:15
  • "Perhaps most importantly of all, the documentation for each method should be precise and descriptive. Chances are methods from this class will be used very often and its good to have high quality documentation to complement the code." Please update the javadoc comments for the above code. See oracle.com/technical-resources/articles/java/javadoc-tool.html
    – razvanone
    Apr 1, 2021 at 8:30
26

According to Joshua Bloch (Effective Java), you should use private constructor which always throws exception. That will finally discourage user to create instance of util class.

Marking class abstract is not recommended because is abstract suggests reader that class is designed for inheritance.

4
  • 1
    I didn't get it. Why do you need to throw an exception in a private constructor if it is private and class will not be instantiated therefore exception will never be thrown? Aug 14, 2019 at 9:12
  • 1
    @JohnnyFive private-constructor-throwing-exception is a Joshua Block concept to promulgate developers reading the code that they should NOT create any instance.
    – michaldo
    Feb 16, 2020 at 19:30
  • 2
    @JohnnyFive the exception, or even an AssertionError should be thrown because by using reflection you can still access a private constructor. By throwing an exception or error you can guarantee that no instance of the class can be created.
    – Felix S
    Jun 9, 2020 at 8:47
  • 1
    @JohnnyFive From the book, "The AssertionError isn't strictly required, but it provides insurance in case the constructor is accidentally invoked from within the class."
    – Leponzo
    Apr 5, 2021 at 15:07
9

I would make the class final and every method would be static.

So the class cannot be extended and the methods can be called by Classname.methodName. If you add members, be sure that they work thread safe ;)

5

Making a class abstract sends a message to the readers of your code that you want users of your abstract class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.

Therefore, adding a private constructor is a better choice here. You should also make the class final to disallow subclassing of your utility class.

Not the answer you're looking for? Browse other questions tagged or ask your own question.