Skip to content
Ameen Abozaid
Planned lessonMID-060-L03

Entities and value objects

  • Lesson 3 of 7
  • Mid-level
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: Order with OrderId.
  • 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 (Money instead of BigDecimal plus a currency string).
Draft outline details

Demonstration

java
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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.