DEV Community

Cover image for How do I refactor IF_ELSE condition
parvej-code
parvej-code

Posted on

How do I refactor IF_ELSE condition

Writing if-else is a daily job for a programmer. Whenever we write code, we check if something is true or false. But writing too many if-else conditions makes code unreadable. Below are some steps which I follow to refactor my if-else blocks.

Method calling:

Sometimes based on one parameter, we had to do different operations.

class SomeClass {
  public action(status: string) {
    if (status === 'draft') {
      //Do some operations
    } else if (status === 'confirmed') {
      //Do some operations
    } else if (status === 'payed') {
      //Do some operations
    } else if (status === 'shipped') {
      //Do some operations
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

We can improve this by calling the method based on the parameter value.

class SomeClass {
  public action(status: string) {
    if (typeof this[status] === 'undefined') {
      //Throw your exception, do some default operations and return
    }
    return this[status]()
  }

  public draft() {
    //Do the draft operations
  }

  public confirmed() {
    //Do the confirm operations
  }

  public payed() {
    //Do the payed operations
  }

  public shipped() {
    //Do shipped operations
  }
}
Enter fullscreen mode Exit fullscreen mode

Object literal:

If you only have to return one value based on a parameter, then you can use an object literal

if (operator === '=') {
  return a === b;
} else if (operator === '<') {
  return a < b;
} else if (operator === '>') {
  return a > b;
} else if (operator === '>=') {
  return a >= b;
} else if (operator === '<=') {
  return a <= b;
} else if (operator === 'like') {
  return String(a).toLowerCase().includes(String(b).toLowerCase());
}
Enter fullscreen mode Exit fullscreen mode

Refactored

action(operator) {
    const operators = {
      '=': (a, b) => a === b,
      '<': (a, b) => a < b,
      '>': (a, b) => a > b,
      '>=': (a, b) => a >= b,
      '<=': (a, b) => a <= b,
      like: (a, b) => String(a).toLowerCase().includes(String(b).toLowerCase()),
    };

    if (typeof operators[operator] === 'undefined') {
      //Do your operation and return
    }
    return operators[operator];
 }
Enter fullscreen mode Exit fullscreen mode

Note: We can also use a factory design pattern for it. But in most cases, it will be an overkill

Top comments (0)