Using `enum` to Represent Complex Immutable States
This is a very cool design pattern I learned on the job.
Say you have a few related states that you want to represent. These states are static and immutable. Think of a collection of states where what actions can be taken depends on the state of object.
A more concrete example is US coin denominations. A penny is always 1c, a nickle is 5c, a dime is 10c and a quarter is 25c.
A naive (but correct) way to represent this would be with a class
containing final
and static
fields:
But, a much cleaner and understandable implementation would use an enum
.
An enum
is implicitly static and final and is immutable.
enum
s can have constructors, variables, methods. Moreover, you can use ==
to compare enum
constants.