代码改变世界

Effective Java 38 Check parameters for validity

2014-04-01 18:29  小郝(Kaibo Hao)  阅读(494)  评论(0编辑  收藏  举报

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.