0%
Records: Data Classes Without Generated Code

Records

Replace a hundred generated lines with a one-line declaration, and know when to hold back.

10-15 min

Records: Data Classes Without Generated Code

Open any Java 8 project and look for a Point, Address, or OrderLine class. You'll find three useful fields buried in a hundred and twenty lines that nobody wrote by hand: a constructor, six accessors, an IDE-generated equals, a matching hashCode, and a toString. This code expresses nothing. Yet it is versioned, reviewed in code review, and above all it lies the moment someone adds a fourth field without regenerating equals. The resulting bug — two identical objects that the HashMap treats as different — is among the hardest to diagnose, because the faulty code looks correct.

A record eliminates this risk by eliminating the code. You declare the list of components; the compiler produces the rest, and regenerates it automatically the day you add a field. This is not just a typing shortcut: it is a statement of intent. A record tells whoever reads the code that this object is transparent, immutable data, entirely defined by its components, rather than an object with behavior whose identity matters.

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!