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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Preferred idiom for iterating over a collection | |
for (Element e : c){ | |
doSomething(e); | |
} |
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Iterator<Elemement> i = c.iterator(); | |
while(i.hasNext()){ | |
doSomething(i.next()); | |
} | |
.... | |
Iterator<Elemement> i2 = c2.iterator(); | |
while(i.hasNext()){ //BUG | |
doSomething(i2.next()); | |
} |
No comments:
Post a Comment