Item 45: Minimize the scope of local variables

1493 단어 scope
1.  By minimizing the scope of local variables, you increase the readability and maintainability of your code and reduce the likelihood of error.
 
2.  The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used.
 
3.  The scope of a local variable extends from the point where it is declared to the end of the enclosing block.
 
4.  Nearly every local variable declaration should contain an initializer.
 
5.  If a variable is initialized by a method that throws a checked exception, it must be initialized inside a try block. If the value must be used outside of the try block, then it must be declared before the try block, where it cannot yet be “sensibly initialized”.
 
6.  Prefer for loops to while loops, assuming the contents of the loop variable aren’t needed after the loop terminates. There’s no incentive to use different variable names in the two for loops. The loops are completely independent, so there’s no harm in reusing the element (or iterator) variable name.
 
7.  You should use the following idiom if the loop test involves a method invocation that is guaranteed to return the same result on each iteration:
for (int i = 0, n = expensiveComputation(); i < n; i++) {
    doSomething(i);
}

 
8.  A final technique to minimize the scope of local variables is to keep methods small and focused.

좋은 웹페이지 즐겨찾기