To validate user inputs, I am unsure of which of two alternatives is better
1
isNull( Object input )
2
notNull( Object input )
apache's commons lang library chose #2 but I am uncomfortable with double negatives. What do you say ?
To validate user inputs, I am unsure of which of two alternatives is better
isNull( Object input )
notNull( Object input )
apache's commons lang library chose #2 but I am uncomfortable with double negatives. What do you say ?
Honestly, I don't think it makes much difference.
If you are designing your own API, implement it the way you are most comfortable with. Indeed, there's no strong reason to not to implement both isNull
and notNull
if that makes you feel happier.
But I think it would be silly to abandon plans to use some third-party library solely because you are "uncomfortable with" double negatives. They really aren't that confusing.
The answer here depends on so many considerations, of which some are:
If you want a more considered answer, do let us know some more of the details. In the meantime, my top tip would be to go for whatever enhances readability of the code: you want to give future maintainers as much help as you can.
To me, double negatives is always a bad thing. I'd say stick to isNull. Checking for nullity then makes sense while reading. The opposite would be
if (! isNull(o) )
// ...
which reads out "if not is null". Sure it sounds retarded read out loud, but it makes more sense than checking for nullity with option #1.
if (! isNotNull(o))
// ...
A statement which makes you rewind and say "hey, wait a minute... if not is not...".
But if there is a standard already with having negatives in method names, stick to it. Standards are good things, and should not be broken just because someone is "uncomfortable".
I am a little confused by the question. If the methods in question are just returning a boolean depending upon whether the argument is null
, then == null
or != null
are much better.
However, the reference to Apache Commons Lang seem to indicate that this is validity checking, and an appropriate exception should be thrown is the reference is null
. In that case you can't invert the output easily.
FWIW, it looks as if JDK7 will introduce a notNull
method, as discussed on an appropriate mailing list, something along the lines of:
public static <T> T notNull(T obj)
Used as:
import static java.util.Object.notNull;
public final MyClass {
private final Thing thing;
public MyClass(Thing thing) {
this.thing = notNull(thing);
}
...
I am uncomfortable with functions which are longer than the code they replace.
I would use x == null or x != null. I agree that double negative isn't clear either.
A puzzle for you, when is (s != s) true? A good example of confusing behaviour. ;)