liveBook · Manning

Enum

As explained in Data-Oriented Programming in Java

An enum is a Java type construct that defines a fixed set of named constant values.

An enum models a fixed set of meaningful named values instead of leaving domain semantics inside serialized strings. In Java, it gives the type system a direct representation of those allowed choices. section 3.3.3 section 8.3

Modeling a curing method

A sample identifier need not remain a string such as "UV-1". Split its meaning into domain types: `enum CuringMethod { HEAT, AIR, UV }`, then store a `CuringMethod` together with a nonnegative sample number in `SampleId`. Grouping measurements by `m.sampleId().method()` now expresses the domain directly, rather than parsing string internals. section 3.3.3 section 3.3.3

Restricting rule attributes

A rule represented as `new Equals("county", "US")` accepts misspelled or nonexistent attributes. Replacing the field with `Attribute` and defining `enum Attribute { REGION, COUNTRY, SECTOR, SEGMENT, CHANNEL }` narrows the model to known account attributes. section 8.3 section 8.3

Use an enum when:

  • A domain concept has a fixed, named set of values. section 3.3.3
  • A wide-open string would permit typos or values that do not exist in the model. section 8.3
  • Business-rule data should refer to known attributes rather than serialized labels. section 8.3
Listing 3.27 Capturing the meaning of Sample ID
record NonNegativeInt(int value){/*...*/}  #A
 
enum CuringMethod {HEAT, AIR, UV}     #B
record SampleId(
    CuringMethod method,        #C
    NonNegativeInt sampleNum    #C
) {
    SampleId {
        Objects.requireNonNull(method);    #D
        Objects.requireNonNull(sampleNum); #D
    }
}  

Inspect the complete typed SampleId model, including the enum, constrained number, and null checks. section 3.3.3

How Data-Oriented Programming in Java covers it

How deep it goes
Explains enum selection through domain refactoring and shows its use in composite records and rule data, without covering enum behavior or advanced members.
Examples
Uses curing methods in SampleId, measurement grouping, and account attributes in an Equals rule.
What it assumes
Assumes familiarity with Java records and basic domain modeling while reinforcing how serialized strings differ from data meaning.
What you can do after
Build it from scratch to replace ambiguous strings with named domain values and compose them into typed records or rules.
How it connects
Connects enums with the type system, records, value constraints, string serialization, business rules, and algebraic data.

Also explained in

Compare how 25 books explain enum →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data-Oriented Programming in Java. The section links point to the parts of the book it draws on.