Code Smell 116 — Variables Declared With ‘var’

TL;DR: Choose wisely your variable names, scope, and mutability.

Problems

Solutions

1. Declare const all variables unless you need to change them

Context

Most languages don’t need variable declarations.

Some other languages allow us to state mutability.

We should be strict and explicit with our declarations.

Sample Code

Wrong

Right

Detection

[X] Manual

With mutation testing by forcing a ‘const’ declaration, we can check if a value remains constant and be more declarative by explicitly enforcing it.

Tags

  • Mutability
  • Javascript

Conclusion

Readability is always very important.

We need to explicitly state our intentions and usages.

Relations

More Info

Just as it is a good practice to make all fields private unless they need greater visibility, it is a good practice to make all fields final unless they need to be mutable.

Brian Goetz

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store