Mutable Data — Code Smells Catalog Skip to content

Mutable Data

Functional Abusers Data Code Smell Between Class

Data that anything can modify at any time. The bug reproduces instantly in production and vanishes in your debugger — by the time you pause execution, something else already changed the value.

2 min read 1 source

Overview

Mutable data are harmful because they can unexpectedly fail other parts of the code. It is a rich source of bugs that are hard to spot because they can occur under rare conditions. Fowler says that this is a significant factor which contributed to the rise of the new programming school, functional programming, in which one of the principles is that the data should never change. While these languages are still relatively small, he states that developers should not ignore the advantages of immutable data [1]. It is hard to reason about these variables, especially when they have several reassignments.

Causation

In Object-Oriented Programming, the immutability of objects was not addressed audibly, if at all, in the context of something desirable. This is a relatively new concept.

Problems

Error-Prone

Mutable Data is a rich source of hidden bugs that might be spotted only when specific rare conditions are met.

🧠
Hard to Understand

Data that might change at any moment is hard to reason about without excluding every corner case.

Example

1@dataclass
2class Foo:
3    name: str
4    value: float
5    premium: bool
6
7# foo object instance will be passed around and modified
PYTHON

Refactoring

  • Remove Setting Method
  • Choose Proper Access Control
  • Separate Query from Modifier
  • Change Reference to Value
  • Replace Derived Variable with Query
  • Extract Method
  • Encapsulate Variable
  • Combine Methods into Class

Sources

Browse All 56 Smells