The first lines of a method are usually devoted to checking the validity
of method arguments. The idea is to fail as quickly as possible in the event
of an error. This is particularly important for constructors.

It's a reasonable policy for a class to skip validating arguments of private methods.
The reason is that private methods can only be called from the class itself. Thus,
a class author should be able to confirm that all calls of a private method are valid.
If desired, the assert keyword can be used to verify private method arguments,
to check the internal consistency of the class. (Using assert for checking the arguments of
a non-private method is not recommended, since disabling such assertions
would mean the contract of the non-private method is no longer being enforced.)

When validating an argument, an Exception is thrown if the test fails.
It's often one of these unchecked exceptions that are thrown:

If every object parameter of every method in a class needs to be non-null
in order to avoid throwing NullPointerException, then it's acceptable
to state this once in the general class javadoc, instead of repeating it
for each method. Another alternative is to state in overview.html
(javadoc's summary description of an entire application) that all parameters
are to be considered non-null unless explicitly stated otherwise.

Example 1

The constructor of this class validates its arguments before doing anything
else. If a validation fails, then an IllegalArgumentException
is thrown.

publicfinalclass ElementaryParticle {
/**
@param aName has content.
@param aSpeed is in the range 0 (inclusive) to 1 (inclusive), and
is expressed as a fraction of the speed of light. (The photon is
an example of an elementary particle which travels at this speed.)
@exception IllegalArgumentException if a param does not comply.
*/public ElementaryParticle (String aName, double aSpeed) {
if (!textHasContent(aName)) {
thrownew IllegalArgumentException("Name has no content.");
}
if (aSpeed < 0.0 || aSpeed > 1.0) {
thrownew IllegalArgumentException("Speed not in range [0..1]: " + aSpeed);
}
fName = aName;
fSpeed = aSpeed;
}
//..other methods elided
// PRIVATE
private String fName;
privatedouble fSpeed;
/**
Returns true if aText is non-null and has visible content.
This is a test which is often performed, and should probably
be placed in a general utility class.
*/privateboolean textHasContent(String aText){
String EMPTY_STRING = "";
return (aText != null) && (!aText.trim().equals(EMPTY_STRING));
}
}

Example 2

Some validations are very common:

check that an object is not null

check that text has visible content

check that a number is in some range

Providing a class for such validations can often be useful. In this example,
the Args class throws IllegalArgumentException
if a corresponding boolean check fails. Using Args to validate
arguments will increase legibility noticeably, especially in the case of
multiple validations.