
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
Use better languages.
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 favour immutability on our designs and take extra care with side effects.
More Info
Credits
Thank you, Oliver Jumpertz for this tip.
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
This article is part of the CodeSmell Series.
About the author
I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
Comments
Join the discussionNo comments yet. Be the first to comment.
Code Smells
In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.





