Friday, February 5, 2016

Refactoring - consolidate conditional expressions

This refactoring is applied when there are multiple conditional tests that have the same outcome. You can combine them in the same condition.

Consider the following piece of code that is checking if the length of a username is correct (that is between 5 and 20).

let username:String?

username = "test"

var lengthCorrect = true
if username == nil {
    lengthCorrect = false
} else if username?.characters.count < 5 {
    lengthCorrect = false
} else  if username?.characters.count > 20 {
    lengthCorrect = false
}

As you can see all the tests have the same outcome: length is incorrect

The first step would be to combine all the checks into the same if statement:

if (username == nil) || (username?.characters.count < 5) 
   || (username?.characters.count > 20) {
    lengthCorrect = false
}

Of course, the next step is to extract this code into its own function:

func checkUsernameLength(username:String?) -> Bool {
    return !((username == nil) || (username?.characters.count < 5) 
           || (username?.characters.count > 20))
}

Now, the code to check the the validity of the username is simply:

var lengthCorrect = checkUsernameLength(username)


No comments:

Post a Comment