Ga naar hoofdinhoud

Implementatie Value van Objects

Hoewel de final modifier uit Java immutability altijd al mogelijk maakte zijn er inmiddels betere opties. De enum is prima voor 'enkelwaardige' Value Objects, zoals kleuren en andere opsommingen. Java biedt sinds versie 14 ook het record als 'immutable' variant van een class:

Basis syntax

In een record som je alle beschikbare velden op in een constructor achtige syntax direct op het record keyword.

"Records offer concise, readable syntax, enforce immutability, and generate standard implementations of commonly used methods like toString() [..] and equals(). These implementations are based on the record’s components and are generated automatically by the compiler. A record is defined using the record keyword, followed by the name of the record and its components." - (Ram, H. (11-5-2024) Custom Constructor in Java Records. Baeldung.com)

record StudentRecord(String name, int rollNo, int marks) {}

Custom constructor

En als je een custom constructor wil voor je record voor bv. een validatie check zie je hieronder de syntax.

"To guarantee data integrity and be able to sort a StudentRecord by name, we can create a custom constructor for input validation and field initialization:" - (Ram, 2024)

record Student(String name, int rollNo, int marks) {
public Student {
if (name == null) {
throw new IllegalArgumentException("Name cannot be null");
}
}
}