Entity

Entity

An entity is a domain object whose identity matters across its lifetime. Two entities with identical fields but different IDs are different. The same entity with different fields over time is still the same.

Defining trait

Python shape

from dataclasses import dataclass, field
from uuid import UUID, uuid4

@dataclass
class User:
    id: UUID = field(default_factory=uuid4)
    email: str = ""
    is_active: bool = True

    def __eq__(self, other):
        return isinstance(other, User) and self.id == other.id

    def __hash__(self):
        return hash(self.id)

    def deactivate(self) -> None:
        if not self.is_active:
            raise ValueError("already deactivated")
        self.is_active = False

Three rules:

  1. Equality + hash by ID alone. Field comparison would treat updated-but-same-entity as different.
  2. Mutators are methods, not raw assignment. user.deactivate(), not user.is_active = False. Methods enforce invariants.
  3. No public setters on raw fields. Every state change goes through a named operation.

Anti-patterns

Entity vs Value Object

Entity Value Object
Defining trait Identity Value
Equality By ID By all fields
Mutable Yes No
Lifecycle Created -> changed -> archived Created -> discarded
Example User, Order, Loan Email, Money, ISBN

When to choose Entity

Three signals:

  1. You'll need to find it later by ID.
  2. It has a non-trivial lifecycle — states it transitions through.
  3. Two with identical fields are still different things.

If none of those apply, it's probably a Value Object.