• 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.

  • 相关阅读:
    session生命周期
    解决安装sql server 需要重启问题
    myeclipse + tomcat 项目自动部署
    JSP页面转向方式
    关于Response.redirect()方法
    MyEclipse修改项目名称后,部署到tomcat问题
    为Eclipse安装主题插件
    MyEclipse自定义快捷键
    如何查看JSP和Servlet版本
    Wannafly挑战赛2 C.Butterfly(线段树优化枚举)
  • 原文地址:https://www.cnblogs.com/haokaibo/p/check-parameters-for-validity.html
Copyright © 2020-2023  润新知