isocpp / isocpp/CppCoreGuidelines
Suggestion: promote better return type
@BjarneStroustrup is already working on this.
Since Feb 14, 2019.
- Dominant language
- CSS
- Stars
- 45.3k
- Forks
- 5.6k
- PR merge metrics
- No merged PRs in 30d
Description
Good day. I want to make a suggestion. I am not 100% sure this is not covered in the guidelines already, but I do not see it upon quick inspection. Below is my argument and suggestion.
A function or method can fail. For example, let's take a simple example, fopen. As we all know, fopen may fail for a number of reasons.
fopen from cstdio looks like this:
FILE * fopen ( const char * filename, const char * mode );
This code implicitly 'expresses' that it can return a FILE pointer or nullptr in case of a problem. In my opinion, this is bad because meaning should be explicit, especially where it comes to success of failure.
So, to combat this, I encourage returning a simple templated type from all functions. For example, if I had to write fopen, I would have done it something like this:
// In order to facilitate conveying success and failure explicitly, I will use FunctionResult as a return value of all functions.
template<typename T> class FunctionResult
{
public:
bool IsSuccess;
T Result;
FunctionResult()
{
IsSuccess = false;
Result = nullptr;
}
};
FunctionResult<FILE*> fopen_enhanced(const char * filename, const char * mode)
{
FunctionResult<FILE*> result;
FILE* ptrFile = fopen(filename, mode);
if (ptrFile == nullptr)
{
result.IsSuccess = false;
}else
{
result.IsSuccess = true;
result.Result = ptrFile;
}
return result;
}
I have been using this mechanism, not only in C++ but in Kotlin as well, and it really adds to the expressiveness. I personally would make this practice a suggestion in the core guidelines, but I am open to criticism!
Thanks.
Marius.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.