Skip to content

Latest commit

 

History

History
92 lines (50 loc) · 2.41 KB

File metadata and controls

92 lines (50 loc) · 2.41 KB

Code Smell 86 - Mutable Const Arrays

Code Smell 86 - Mutable Const Arrays

Const declares something to be constant. Can it mutate?

TL;DR: Don't rely on languages cheating about directives.

Problems

  • Unexpected side effects

  • Accidental complexity

Solutions

  1. Use better languages

  2. Use spread operator

Sample Code

Wrong

const array = [1, 2];

array.push(3)

// array => [1, 2, 3]
// Wasn't it constant ?
// constant != immutable ?

Right

const array = [1, 2];

const newArray = [...array, 3]

// array => [1, 2] Didn't mutate
// newArray = [1, 2, 3]

Detection

Since this is a "language feature", we can explicitly forbid it.

Tags

  • Mutability

  • JavaScript

Conclusion

We should always favor immutability on our designs and take extra care with side effects.

Relations

Code Smell 116 - Variables Declared With 'var'

Code Smell 127 - Mutable Constants

More Info

The Evil Power of Mutants

Credits

Photo by Zorik D on Unsplash

Twitter


Correctness is clearly the prime quality. If a system does not do what it is supposed to do, then everything else about it matters little.

Bertrand Meyer

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code