Video in progress

Strong Middle 🧱 OOP and SOLID

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, do items = List.copyOf(items); in the compact constructor, otherwise it can be changed from outside;
  • in a record with a BigDecimal component, equals also compares the scale: 1.0 and 1.00 are not equal. Normalize with setScale in the constructor;
  • a record's accessors (from()) are public to everyone: if you need hidden state, write a plain final class.

In JPA a value object becomes an @Embeddable; Hibernate 6.2+ supports records as embeddables.