Object-oriented – In what situations does it make sense to use an enumeration when writing object-oriented code

enumobject-oriented

Enumerations1 are often associated with procedural code rather than object-oriented code. They tend to give rise to similar switch statements scattered through the code, and in general, these are replaced by polymorphism in object-oriented code.

For example, see Replace Type Code with Class, Replace Type Code with Subclasses, and Replace Type Code with State/Strategy in Refactoring by Martin Fowler. Closely related, see Replace Conditional With Polymorphism in the same volume; Bob Martin also has quite a bit to say on the disadvantages of switch statements in Clean Code (for example, heuristic G23 Prefer Polymorphism to If/Else or Switch/Case).

However, since object-orientation, like any other good paradigm, can be a powerful tool but is not a silver bullet, are there times when using an enumeration is a good decision?


1I use this term broadly; not just for something which is strictly an enum in a C-based language, but for any set of entities that are used to represent it (a class with a set of static members, etc…).

Best Answer

PEP 435 was the proposal to add enumerations to Python. The motivation for adding enumerations:

The properties of an enumeration are useful for defining an immutable, related set of constant values that may or may not have a semantic meaning. Classic examples are days of the week (Sunday through Saturday) and school assessment grades ('A' through 'D', and 'F'). Other examples include error status values and states within a defined process.

Enumerations serve the same purpose in object-oriented code as in procedural code.