MEPX
Chapter 8 of 10All chapters

Chapter 8 of 10

State and mutation

Where object code goes wrong.

Shared references

Objects are passed by reference, so two variables can point at one object. A change through either is visible through both, which is how surprising bugs appear at a distance.

  • Copy defensively when handing out internal collections.
  • Immutable objects remove the problem entirely and are worth it for value types.

Keeping it small

The less state an object holds, the fewer combinations exist and the easier it is to test. Objects that are mostly behaviour with a little state age far better than the reverse.