hatcat / cg30_issues

The public issues repository for the book "Beautiful C++"
4 stars 1 forks source link

Arthur and I disagree about default parameters #3

Open hatcat opened 3 years ago

hatcat commented 3 years ago

[From Arthur] Page 18 Edit#1 ...Interesting... that you should title this chapter "Bikeshedding is bad", and then devote it to bikeshedding. ;) Many of your bike sheds are the right color, e.g. nobody's likely to argue with "Use Standard C++"; but I very vocally believe you're on the wrong side with default arguments.

See e.g. https://quuxplusone.github.io/blog/2020/04/18/default-function-arguments-are-the-devil

Your particular example is good, though. See e.g. https://quuxplusone.github.io/blog/2020/10/11/overloading-considered-harmful/ https://youtu.be/OQgFEkgKx2s "When Should You Give Two Things the Same Name?"

In your make_office example, the different versions of make_office definitely shouldn't have the same name at all. There should either be a makeOffice, a makeTwoFloorOffice, and a makeNamedOffice; or else there should be just one version of makeOffice taking all four parameters all the time. These two approaches are isomorphic to the two approaches to openConnection I show in "When Should You Give..." around the 75-minute mark. Reusing the identifier make_office for both the bool-taking and string-taking versions is definitely a bad idea.

I assume we agree that both overloading and default-argument-ing are inferior to just using different identifiers for different functionalities. Titus Winters has a talk on API design where he talks about using overload sets only for functions that in some sense "do the same thing," which is clearly not the case for makeNamedOffice versus makeTwoFloorOffice. Titus would reserve overload sets for situations where it "doesn't matter" which overload is called, because they all "do the same thing"; e.g. you might have one overload taking (const char*), another taking (const string&), and another taking (string&&).