Open utterances-bot opened 1 year ago
You need to be careful with exceptions, your code can be up to 500 times slower. https://gunnarpeipman.com/cost-of-exceptions/
Yes indeed - exceptions should not be used to control operation flow.
But they must be used to "notify" callers that an unrecoverable error occurred.
(even though I'd like to find a way to totally get rid of exceptions... maybe railway-oriented patterns?)
What you are saying is logically fine. In practice returning a null
or false
for a non-implemented function is not a common approach, so the usage of exception handling is a good solution here for making the method's behavior explicit. On another hand, you should keep in mind that exception handling can cost you a lot on the performance side. If you do that for every function, then you really mess up your runtime.
I strongly believe that these kind of issues need a fix on the design level, not on the behavior level. Maybe you can use an enum
class as a return value, or maybe a class instance that can hold both the result and status values.
Yes, something like OperationResult
Do you know a good implementation of something similar to it?
class abstract Result
{
// Common properties
}
class Success : Result
{
object data {get; set;}
}
class Error : Result
{
string errorMessage {get; set;}
}
// usage
Result GetResult()
{
var httpResponse = api.Get();
if(httpResponse.OK)
{
return new Success(httpResponse.data);
}
else
{
return new Error(httpResponse.statusMessage);
}
}
var result = GetResult();
if(result is Success s)
{
print(s.data);
}
if(result is Error e)
{
print(e.ErrorMessage);
}
You can find more advanced solution but that's the idea. LangageExt.Core library is the most complete one in my opinion
Clean Code Tip: throw exceptions instead of returning null when there is no fallback - Code4IT
In case of unmanageable error, should you return null or throw exceptions?
https://www.code4it.dev/cleancodetips/exceptions-instead-of-null?utm_source=csharpdigest&utm_medium=email&utm_campaign=435