Refactoring – Replace Nested Conditional with Guard Clauses

Say you’ve got multiple nested if statements. 

It’s not clear what the path of execution is.

Here’s an example with multiple nested ifs:

  double getPayAmount() {
    double result;
    if (_isDead) result = deadAmount();
    else {
        if (_isSeparated) result = separatedAmount();
        else {
            if (_isRetired) result = retiredAmount();
            else result = normalPayAmount();
        };
    }
  return result;
  };

and without:

  double getPayAmount() {
    if (_isDead) return deadAmount();
    if (_isSeparated) return separatedAmount();
    if (_isRetired) return retiredAmount();
    return normalPayAmount(); 

  }; 

http://sourcemaking.com/refactoring/replace-nested-conditional-with-guard-clauses

Leave a Reply

Your email address will not be published. Required fields are marked *