Immutable objects cannot change after construction, which makes them simpler to reason about and safe to share between threads. Records (Java 16+) public record Money(BigDecimal amount, String currency) { public Money { Objects.requireNonNull(amount); if (amount.signum() < 0) throw new IllegalArgumentException("Negative amount"); currency = currency.toUpperCase(Locale.ROOT); } public Money add(Money other) { if (!currency.equals(other.currency)) throw new IllegalArgumentException("Currency mismatch"); return new Money(amount.add(other.amount), currency); // returns a new instance } } - Fields are private and final, there are no setters, and equals, hashCode and toString are generated from the components. - The compact constructor validates and normalises input, so invalid instances cannot exist. Classic immutable class - Declare the class final (or use private constructors), make all fields private final, set them in the constructor, provide no setters, and return new instances for "changes". Shallow vs deep immutability — the common trap public record Order(String id, List<OrderLine> lines) { } The list itself can still be modified by whoever holds a reference. Fix with defensive copies: public Order { lines = List.copyOf(lines); } List.copyOf and Map.copyOf create unmodifiable copies; nested objects should be immutable too. Also beware of returning mutable types like java.util.Date — use java.time types (LocalDate, Instant), which are immutable. Value in API models - Request and response DTOs as records are concise, self-documenting and cannot be modified accidentally by layers that receive them. Jackson supports records for JSON serialisation and deserialisation. - Validation in one place (constructor or Bean Validation annotations on record components). - Thread safety: immutable objects can be cached and shared without locks. - Safe as Map keys and Set elements, since hash codes never change. - Easier reasoning and testing: no hidden state changes between calls. - Messages and events (Kafka payloads) should never change after publishing, so records fit naturally. Where not to use records - JPA entities: Hibernate needs mutable state, a no-argument constructor and proxies, so entities are usually regular classes. Records work well for projections (Spring Data interface or record projections) and DTOs.
Ravindra Wadile · · 0 likes