Entities and value objects
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
model identity versus value in Java.
Planned topics
- An entity has an identity that persists as its attributes change:
OrderwithOrderId. - A value object has no identity; equal values are interchangeable:
Money,Address. It is immutable. - Java records fit value objects well and validate in the compact constructor.
- Entity equality is by ID; value equality is by all fields.
- Prefer value objects over primitives (
Moneyinstead ofBigDecimalplus a currency string).
Draft outline details
Demonstration
public record Money(BigDecimal amount, Currency currency) {
public Money {
if (amount.signum() < 0) throw new IllegalArgumentException("negative");
}
public Money plus(Money o) { /* same currency check */ return new Money(amount.add(o.amount), currency); }
}Check your understanding
Which one is Money, entity or value object?
Show answer
Value object.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.