Video in progress
What risks does using a record as a public API across many services or a library boundary create from an evolution standpoint?
Adding a component to a record changes the canonical constructor signature and equals/hashCode/toString, which breaks binary and source compatibility. If it's used at a boundary, you need to keep the old constructor as an extra constructor, use factory methods, or version at the serialization level.
📖 Answer
A record is a "nominal tuple": its whole API follows automatically from the list of components. Inside your own code that's great; in an external contract, every change is a break.
// v1
public record Money(BigDecimal amount, String currency) {}
// v2
public record Money(BigDecimal amount, String currency, int scale) {}
What breaks:
new Money(a, c): a client compiled against v1 getsNoSuchMethodError;- the deconstruction pattern
case Money(var a, var c)is now broken at the source level; equalstakes the new component into account too, so keys in caches andSets behave differently;- reordering components is the worst: if the types are the same, even the compiler doesn't notice.
What you can do:
- Keep the old signature as an extra constructor:
public record Money(BigDecimal amount, String currency, int scale) {
@Deprecated
public Money(BigDecimal amount, String currency) { this(amount, currency, 2); }
}
This keeps constructor calls working, but not deconstruction patterns.
2. If you expose a record in a library API, use it for a "value that doesn't change" (a coordinate, a money pair); for a DTO that will keep growing, use a plain class plus a builder, or an interface.
3. Between services, the contract is a schema, not a Java type: JSON/Protobuf/Avro. Jackson works well with records; ignoring unknown fields (FAIL_ON_UNKNOWN_PROPERTIES = false) and having defaults for new fields is where forward compatibility comes from.
4. Avoid sharing a common "DTO JAR" between services: that's tight coupling at the Java level, and every release ends up requiring everyone to deploy at the same time.
In practice you can use a record at a boundary, but teams have to accept up front that "a schema change = an API major version".
Sign up to mark studied questions and save your progress.