Global scope is easy or a nightmare, or both
TL;DR: Avoid side effects on your code.
Problems
Coupling
Least Astonishment Principle violation
Solutions
- Favor referential transparency
Context
Referential transparency always produces the same output for a given input and does not have any side effects, such as modifying global variables or performing I/O operations.
A function or expression is referentially transparent if it can be replaced with its evaluated result without changing the behavior of the program.
This property allows for easier reasoning about the behavior of a program and enables optimizations such as caching and memorization.
Functions are treated as mathematical expressions that map inputs to outputs.
Sample Code
Wrong
let counter = 0;
function incrementCounter(value: number): void {
// Two side effects
counter += value;
// it modifies the global variable counter
console.log(`Counter is now ${counter}`);
// it logs a message to the console.
}
Right
function incrementCounter(counter: number, value: number): number {
return counter + value;
// Not too efficient
}
Detection
[X] Automatic
Most linterns can warn you when accessing the global state or Functions and create side effects.
Tags
- Global
Conclusion
Functional Programming is amazing and can teach us a lot about how to write clean code.
We need to understand its pillars.
Relations
Disclaimer
Code Smells are my opinion.
Credits
Photo by Daan Mooij on Unsplash
The most effective debugging tool is still careful thought, coupled with judiciously placed print statements.
Brian W. Kernighan
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.