Closed vicmosin closed 6 years ago
Hi @vicmosin,
You are certainly right that there are cases where a custom exception is more suitable.
ValueOrFailure()
should be seen as a shortcut that does the right thing in a lot of cases, e.g. acting as an assertion when you know the value should be present. It throws a uniquely identifiable exception, which is reasonable for such scenarios.
Although I generally prefer to handle None-cases without actually introducing exceptions, there might be scenarios where throwing a custom exception is the most reasonable thing to do. This is actually already supported using ValueOr()
(although this might not be explicitly described in the documentation):
var value = option.ValueOr(() => throw new InvalidOperationException("Some error message..."));
This, of course, is just standard C# features in use, and it will certainly be a bit more verbose in C# version < 7. Even so, I find it unlikely that I will introduce a new overload for ValueOrFailure
, which can instead continue to be used for strict assertions that a value is present.
Hope it helps.
/Nils
Thanks for your reply. It's indeed not covered by documentation, so maybe you should improve it a bit ;) Thanks again
There are cases when it would be nice to have custom exception throwing as a default behavior in case of Optional has no value since default exception (OptionalValueMissing..) is too private and forces you to handle it. The user-defined exception will be much common. Something like
Optional.Map(..).ValueOrFailure(() => AnyKindOfCustomException())
I noticed that you have
Optional<T, TException>
but this solution also problematic since it requires to define the optional of this particular type in advance, while exceptional behavior might pop up only on runtime..