Live data from Hacker News

Maybe Functions

blog.benwinding.com

1–10 of 103 posts

Re: Maybe Functions

#2
After reading this I realise that I am guilty of building many "maybe" functions in my own code. Definitely something I need to be aware of

Re: Maybe Functions

#6
Another option is Exceptions. The function either does what it's supposed to, or freaks out.

You can remove the null checks and the software will raise a null pointer exception. In the first example, could raise a NotLoggedInException.

It's still a maybe function, but you have a mechanism for expressing the why-notness of the function run, as opposed to returning a generic null.

As an aside, I prefer the "Unless" model of thinking vs the "Maybe" model of thinking. It's biased towards success. It presumes that the function is most likely to do something unless a precheck fails. filterBestFriendsUnless vs maybeFilterBestFriends. getUserUnless vs maybeGetUser. If we go this far down the rabbit hole, we can assume there's always an "unless". Programs run out of memory, stacks have limited depth. There are maybe conditions for which we can not account.

Re: Maybe Functions

#7
An alternative I've used or seen used in Java is to put @Nullable on the function. The caller knows the result could be null, and must check for it. Linters/Static analysis can verify when you haven't checked it as well.

There's an urge to return Optional but now you must check Optional.isPresent AND object != null.

Re: Maybe Functions

#8
Agreed with this essay, and I think it rhymes with two others that I've found pretty influential over the past five years:

1. Parse, don't validate (https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-va...)

2. Pipeline-oriented programming (https://fsharpforfunandprofit.com/pipeline/)

In my experience, the "best" code (defining "best" as some abstract melange of "easy to reason about", "easy to modify", "easy to compose", and "easy to test") ends up following the characteristics outlined by the sum of these three essays — strictly and rigorously elevating exceptions/failures/nulls to first-class types and then pushing them as high in the stack as possible so callers _must_ deal with them.

Re: Maybe Functions

#9
Not everthing that can return null is a maybe function, sometimes you need a difference between zero and nothing.

Solution3 for their example:

  function maybeRenderBestFriends() {
    const user = maybeGetUser();
    if(user!=null){
      const friends = maybeGetFriends(user);
      const bestFriends = maybeFilterBestFriends(friends);
      return render(bestFriends);
    }
    return null;
  }
Post reply on HN