Wednesday, January 13, 2016

Refactoring in Swift - Inline function

Refactoring by inline function is the opposite of the Extract function we analyzed in a previous post.

In this case, a function is so short and it is used only in one or two spots that is it not worth having it separately.

This refactoring is done by removing the function and replacing each call with its content.

Consider the following piece of code:

var name: String?
name = "John"

func checkNameIsPresent() -> Bool {
    if (name == nil) || (name!.characters.count == 0) {
        return false
    }
    return true
}

func doSomething() {
    //some code
    
    if !checkNameIsPresent() {
        print("Please enter your name first")
    }
    
    //some code
}

doSomething()

In this case we can replace the code with the following one:

var name: String?
name = "John"

func doSomethingBetter() {
    //some code
    
    if (name == nil) || (name!.characters.count == 0) {
        print("Please enter your name first")
    }
    
    //some code
}

doSomethingBetter()


In this simple example it might not be obvious the advantage of the second option. But imagine that checkNameIsPresent is in a different part of the class, in another class or even in a parent. One developer might need to spend few minutes to discover what it does.

In the second example, it is obvious what the code does right away.

No comments:

Post a Comment