Say I have a C++ function
/**
* @param path If empty, the system default is used
*/
void foo(const std::string& path);
And in my implementation I have a default handling for empty path
s
void foo(const std::string& path) {
if (path.empty()) {
// Use some default
} else {
// Use the given path
}
}
However, the if-else blocks are quite the same so I would either write
A
void foo(const std::string& path_) {
const std::string& path = path_.empty() ? "some default" : path_;
// Use the given path
}
B
or change the function definition altogether:
void foo(std::string path) {
if (path.empty() {
path = "some default";
}
// Use the given path
}
Now I am wondering what is advised in terms of style in such cases:
- A seems a little odd at first because I explicitly made the parameter const and now start to somehow "rewrite" it. Would this code look like overkill?
- B seems a little odd because then, this function would have a different signature just because of some implementation details. It would stand out from the other functions which still use
const&