Rule1:Check parameters for validity
Methods have restrictions on what values can be passed as parameter.
For example: Array index must be non-negative and reference must be non-null.
Specific use cases :
Null check – we donot have to resort to manul null check proceses. Java 7 provides FLEXIBLE and CONVINIENT method for null check
objects.requireNonNull(referec,”exception message”)
which is i.e custom exception message can be passed so flexible and and can be used inline so convinient.
there is asset method whch esures the validity check . it it fails gives AssertionError.
example- asset a >10;
Unlike normal exception asser gave no effect and no cost unless you enable it by setting vm argument as -ea (enable assert).You can see some real prorld worject implementing this.
Practice:
for the exported methods(public and protected) – ensure to documrny the restriction
i.e add java doc –
@throws
@param
@return
for unexported methods(private).the author of method has to ensure the validity check of parameters.
Even if the data is not used in method but stored in collection for latter use , the validity check should be ensure for safety:
Example-
If List stores programs data, by mistake someone stored the null then the explicit check objects.requireNonNull will through exception otherwise the list would be propogated to client and incase it would have been accessed , would have resulted in Nullpointer expection hard to point out point-of-occurence.
It’s is SPECIFIC CASE OF GENERAL PRINCIPLE that fix the error as soon as it is detected.The later it is detected the more tedious it is to fix.
Failure to validate the parameter results in violation of FAILURE ATOMICITY i.e unexpected failure can occurr i.e unexpected result or unintended exception that what was intended(refer Exception Rule-8)
Summary:
Each time you write a method or constructor you should THINK ABOUT WHAT RESTRICTION EXIST on it’s parameters. You should document them and perform the validity check at beggining .
the modest work that it entails PAYS YOU BACK WITH INTEREST THE FIRST TIME THE VALIDITY CHECK FAILS.
Cautions: donot infer from this rule that arbitrary restriction are the good thing.Design methods to be as general as it is PRACTICAL to make it(no arbitrary restrictions that inhibits performance).The fewer restriction on parameters the better.