Domain-Driven Design (50 Qs)•Part 1: Basic & Foundational Concepts (Junior / Entry-Level)
What is the difference between an Entity and a Value Object?
junior LevelCode Exampledomain-driven-designBasic
In Simple Words: The most fundamental distinction in Tactical DDD:
- Entity: Defined by its persistent Identity (ID), not by its attributes. Two entities with identical attributes are different objects if their IDs differ (e.g. two
Customerobjects named "John Smith" born on the same day). Entities are mutable over time. - Value Object: Defined entirely by the combination of its attributes, with NO identity. Value objects are strictly Immutable:
- Example:
Money(amount: 50, currency: "USD")orAddress(street, zip). - Two
Moneyobjects with the same amount and currency are 100% equal! To modify money, you create a new Value Object (money.add(otherMoney)).
- Example:
typescript
// Value Object: Immutable with Value Equality:
class Money {
constructor(public readonly amount: number, public readonly currency: string) {
if (amount < 0) throw new Error("Amount cannot be negative");
}
equals(other: Money): boolean {
return this.amount === other.amount && this.currency === other.currency;
}
}