DEV Community

Cover image for Code Smell 209 - Side Effects
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

2

Code Smell 209 - Side Effects

Global scope is easy or a nightmare, or both

TL;DR: Avoid side effects on your code.

Problems

  • Coupling

  • Least Astonishment Principle violation

Solutions

  1. 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.
}
Enter fullscreen mode Exit fullscreen mode

Right

function incrementCounter(counter: number, value: number): number {  
  return counter + value; 
  // Not too efficient  
}

Enter fullscreen mode Exit fullscreen mode

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


This article is part of the CodeSmell Series.

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay