re: Refactoring If-else statement VIEW POST

FULL DISCUSSION
 

For the first one, I would write it like this (if returning was an option)

if (isEmpty(object)) {
    log("Is a special character");
    return;
}
if (IsString(object.number))
{
    log("Is  a String");    
}
if (IsNumber(object.number))
{
    log("Is a number");
}

If you stated having more than just the check for a string and a number, I would change this a switch statement (leave the first if that checks if it's empty, and make the rest a switch)

For the second one, I would use a switch statement.

 

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

 

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

code of conduct - report abuse