2 ms·
The author kind of sabotaged his point here. Optional values are a greate choice if you expect the operation to fail and if you expect the consumer to do someth
by danbruc 9y ago
The author kind of sabotaged his point here. Optional values are a greate choice if you expect the operation to fail and if you expect the consumer to do something meaningful in case of a failed operation. But if the the consumer can't really do anything in case of a failed operation it becomes a burden to deal with the optional values and you have to bring in additional machinery to keep your code clean and propagate the failure transparently one level up the call stack.
With exceptions on the other hand propagating the failure up the call stack is the default behavior not requiring additional code unless you can and want to deal with the failure. As so often it seems to me that you don't want one or the other but the right one for the situation. The author unfortunately picked an example that seems a much better fit for exception because in his example he is unable to respond to the possible failures and just wants to propagate it on level up the call stack.
- zmj 9y agoA method shouldn't know whether its consumer can do something meaningful on failure. Return an error value and let them decide.
- danbruc 9y agoYou are not writing a function in a vacuum. You make choices about how arguments are passed into the function and choices about how results are returned from the function including errors. Optional values and exceptions offer different trade-offs and you should pick the one that is probably most useful and most easy to work with. What do I know what the caller will do with my return value, I will just return a XML string with the serialized result and let them do with that whatever they want is probably not a good design philosophy to adopt either.
- Terr_ 9y agoI think there is also a niche for checked exceptions, which kind of fall in the middle between those two approaches. A checked-exception forces the programmer to notice and make a design-decision. At the same time, if the designer chooses to merely propagate it up the stack, that's extremely easy to do just by editing the function signature.