Optional function parameters: Use default arguments (NULL) or overload the function?

前端 未结 12 1559
情书的邮戳
情书的邮戳 2020-12-08 00:44

I have a function that processes a given vector, but may also create such a vector itself if it is not given.

I see two design choices for such a case, where a func

12条回答
  •  误落风尘
    2020-12-08 01:01

    I would favour a third option: Separate into two functions, but do not overload.

    Overloads, by nature, are less usable. They require the user to become aware of two options and figure out what the difference between them is, and if they're so inclined, to also check the documentation or the code to ensure which is which.

    I would have one function that takes the parameter, and one that is called "createVectorAndFoo" or something like that (obviously naming becomes easier with real problems).

    While this violates the "two responsibilities for function" rule (and gives it a long name), I believe this is preferable when your function really does do two things (create vector and foo it).

提交回复
热议问题