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



Question:

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


Solution:1

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


Solution:2

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


Solution:3

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.


Solution:4

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.


Solution:5

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


Solution:6

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


Solution:7

I would stick with option A but thats just me.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »