1.4-Software-Development-Principles

Enums

Introduction

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.

Advantages of Enums

  1. Typesafety: Enums ensure that a variable of this type can only accept values from this predefined list. This avoids errors by assigning values from another list.
  2. Readability: Using enums replaces random (magic) numbers with clearly readable text, assuming that the names of the values are logically chosen.
  3. Methods and fields: Enums in Java are more than just a list of values. As they are defined as an object you have the chance to add variables, fields and methods providing powerful abilities.
  4. Use with switch statements: Enums are accepted as case values within a switch statement, once again enhancing readability.

Using enums well

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!");
        }
    }
}

A bad example

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.

Advanced enums

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");
        }
    }
}

Conclusion

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.