Wednesday, November 25, 2015

Refactoring the evil i, j, k

For the sake of argument, consider you have the following input data:

let userIds = [1,2,3,4,5]

let userNames = [
    1 : "John",
    2 : "Mary",
    4 : "James"
]

let userAges = [
    2 : 30,
    4 : 40,
    5 : 25

]



The task is to find all the users with name and age.

Consider the following solution:

for i in userIds {
    for (j,name) in userNames {
        for (k,l) in userAges {
            if (i == j) && (j == k) {
                print("user with id \(i) has name \(name) and age \(k)")
            }
        }
    }

}

Correct solution?

Let's see the result:

user with id 2 has name Mary and age 2 
user with id 4 has name James and age 4

So the solution is incorrect not because the algorithm is failing, just because we got lost into i,  j,  k that have meaningless names.

Consider the following solution:

for userId in userIds {
    for (namesUserId,name) in userNames {
        for (ageUserId,age) in userAges {
            if (userId == namesUserId) && (namesUserId == ageUserId) {
                print("user with id \(userId) has name \(name) and age \(ageUserId)")
            }
        }
    }

}

The error is now obvious and the solution as well:

for userId in userIds {
    for (namesUserId,name) in userNames {
        for (ageUserId,age) in userAges {
            if (userId == namesUserId) && (namesUserId == ageUserId) {
                print("user with id \(userId) has name \(name) and age \(age)")
            }
        }
    }
}

No comments:

Post a Comment

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