zoukankan      html  css  js  c++  java
  • Effective Java 45 Minimize the scope of local variables

    Principle

    1. The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used.
    2. Nearly every local variable declaration should contain an initializer.

      Note

      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.

    3. prefer for loops to while loops

      Advantage

      1. The loops are completely independent, so there's no harm in reusing the element (or iterator) variable name.
      2. It's much less likely that you'll make the cut-and-paste error, as there's no incentive to use different variable names in the two loops.

           

      // Preferred idiom for iterating over a collection

      for (Element e : c) {

      doSomething(e);

      }

         

      // No for-each loop or generics before release 1.5

      for (Iterator i = c.iterator(); i.hasNext(); ) {

      doSomething((Element) i.next());

      }

         

      Use this idiom below 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);

      }

         

      It has two loop variables, i and n, both of which have exactly the right scope. The second variable, n, is used

      to store the limit of the first, thus avoiding the cost of a redundant computation on every iteration.

         

    4. Keep methods small and focused .

      If you combine two activities in the same method, local variables relevant to one activity may be in the scope of the code performing the other activity. To prevent this from happening, simply separate the method into two: one

      for each activity.

    Summary

    By minimizing the scope of local variables, you increase the read-ability and maintainability of your code and reduce the likelihood of error.

  • 相关阅读:
    SQL Server如何使用表变量
    Msys/MinGW与Cygwin/GCC(转)
    内存段划分:代码段、数据段、堆、栈
    Codeblocks+MinGW+wxWidgets搭建方法(转)
    Java GUI图形界面开发工具
    MinGW离线安装方法汇总(转)
    Linux系统的启动过程(转)
    详解VOLATILE在C++中的作用(转)
    C++虚函数与纯虚函数用法与区别(转)
    C++中值传递、指针传递和引用传递的比较 (转)
  • 原文地址:https://www.cnblogs.com/haokaibo/p/minimize-the-scope-of-local-variables.html
Copyright © 2011-2022 走看看