liveBook · Manning

Invariant

As explained in Data-Oriented Programming in Java

An invariant is a condition that must remain true across the valid states of a data structure or computation.

An invariant is a fact that must hold whenever data is considered valid. Find it by asking what the data means and, just as importantly, what values would make no sense. A measurement of elapsed days can be zero or positive, for example; a negative elapsed time breaks the model rather than merely looking suspicious. section 3.1 section 3.2.1

Names and documentation can describe those rules, but they cannot stop callers from constructing nonsense. Put the rule in code at the boundary where raw values become domain data. A record’s compact constructor is a natural place to reject invalid inputs, normalize equivalent representations, and protect value-like data from unexpected mutability. section 2.6.1 section 3.2

Reject an impossible rational number

A rational number requires a nonzero denominator. A compact constructor can reject zero immediately, so every constructed Rational satisfies that condition. It can then divide numerator and denominator by their greatest common divisor, giving equivalent inputs one normalized representation. section 2.6.1

Validation enforces invariants at runtime, but representation can sometimes enforce them earlier. Model lifecycle states as distinct types or type parameters, so an operation can accept only the state it needs. The compiler then prevents certain invalid flows before execution, though this added type detail is a deliberate tradeoff rather than a universal requirement. section 5.4.3 section 5.4.5

Listing 9.17 Modeling the Cart items as a Map
record ProductSeller(String productId, String sellerId){}  #A

record ValidCart(
    Map<ProductSeller, Item> active,   #B
    Map<ProductSeller, Item> saved     #B
) {
  ValidCart {
     #C
     for (Item item : active.values()) {        #D
      if (item.desiredQty() >= item.availableQty()
          || item.desiredQty() <= 0) {
        throw new IllegalArgumentException("..."); 
      }
    }
    for (Item item : saved.values()) {          #D
      if (item.desiredQty() <= 0) {
        throw new IllegalArgumentException("..."); 
      }
    }
  }
}

A cart represented as maps keyed by ProductSeller makes item identity explicit while its constructor checks quantity rules for active and saved items. section 9.3.1

Use invariants as a design and refactoring tool:

  • Work backward from requirements: restate what must hold across every valid state, not only the steps that usually produce it. section 9.3.1
  • Choose collections and types whose semantics encode known constraints, rather than hiding crucial checks in scattered defensive code. section 9.3.1
  • Make validated data a boundary: code that needs the guarantee should accept the validated type, not partially checked inputs. section 9.3.2
  • Test global properties when rules interact, especially when correctness means rule domains and outputs must not overlap. section 8.1.1

Invariants may also belong to systems outside the process. A database that stores task lifecycles must itself reject forbidden transitions, because application-side checks can lose races. Express the lifecycle property clearly, then integration-test the dependency against every relevant transition. section 12.3

How Data-Oriented Programming in Java covers it

How deep it goes
Develops runtime constructor validation, compile-time type modeling, formal statements, property tests, and database-verified state transitions.
Examples
Uses Rational denominators, oil-curing measurements, late-fee lifecycles, shopping carts, rule functions, and task state transitions.
What it assumes
Assumes intermediate Java while introducing invariant derivation from domain meaning and constructor-based enforcement.
What you can do after
Build it from scratch by deriving valid states, enforcing them at boundaries, and selecting representations that exclude illegal states.
How it connects
Connects invariants with domain modeling, records, compact constructors, immutability, algebraic data types, validation, and integration testing.

Also explained in

Compare how 18 books explain invariant →

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.