ARC-38Required
Pass state in instead of sharing globals
Never share changeable data through globals, singletons or module-level variables when it changes how code behaves. Pass state in, and return new state out.
How to do it
Keep settings in one object built at startup and passed to the code that needs it. Make shared values constant. Replace singletons with one instance created at startup and injected. A module-level cache of pure results is allowed, such as memoised formatters or ETags of fixed files. It only saves work, so it never changes an answer. Return new state instead of changing it, as Make data objects immutable says.
Examples
Python example
# Bad: any function can change it, and tests leak into each other
current_currency = "EUR"
def price(amount):
return f"{amount} {current_currency}"
# Good: the value is passed in
def price(amount: Decimal, currency: Currency) -> str:
return f"{amount} {currency.code}"
TypeScript example
// Bad
let currentCurrency = 'EUR';
const price = (amount: number) => `${amount} ${currentCurrency}`;
// Good
const price = (amount: number, currency: Currency) => `${amount} ${currency.code}`;
How to check
Tests run in random order and still pass, for example with Jest --randomize, pytest-randomly or PHPUnit --order-by=random. Pylint global-statement flags writes to globals. In JavaScript, a grep fails let or var at the start of a line, which marks a module-level variable.
Sources
- CWE-1108 Excessive Reliance on Global Variables
- .NET architectural principles on explicit dependencies
Related rules
- ARC-54 Make data objects immutable in Clean code and architecture
- ARC-40 Guard state that concurrent code shares in Clean code and architecture
- TST-57 Test both states of every live flag in Testing
- TST-27 Find hidden order dependencies in Testing
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/architecture/coupling/no-global-state">Agent Wranglers clean code and architecture playbook</a>. In code you write, add a comment next to it with the same link.