3

Are there best practices for function names in that case where an in-place and an out-of-place function exists and they can not be distinguished using the parameters?

Example: Suppose I have a function to make a string uppercase:

void toUppercase(std::string & s); // modify s directly, in-place
void toUppercase(const std::string & s, std::string & result); // result will contain the modified string
std::string toUppercase(const std::string & s); // return the modified string

Functions 1 and 2 can be distinguished by C++ even if they have the same name, but 1 and 3 cannot. What names would make it clear to the user which function does what? Are there maybe any library examples where this problem has been solved in some way?

Fabian
  • 4,001
  • 4
  • 28
  • 59
  • Chose one or another if possible. I try to do everything with the second approach with `in` and `out`. Mostly I use a return value like `bool` to check if everything was ok or an error occured (my method for error handling, exceptions are not allowed). So my suggestion is use one style and if you have to, use another name for the function like `toUppercase_inplace(...)` not beautiful, but every developer sees, that this is not the `standard` interface – RoQuOTriX Jan 22 '20 at 09:09
  • @RoQuOTriX I also prefer 2 because it allows to signal success or failure as a return value. But for simple functions I prefer 3 because I can assign the result to a const variable. – Fabian Jan 22 '20 at 09:29
  • You could provide the third as a wrapper for the second to post-pone the decision which one to prefer to the moment you have to use it. As they have a different number of arguments, they can have the same name. It can become interesting if you allow for the second function that first and second argument may actually be a reference to the same variable. ;-) – Scheff's Cat Jan 22 '20 at 09:45
  • I'd say I'd change the 3rd method prefix to make it clear something is returned: asUppercase() or getUppercase() or makeUppercase(). – m88 Jan 22 '20 at 12:28

0 Answers0