4 ms·
The functional paradigm answer to this is to have an Option<T> type, or Result<TSuccess, TFailure>, which allow you to flexibly account for the “null case” whil
by camdenreslink 8y ago
The functional paradigm answer to this is to have an Option<T> type, or Result<TSuccess, TFailure>, which allow you to flexibly account for the “null case” while still having total functions (https://en.m.wikipedia.org/wiki/Total_functional_programming https://en.m.wikipedia.org/wiki/Total_functional_programming).
The only catch, is now you have to unwrap your function results somehow (functional languages provide ways to do that, like the scary monad).
I like this website, which demonstrates the concept: https://fsharpforfunandprofit.com/rop/ https://fsharpforfunandprofit.com/rop/
- barrkel 8y agoOption monads have the same semantics as C# null described in the article; they don't apply the function if the value isn't present, you get another non-present value back out. Result<,> has the same semantics as checked exceptions, BTW. The conversion between the two representations of code is mechanical. Checked exceptions are a poor idea the more dynamically bound your language is, and are generally anti-abstraction in any case (failure modes are implementation specific, i.e. non-conformant with an information hiding interface). An error result is only useful if you can make a decision based on the specific value; that's not the case for almost all sources of error in most user (i.e. non-system) programs, where complete coverage of error cases with specific handlers is outside their design parameters, and termination (of program or request or whatever) is preferable.
- camdenreslink 8y agoIt’s about the ability to reason about the code. Option types force matching expressions whenever you encounter the wrapped value, forcing the developer to handle the failure case. Equivalent C# code is to add checks for nulls all over the place, aka “defensive coding”. C# has an Option type sort of with nullable types, but they are for value types only, and developers can still reach in and just grab the value, eliminating the safety that option types provide.