Monday, January 25, 2016

Refactoring in Swift - simplify nested conditionals with returns

Consider the case when a function needs to calculate the result using a complicated set of logic statements based on the input.

We would need to store the result in a variable and return it at the end. Or do we?


As for the previous posts, the following example is simple and is not necessary benefiting a lot from the refactoring. They are just simple examples to make the topic more clear and prove the point.

In the real life applications, small refactoring like this can half the amount of code needed and provide a huge increase in clarity.

Let's consider a company where the bonus of the employee is calculated based on the number of kids.

Yes, this company is in a parallel universe, you are right.

func bonusForSalary(salary:Float, numberOfKids: Int) -> Float {
    var bonus: Float
    
    if numberOfKids == 0 {
        bonus = salary * 0.2
    } else if numberOfKids == 1 {
        bonus = salary * 0.3
    } else if numberOfKids == 2 {
        bonus = salary * 0.4
    }else if numberOfKids == 3 {
        bonus = salary * 0.5
    } else {
        bonus = salary * 0.6
    }
    
    return bonus
}

We notice that bonus variable is used only twice for each case, once when it is assigned and once when it is returned.

We can simplify this function by directly returning the result and removing the bonus variable:

func bonusForSalary(salary:Float, numberOfKids: Int) -> Float {
    
    if numberOfKids == 0 {
        return salary * 0.2
    }
    if numberOfKids == 1 {
        return salary * 0.3
    }
    if numberOfKids == 2 {
        return salary * 0.4
    }
    if numberOfKids == 3 {
        return salary * 0.5
    }
    return salary * 0.6
}

Getting rid of the code and of the variables is always a good idea when the clarity of the code is not reduced. And of course, when bugs are not added.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.