## 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)
{"ft_lang_label":"__label__en","ft_lang_prob":0.6001311,"math_prob":0.9864338,"size":1157,"snap":"2019-51-2020-05","text_gpt3_token_len":306,"char_repetition_ratio":0.19601041,"word_repetition_ratio":0.3125,"special_character_ratio":0.27312014,"punctuation_ratio":0.13170731,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.98940974,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-12-13T01:11:58Z\",\"WARC-Record-ID\":\"<urn:uuid:8144cba0-8d3a-4eb5-b3a7-bdeef42601a6>\",\"Content-Length\":\"51840\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:aeb083b9-ccc1-4ba3-b3ec-f0358d75976e>\",\"WARC-Concurrent-To\":\"<urn:uuid:493fd490-a19d-4bb9-be7d-cebebe9d198e>\",\"WARC-IP-Address\":\"172.217.7.211\",\"WARC-Target-URI\":\"http://blog.adelante.ca/2016/03/refactoring-remove-named-parameters.html\",\"WARC-Payload-Digest\":\"sha1:62AJWMFBETQLEUWKSIFIFRJRXSZEQLGV\",\"WARC-Block-Digest\":\"sha1:US2W5HWUNO2P6V5BKOWU6RR35GGQFSM5\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-51/CC-MAIN-2019-51_segments_1575540547536.49_warc_CC-MAIN-20191212232450-20191213020450-00389.warc.gz\"}"}