Patterncore
Global Data
Also called global variable, global state, global mutable state.
A code smell: data that any part of the program can read and change, so a reader cannot find which code changed it, and a change in one place breaks code in another.
- Family
- code-smell
- Intent
- Find the data that any code can change, and put it behind a small interface that controls and shows each change, or pass it to the code that needs it.
- Refactorings
- Encapsulate variable
Intent
Find the data that any code in the program can change, and limit who can change it. The first step is to put the data behind functions, so that each change goes through one place that a reader can find. The next step is often to pass the data as a parameter to the code that needs it.
Problem
A global variable is visible to the whole program. Wikipedia defines it as "a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed."1 Any function can read it, and in most languages any function can write it.
The problem is the write. When a global value is wrong, the cause can be in any function of the program, and nothing in the code shows which one. Refactoring gives this as the reason for the smell: the data can be changed from anywhere in the code base, and there is no mechanism to find the code that changed it.2
The forces are these:
- Global data is convenient. A value that many functions need, such as a configuration setting, a logger or a cache, is available without a parameter in each signature.
- A function that reads a global has an input that is not in its signature. Two calls with the same arguments can give different results, and a test must set the global before it calls the function and reset it after.
- Tests that share a global can pass alone and fail together, because one test leaves the global in a state that the next one does not expect.
- Wikipedia notes that "Without proper locking (such as with a mutex), code using global variables will not be thread-safe except for read only values in protected memory."1 Two threads that write the same global without a lock make a data race.
The smell includes more than variables at the top level of a file. Refactoring also names class variables and singletons as forms of global data.2 A static field that any class can set is global data with a class name in front of it.
The first edition of Refactoring has no smell for global data. The second edition adds it to the list.32
Solution
Refactoring names one main refactoring: Encapsulate Variable.2 Put the data behind a function to read it and a function to write it, and make the variable itself private to a module or a class. In the online catalogue, this refactoring also has the names Encapsulate Field and Self-Encapsulate Field.4
The wrapper does not make the data less global. It gives the data a door:
- Each write goes through one function, so a search for that function finds all the code that changes the data.
- The write function can check the value, and reject a value that is out of range.
- The write function can be removed, or kept private, once it is clear that only the module itself needs to write.
Then reduce the scope. A function that reads the global can take the value as a parameter. Code that sets up the program can pass the values down, which is the idea of Dependency injection. A value that never changes after start-up can be made a constant, and constant global data is much less of a problem than mutable global data. Refactoring makes the same point about the dose: a small amount of global data can be managed, and a large amount is hard to work with.2
Example
The price function reads a global tax rate. The export function sets the rate to zero for a tax-free order, and does not put it back. After one export, every domestic price is wrong.
import assert from "node:assert/strict";
// Before: any code can write the global.
let taxRate = 0.2;
function priceBefore(cents) {
return Math.round(cents * (1 + taxRate));
}
function exportOrderBefore(cents) {
taxRate = 0; // the export is tax free
return priceBefore(cents); // and nothing puts the rate back
}
assert.equal(priceBefore(1000), 1200);
assert.equal(exportOrderBefore(1000), 1000);
assert.equal(priceBefore(1000), 1000); // the domestic price has changed
console.log("before: the export changed the domestic price");
// After: the rate is encapsulated, and the export passes its own rate.
const taxSettings = (() => {
let rate = 0.2;
return {
rate: () => rate,
setRate(r) {
if (!(r >= 0 && r <= 1)) throw new RangeError(`tax rate ${r}`);
rate = r;
},
};
})();
function price(cents, rate = taxSettings.rate()) {
return Math.round(cents * (1 + rate));
}
const exportOrder = (cents) => price(cents, 0);
assert.equal(price(1000), 1200);
assert.equal(exportOrder(1000), 1000);
assert.equal(price(1000), 1200);
assert.throws(() => taxSettings.setRate(20), RangeError);
console.log("after: tests pass");
before: the export changed the domestic price
after: tests pass
The "after" version has two changes. The rate lives in a closure, and the only way to change it is setRate, which also rejects a rate of 20 (a percentage passed where a fraction is expected). The export no longer changes shared data at all: it passes its rate as an argument. The global is now read in one place, the default value of the parameter.
| Language | What the example shows |
|---|---|
| JavaScript | a closure as the private home of the rate, and a parameter with a default |
| Python | the global statement in the "before" version, and a small class in the "after" version |
| Java | a public static field, then a private static field with a getter and a checked setter |
| Go | an exported package variable, then an unexported one with accessor functions |
# Before: any code can write the global.
tax_rate = 0.2
def price_before(cents):
return round(cents * (1 + tax_rate))
def export_order_before(cents):
global tax_rate
tax_rate = 0 # the export is tax free
return price_before(cents) # and nothing puts the rate back
assert price_before(1000) == 1200
assert export_order_before(1000) == 1000
assert price_before(1000) == 1000 # the domestic price has changed
print("before: the export changed the domestic price")
# After: the rate is encapsulated, and the export passes its own rate.
class TaxSettings:
def __init__(self, rate):
self._rate = rate
@property
def rate(self):
return self._rate
@rate.setter
def rate(self, value):
if not 0 <= value <= 1:
raise ValueError(f"tax rate {value}")
self._rate = value
settings = TaxSettings(0.2)
def price(cents, rate=None):
if rate is None:
rate = settings.rate
return round(cents * (1 + rate))
def export_order(cents):
return price(cents, rate=0)
assert price(1000) == 1200
assert export_order(1000) == 1000
assert price(1000) == 1200
try:
settings.rate = 20
except ValueError:
print("after: tests pass")
else:
raise AssertionError("rate of 20 accepted")
before: the export changed the domestic price
after: tests pass
export_order_beforeneedsglobal tax_rate. Without it, the assignment would make a local variable, and the global would not change. Thegloballine is the one place where the code says that it writes shared data, and Pylint reports it asglobal-statement.- The default of
rateisNone, and the function readssettings.rateat call time. A default ofsettings.ratein thedefline would be read once, when the function is defined, and later changes to the setting would not be seen. - The leading underscore in
_rateis a convention, not a rule that Python enforces. The property is the door that the rest of the code is expected to use.
public class Main {
// Before: any code can write the public static field.
static class Globals {
public static double taxRate = 0.2;
}
static long priceBefore(long cents) { return Math.round(cents * (1 + Globals.taxRate)); }
static long exportOrderBefore(long cents) {
Globals.taxRate = 0; // the export is tax free
return priceBefore(cents); // and nothing puts the rate back
}
// After: the field is private, and the setter checks the value.
static final class TaxSettings {
private static double rate = 0.2;
private TaxSettings() {}
static double rate() { return rate; }
static void setRate(double r) {
if (!(r >= 0 && r <= 1)) throw new IllegalArgumentException("tax rate " + r);
rate = r;
}
}
static long price(long cents, double rate) { return Math.round(cents * (1 + rate)); }
static long price(long cents) { return price(cents, TaxSettings.rate()); }
static long exportOrder(long cents) { return price(cents, 0); }
static void check(boolean ok, String what) {
if (!ok) throw new AssertionError(what);
}
public static void main(String[] args) {
check(priceBefore(1000) == 1200, "before");
check(exportOrderBefore(1000) == 1000, "export");
check(priceBefore(1000) == 1000, "the domestic price has changed");
System.out.println("before: the export changed the domestic price");
check(price(1000) == 1200 && exportOrder(1000) == 1000 && price(1000) == 1200, "after");
try {
TaxSettings.setRate(20);
throw new AssertionError("rate of 20 accepted");
} catch (IllegalArgumentException expected) {
System.out.println("after: tests pass");
}
}
}
before: the export changed the domestic price
after: tests pass
- Java has no global variables, but a
public staticfield that is notfinalhas the same problem: any class can write it, and the field has one value for the whole program. - Java has no default parameter values, so the "after" version uses two overloads of
price. The overload without a rate is the only code that reads the setting. - In the setter,
!(r >= 0 && r <= 1)also rejectsNaN, because each comparison withNaNis false.r < 0 || r > 1would letNaNthrough.
package main
import (
"fmt"
"math"
)
// Before: an exported package variable, so any package can write it.
var TaxRate = 0.2
func priceBefore(cents int) int { return int(math.Round(float64(cents) * (1 + TaxRate))) }
func exportOrderBefore(cents int) int {
TaxRate = 0 // the export is tax free
return priceBefore(cents) // and nothing puts the rate back
}
// After: an unexported variable, with accessor functions.
var taxRate = 0.2
func Rate() float64 { return taxRate }
func SetRate(r float64) error {
if !(r >= 0 && r <= 1) {
return fmt.Errorf("tax rate %v", r)
}
taxRate = r
return nil
}
func priceWithRate(cents int, rate float64) int { return int(math.Round(float64(cents) * (1 + rate))) }
func price(cents int) int { return priceWithRate(cents, Rate()) }
func exportOrder(cents int) int { return priceWithRate(cents, 0) }
func main() {
if priceBefore(1000) != 1200 || exportOrderBefore(1000) != 1000 || priceBefore(1000) != 1000 {
panic("before")
}
fmt.Println("before: the export changed the domestic price")
if price(1000) != 1200 || exportOrder(1000) != 1000 || price(1000) != 1200 || SetRate(20) == nil {
panic("after")
}
fmt.Println("after: tests pass")
}
before: the export changed the domestic price
after: tests pass
- In Go, a package-level name that starts with a capital letter is exported.
TaxRatecan be written by any package that imports this one.taxRatecan be written only by code in the same package, and other packages must callSetRate. SetRatereturns anerrorin place of a panic, which is the usual Go way to report a bad argument that the caller can handle.- The linter
gochecknoglobalsreports both versions, because each has a package-levelvar. Encapsulation is the first step. Passing the rate topriceWithRateis the step that removes the hidden input.
Consequences
Encapsulation makes each write visible, and makes it possible to check the values. It does not remove the hidden input: a function that calls taxSettings.rate() still depends on global state. Only passing the value as a parameter removes that.
Passing values has a cost. A setting that is needed deep in the call tree must be passed through each function above it, and the signatures grow. That is the trade-off with Long Parameter List. A parameter object or a context object that holds the settings keeps the lists short.
Languages and tools push in the same direction:
- Python requires the
globalstatement to assign to a global from inside a function. The Python FAQ explains why: "requiring global for assigned variables provides a bar against unintended side-effects."5 The language reference states the rule: "It would be impossible to assign to a global variable without global".6 Pylint reportsglobal-statement(W0603) "when you use the "global" statement to update a global variable".7 - In JavaScript, ES modules give each file its own scope. The ESLint rule
no-implicit-globalsis for browser scripts, where top-levelvarandfunctiondeclarations become global variables on thewindowobject.8 - golangci-lint has the linter
gochecknoglobals, which checks "that no global variables exist".9 - Rust requires an
unsafeblock to read or write astatic mut. The Rust Reference calls mutable statics "a very large source of race conditions or other bugs".10
How to fix it
- A global variable with many writers: Encapsulate Variable. Then search for the calls to the write function, and move each write to the module that owns the data.2
- A function that reads a global: pass the value as a parameter, and let the caller decide where it comes from.
- A setting that never changes after start-up: make it a constant, or a read-only value that is set once.
- A singleton that many classes reach for: pass the instance to the classes that need it. See Dependency injection.
- Shared data between threads: protect it with a lock, or replace it with a message between the threads. See Data race.
Variants and related patterns
Mutable Data. The general smell: data that changes, in any scope. Global data is the worst case, because its scope is the whole program. See Mutable Data.
Singleton. A class with one instance and a global access point. The pattern gives a name and a type to global data, but the data is still reachable from anywhere. See Singleton pattern.
Side effects. A function that writes a global has a Side effect that its signature does not show.
Lexical scope. The rule that a name is visible only in the block that declares it. Each step from global to module to function scope reduces the code that can reach a value. See Lexical scope.
References
- Wikipedia, Global variable, revision 1383619991, the introduction and Use
- Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Global Data
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, the list of 22 smells, which has no entry for global data
- Martin Fowler, Catalog of Refactorings, the card Encapsulate Variable, with the aliases Encapsulate Field and Self-Encapsulate Field
- Python Programming FAQ, Python 3.14, What are the rules for local and global variables in Python?
- The Python Language Reference, Simple statements, Python 3.14, 7.12 The global statement
- Pylint documentation, global-statement / W0603, Description
- ESLint documentation, Rules, no-implicit-globals, Rule Details
- golangci-lint documentation, Linters, gochecknoglobals
- The Rust Reference, Static items, Mutable statics, items.static.mut.intro and items.static.mut.safety
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 68AC90 Edit this page History Report an error Markdown