Skip to content
Guest
Learn OOP · Course Syllabus Show lessons
Architecture & Testing · 8 min read · Beginner

Immutability & Value Objects

Eliminate shared-mutation bugs by modeling concepts like Money, Email, and DateRange as immutable Value Objects.

What you'll learn

  • Distinguish Entities (identity-based) from Value Objects (value-based)
  • Return new instances on operations instead of mutating in place
  • Enforce domain validation at construction time so invalid states cannot exist

A Value Object (like Money(10, "USD") or Email("a@b.com")) has no unique ID; two value objects are equal if their values match. Making value objects immutable eliminates subtle side-effect bugs where changing a price in one service silently mutates another object.

Fill-in-the-Blank Exercise

Immutable Money Addition

Return a brand-new Money object instead of mutating this.amount.

add(other) {
if (this.currency !== other.currency) throw new Error("Mismatch");
return  Money(this.amount + other., this.currency);
}

Live OOP Playground

Immutable Money Value Object
Live Result
Console Output

No console output yet. Try calling console.log(...) in JS.

Check Your Understanding

Score: 0 / 1

1. How do two immutable Value Objects like Money(10, 'USD') determine equality?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind