zoukankan      html  css  js  c++  java
  • 第38条:检查参数的有效性

    绝大多数方法和构造器对于传递给它们的参数值都会有某些限制。如索引值不能为负数,对象引用不能为null。应该在文档中清楚指明限制,并且在方法体的开头处检查参数,以强制施加这些限制,以便在错误发生之后尽快检测出错误和确定错误根源。

    对于公有方法,要用javadoc的@throws标签在文档中说明违法参数限制时会抛出的异常,就像这样:

    /**
         * Returns a BigInteger whose value is {@code (this mod m}).  This method
         * differs from {@code remainder} in that it always returns a
         * <i>non-negative</i> BigInteger.
         *
         * @param  m the modulus.
         * @return {@code this mod m}
         * @throws ArithmeticException {@code m} &le; 0
         * @see    #remainder
         */
        public BigInteger mod(BigInteger m) {
            if (m.signum <= 0)
                throw new ArithmeticException("BigInteger: modulus not positive");
    
            BigInteger result = this.remainder(m);
            return (result.signum >= 0 ? result : result.add(m));
    }

    对于未被导出的方法,作为包的创建者,可以控制方法在那些情况下被调用,因此,非公有方法通常应该使用断言来检查参数。

    考虑为对象排序的方法,列表中所有的对象必须是可以互相比较的,如果对象不能相互比较,某个比较操作会抛出ClassCastException,这正是sort方法要做的事,因此,提前检查列表是否可以互相比较无太大意义,但这样会失去失败原子性(没有在出错的时候马上抛出异常或错误,对于这个例子,出错的时候应该是传入的参数不能互相比较,而不是在比较的时候)。

    在设计方法时,应该使它们尽可能地通用,对参数的限制应该越少越好。

  • 相关阅读:
    LeetCode "Jump Game"
    LeetCode "Pow(x,n)"
    LeetCode "Reverse Linked List II"
    LeetCode "Unique Binary Search Trees II"
    LeetCode "Combination Sum II"
    LeetCode "Divide Two Integers"
    LeetCode "First Missing Positive"
    LeetCode "Clone Graph"
    LeetCode "Decode Ways"
    LeetCode "Combinations"
  • 原文地址:https://www.cnblogs.com/13jhzeng/p/5743115.html
Copyright © 2011-2022 走看看