For the past decade or so, I've been using the pattern below for my Java utility classes. The class contains only static methods and fields, is declared final
so it can't be extended, and has a private
constructor so it can't be instantiated.
public final class SomeUtilityClass {
public static final String SOME_CONSTANT = "Some constant";
private SomeUtilityClass() {}
public static Object someUtilityMethod(Object someParameter) {
/* ... */
return null;
}
}
Now, with the introduction of static methods in interfaces in Java 8, I lately find myself using a utility interface pattern:
public interface SomeUtilityInterface {
String SOME_CONSTANT = "Some constant";
static Object someUtilityMethod(Object someParameter) {
/* ... */
return null;
}
}
This allows me to get rid of the constructor, and a lot of keywords (public
, static
, final
) that are implicit in interfaces.
Are there any downsides to this approach? Are there any benefits to using a utility class over a utility interface?