DEV Community

Cover image for Code smell | Side Effects
Jesús Mejías Leiva for Product Hackers

Posted on • Originally published at blog.susomejias.dev

Code smell | Side Effects

Hello, today I am writing again and in this post I am going to introduce you to how we incur in a frequently common code smell called "Side Effects," which occurs when a function modifies an external state beyond its own scope.


Cause

Side effects arise when a function alters variables outside its scope, leading to unexpected behaviors and complicating code comprehension.


Example

let total = 0

function addToTotal(value: number): void {
  total += value
  console.log(`Total is now: ${total}`)
}

addToTotal(5)
Enter fullscreen mode Exit fullscreen mode

Solution

An effective solution is to avoid side effects by using pure functions that do not modify external states. Instead of changing global variables, the function should return a new state.

function addToTotal(currentTotal: number, value: number): number {
  const newTotal = currentTotal + value
  console.log(`Total is now: ${newTotal}`)
  return newTotal
}

let currentTotal = 0
currentTotal = addToTotal(currentTotal, 5)
Enter fullscreen mode Exit fullscreen mode

Benefits

  • Improves Readability: By eliminating side effects, the code becomes clearer and more understandable, making it easier for developers to grasp the execution flow without unexpected surprises.

  • Facilitates Maintenance: Side-effect-free functions are easier to maintain as their behavior is confined to their scope, avoiding potential conflicts with other parts of the program.

  • Reduces Unexpected Errors: By avoiding external modifications, the likelihood of subtle errors arising from unexpected changes in variable states is minimized.

  • Promotes Predictability: Functions without side effects yield consistent results, promoting code predictability and facilitating unit testing.

  • Enhances Scalability: Code that avoids side effects is more modular and adaptable, easing scalability as the system grows and evolves.


Thanks for reading me 😊

Top comments (0)