liveBook · Manning

Enum

As explained in The Art of Code

An enum is a language construct that defines a finite set of named constants as a distinct type.

Use an enum when data can belong to a fixed set of known states. Naming those categories explicitly preserves the constraint and makes intent easier to understand than free-form strings or numeric codes. section 4.3

Representing closed categories

Instead of passing a string or numeric code whose allowed values must be remembered, represent the value with an enum or equivalent construct. The model then communicates that only the defined categories are valid. section 4.3

Keep the design useful rather than ceremonial:

  • Choose an enum when explicit categories reduce ambiguity and make behavior easier to follow. section 4.3
  • Route limited data-driven variation through clear switching expressions or pattern matching when explicit branching communicates the decision better than added abstraction. section 4.3

How The Art of Code covers it

How deep it goes
Explains the modeling rationale and tradeoff with strings or numeric codes, but stops short of syntax or runtime behavior.
Examples
Contrasts enums with free-form strings and numeric codes for representing closed sets of values.
What you can do after
Apply it by modeling fixed categories explicitly and routing limited data-driven variation through clear branching.
How it connects
Connects enums with data modeling, explicit branching, switching expressions, pattern matching, and polymorphism.

Also explained in

Compare how 23 books explain enum →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Code. The section links point to the parts of the book it draws on.