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
- Identity outlives state.
- A
Userwho changes email is still the same user. - Two
Userrecords with the same email but different IDs are two different users.
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:
- Equality + hash by ID alone. Field comparison would treat updated-but-same-entity as different.
- Mutators are methods, not raw assignment.
user.deactivate(), notuser.is_active = False. Methods enforce invariants. - No public setters on raw fields. Every state change goes through a named operation.
Anti-patterns
- Anemic entity. A class that's just fields + getters/setters. Business rules live in services that mutate it from outside. Symptom:
UserService.deactivate(user)instead ofuser.deactivate(). The entity becomes a struct; invariants get scattered. - Equality by value. Comparing entities by all-fields equality. A
Userafter a name change becomes "not equal" to its prior self. - Multiple identities. Treating both
idandemailas identifiers. Pick one — the rest are queryable attributes.
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:
- You'll need to find it later by ID.
- It has a non-trivial lifecycle — states it transitions through.
- Two with identical fields are still different things.
If none of those apply, it's probably a Value Object.