Video in progress
What is a value object in DDD, and how do you write one properly in Java with a record?
A value object is an immutable object with no identity, defined only by its value: Money, Email, DateRange. A record gives you equality and immutability, and you add validation and normalization yourself in the compact constructor.
📖 Answer
Two Money(100, UZS) are the same thing: which one you hold doesn't matter. Two Customers are two different people even if they have the same name. The first is a value object, the second an entity.
public record DateRange(LocalDate from, LocalDate to) {
public DateRange {
Objects.requireNonNull(from);
Objects.requireNonNull(to);
if (to.isBefore(from)) {
throw new IllegalArgumentException("to < from: " + from + ".." + to);
}
}
public boolean overlaps(DateRange other) {
return !to.isBefore(other.from) && !other.to.isBefore(from);
}
public long days() { return ChronoUnit.DAYS.between(from, to) + 1; }
}
What we gain: an invalid DateRange can't be created at all. Services no longer need a "is from not after to" check: the type guarantees it. The overlaps logic also lives in one place, so nobody writes their own (wrong) version.
Be careful with records:
- if a component is a
List, doitems = List.copyOf(items);in the compact constructor, otherwise it can be changed from outside; - in a record with a
BigDecimalcomponent,equalsalso compares the scale:1.0and1.00are not equal. Normalize withsetScalein the constructor; - a record's accessors (
from()) are public to everyone: if you need hidden state, write a plainfinalclass.
In JPA a value object becomes an @Embeddable; Hibernate 6.2+ supports records as embeddables.
Sign up to mark studied questions and save your progress.