Code smell | Side Effects

Code smell | Side Effects

November 26, 2023

codequality
refactorit
code-smell

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)

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)

Benefits


Thanks for reading me 😊