code4it-dev / blog-comments

https://www.code4it.dev/
1 stars 0 forks source link

cleancodetips/exceptions-instead-of-null #39

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

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

tomashevich commented 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/

bellons91 commented 1 year ago

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?)

vberkaltun commented 1 year ago

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.

bellons91 commented 1 year ago

Yes, something like OperationResult where you can specify the result if everything went fine and the error in the other case.

Do you know a good implementation of something similar to it?

KiritchoukC commented 1 year ago
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

ekennedy6334 commented 1 year ago

Try https://github.com/louthy/language-ext.