Custom Enum

About

A Custom Enum is an enum that we define yourself in a project to fit our own specific needs. We can add fields, methods, and constructors to an enum to expand its capabilities, making it powerful and functional beyond just a list of constants.

Adding Fields and Methods to a Custom Enum

Custom enums can contain instance variables, constructors, and methods, enabling them to store and manipulate additional data.

Example of a Custom Enum with Fields and Methods

public enum ProductType {
    PREPAID_CARD("prepaid-card", "A prepaid card"),
    CREDIT_CARD("credit-card", "A credit card"),
    DEBIT_CARD("debit-card", "A debit card");

    private String code;
    private String description;

    ProductType(String code, String description) {
        this.code = code;
        this.description = description;
    }

    public String getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }

    public static ProductType fromCode(String code) {
        for (ProductType type : ProductType.values()) {
            if (type.code.equals(code)) {
                return type;
            }
        }
        throw new IllegalArgumentException("Unknown code: " + code);
    }
}

Usage of Custom Enum

In this example, ProductType stores a code and description for each constant

Examples

Payment Confirmation Status

PaymentConfirmationStatus.java

Validation Enum

ValidationResult.java

Version Type

VersionType.java

Yes or No Flag

YesNoFlagType.java

Multi-stage order processing system

OrderState Enum: The OrderState enum defines multiple states for an order, such as RECEIVED, PROCESSING, SHIPPED, DELIVERED, and COMPLETED. Each enum constant has a stage number (int stage), which allows us to track the order's progress. Every state has a behavior defined in the handleOrder method. This method is abstract in the enum and is overridden in each state to handle the order’s transition logic. OrderState is a polymorphic enum. The method handleOrder is defined for each state, allowing us to change the order's state and behavior dynamically. The enum constants (RECEIVED, PROCESSING, etc.) override the abstract method to define their specific behavior. validTransitions is an EnumMap used to store valid transitions between states. For instance, an order can only go from RECEIVED to PROCESSING, from PROCESSING to SHIPPED, etc. The isTransitionValid static method checks if a state transition is allowed based on the current and next states.

OrderState.java

Order Class: The Order class holds an OrderState and provides a method (setState) to change the state. The setState method ensures that only valid state transitions are allowed using isTransitionValid. If a transition is invalid (e.g., trying to go backward in the state machine), it prints a message and does not update the state.

Order.java

OrderProcessingSystem.java

Last updated