Wednesday, March 9, 2016

Refactoring: remove the named parameters

The functions in Swift can have named or unnamed parameters. Usually, named parameters give more clarity on their purpose. Sometime though, the names are redundant. In those cases, the names can be removed.

For example, in the following cases:

func max(firstValue firstValue:Float, secondValue:Float) -> Float {
    if firstValue < secondValue {
        return secondValue
    } else {
        return firstValue
    }
}

func powerOfTwo(power power:Int) -> Float {
    if power < 0 {
        return 1 / powerOfTwo(power: -power)
    }
    if power == 0 {
        return 1
    }
    return 2 * powerOfTwo(power: power-1)
}

We can invoke the functions as follows:

max(firstValue:10, secondValue: 20)

powerOfTwo(power: 10)

The parameters' names are not bringing any value to the code. It is obvious that the first one is calculating the maximum between two numbers. The order of the numbers does not matter.

The second one is calculating the power of two. The parameter is the power and that is obvious.

We can remove the parameter names, making the code simpler:

func max(firstValue:Float, _ secondValue:Float) -> Float {
    if firstValue < secondValue {
        return secondValue
    } else {
        return firstValue
    }
}

func powerOfTwo(power:Int) -> Float {
    if power < 0 {
        return 1 / powerOfTwo(-power)
    }
    if power == 0 {
        return 1
    }
    return 2 * powerOfTwo(power-1)
}

In this case, we can call the functions as follows:

max(10, 20)
powerOfTwo(10)


No comments:

Post a Comment