Entities
An Entity is a domain object that has a unique identity that persists over time, even if its attributes change.
Example:
- A
User
entity has a unique ID. - Even if the user’s email or name changes, it’s still the same entity.
Real-life Analogy
Section titled “Real-life Analogy”Think of a person:
- Even if they change their name or address — they remain the same individual.
In contrast, a Value Object like an email or address is defined only by its value, not by any persistent identity.
Example in DomusJS
Section titled “Example in DomusJS”import { Entity, UniqueEntityId } from '@domusjs/core';import { Email } from './value-objects/email.vo';
interface UserProps { email: Email; password: string;}
export class User extends Entity<UserProps> { constructor(props: UserProps, id?: UniqueEntityId) { super(props, id); }
get email(): Email { return this.props.email; }
get password(): string { return this.props.password; }
changePassword(newPassword: string) { this.props.password = newPassword; }}
✅ This ensures:
- The user is always identified by their
id
. - You can change attributes like
password
without changing the entity itself.
Benefits of Entities
Section titled “Benefits of Entities”- Unique identity → track objects over time.
- Encapsulate behavior → entities can have methods, not just data.
- Rich domain modeling → combine with value objects to express complex logic.
Common Mistakes
Section titled “Common Mistakes”- Avoid using entities where a value object is sufficient — adding unnecessary IDs increases complexity.
- Keep entity identity immutable once set — changing the
id
undermines its role.
Relationship Between Entities and Value Objects
Section titled “Relationship Between Entities and Value Objects”- Entities contain or use value objects.
- Example: a
User
entity has anEmail
value object, anAddress
value object, etc.
This combination leads to a rich, expressive, and maintainable domain model.