Video in progress

What is the difference between an Entity and a Value Object in DDD?

An Entity has its own identifier and stays "the same object" even as its state changes over time (a customer, an order). A Value Object has no identifier, is defined only by its values, and is usually immutable (an amount of money, an address, a date range).

📖 Answer

Even if two customers have the same name, they are different people, since their id differs. This is an entity:

public class Customer {
    private final CustomerId id;
    private String fullName;          // can change
    // equals/hashCode by id only
}

Two "100,000 som" amounts, on the other hand, are no different from each other, and which one is which doesn't matter. This is a value object:

public record Money(BigDecimal amount, String currency) {
    public Money {
        if (amount.signum() < 0) throw new IllegalArgumentException("Manfiy summa");
    }
    public Money plus(Money other) {
        if (!currency.equals(other.currency)) throw new IllegalArgumentException("Valyuta mos emas");
        return new Money(amount.add(other.amount), currency);
    }
}

The benefit of value objects: the rules (non-negative, matching currency) live in one place. If you use Money instead of passing long amount and String currency around separately, the mistake of "adding som to dollars" becomes impossible.

To tell them apart, ask yourself: "If all the fields of two objects are equal, are they the same thing?" Yes means a value object, no means an entity.