Skip to content
javahacks.dev
Architecture

Value Objects Java Design for Money Time and Identifiers

Model money, time ranges and identifiers as value objects in Java with records, validation in the constructor, immutability and equality by value.

6 min read
Summarize in AI
Flat illustration of a controller, a service and a repository stacked above a database, with the OpenJDK, Spring Boot, PostgreSQL, Hibernate and Swagger logos.

A long customerId and a long orderId are both numbers, and the compiler will happily let you swap them. A double price loses cents the first time you add three of them. A pair of LocalDate parameters says nothing about which is the start. Value objects give such values a meaning and a set of rules, so the compiler and the constructor catch mistakes that tests would otherwise have to. Java's records make them cheap to write. This post covers identifiers, money and date ranges, then persistence and when not to bother.

What makes something a value object

A value object has no identity. It is defined entirely by its values: two Money objects with the same amount and currency are the same money, and there is no sense in asking which one you hold. It is immutable, so it can be shared freely and used as a map key, and it validates itself on creation, so an invalid instance cannot exist. Entities are the opposite, with an identity that persists while their fields change, and they are compared by id.

Identifiers

java
public record OrderId(long value) {
    public OrderId {
        if (value <= 0) throw new IllegalArgumentException("order id must be positive");
    }
    @Override public String toString() { return "order-" + value; }
}

public record CustomerId(long value) {
    public CustomerId {
        if (value <= 0) throw new IllegalArgumentException("customer id must be positive");
    }
}
java
void assign(OrderId order, CustomerId customer) { ... }

assign(new CustomerId(7), new OrderId(42));       // compile error: arguments swapped

The compact constructor validates every instance, so an invalid id never exists. Method signatures now say what they take, which removes a class of bug that code review rarely catches: two arguments of the same primitive type in the wrong order. The same discipline as the status types in rich domain models applies here.

Money

java
public record Money(BigDecimal amount, Currency currency) {

    public Money {
        Objects.requireNonNull(amount);
        Objects.requireNonNull(currency);
        amount = amount.setScale(currency.getDefaultFractionDigits(), RoundingMode.HALF_EVEN);
    }

    public static Money of(String amount, String currency) {
        return new Money(new BigDecimal(amount), Currency.getInstance(currency));
    }

    public Money plus(Money other) {
        requireSameCurrency(other);
        return new Money(amount.add(other.amount), currency);
    }

    public Money times(int quantity) {
        return new Money(amount.multiply(BigDecimal.valueOf(quantity)), currency);
    }

    public boolean isNegative() { return amount.signum() < 0; }

    private void requireSameCurrency(Money other) {
        if (!currency.equals(other.currency)) throw new IllegalArgumentException("currency mismatch");
    }
}

Three decisions are in those few lines. BigDecimal avoids the binary rounding of double, where 0.1 + 0.2 is 0.30000000000000004. The compact constructor normalises the scale to the currency's own number of decimals, so Money.of("10", "EUR") and Money.of("10.00", "EUR") are equal. That matters because BigDecimal.equals compares scale as well as value, and 10 is not equal to 10.00 under it. And adding amounts in different currencies is an error, not a silent sum. Choose the rounding mode your business needs, with banker's rounding as the usual choice in accounting, and apply it in one place.

Libraries such as JavaMoney (JSR 354) provide a fuller model with conversion and formatting. For many services a small record like the one above is all that is needed, and it has no dependencies.

Time ranges

java
public record DateRange(LocalDate start, LocalDate end) {

    public DateRange {
        if (end.isBefore(start)) throw new IllegalArgumentException("end before start");
    }

    public boolean contains(LocalDate date) {
        return !date.isBefore(start) && date.isBefore(end);
    }

    public boolean overlaps(DateRange other) {
        return start.isBefore(other.end) && other.start.isBefore(end);
    }

    public long days() { return ChronoUnit.DAYS.between(start, end); }
}

State the convention in the type: this range is half open, so the start is included and the end is excluded. That removes the off-by-one question from every caller, and two adjacent ranges that share a boundary do not overlap. Test the edges, since that is where the bugs are: a date equal to the start, a date equal to the end, ranges that touch, and a range of zero days. Use Instant for a moment in time and LocalDate for a calendar date; the choice and its persistence are covered in Hibernate time mapping.

Why records fit

A record is final, its fields are final, and the compiler generates equals, hashCode and toString from its components. That is close to the definition of a value object. Two limits are worth knowing. The canonical constructor is public, so validation has to live in the compact constructor and cannot be bypassed by a factory only. And you cannot hide the representation completely, because the components are part of the record's public shape. For most domain values neither matters. The language features are covered in the modern Java guide.

Persistence and JSON

Hibernate can map a record as an embeddable:

java
@Embeddable
public record Money(
        @Column(name = "amount") BigDecimal amount,
        @Column(name = "currency", length = 3) String currencyCode) { }

That version keeps the currency as its code, since a column holds text. For single-value types such as OrderId, an AttributeConverter stores the long in one column; see embeddable value objects. Jackson serialises a one-component record as an object by default, so OrderId would appear as {"value": 42}. Add @JsonValue on the accessor and @JsonCreator on the constructor when you want it to travel as a plain number or string. A Spring Converter<String, OrderId> lets a path variable bind directly to the type.

Testing a value object

Value objects are the easiest code to test and the most worthwhile, because everything else leans on them. Test the rules in the constructor, the equality, and the operations at their edges.

java
@Test
void tenAndTenPointZeroZeroAreTheSameMoney() {
    assertEquals(Money.of("10", "EUR"), Money.of("10.00", "EUR"));
}

@Test
void addingDifferentCurrenciesFails() {
    assertThrows(IllegalArgumentException.class,
            () -> Money.of("1", "EUR").plus(Money.of("1", "USD")));
}

@Test
void roundsHalfEvenToTheCurrencyScale() {
    assertEquals(Money.of("0.12", "EUR"), new Money(new BigDecimal("0.125"), Currency.getInstance("EUR")));
}

The third test pins down the rounding rule, which is the thing most likely to be changed by accident and most expensive to get wrong. Add a test for each edge a bug report has ever mentioned. A set of ten such tests runs in a few milliseconds and documents the contract better than any comment.

Moving an existing code base toward value objects

Do not rewrite everything. Pick the identifier or amount that has caused a bug, usually an id passed in the wrong order or a price rounded twice, and introduce a type for that one. Change the method signatures at the boundary first, convert at the edges where raw values arrive from a database or a request, and let the compiler list every call site that needs updating. The change is large in lines and small in risk, because the compiler checks nearly all of it. Do the next type only when the first has paid for itself. Teams that wrap a dozen types in one pull request tend to abandon the idea after the review, while teams that do one a week finish within a quarter and never look back.

Resist adding behaviour that does not belong. A Money type should know how to add, compare and format. It should not know about tax rules or discounts, which belong in domain services that use it.

When not to wrap

Do not wrap every String. Wrap values that have rules (an email address, an ISO code), values that are easily confused (identifiers), and values that carry units (money, durations, distances). Wrapping a free-text name that has no rules adds a class and no safety. Each wrapper is an extra object per instance, which only matters for collections with millions of elements, where the footprint described in object layout becomes visible.

Where this stops

Entities with identity and a life cycle are different, and they are compared by id, not by value. Future Java versions may make wrapper types free of overhead through value classes under Project Valhalla, which would remove the one remaining cost. The concept is described in Fowler's note on value objects, and JEP 395 defines records.

Also inJava Core
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.