zoukankan      html  css  js  c++  java
  • Effective Java 38 Check parameters for validity

    For public methods, use the Javadoc @throws tag to document the exception that will be thrown if a restriction on parameter values is violated (Item 62). Typically the exception will be IllegalArgumentException, IndexOutOfBounds Exception, or NullPointerException(Item 60).

       

    /**

    * Returns a BigInteger whose value is (this mod m). This method

    * differs from the remainder method in that it always returns a

    * non-negative BigInteger.

    *

    * @param m the modulus, which must be positive

    * @return this mod m

    * @throws ArithmeticException if m is less than or equal to 0

    */

    Public BigInteger mod(BigInteger m) {

    if (m.signum() <= 0)

    throw new ArithmeticException("Modulus <= 0: " + m);

    ... // Do the computation

    }

       

    For an unexported method, you as the package author control the circumstances under which the method is called, so you can and should ensure that only valid parameter values are ever passed in. Therefore, nonpublic methods should generally check their parameters using assertions.

       

    // Private helper function for a recursive sort

    private static void sort(long a[], int offset, int length) {

    assert a != null;

    assert offset >= 0 && offset <= a.length;

    assert length >= 0 && length <= a.length - offset;

    ... // Do the computation

    }

       

    Unlike normal validity checks, assertions throw AssertionError if they fail. And unlike normal validity checks, they have no effect and essentially no cost unless you enable them, which you do by passing the -ea(or -enableassertions) flag to the java interpreter.

       

    Note

    It is particularly important to check the validity of parameters that are not used by a method but are stored away for later use.

       

    Summary

    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.

  • 相关阅读:
    uC/OS-II内核的服务文件
    uC/OS-II汇编代码
    uC/OS-II类型定义
    uC/OS-II核心(Os_core)块
    uC/OS-II配置文件
    uC/OS-II应用程序exe
    uC/OS-II应用程序代码
    技术人员如何创业《四》- 打造超强执行力团队(转载)
    最近做抽奖的活动
    install docker
  • 原文地址:https://www.cnblogs.com/haokaibo/p/check-parameters-for-validity.html
Copyright © 2011-2022 走看看