Video in progress
What is an enum, and what makes it better than plain int or String constants?
An enum is a special class for a limited, known-in-advance set of values. The compiler accepts only the allowed values, it works nicely with switch, and you can add fields and methods to an enum.
📖 Answer
With constants:
static final int NEW = 0, PAID = 1, SHIPPED = 2;
void setStatus(int s) { ... } // setStatus(42) compiles too
With an enum:
public enum OrderStatus {
NEW("Yangi"), PAID("To'langan"), SHIPPED("Jo'natilgan");
private final String label;
OrderStatus(String label) { this.label = label; }
public String label() { return label; }
public boolean canCancel() { return this == NEW || this == PAID; }
}
You can't pass a wrong value, and each value is unique, so comparing with == is safe. values(), valueOf("PAID"), EnumMap and EnumSet are fast and handy. And you can put behavior on the value itself (canCancel).
The place that hurts most in prod is the database: in JPA, @Enumerated(EnumType.ORDINAL) writes the ordinal number of the value. If you add a new value in the middle of the enum, the old data gets read wrong. Use EnumType.STRING.
Sign up to mark studied questions and save your progress.