Validate method arguments
Design by Contract
assert
keyword is not meant
for these types of validations. (Some may find this surprising; here
is the Oracle guideline.)
Assertions can be disabled. Since checks on parameters to non-private methods implement the requirements demanded of the caller, turning off such checks at runtime would mean that part of the contract is no longer being enforced.
Conversely, checks on arguments to private methods can indeed use assert
.
These checks are made to verify assumptions about internal implementation
details, and not to check that the caller has followed the requirements
of a non-private method's contract.
In addition, if an AssertionError
can be thrown by a method,
then this fact should not appear in the method's javadoc comment.
The specification of a method's behaviour should never mention assertions,
since assertions can be disabled.
Example
import java.util.Objects; public final class SpaceShuttle { /** * The non-nullity of name is part of the contract of the * constructor. * * @param name is non-null. */ public SpaceShuttle(String name) { //WRONG way: assert name != null : "Name must not be null"; //RIGHT way: this.name = Objects.requireNonNull(name); } public String getName() { return name; } //..elided // PRIVATE private final String name; }