Enums (enumerations) within Java offer a way to define a set of constant values. This too will make your code safer, more readable and more maintainable.
A great example for the use of enums is the choice to define the days of the week as a list of specific values. This makes the code much more readable and maintainable.
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class Schedule {
private Day day;
public Schedule(Day day) {
this.day = day;
}
public void printActivity() {
switch (day) {
case SATURDAY:
case SUNDAY:
System.out.println("Relax, it's weekend!");
break;
default:
System.out.println("Working day. Time to code!");
}
}
}
The reason days of the week as enums work so well is because this list is well known and isn’t likely to change (any time soon).
A bad example would be using enums for values that you wish to extend at a later time. In such cases other datastructures may be a better choice.
In the example below we will attempt to use enums to manage user roles in an application where we are quite certain that additional roles may be added at a later time. This should be avoided.
This restricts fexibility because enums are defined in a static way, and cannot be altered or extended during runtime.
public enum UserRole {
ADMIN, USER, GUEST; // Not flexible; difficult to expand with new roles without changing the code
}
A better solution would be a UserRoleManager that simply maintains a list of known roles through a list that can be extended.
Enums are a type of class definition and allow the addition of member variables and methods. This allows each constant to provide additional state and behaviour.
For instance a TrafficLight enum that also stores the time each light should be shown.
public enum TrafficLight {
RED(30),
GREEN(45),
YELLOW(5); // Duration in seconds for each light
private final int duration;
TrafficLight(int duration) {
this.duration = duration;
}
public int getDuration() {
return duration;
}
}
public class TrafficControl {
public static void main(String[] args) {
for (TrafficLight light : TrafficLight.values()) {
System.out.println(light + " light duration: " + light.getDuration() + " seconds");
}
}
}
Using enums are a powerful way to define a list of constants that share the same type. Additionally it’s a great way to store corresponding data in a clear way. Choosing clear names for each value makes you code safer, more readable and more maintainable.