Enums


Sexy, Chic , Powerful

Sexy and Chic because they produce elegant code by constraining the choices of what you can pass.
Powerful, because by limit your choices , actually increase the code effectiveness (it means the code you write today will work if reused 10 years later )

But , first things first…

What is an Enum type? 
They are classes that export one instance for each enumeration constant (think a public static final field ), or consider it as a generalization of singletons ( singleton as an single element enum)

What they Provide?:

  • Compile-time Type Safety:
    Prevent typos and invalid parameters passing in compile-time checking and prevent errors like passing Null values that will fail in Run-time
  • Make testing easier
    If enum is passed as parameter in a method, testing is easier for edge conditions, for example no need to write unit tests for invalid input
  • They are Self-documented
    The set of choices for a parameter is finite and self-describing, so no need to write comments or documentation
  • Can have methods and other fields 
    In Java doc , enum is defined as:

public abstract class Enum<E extends Enum<E>>

extends Object

implements Comparable<E>, Serializable

So you can add methods, fields and implement any behavior you want. **PS** An Enum cannot extend other Enum, all of them extend java.lang.Enum class and Java doesn’t supports multiple inheritance !

When to use them?

  • When you need a set of constants that are known at compile time(e.g transaction statuses, planets , days of week , lipstick color codes )
  • According to Bloch , a single-element enum type is the best way to implement a singleton.
  • Use them to implement the Strategy design pattern
    In this case each enum or many enums can share a behavior.
    Let’s see the below example, the strategy is the ConnectType , enums INSTAGRAM, LINKEDIN, TINDER share the same way to connect, sending a PM, but PHONE and SKYPE follow a different approach.
public enum Networking {

    INSTAGRAM,LINKEDIN, TINDER,
    PHONE(ConnectType.LANDLINE), SKYPE(ConnectType.VoIP);

    private final ConnectType connectType;
    Networking() { this.connectType= ConnectType.TEXT; }
    Networking(ConnectType connectType) {
        this.connectType=connectType;
    }

    void connect(){
        connectType.connect();
    }

    private enum ConnectType {

        TEXT {
            @Override
            void connect() {
                System.out.print("Send a PM ..");
            }
        },

        VoIP {
            @Override
            void connect() {
                System.out.print(" Do a video call! ");
            }
        },

        LANDLINE {
            @Override
            void connect() {
                System.out.print("Classic and Vintage! ");
            }
        };

        abstract void connect();
    }
}