intermediate

Entities

Model objects with identity and lifecycle when behavior must preserve invariants across state changes.

Entities are domain objects defined by identity that persists across state changes—users, orders, accounts. They encapsulate invariants and lifecycle transitions instead of exposing mutable bags of fields. Identity equality differs from value equality; two orders with same data but different IDs are not interchangeable.

On interviews: model an order entity with status transitions. Explain why not every database row deserves rich entity behavior.

Common pitfalls: entities without invariant enforcement; identity compared by attributes incorrectly; god entities knowing about HTTP or SQL.

The trade-off is flexibility versus complexity—know when the simpler path is enough.

Checklist:

  • Identity field stable across updates.
  • Behavior methods preserve invariants.
  • Equality based on identity, not all fields.
  • Persistence mapping separate from entity API.