Immutable Objects

Why is immutability great?

  • Avoids sneaky state-related bugs. Recently saw a bug at work where a single array reference was being used my multiple objects and the mutation of this array led to a very surprising bug.
  • Encourages testability. Immutable objects lead you to write pure functions which are always easier to test than impure functions. Think "pit of success".
  • Concurrency. Much easier to do concurrency with immutable objects.

See Effective Java on how to make classes immutable.

Typescript - a way to almost make classes immutable through readonly modifier & conditional types.

Boundaries by Gary Bernhardt

FP vs OOP: Choose Two by Brian Goetz


views