I am modifying some code and I am seeing consistent use of "validate" for error checking.
What is the difference between Validate.notNull(x, "x cannot be empty")
and if(null != x){...}
and what are the advantages of one over the other?
EDIT: I am using org.apache.commons.lang.Validate
edit: assuming you are referring to org.apache.commons.lang.Validate
The first says that calling the method with a null parameter is entirely illegal, it was a coding mistake on the part of the programmer who used the method.
The second is just saying that there are different behaviours depending on if x is null or not.
It becomes just a readability issue if you're actually doing this:
if(null != x)
{
//...
} else {
throw new IllegalArgumentException( "x cannot be empty");
}
How long is the body of that if going to be? Why is the consequence of calling the method illegally physically separated from the check for if it was called illegally? As soon as you add some more parameters, that have various different legal states, this can get really hard for others to understand. It is much friendlier to other programmers if you explicitly reject every invocation that is known to be absolutely illegal right at the start.