Monday, January 25, 2016

Refactoring in Swift - substitute algorithm

In previous post (Simplify nested conditionals with returns) we arrived at the following code:

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

}

This code might be okay. 

What if there are a lot of different cases? 

What if we have a different percentage for 0 to 10 kids?

Also what if it is different if the mother is married or not. In this case we'll have 22 different cases to analyze. 

Lots of times, after few iterations, an algorithm can be recreated from start.

In this case, there are multiple solutions. Here is one:

func bonusForSalary(salary:Float, numberOfKids: Int) -> Float {
    
    let bonusArray:[Float] = [0.2, 0.3, 0.4, 0.5];
    
    if numberOfKids < bonusArray.count {
        return salary * bonusArray[numberOfKids]
    }
    return salary * 0.6
}

Not only the code is clearer, but we can very easy increase the number of cases by simply adding new values to the array.

No comments:

Post a Comment

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