Wednesday, January 20, 2016

Refactoring in Swift - Move method

"Yesterday, I froze some water."

While this is possible (I took some water, put it in a container, and in the freezer), it sounds funny. Of course, I did not froze the water, because I don't do that. I am not a freezer. The freezer freezes water, that is why it is called a freezer.

"As it snowed today, I will blow the snow."

I will what?!? Of course, I will use the snowblower to blow the snow. That is why it is called a snowblower because it blows the snow.

All this is obvious.

Let's see the following example:


class Address {
    var street = ""
    var city = ""
    var country = ""
    var postalCode = ""
}

class User {
    var address = Address()
    
    func createFullAddress() -> String {
        return address.street + ", " + address.city + " ," + address.postalCode + ", " + address.country
    }

}

All good? Sort of. 

Why does User class need to know about how to format the address? Address needs to know how to format itself. 

So, move the method over and get the following nice and refactored code:

class Address {
    var street = ""
    var city = ""
    var country = ""
    var postalCode = ""

    func createFullAddress() -> String {
        return street + ", " + city + " ," + postalCode + ", " + country
    }
}

class User {
    var address = Address()
}

And if you really need to have a method in User called createFullAddress, for example  when this code is part of the library, add it to the User class but delegate the functionality to the right owner, Address:

class User {
    var address = Address()
    
    func createFullAddress() -> String {
        return address.createFullAddress()
    }
}

No comments:

Post a Comment