Chapter 5. Mutability
No person ever steps in the same river twice. For it’s not the same river and he’s not the same person.
Heraclitus
5.0 Introduction
Since the beginning of the stored-program concept, you have learned that software is programs plus data. It is clear that without data there is no software. In object-oriented programming you build models that evolve over time, emulating the knowledge you learn by observing the reality you are representing. However, you manipulate and sometimes abuse those changes uncontrollably, violating the only important design principle by generating incomplete (and therefore invalid) representations and propagating the ripple effect with your changes.
In the functional paradigm, this is elegantly addressed by forbidding mutations. You can be (a little) less drastic. Being true to the bijection in your computable model as defined in Chapter 2, you should be able to distinguish when an object changes in terms of the accidental and forbid all essential changes (because they would violate the bijection principle).
Immutability is a strict property in functional programming, and many object-oriented languages are developing tools to favor it. Nevertheless, many of them have leftovers in the core classes like Date
or String
. Objects should know how to defend themselves against invalid representations. They are the powers against mutants.
Let’s review the Date
class in the most widely used languages in today’s industry:
- Go
Date
is a struct. ...
Get Clean Code Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.