Hacker News new | ask | show | jobs
by tester34 1749 days ago
Have you considered using patterns that help dealing with that?

like Railway Oriented Programming

https://www.youtube.com/watch?v=45yk2nuRjj8

I believe that almost every thing should return Result<T>, because almost everything can fail and compiler should scream when you do not handle those fail pathes.

That makes me believe that C#'s "FirstOrDefault" for value types sucks, because you're never sure whether the "Default" comes due to lack of value or because the found value is actually the same as default

e.g

var list = new List<int> {1,2,3};

var found = list.FirstOrDefault(x => x < 1);

found = 0 (default)

meanwhile 0 may be valid value! so we aren't sure whether it is error or an actual value

and we have to perform e.g casts to `int?` or stuff to detect that.

using Result<T> gives very precise information

1 comments

> meanwhile 0 may be valid value! so we aren't sure whether it is error or an actual value

This function is useful when you don't really care whether it's an error or the value. Imagine you're querying the view count of an item of the user. If the user is anonymous, the select might give an empty result, but you only care about showing a number to the user. So 0 is absolutely fine in that case.

If it's important to you whether the item actually exist, you're using the method in the wrong place.

Yes, I can always use First and catch Exception, which is meh.

First returning Result<T> or something like FirstOrNull would be better, because FoN would work for ref types - classes and stuff the same way (afaik) as FoD does, but it'd make error handling for value types like ints more precise