Monday, March 14, 2016

Replace parameter with method

Apply this method when the code is invoking one function and passes the result to another function.

If the second function can invoke the function by itself, it should.

Let's consider the following class:

class User {}

And a function that retrieves the current user:

func getCurrentUser() -> User {
    var currentUser: User
    //find the user
    return currentUser
}

The following function returns all the friends of a user:

func findFriendsForCurrentUser(user:User) -> Array<User> {
    var array = [User]()
    //uses user to find his friends
    return array
}

We can invoke the functionality as follows:

let currentUser = User()

let currentUserFriends = findFriendsForCurrentUser(currentUser)

We notice though, that we always use the functionality for the current user.

So there is no point in passing the current user, when the function can get it by itself.

We remove the parameter and change the function to get the current user by itself:

func findFriendsForCurrentUser() -> Array<User> {
    let user = getCurrentUser()
    var array = [User]()
    //uses user to find his friends
    return array
}


No comments:

Post a Comment

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