A common thing to do to utility classes is to give them a private constructor:
public final class UtilClass {
private UtilClass() {}
...
}
But unfortunately, some tools don't like that private constructor. They may warn that it's never called within the class, that it's not covered by tests, that the block doesn't contain a comment, etc.
A lot of those warnings go away if you do this instead:
public enum UtilClass {;
...
}
My question is: besides the unending hatred of future developers, what important differences are there between an enum with no values and a class with a private constructor in Java?
Note that I am not asking What's the advantage of a Java enum versus a class with public static final fields?. I'm not deciding between whether a list of things should be a bunch of constants or an enum, I'm deciding between putting a bunch of functions in a constructor-less class or a value-less enum.
Also note that I don't actually want to do this. I just want to know the trade-offs as part of general language knowledge.
For example, using an enum pollutes the autocomplete with useless methods like UtilClass.values()
. What other downsides are there? Upsides?
One benefit is that you're absolutely guaranteed that no instances can be created, even from inside the class.
A disadvantage is that this goes beyond the usual intent of enums. However, we already do this for singletons implemented with enums.
This bit from "Effective Java" by Joshua Bloch about such singletons also applies to utility classes:
...you get an ironclad guarantee that there can be no instances besides the declared constants. The JVM makes this guarantee, and you can depend on it.
Disclaimer: I have not used this pattern, and am not recommending for or against it.