Is it worth trying to have a function that returns the opposite of another function?

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

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

And during the escort with a colleague, we came up with the idea of โ€‹โ€‹adding another function that would basically be just inverse: perhaps HasNoValue or IsNothing If we finished this, we would get:

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

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

A:

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

IN:

if (HasValue(x) && HasNoValue(y))
+5
source share
7 answers

I really prefer from A to B. "!" it is an idiom of programming that should be understood by everyone.

+20
source

!HasValue(y) HasNoValue(y) y, !HasValue(y).

HasNoValue(y), - !HasNoValue(y).

+12

"".

, , "!", , "B" , "" .

+8

, , , A, , , , B. , , - , .

, , IDE , , , , . 9 10, , .

+2

Just in order to have fewer lines of code, and because your function returns a boolean, I would say to go with method A. If you need to worry about readability, you can always try:

if ( HasValue(x) && !(HasValue(y)) )
+1
source

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

0
source

I would stick with option A, but that's just me.

0
source

All Articles