Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Follow publication

Code Smell 86 — Mutable Const Arrays

Photo by Zorik D on Unsplash

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

Right

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

Sign up to discover human stories that deepen your understanding of the world.

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Written by Maximiliano Contieri

I’m a senior software engineer specialized in declarative designs. S.O.L.I.D. and agile methodologies fan. Maximilianocontieri.com

Responses (1)

Write a response

Even better is to properly understand the tools the language gives you and how to use them.
* If you want shallow immutability, you use `Object.freeze()` (this can be used on arrays).
* If you want a constant reference, you use `const`.
Both of these…

--