in ,

Be wary of functions which take several parameters of the same type, Hacker News


APIs should be easy to use and hard to misuse.

– Josh Bloch

A good example of a simple looking, but hard to use correctly, API is one which takes two or more parameters of the same type. Let’s compare two function signatures:

func Max (a, b int) int func CopyFile (to, from string) error

What’s the difference between these functions? Obviously one returns the maximum of two numbers, the other copies a file, but that’s not the important thing.

Max (8, 10) // 10 Max (10, 8) // 10

Maxiscommutative; the order of its parameters does not matter. The maximum of eight and ten is ten regardless of if I compare eight and ten or ten and eight.

However, this property does not hold true forCopyFile.

CopyFile ("/ tmp / backup", "presentation.md") CopyFile ("presentation.md", "/ tmp / backup")

Which one of these statements made a backup of your presentation and which one overwrite your presentation with last week’s version? You can’t tell without consulting the documentation. A code reviewer cannot know if you’ve got the order correct without consulting the documentation.

The general advice is to try to avoid this situation. Just like long parameter lists, indistinct parameter lists are a design smell.

A challenge

When this situation is unavoidable my solution to this class of problem is to introduce a helper type which will be responsible for callingCopyFileCorrectly.

type Source string  func (src Source) CopyTo (dest string) error { return CopyFile (dest, string (src)) }  func main () { var from Source="presentation.md" from.CopyTo ("/ tmp / backup") }

In this wayCopyFileis always called correctly and, given its poor API can possibly be made private, further reducing the likelihood of misuse.

Can you suggest a better solution?

Brave Browser
Read More
Payeer

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *

GIPHY App Key not set. Please check settings

Dow Futures Drop Ahead of 'Highly Consequential' U.S.-China Trade Talks, Crypto Coins News

Dow Futures Drop Ahead of 'Highly Consequential' U.S.-China Trade Talks, Crypto Coins News

Nick Jonas head-bangs to First Class before band show. Has Priyanka Chopra seen this video yet? – India Today, Indiatoday.in

Nick Jonas head-bangs to First Class before band show. Has Priyanka Chopra seen this video yet? – India Today, Indiatoday.in