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?
enum
should trigger a more severe warning than a private default constructor.Enum
s are an under-rated feature of Java. They have all sorts of uses that most would never think of, and in my opinion the fact that most developers artificially limit their capabilities is not a good reason for you to do the same. That being said, it's not what I normally do.throw new AssertionError()
. It's assertively (?) wrong to ever instantiate an utility class.