Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 28, 2023 02:56 am GMT

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.}

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

This article is part of the CodeSmell Series.


Original Link: https://dev.to/mcsee/code-smell-209-side-effects-13l8

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To