DEV Community

Question: Is this a terrible idea?

harleybl on April 30, 2020

I have a bunch of utility functions in typescript for doing various things. I find that I often want to check if an array has any elements in it, b...
Collapse
 
sargalias profile image
Spyros Argalias • Edited

I don't see a big problem with it. If you and your team are happy, then by all means use anything :).

But since you're asking, I would personally name the function something like safeHasElements(array). The reasoning for this is because you (or someone new to the code) might expect atLeastOne to take an array only, and error if it gets null or undefined. But in functional programming, the word "safe" normally implies that things won't throw errors but fail silently instead, or in your case just return false / undefined.

Collapse
 
harleybl profile image
harleybl

Thanks, Spyros - I like your naming suggestion.

Collapse
 
pigozzifr profile image
Francesco Pigozzi

Why don't you reverse the logic and name it isEmpty instead?

Collapse
 
harleybl profile image
harleybl • Edited

I have another method for the isEmpty case, but often I find it more readable to have if statement logic checks for a positive condition rather than a negative one. I read somewhere, I think it was Clean Code, that using positive logic requires less cognitive load when reading through the code. Especially when you are checking for more than one condition.

Which is more readable?

if (!isEmpty(arr) || !isEmpty(arr2) {
  doSomething()
} else {
  doNothing()
}

or

if (any(arr) || any(arr)) {
  doSomething()
} else {
  doNothing()
}

I prefer the second.

Note: isEmpty is an rxjs operator since that could be confusing I will call it something else like safeIsEmpty.

Collapse
 
pigozzifr profile image
Francesco Pigozzi

Just like you said: positive logic requires less cognitive load

For that reason, checking for a negative logic first and quit if true should be safer, more concise and readable than nesting two different logic inside an if/else statement