2 ms·
The author is conflating two separate concepts, and calling them both "the maybe function": 1) functions which do hidden things outside of their contract a
by mrkeen 3y ago
The author is conflating two separate concepts, and calling them both "the maybe function":
1) functions which do hidden things outside of their contract and/or whose implementation doesn't properly line up with their types.
2) functions which (by necessity) cannot always return the desired value and must return something else instead.
> The maybe function is a subtle monster that spreads it’s tentacles across the code-base.
This applies to both points 1 and 2.
> It’s alternating functionality of “does/doesn’t do something” makes code hard to understand, maintain and debug.
This only applies to point 1.
> They seem to be trivial to add, but difficult to remove. But hopefully this illustrates the concern and ways to fix it.
This cannot apply to point 2, because you cannot take a function which might return a user and `fix` it to make it always return a user.
> Solution 2 - Monads
This is not a monad.
He has implemented the Maybe Functor. runSafely most likely corresponds to map in whatever library you're using, not flatMap.
This is visible from its type signature:
> runSafely(fn: (val: T) => V): Maybe<V> // map
which should be
> runSafely(fn: (val: T) => Maybe<V>): Maybe<V> // flatMap
And it's also visible in the example function:
function getUser(): User {
if (!loggedIn) {
return null
}
return fetchUser();
}
... which still suffers from points 1 and 2. Because it's the same function which was highlighted as bad code at the top.