Navs
Code Smells Catalog
Global Data

Last Revision — April 19, 2022

2 Min Read


Global Data

The Global Data is quite similar to the Middle Man code smell, but here rather than a class, the broker is the global scope in which the data is freely available to everyone. These global scope variables are undesirable because it directly causes the Hidden Dependencies code smell and a highly nasty Mutable Data code smell. Global data can be read from anywhere, and there is no easy way to discover which bit of code touches it. If the variable in the global scope is additionally mutable, then this becomes an extremally bad case of Mutable Fate over Action (data class). Fowler, in 1999 recalled that in the early days of programming, back when there were no objects, even causing the Long Parameter List code smell was preferable to the Global Data [1]. For the same reasons, a Singleton Pattern can also be problematic [2].

Problems

Hard to Test

Each Global Variable is a hidden dependency that a tester has to mock.

Hard to Reason About

Global Variables exponentially fuzz the clarity of the codebase.

Inter Component Coupling

Encapsulation Violation

Refactoring:

  • Encapsulate Variable

Exceptions

In the context of the system as a whole, some communication between modules must take place. All possibilities should be appropriately balanced so that none of the smells dominate (Global Data, Tramp Data, Message Chain, Middle Man) to make the entire codebase as clear as possible.


Sources
  • [1] - Martin Fowler, "Refactoring: Improving the Design of Existing Code" (1999)
  • [2] - Martin Fowler, "Refactoring: Improving the Design of Existing Code (3rd Edition)" (2018)