CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 3 of 6 · 2 min read

Value objects

Equal by content, not by identity.

A value object is an object defined by its content. Two Money objects of 500 rupees are the same value, whichever one you hold. This differs from an entity, such as a booking or an account, which has an identity that stays the same while its details change.

For a value object, equals compares content and hashCode agrees (Level 1, module 1). That lets values act as map keys and set members. In the example, fee.equals(Money.rupees(500)) is true, and so is Money.ZERO.plus(fee).equals(fee).

Values help design in three ways:

  • They give a name and a home to a concept. Money can hold the currency check once, where a bare long cannot. Passing a Money where a rupee amount is expected is also much harder to confuse with a count of hours.
  • They are safe to share. One Money.ZERO serves the whole program. EJ suggests public constants for common values and caching factories for frequent ones.
  • They make rules local. A check such as "currencies must match" sits in plus, and every caller gets it.

Java's record gives a value class with the fields, accessors, equals, hashCode and toString generated. A time slot is a good fit.

record Slot(Instant start, Instant end) {
    Slot { if (start.isAfter(end)) throw new IllegalArgumentException("start after end"); }
    Slot shiftHours(long h) {
        return new Slot(start.plusSeconds(3600 * h), end.plusSeconds(3600 * h));
    }
}

A slot from 09:00 to 10:00 shifted by two hours is a new slot from 11:00. The original still starts at 09:00. A record's fields are final, and Instant is itself immutable, so the whole slot is safe. Take care when a record holds a mutable field, such as a List or a Date, since the record alone does not make that field safe.

Value object

A value object is an immutable object that is equal to any other with the same content, and has no identity of its own.

Example: Money.rupees(500).

Check yourself: 1. How does an entity differ from a value object? 2. Why does a bare long for money lose the currency rule? 3. What is the risk of a record with a List field?