compact constructor

A record constructor written without a parameter list, which runs checks before the record's fields are assigned.

In more detail

Because the component names are already declared in the record header, the compact constructor only contains validation or normalisation. Throwing an exception there, such as IllegalArgumentException, prevents an invalid record from ever existing. That is the place for invariants every instance must satisfy.

Example

public Customer { if (id.isBlank()) throw new IllegalArgumentException("customer fields are required"); }

Related terms

Taught in

References

Certification courses