Asdfasf

Thursday, September 18, 2014

EJ-45 Minimize the Scope of Local Variables

Ref: Effective Java by Joshua Bloch

This principle is similar in nature to "Minimize the accessibility of classes and members". By minimizing the scope of local variables, you increase the readibility and maintainability of your code and reduce the likelihood of error.

The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used.

Lets demonstrate this principle with for and while loops which will show why to prefer for loops to while loops.



To see why these for loops are preferable to a while loop, consider the following code fragment, which contains two while loops and one copy-and-paste bug:


No comments: