Item 38: check parameters for validity
Most methods and constructors have some restrictions on what values may be passed into their parameters. For example, index values must be non-negative and object values must be non-null.
You should enforce them with checks at beginning of the method body.Notes:
- Once an error occur, throw the exception as early as possible
- For public methods, use Javadoc @throws tag to document the exception. (
IlliegalArgumentException
,IndexOutofBoundsException
, orNullPointerException
) - For un exported methods, use
assert
for validity checks, e.g.,assert a != null;
. Enable assert by command-ea
(or-enableassertions
) to the java interpreter. - It is particular important to check the validity of parameters that are not used by a method but are stored away for later use. (It’s quite hard to debug if there is an error in this case)
- Design API to be as general as it is practical to make them.
Item 39: Make defensive copies when needed
Notes:
- Never trust a user input data
Item 40: Design method signatures carefully
Notes:
- Avoid too many functions in a class | interface
- Avoid long parameter list (larger than 4)
- For parameter types, use interfaces instead of classes
- For control parameters, prefer two-element
enum
types toboolean
Item 41: Use overloading judiciously
Notes:
overload
: polymorphism in compile time;override
: polymorphism in run time- Avoid using different types of a parameter to design overloading methods
- Never export two overloading with the same number of parameters
Item 42: Use varargs judiciously
Item 43: Return empty arrays or collections, not nulls
Notes:
- It’s arguable that a null return is preferable to an empty array in case of mitigating system expense.
The right way to return an array of a collection
// The right way to return an array of a collection
private final List<Cheese> cheeseInStock = ...;
private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];
public Cheese[] getCheese() {
return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);
}The right way to return a copy of a collection
// The right way to return a copy of a collection
public List<Cheese> getCheeseList() {
if (cheesesInStock.isEmpty())
return Collections.emptyList(); // Always returns same list
else
return new ArrayList<Cheese>(cheesesInStock);
}
Item 44: Write doc comments for all exposed API elements
Notes:
- @param, @return, @throws
- @throws starts with if statement
- @{code} and@{literal}
- Document enum and annotation types