liveBook · Manning

Constructor method

As explained in Data-Oriented Programming in Java

A constructor is a class member that initializes a newly created object and establishes its initial state.

A constructor is a useful boundary for turning loose requirements into valid data. Put checks on the data type itself so newly created instances cannot violate constraints, even when callers ignore documentation. section 3.2.2 section 9.6

Validating a measurement

A Measurement constructor can reject malformed sample identifiers, negative elapsed days, and contact angles outside the permitted range. This prevents incorrect measurements from entering the rest of the program. section 3.2.2

Listing 3.13 Defending invariants during construction
record Measurement(
      String sampleId,
      int daysElapsed,
      double contactAngleDegrees) {
      
  Measurement {  #A
      if (!sampleId.matches("(HEAT|AIR|UV)-\\d+")) {             #B
          throw new IllegalArgumentException(  
              "Must honor the form {CuringMethod}-{number}" + 
              "Where CuringMethod is one of (HEAT, AIR, UV), " +
              "and number is any positive integer"
          );
      }
      if (daysElapsed < 0) {                                     #C
          throw new IllegalArgumentException(
              "Days elapsed cannot be less than 0!");
      }
      if (!(value >= -180.0 && value < 180.0)) {                 #C
          throw new IllegalArgumentException(
              "Contact angle must be between -180 and +180");
      }
  }
}

Inspect the compact constructor to see how each invariant becomes executable code at the creation boundary. section 3.2.2

Construction-time validation improves safety but does not preserve meaning by itself. After construction, a value such as contactAngleDegrees can still behave as an ordinary double, requiring stronger data types when semantic distinctions must survive transformations. section 3.2.2

How Data-Oriented Programming in Java covers it

How deep it goes
Explains executable invariant checks and stops short of preserving field meaning after construction.
Examples
Uses a Measurement record with sample identifiers, elapsed days, and bounded contact angles.
What you can do after
Apply constructors to encode invariants and reject invalid instances at creation time.
How it connects
Connects constructors with invariants, validation, data types, records, and illegal states.

Also explained in

Compare how 18 books explain constructor method →

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.