Immutable objects, records and builders

An immutable object cannot change after it is built, so it is safe to share between threads and easy to reason about. Groovy has an annotation for it, Java has a record, and a builder keeps a constructor with many parameters readable.

@Immutable

immutable.groovy

import groovy.transform.Immutable @Immutable class Point { int x int y } def point = new Point(1, 2) println point try { point.x = 5 } catch (ReadOnlyPropertyException error) { println error.message } println point == new Point(1, 2)

groovy immutable.groovy

Point(1, 2)
Cannot set read-only property: x for class: Point
true

@Immutable makes every property final, adds the tuple constructor and the value methods, and gives the class a toString of its fields. A write raises ReadOnlyPropertyException, not a compiler error, because the property exists.

A record

record.groovy

record Pair(int left, int right) { int total() { left + right } } def pair = new Pair(3, 4) println pair.left() println pair.right() println pair.total() println pair

groovy record.groovy

3
4
7
Pair[left=3, right=4]

A record is a Java class with final components, an accessor per component, a canonical constructor and value equality. Groovy compiles a record as it compiles any other class, so a method may be added to it, as total is here.

@Builder

builder.groovy

import groovy.transform.ToString import groovy.transform.builder.Builder @Builder @ToString class Order { String customer int items BigDecimal total } def order = Order.builder() .customer('Ada') .items(2) .total(19.98) .build() println order.customer println order.items println order

groovy builder.groovy

Ada
2
Order(Ada, 2, 19.98)

The builder is a class with one method per property and a build(), which reads better than four positional arguments and stays readable when a fifth arrives. @Builder takes the strategy of the builder as an option; the default one is what this example uses.

Related

Article author: Arthur Isaev