Item 45 - Minimize the scope of local variables

From Effective Java 2/e by Joshua Bloch


  • Increase the readability
  • Increate the maintainability
  • 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
  • Nearly every local variable declaration should contain an initializer
  • Loops present a special opportunity to minimize the scope of variables (prefer for loops to while loops)

    // Preferred idiom for iterating over a collection
    for (Element e : c) {
    // No for-each loop or generics before release 1.5
    for (Iterator i = c.iterator(); i.hasNext(); ) {
  • Keep methods small and focused

Posted by The Finest Artist