45 min
Java Records is one of the most prominent language feature introduced of the recent time. It is not only an elegant way to declare an immutable value object type but also a tool to improve overall code quality. Using records reduces the amount of boilerplate code, eliminates the need for third-party code generators such as Lombok, and enables new language features and programming techniques.
In this talk I want to share my experience of migration our codebase to use records by looking at simple code examples.
What is the key difference between a record and a class? What are the ways to validate record instances? How to apply a builder design pattern? Why records are useful when writing functional code? How records will work with pattern matching?
- What is a record: definition, rationale and history
- Let's compare to a class (Point.java vs PointClass.java)
- Unique record features
- Canonical and compact
constructors (Rectangle.java
and Address.java)
- Validation
- Setting default values
- Forcing immutability on collection record components (Paragraph.java)
- Canonical and compact
constructors (Rectangle.java
and Address.java)
- Record polymorphism with
interfaces (Request.java)
- Using interface default methods (BaseConfig.java)
- Annotations and documentation inheritance (RequestApi.java)
- Use case examples
- Statically typed documents (Document.java)
- API request/response types (Request.java)
- Data access objects (DbTransaction.java)
- Tuples, local records, intermediate result in functional style stream (Tuples.java)
- Map keys (Maps.java)
- Immutability
- Making a copy (Transaction.java)
- Using builder pattern with custom annotation processor (Transaction.java)
- Tools support
- Records != JavaBeans:
- fields may not be recognized by default
- don't work as class proxies, cannot be ORM or JAX-RS entities
- different reflection API
- Records are final: impossible to mock using standard technique
- IDE suggests to convert a class to a record
- Records != JavaBeans:
- Why records are important?
- Better code using standard language features
- No need to learn third-party libraries, track dependency updates
- Performance
- Java platform knows beforehand that records are immutable data carriers
- Future improvements such as value objects: https://openjdk.org/jeps/8277163
- Record pattern matching (Preview)
- The future: 'wither', serialization 2.0 and possibly even abstract records
Point pp = p with { x = 3; }
https://github.com/openjdk/amber-docs/blob/master/eg-drafts/reconstruction-records-and-classes.md- Towards better serialisation: https://openjdk.org/projects/amber/design-notes/towards-better-serialization
- https://twitter.com/BrianGoetz/status/1214224277467271168
- Better code using standard language features
- Q/A