<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 6

    Chapter 6. Methods

    Item 23: Check parameters for validity
    Each time you write a method or constructor, you should think about what restrictions exist on its parameters. You should document these restrictions and enforce them with explicit checks at the beginning of the method body.

    Item 24: Make defensive copies when needed
    You must program defensively with the assumption that clients of your class will do their best to destroy its invariants.
    // Broken "immutable" time period class
    public final class Period {
        
    private final Date start;
        
    private final Date end;
        
        
    /**
         * 
    @param start
         *            the beginning of the period.
         * 
    @param end
         *            the end of the period; must not precede start.
         * 
    @throws IllegalArgumentException
         *             if start is after end.
         * 
    @throws NullPointerException
         *             if start or end is null.
         
    */

        
    public Period(Date start, Date end) {
            
    if (start.compareTo(end) > 0)
                
    throw new IllegalArgumentException(start + " after "
                        
    + end);
            
    this.start = start;
            
    this.end = end;
        }

        
        
    public Date start() {
            
    return start;
        }

        
        
    public Date end() {
            
    return end;
        }

        
         
    // Remainder omitted
    }
    Violate this invariant by exploiting the fact that Date is mutable:
    // Attack the internals of a Period instance
    Date start = new Date();
    Date end 
    = new Date();
    Period p 
    = new Period(start, end);
    end.setYear(
    78); // Modifies internals of p!
    It is essential to make a defensive copy of each mutable parameter to the constructor:
    // Repaired constructor - makes defensive copies of parameters
    public Period(Date start, Date end) {
        
    this.start = new Date(start.getTime());
        
    this.end = new Date(end.getTime());
        
    if (this.start.compareTo(this.end) > 0)
            
    throw new IllegalArgumentException(start +" after "+ end);
    }
    Defensive copies are made before checking the validity of the parameters (Item 23), and the validity check is performed on the copies rather than on the originals.
    Do not use the clone method to make a defensive copy of a parameter whose type is subclassable by untrusted parties.

    // Second attack on the internals of a Period instance
    Date start = new Date();
    Date end 
    = new Date();
    Period p 
    = new Period(start, end);
    p.end().setYear(
    78); // Modifies internals of p!
    To defend against the second attack, merely modify the accessors to return defensive copies of mutable internal fields:
    // Repaired accessors - make defensive copies of internal fields
    public Date start() {
        
    return (Date) start.clone();
    }


    public Date end() {
        
    return (Date) end.clone();
    }
    Note that the new accessors, unlike the new constructor, do use the clone method to make defensive copies. This is acceptable (although not required), as we know with certainty that the class of Period's internal Date objects is java.util.Date rather than some potentially untrusted subclass.

    Item 25: Design method signatures carefully
    Too many methods make a class difficult to learn, use, document, test, and maintain. This is doubly true for interfaces.
    Avoid long parameter lists (3 as practical max).
    Long sequences of identically typed parameters are especially harmful.
    For parameter types, favor interfaces over classes.
    Use function objects judiciously.

    Item 26: Use overloading judiciously
    Selection among overloaded methods is static (at compile time), while selection among overridden methods is dynamic (at run time).

    //Broken - incorrect use of overloading!
    public class CollectionClassifier {
        
    public static String classify(Set s) {
            
    return "Set";
        }


        
    public static String classify(List l) {
            
    return "List";
        }


        
    public static String classify(Collection c) {
            
    return "Unknown Collection";
        }


        
    public static void main(String[] args) {
            Collection[] tests 
    = new Collection[] new HashSet(), // A Set
                    new ArrayList(), // A List
                    new HashMap().values() // Neither Set nor List
            }
    ;
            
    for (int i = 0; i < tests.length; i++)
                System.out.println(classify(tests[i]));
        }

    }
    For all three iterations of the loop, the compile-time type of the parameter is the same: Collection. The run-time type is different in each iteration, but this does not affect the choice of overloading.

    class A {
        String name() 
    {
            
    return "A";
        }

    }


    class B extends A {
        String name() 
    {
            
    return "B";
        }

    }


    class C extends A {
        String name() 
    {
            
    return "C";
        }

    }


    public class Overriding {
        
    public static void main(String[] args) {
            A[] tests 
    = new A[] new A(), new B(), new C() };
            
    for (int i = 0; i < tests.length; i++)
                System.out.print(tests[i].name());
        }

    }
    As you would expect, this program prints out "ABC" even though the compile-time type of the instance is A in each iteration of the loop.

    You should generally refrain from overloading methods with multiple signatures that have the same number of parameters. In some cases, especially where constructors are involved, it may be impossible to follow this advice. In that case, you should at least avoid situations where the same set of parameters can be passed to different overloadings by the addition of casts.

    Item 27: Return zero-length arrays, not nulls
    It is possible to return the same zero-length array from every invocation that returns no items because zero-length arrays are immutable and immutable objects may be shared freely (Item 13).
    private List cheesesInStock = ;

    private final static Cheese[] NULL_CHEESE_ARRAY = new Cheese[0];

    /**
     * 
    @return an array containing all of the cheeses in the shop.
     
    */

    public Cheese[] getCheeses() {
        
    return (Cheese[]) cheesesInStock.toArray(NULL_CHEESE_ARRAY);
    }

    There is no reason ever to return null from an array-valued method instead of returning a zero-length array.

    Item 28: Write doc comments for all exposed API elements
    /**
    * Returns the element at the specified position in this list.
    *
    @param index index of element to return; must be
    * nonnegative and less than the size of this list.
    @return the element at the specified position in this list.
    @throws IndexOutOfBoundsException if the index is out of range
    * (<tt>index &lt; 0 || index &gt;= this.size()</tt>).
    */

    Object get(
    int index)
    For methods and constructors, the summary description should be a verb phrase describing the action performed by the method.
    For classes, interfaces, and fields, the summary description should be a noun phrase describing the thing represented by an instance of the class or interface or by the field itself.
    Be careful not to include a period within the first sentence of a doc comment.

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

    主站蜘蛛池模板: 中文字幕人成人乱码亚洲电影| 午夜亚洲www湿好大| 在线免费视频你懂的| 亚洲一区二区三区高清| 成人影片麻豆国产影片免费观看 | 在线A亚洲老鸭窝天堂| 在线观看免费视频资源| 亚洲AV无码AV男人的天堂不卡| 国产a v无码专区亚洲av| 中文字幕免费在线看线人 | 免费观看激色视频网站(性色)| 亚洲Aⅴ在线无码播放毛片一线天| 国产AV无码专区亚洲AV手机麻豆| 2021在线永久免费视频| 丁香六月婷婷精品免费观看| 91亚洲一区二区在线观看不卡| 免费人成年轻人电影| 最近中文字幕免费mv在线视频 | 日本妇人成熟免费中文字幕| 日韩精品视频在线观看免费| 亚洲精品乱码久久久久久下载 | 亚洲 欧洲 日韩 综合在线| 久久精品国产精品亚洲艾草网美妙| 一级毛片成人免费看免费不卡| 日韩亚洲翔田千里在线| 亚洲福利秒拍一区二区| 亚洲国产中文v高清在线观看| 91九色老熟女免费资源站| 五月天婷婷免费视频| 亚洲中文字幕乱码一区| 日韩亚洲Av人人夜夜澡人人爽 | 夜色阁亚洲一区二区三区| 美女视频黄免费亚洲| 国偷自产一区二区免费视频| 免费亚洲视频在线观看| 亚洲天堂免费在线| 亚洲高清中文字幕| 亚洲精选在线观看| 亚洲日韩国产精品第一页一区| 免费在线一级毛片| 欧洲精品免费一区二区三区|