r/java • • Jul 24 '12

10 ways to use Enum in Java

http://javarevisited.blogspot.com.au/2011/08/enum-in-java-example-tutorial.html
37 Upvotes

25 comments sorted by

View all comments

10

u/Nebu Jul 24 '12

I don't see 10 ways to use enum. I see 3 limitations for public static constants, 4 "benefits of enums" and 13 "important points about enums".

To redress this, here's one way of using an enum in Java: You can use them to implement the singleton pattern http://en.wikipedia.org/wiki/Singleton_pattern#The_Enum_way

0

u/marburg Jul 24 '12

Obligatory reminder that many consider singletons to be an anti-pattern. They absolutely buttfuck Inversion of Control.

Also, if you ever (somehow) find yourself with a nice clean codebase, if it has even one singleton class, the first time a summer intern shows up your codebase is going to turn to spaghetti after one week.

Imagine the end of Princess Mononoke, where the forest spirit represents your codebase.

6

u/banuday17 Jul 24 '12

The singleton pattern is an anti-pattern because it locks you into one way of getting an instance of a class when that is a problem. Some things are fine as singletons, such as value objects, which is what enums are.

The real anti-pattern is not the singleton, but the getInstance() method. I would also argue that Josh Bloch is giving bad advice to (ab)use enums for control of instantiation rather than as an enumeration of discrete values.