views:

226

answers:

7

I have recently added a HasValue function to our internal javascript library:

function HasValue(item) {
    return (item !== undefined && item !== null);
}

A during a convorsation with a coworker, we came up with the idea of also adding another function that would basically just be the inverse: perhaps HasNoValue, or IsNothing If we ended up doing that we would have:

function HasNoValue(item) {
    return (item === undefined || item === null);
}
function HasValue(item) {
    return !HasNoValue(item);
}

However, we're not sure whether it is more readable to have both, or HasValue. Which is more readable/preferred?

A:

if (HasValue(x) && !HasValue(y))

B:

if (HasValue(x) && HasNoValue(y))
+19  A: 

I vastly prefer A to B. "!" is a programming idiom that should be understood by all.

Daniel Lew
+1  A: 

Just for the sake of having less lines of code and because your function returns a Boolean, I'd say to go with method A. If you have to worry about readability, you can always try:

if ( HasValue(x) && !(HasValue(y)) )
Stephen
A: 

I would say option A is clearer, you know exactly what it means.

JRL
+8  A: 

I'm voting "A" by far.

The additional maintenance burden of doing this for each and any boolean return function isn't worth it versus the well-understood and quite readable "!", and in fact I believe "B" is actually less readable, since it's so easy to miss the "No" in the middle of the name.

annakata
A: 

I would stick with option A but thats just me.

John Isaacks
+11  A: 

If !HasValue(y) and HasNoValue(y) are guaranteed to be logically equivalent over the entire input range of y, then I would greatly prefer !HasValue(y).

I would hesitate to even have a function named HasNoValue(y) because inevitably someone will write !HasNoValue(y).

Bill the Lizard
Strongly agree with this. I hate it when people write code like `while (!IsNotDisabled()) ...`, because it takes me way too much mental effort to figure out all the negations of negations. Functions that return booleans should not have `Not`or any variation within their names.
Kristopher Johnson
+2  A: 

I know I'll be quite alone with this opinion and if I'd be faced with this choise in a collaborative project, I'd surely go with A, since it's quite obvious it's the right thing to do, but I have to say I do appreciate the verbosity of option B. Words are just infinitely easier to read and understand than symbolics, even if it's something as mundane as our beloved ol' exclamation point.

Especially now that IDE's have so much better intellisense than before, I usually tend to opt for far more verbosity than before with all naming. 9 times out of 10, readability trumps small performance differences, hands down.

Tommi Forsström
Right, that was why we came up with the second option, in the end I do think that A is the correct solution, but I like the readability.
chills42