<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    Scott@JAVA

    Java, 一杯濃濃的咖啡伴你到深夜

    《Effective Java》Chapter 7

    Chapter 7. General Programming

    Item 29: Minimize the scope of local variables

    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.
    Keep methods small and focused.

    The for loop allows you to declareloop variables, limiting their scope to the exact region where they're needed. (This region consists of the body of the loop as well as the initialization, test, and update preceding the body.) Therefore prefer for loops to while loops.
    for (Iterator i = c.iterator(); i.hasNext(); ) {
        doSomething(i.next());
    }

    for (int i = 0, n = expensiveComputation(); i < n; i++{
        doSomething(i);
    }
    Again, this idiom uses two loop variables, and the second variable, n, is used to avoid the cost of performing redundant computation on every iteration. As a rule, you should use this idiom if the loop test involves a method invocation and the method invocation is guaranteed to return the same result on each iteration.

    Item 30: Know and use the libraries
    Suppose you want to generate random integers between 0 and some upper bound.
    static Random rnd = new Random();

    // Common but flawed!
    static int random(int n) {
        
    return Math.abs(rnd.nextInt()) % n;
    }
    The method attempts to map the value returned by rnd.nextInt() into a nonnegative integer with Math.abs. If nextInt() returns Integer.MIN_VALUE, Math.abs will also return Integer.MIN_VALUE, and the remainder operator (%) will return a negative number. Use Random.nextInt(int) instead.

    By using a standard library, you take advantage of the knowledge of the experts who wrote it and the experience of
    those who used it before you.
    Numerous features are added to the libraries in every major release, and it pays to keep abreast of these additions.
    Every programmer should be familiar with the contents of java.lang, java.util, and, to a lesser extent, java.io.

    In the 1.2 release, a Collections Framework was added to the java.util package. It should be part of every programmer's basic toolkit.

    A third-party library worthy of note is Doug Lea's util.concurrent, which provides high-level concurrency utilities to simplify the task of multithreaded programming.

    There are many additions to the libraries in the 1.4 release. Notable additions include the following:
       ? java.util.regex— A full-blown Perl-like regular expression facility.
       ? java.util.prefs— A facility for the persistent storage of user preferences and program configuration data.
       ? java.nio— A high-performance I/O facility, including scalable I/O (akin to the Unix poll call) and memory-mapped I/O (akin to the Unix mmap call).
       ? java.util.LinkedHashSet, LinkedHashMap, IdentityHashMap— New collection implementations.

    Item 31: Avoid float and double if exact answers are required
    The float and double types are particularly ill-suited for monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly.

    For example, suppose you have a dollar in your pocket, and you see a shelf with a row of delicious candies priced at 10, 20, 30, and so forth, up to a dollar.
    // Broken - uses floating point for monetary calculation!
    public static void main(String[] args) {
        
    double funds = 1.00;
        
    int itemsBought = 0;
        
    for (double price = .10; funds >= price; price += .10{
            funds 
    -= price;
            itemsBought
    ++;
        }

        System.out.println(itemsBought 
    + " items bought.");
        System.out.println(
    "Change: $" + funds);
    }
    If you run the program, you'll find that you can afford three pieces of candy, and you have $0.3999999999999999 left. This is the wrong answer! The right way to solve this problem is to use BigDecimal, int, or long for monetary calculations:
    public static void main(String[] args) {
        
    final BigDecimal TEN_CENTS = new BigDecimal(".10");
        
        
    int itemsBought = 0;
        BigDecimal funds 
    = new BigDecimal("1.00");
        
    for (BigDecimal price = TEN_CENTS; funds.compareTo(price) >= 0;    price = price.add(TEN_CENTS)) {
            itemsBought
    ++;
            funds 
    = funds.subtract(price);
        }

        System.out.println(itemsBought 
    + " items bought.");
        System.out.println(
    "Money left over: $" + funds);
    }
    An alternative to using BigDecimal is to use int (don't exceed nine decimal digits) or long (don't exceed eighteen digits), depending on the amounts involved, and to keep track of the decimal point yourself:
    public static void main(String[] args) {
        
    int itemsBought = 0;
        
    int funds = 100;
        
    for (int price = 10; funds >= price; price += 10{
            itemsBought
    ++;
            funds 
    -= price;
        }

        System.out.println(itemsBought 
    + " items bought.");
        System.out.println(
    "Money left over: "+ funds + " cents");
    }

    Item 32: Avoid strings where other types are more appropriate
    Strings are poor substitutes for other value types. More generally, if there's an appropriate value type, whether
    primitive or object reference, you should use it; if there isn't, you should write one.


    Strings are poor substitutes for aggregate types. A better approach is simply to write a class to represent the aggregate, often a private static member class

    Strings are poor substitutes for capabilities. Occasionally, strings are used to grant access to some functionality, replace the string with an unforgeable key (sometimes called a capability).

    Item 33: Beware the performance of string concatenation
    Don't use the string concatenation operator to combine more than a few strings unless performance is irrelevant. Use StringBuffer's append method instead. Alternatively, use a character array, or process the strings one at a time instead of combining them.

    Item 34: Refer to objects by their interfaces
    If appropriate interface types exist, parameters, return values, variables, and fields should all be declared using interface types.
    // Good - uses interface as type
    List subscribers = new Vector();
    rather than this:
    // Bad - uses class as type!
    Vector subscribers = new Vector();
    If you get into the habit of using interfaces as types, your program will be much more flexible. For example, the first
    declaration could be changed to read
    List subscribers = new ArrayList();
    There is one caveat: If the original implementation offered some special functionality not required by the general contract of the interface and the code depended on that functionality, then it is critical that the new implementation provide the same functionality. For example, if the code surrounding the first declaration depended on the fact that Vector is synchronized,
    then it would be incorrect to substitute ArrayList for Vector in the declaration.

    It is entirely appropriate to refer to an object by a class rather than an interface if no appropriate interface exists.
    For example, it is perfectly appropriate to use a value class as a parameter, variable, field, or return type.

    If an object belongs to such a class-based framework, it is preferable to refer to it by the relevant base class, which is
    typically abstract, rather than by its implementation class.

    A final case in which there is no appropriate interface type is that of classes that implement an interface but provide extra methods not found in the interface—for example, LinkedList. Such a class should be used only to refer to its instances if the program relies on the extra methods: it should never be used as a parameter type (Item 25).

    Item 35: Prefer interfaces to reflection
    Reflection comes at a price:
       You lose all the benefits of compile-time type checking.
       The code required to perform reflective access is clumsy and verbose.
       Performance suffers.

    As a rule, objects should not be accessed reflectively in normal applications at run time.

    You can obtain many of the benefits of reflection while incurring few of its costs by using it only in a very limited form. For many programs that must use a class unavailable at compile time, there exists at compile time an appropriate interface or superclass by which to refer to the class (Item 34). If this is the case, you can create instances reflectively and access them normally via their interface or superclass. If the appropriate constructor has no parameters, as is usually the case, then you don't even need to use the java.lang.reflect package; the Class.newInstance method provides the required functionality.
    // Reflective instantiation with interface access
    public static void main(String[] args) {
    // Translate the class name into a class object
    Class cl = null;
    try {
    cl 
    = Class.forName(args[0]);
    }
     catch(ClassNotFoundException e) {
    System.err.println(
    "Class not found.");
    System.exit(
    1);
    }

    // Instantiate the class
    Set s = null;
    try {
    = (Set) cl.newInstance();
    }
     catch(IllegalAccessException e) {
    System.err.println(
    "Class not accessible.");
    System.exit(
    1);
    }
     catch(InstantiationException e) {
    System.err.println(
    "Class not instantiable.");
    System.exit(
    1);
    }

    // Exercise the set
    s.addAll(Arrays.asList(args).subList(1, args.length-1));
    System.out.println(s);
    }

    Item 36: Use native methods judiciously
    Think twice before using native methods. Rarely, if ever, use them for improved performance. If you must use native methods to access low-level resources or legacy libraries, use as little native code as possible and test it thoroughly. A single bug in the native code can corrupt your entire application.

    Item 37: Optimize judiciously
    Strive to write good programs rather than fast ones.
    Strive to avoid design decisions that limit performance.
    Consider the performance consequences of your API design decisions.
    It is a very bad idea to warp an API to achieve good performance.
    Measure performance before and after each attempted optimization.

    Item 38: Adhere to generally accepted naming conventions
    Internalize the standard naming conventions and learn to use them as second nature. The typographical conventions are straightforward and largely unambiguous; the grammatical conventions are more complex and looser. To quote from The Java Language Specification, "These conventions should not be followed slavishly if long-held conventional usage dictates otherwise." Use common sense.

    posted on 2005-12-18 00:26 Scott@JAVA 閱讀(565) 評論(0)  編輯  收藏 所屬分類: Effective Java

    主站蜘蛛池模板: 亚洲人成伊人成综合网久久久| 在线观看免费污视频| 亚洲精品tv久久久久| 亚洲精品无码专区| 免费的一级黄色片| 亚洲国产AV一区二区三区四区| 国外成人免费高清激情视频 | 亚洲色自偷自拍另类小说| 一区在线免费观看| 亚洲日韩国产成网在线观看| 一个人看的www免费在线视频| 亚洲日韩人妻第一页| 精品无码一级毛片免费视频观看| 国产亚洲AV手机在线观看| 国产在线观看免费av站| 西西人体44rt高清亚洲| 亚洲人成免费电影| 亚洲色欲色欲www在线播放| 国产一区二区三区免费在线观看| 日日摸夜夜添夜夜免费视频| 亚洲国产精品无码久久一线| 99ee6热久久免费精品6| 亚洲精品美女网站| 精品久久久久久久免费人妻 | 亚洲精品自在在线观看| 57pao国产成永久免费视频| 亚洲国产精品无码第一区二区三区 | 亚洲韩国在线一卡二卡| 无码人妻一区二区三区免费手机 | 日本精品久久久久久久久免费| 国产亚洲日韩一区二区三区| 日本免费一区二区三区| 国产精品久久亚洲不卡动漫| 夜色阁亚洲一区二区三区| 暖暖日本免费中文字幕| 中文字幕亚洲精品无码| 免费看男女下面日出水视频| 久久精品国产这里是免费| 99亚偷拍自图区亚洲| 亚洲无线码在线一区观看| 国产精品久久免费|