Improved error handling with a Result class #4777
Replies: 2 comments
-
It wouldn't be nearly as nice, because of limitations of C# type inference. You could fairly easily create a type like static Result<uint> GetMinusOne(uint i)
{
if (i == 0)
return new Err<uint>();
return new Ok<uint>(i - 1);
}
void Use(uint i)
{
/* Handle result via a switch */
switch (GetMinusOne(i))
{
case Ok<uint>(var newVal): Console.WriteLine("Val: {}", newVal); break;
case Err<uint>: Console.WriteLine("Failed"); break;
}
} In general, I think attempting to bolt a second error-handling mechanism onto a language that already has one is not worth it. I think your |
Beta Was this translation helpful? Give feedback.
-
Result-based error handling isn't "better" than exception. It's just an alternative. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Background
Half a year ago I discovered this programming language called Beef. In essence, it is a programming language that targets native code, and that borrows heavily on C#, but with some improvements. The base class library has been made to look like .NET:s. Namespaces and classes are largely named the same. It even has got Reflection-support!
Idea
One of the ideas that got me interested was their method of handling errors:
Result
enum ([docs] (Enums are different in Beef). The designers opted to follow this pattern instead of exceptions.The consequence is that method returns an object that then can be pattern matched for the result.
Here is an example taken from the docs:
Since result is an enum, the type can be inferred, simply by
.value
. And enums may take args.Questions
Enum in Beef (Data types):
They are more like discriminated unions.
Beta Was this translation helpful? Give feedback.
All reactions