archive2021

Java var and records: rules that keep the code readable

var (Java 10) and records (final in Java 16) both cut boilerplate. Where each one fits, where it makes code harder to read, and the traps I hit with both.

3 min read#dev#java

I tried records on a small tool this week. They are a final feature in JDK 16, released on 16 March 2021 (JEP 395), together with pattern matching for instanceof (JEP 394). With var from Java 10, they change how small Java classes and methods look. Java 16 is not an LTS release, so my production services wait for 17, but the rules for both features are ready for when they move.

var

var (JEP 286) lets the compiler infer the type of a local variable from the right side. The type is still static and never changes.

It is allowed for local variables with an initializer, in both kinds of for loop, and in try-with-resources. Not for fields, parameters or return types. var x = null; does not compile, and neither does var f = () -> 1;, because a lambda needs a target type.

I use it when the type is obvious on the same line:

var users = new HashMap<String, List<User>>();
var conn = dataSource.getConnection();
for (var entry : users.entrySet()) { ... }

And I write the type when the right side hides it:

var result = service.process(input);   // what is result? The reader has to open process().

The traps:

var list = new ArrayList<>();   // ArrayList<Object>: the diamond has nothing to infer from
var total = 0;                  // int, not long
var price = 9.99;               // double, not BigDecimal

var list = new ArrayList<String>() also gives the type ArrayList, not List. Inside one method this rarely matters, and when I want the interface type I write it.

With var the variable name carries more of the meaning. var customers is fine, var c is not. And I do not change old code just to add var. It only makes the diff noisy.

Records

public record Reading(String sensorId, double value, Instant time) {}

This gives a final class with private final fields, a constructor, accessors sensorId(), value() and time() (no get prefix), and equals, hashCode and toString based on all fields. You cannot add instance fields, and a record cannot extend another class.

Validation goes into a compact constructor:

public record Reading(String sensorId, double value, Instant time) {
    public Reading {
        Objects.requireNonNull(sensorId);
        Objects.requireNonNull(time);
        if (Double.isNaN(value)) {
            throw new IllegalArgumentException("value is NaN");
        }
    }
}

Where they fit:

  • Request and response objects of a REST API. Jackson 2.12 and later reads and writes records without annotations.
  • Small value types: a coordinate, a time range, an amount with a currency.
  • Returning two or three values from a method. A local record inside the method is allowed, and it is much clearer than Map.Entry or an Object[].
  • Map keys, because equals and hashCode are correct by default.

Where they do not fit:

  • JPA entities. Hibernate needs a no-argument constructor, mutable fields and often proxy subclasses. A record has none of these. I return records from the API and keep entities as normal classes.
  • Mutable state. A record with a List field is only shallow immutable, so I copy lists in the compact constructor: readings = List.copyOf(readings);.
  • Many fields. Ten fields mean a constructor with ten parameters, and the call sites become hard to read. At that point a builder is better.

Small things that surprised me: some older libraries and templates look only for getValue()-style getters. Arrays inside a record compare by reference in equals, as everywhere else in Java. And toString prints all fields, so a password or a token does not belong in a record that might get logged.

The two together

Records and var work well together in small methods: a local record holds an intermediate result, and var saves repeating its name. In longer methods I write the types out. The goal is the same for both features: less code to read, not less information.