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, you can’t assign just any value to a variable declared as an enum type.
Enums are perfect when a variable can only take one out of a small set of predefined values.
PENDING
, IN_PROGRESS
, COMPLETED
)ADMIN
, CUSTOMER
, DRIVER
)CAR
, BIKE
, TRUCK
)NORTH
, SOUTH
, EAST
, WEST
)Enums help avoid magic strings or numbers, improve readability, enable compiler checks, IDE auto-completion and reduce bugs caused by invalid values.
Enum representing status of an order in an e-commerce application.
This defines a clear set of valid statuses for an order.
Using it in code:
Enums can have additional data and even behavior. This makes them even more powerful.
Coin Enum with Denomination
Usage:
This is far more elegant and safe than using integers directly.