DEV Community

Discussion on: Refactoring If-else statement

Collapse
 
leightondarkins profile image
Leighton Darkins • Edited

My thoughts line up with this, for the most part.

"...and what will happen if these IF statements get bigger?"

One of the best pieces of feedback I got early in my career was to extract boolean expressions into functions when they become too large (typically more than one || or &&)

So if i started with:

if (!isEmpty(object) && isNumber(object.value) && isGreaterThanOne(object.value) {
    log("It's a number that's greater than 1");
}

I'd just snatch that whole boolean expression and extract it into something like:

if (valueIsANumberGreaterThanOne(object)) {
    log("It's a number that's greater than 1");
}

function valueIsANumberGreaterThanOne(object) {
    if (isEmpty(object)) return false;
    if (!isNumber(object.value)) return false;
    return isGreaterThanOne(object.value);
}

This way the if statement is easily human readable.

In the first instance you read "If the object is empty, and the objects' value is a number and the objects' value is greater than one, then..."

In the second instance you read "If the object value is a number that's greater than one, then..."

Collapse
 
mervinsv profile image
Mervin

Yeah. Boolean functions are great. It makes your code more readable and usable. And also it removes duplicates.