Glossary

Immutability

An immutable object is one whose state cannot be changed after creation. Instead of mutation, a new object is returned with updated values. This eliminates an entire class of bugs caused by unexpected mutations.

Benefits

Example (Value Object)

class Money {
  public function __construct(
    public readonly int $amount,
    public readonly string $currency
  ) {}

  public function add(Money $other): self {
    return new self($this->amount + $other->amount, $this->currency);
  }
}

In JavaScript

const, Object.freeze(), spread operator {...obj, key: newVal}. Libraries: Immer, Immutable.js.