Reputation: 4385
Time after time I have a situation where I have an utility class containing only static methods.
The question is not about the fact of having such classes themselfes, so not a debate about utility classes. We just assume that there is a use case where this class makes sense.
Now I have seen different possibilities to prevent instantiation/extension:
What is the best practice here? Could you elaborate the benefits/drawbacks of the two possibilities?
Personally I prefer the enum solution, as it completely prevents instantiation and extension out of the box, but maybe I am wrong.
Thank you already!
Upvotes: 1
Views: 1209
Reputation: 271040
I would prefer the former.
First of all, using a final class with a private constructor is what I do all the time when I'm writing a utility class. I have never even thought of using enums.
The main reason for not using an enum is that you can still technically write something like this:
MyEnum var = MyEnum.valueOf("Hello");
and the compiler doesn't say a thing about it, not even IntelliJ IDEA!
Upvotes: 7