Daily tip #8

If you are using JDK 16 or above, try to use Records to model your DTOs - immutability is free.

More info:

Records started in JDK 14 as a preview feature, and it was finalized in JDK 16.

Goals

  • Devise an object-oriented construct that expresses a simple aggregation of values.

  • Help developers to focus on modeling immutable data rather than extensible behavior.

  • Automatically implement data-driven methods such as equals and accessors.

  • Preserve long-standing Java principles such as nominal typing and migration compatibility.

A record declaration specifies in a header a description of its contents; the appropriate accessors, constructor, equals, hashCode, and toString methods are created automatically. A record’s fields are final because the class is intended to serve as a simple “data carrier”.

Take a look in repo-tip-8 to see a real example of today’s tip.