Enums (short for enumerations) are a powerful yet underappreciated feature in object-oriented design. They allow you to define a fixed set of named constants that improve clarity, type safety, and maintainability in your system.
Used correctly, enums can make your code more expressive, self-documenting, and resilient to errors.
An enum is a special data type that defines a collection of constant values under a single name. Unlike primitive constants or string literals, enums are type-safe, which means you can’t assign just any value to a variable declared as an enum type.
They ensure that a variable can only take one out of a predefined set of valid options.
In short: If a value can only be one of a predefined set of options, use an enum.
Enums provide several key advantages over plain constants or strings:
"PENDING" or 3 in your code.OrderStatus.SHIPPED is far more descriptive than 3.Enums are perfect for defining categories or states that rarely change.
PENDING, IN_PROGRESS, COMPLETED)ADMIN, CUSTOMER, DRIVER)CAR, BIKE, TRUCK)NORTH, SOUTH, EAST, WEST)By using enums instead of raw strings, you make your system easier to understand and harder to misuse.
Let’s start with a simple example representing the status of an order in an e-commerce application.
This enum defines a finite set of valid states an order can have. Nothing else is allowed.
Enums can have additional data and even behavior. This makes them even more powerful.
Let’s consider a Coin enum that represents U.S. coins and their denominations.
This is far more elegant and safe than using integers directly.
Enums help you define a fixed set of well-known values, giving structure and clarity to your data. But what if you want to define a common set of behaviors that different classes can implement in their own way?
That’s where Interfaces come in. In the next chapter, we'll dive into interfaces.