Code Quality – Should Variables Be Reused?

code-qualitycoding-stylevariables

Should I reuse variables?

I know that many best practices say you should not do it, however, later, when different developer is debugging the code and have 3 variables that look alike and the only difference is that they are created in different places in the code, he might be confused. Unit-testing is a great example of this.

However, I do know that best practices are most of the time against it.
For example they say not to "override" method parameters.

Best practices are even are against nulling the previous variables (in Java there is Sonar that gives a warning when you assign null to variable, that you don't need to do it to call the garbage collector since Java 6. You can't always control which warnings are turned off; most of the time the default is on.)

Best Answer

Your problem appears only when your methods are long and are doing multiple tasks in a sequence. This makes the code harder to understand (and thus maintain) per se. Reusing variables adds on top of this an extra element of risk, making the code even harder to follow and more error prone.

IMO best practice is to use short enough methods which do one thing only, eliminating the whole problem.

Related Topic