Wednesday, February 24, 2016

Refactoring in Swift: Introduce named parameter

Functions in Swift allow two types of parameters: named and unnamed.

When calling the function, for the named parameters their name has to be provided. For the unnamed, just the value of the parameter is sufficient.

Sometimes it makes sense to have unnamed parameters.


For example a function that has is calculating the maximum of two numbers can be invoked as max (3, 7) without causing any confusion.

Some functions have the first parameter unnamed and the rest of them named (actually this is the default setting for functions in Swift).

For example:

class User {
    //...
}

func calculateYearlySalaryForUser(user:User, year: Int) {
    //...
}

let user = User()

calculateYearlySalaryForUser(user, year: 2016)

This is pretty clear.

In some cases, for some unknown reasons, the developer might choose to use only unnamed parameters, like in the following example:

func formatAddress(street: String,_ number: String,
     _ city: String,_ country: String) {
    print("\(number) \(street), \(city), \(country) ")
}

For calling this function, we need to use the following code:

formatAddress("Younge St.", "1234", "Toronto", "Canada")

This can be a bit hard to remember and it is prone to mistakes.

The solution is to use only named parameters, like follows:

func formatAddress(street street: String, number: String, 
       city: String, country: String) {
    print("\(number) \(street), \(city), \(country) ")
}

In this case, calling the function has the following format:

formatAddress(street: "Younge St.", number: "1234", 
   city: "Toronto", country: "Canada")

Now it is clear what each parameter is.


No comments:

Post a Comment

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