Tuesday, March 1, 2016

Refactoring - Preserve whole object

You can use this refactoring when your code is getting few properties from an object and then pass them to a function. You can simply pass the whole object.

Let's consider a User class that has among other properties, a first name and a last name.

class User {
    var firstName: String
    var lastName: String

We have a function that creates the header for a report. It is using the two values like follows:

func createHeader(firstName firstName:String, lastName:String) {

To use the code we need to do the following

let user = User()
let firstName = user.firstName
let lastName = user.lastName

createHeader(firstName:firstName, lastName: lastName)

We observe that the firstName and lastName variables are just temporary ones that do not bring any value.

One first step would be to remove them in the following way:

let user = User()
createHeader(firstName:user.firstName, lastName: user.lastName)

But we can do even better than that. We can change the function to accept the User object altogether:

func createHeader(user: User) {

If in the future, we want the add other information to the header, for example user's phone number, the change is a piece of cake.

No comments:

Post a Comment

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