Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it worth the effort to have a function that returns the inverse of another function?

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))
like image 839
chills42 Avatar asked Apr 23 '09 15:04

chills42


2 Answers

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

like image 52
Dan Lew Avatar answered Oct 06 '22 02:10

Dan Lew


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).

like image 43
Bill the Lizard Avatar answered Oct 06 '22 01:10

Bill the Lizard