Skip to content

Value Object

Spicy — senior dev territoryBackend

ELI5 — The Vibe Check

A value object is defined by its values, not its identity. Two $10 bills are interchangeable — you don't care which specific bill you have. Same with value objects: an Email('a@b.com') equals another Email('a@b.com'). They're immutable, simple, and carry validation logic.

Real Talk

A value object is a domain-driven design concept representing an immutable object defined by its attributes rather than a unique identity. Two value objects with the same attributes are considered equal. They encapsulate validation logic, are self-validating on creation, and are always replaced rather than modified. Common examples: Money, Email, Address, DateRange.

Show Me The Code

class Money {
  constructor(
    public readonly amount: number,
    public readonly currency: string
  ) {
    if (amount < 0) throw new Error('Amount cannot be negative');
  }

  add(other: Money): Money {
    if (this.currency !== other.currency) throw new Error('Currency mismatch');
    return new Money(this.amount + other.amount, this.currency);
  }

  equals(other: Money): boolean {
    return this.amount === other.amount && this.currency === other.currency;
  }
}

When You'll Hear This

"Money is a value object — two Money(100, 'USD') instances are equal." / "Make value objects immutable so they can be shared safely across the domain."

Made with passive-aggressive love by manoga.digital. Powered by Claude.