The vast majority of methods and constructors have some limitations on the parameter values passed to them. An object reference cannot be null if the index value cannot be negative. Limits should be clearly specified in the document, and parameters should be checked at the beginning of the method body to enforce these restrictions so that errors can be detected and the source of the error as soon as possible after the error occurs.
For public methods, the exception that is thrown when the Javadoc @throws tag is used in the document to describe the illegal parameter limit is as follows:
/*** Returns A BigInteger whose value is {@code(this mod m}). This method * differs from {@coderemainder} In the IT always returns a * <i>non-negative</i> BigInteger. * * @paramm the modulus. * @return {@codeThis mod m} *@throwsArithmeticException {@codem} ≤ 0 *@see#remainder*/ PublicBigInteger mod (BigInteger m) {if(M.signum <= 0) Throw NewArithmeticException ("Biginteger:modulus not Positive"); BigInteger result= This. Remainder (m); return(result.signum >= 0?)Result:result.add (M));}
For a method that is not exported, as the creator of the package, you can control how the method is called in those cases, so the non-public method should usually use assertions to check the parameters.
Considering the method of sorting objects, all objects in the list must be comparable, and if the objects cannot be compared to each other, a comparison operation throws ClassCastException, which is exactly what the sort method does, so it is not very meaningful to check the list in advance to see if it can compare to each other. But this will lose the atomic nature of failure (without immediately throwing an exception or error at the time of the error, for this example, it should be that the parameters passed in cannot be compared to each other, not at the time of comparison).
When designing a method, you should make them as generic as possible, and the less restrictive the parameters should be.
38th: Check the validity of the parameters