Monday, February 8, 2016

Refactoring - Consolidate Duplicate Conditional Fragments

Apply this refactoring when the same code is duplicated in the branches of a if/else or switch statement.

Move the common code outside of the statement.

Let's consider the following code that is creating the full name using the first and last name:

var firstName, lastName: String?

//....

var fullName = ""
if firstName == nil {
    if lastName == nil {
        fullName = "unknown name"
        print(fullName)
    } else {
        fullName = lastName!
        print(fullName)
    }
} else {
    if lastName == nil {
        fullName = firstName!
        print(fullName)
    } else {
        fullName = firstName! + " " + lastName!
        print(fullName)
    }
}

We can easily notice that for each branch the full name is printed.

We can move it outside the branch as follows:

var fullName = ""
if firstName == nil {
    if lastName == nil {
        fullName = "unknown name"
    } else {
        fullName = lastName!
    }
} else {
    if lastName == nil {
        print(fullName)
    } else {
        fullName = firstName! + " " + lastName!
    }
}
print(fullName)

No comments:

Post a Comment

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