Maybe monad in Java (with example)

In the bibliography I put only the resources that helped me understand. I started with the intention to not use Haskell resources, but at the end I was forced to study at least the simple [3]. Doing that the bulb in my head went on all of sudden.

I must also say that my working example was born by fixing shortcomings in the solutions provided by [1] (won’t implement bind) and [2] (will chain only homogeneous Maybe’s). Sometimes you learn more by falsifying than by verifying.

Here is my Maybe monad in Java. The main point is chainability of different types of Maybe’s. For example:

Maybe<Boolean> isMarcoInTheRed = Maybe.unit(new Person(“marco”))
.bind(new PersonIdLookup()).bind(new AccountLookup()).bind(new BalanceLookup()).bind(new CheckBounce(check));

where e.g.

public class PersonIdLookup implements F<Person, Maybe<Integer>>

public class AccountLookup implements F<Integer, Maybe<BankAccount>>

…and so on.

Why chainability of different types of Maybe’s matters so much to me? Because a lonely Maybe<User> in my code, expressing whether a login was successful, is not worth the hassle. I’d have to write the plumbing code in my legacy, I’d have to explain the concept to all colleagues, I’d have to defend my choice once summoned in front of the Keeper of the Grand and Only Architecture. No, I’ll just put another if to guard against null pointers and get on.

Instead I wish to bind that Maybe<User> to a function returning a Maybe<Authorisation>, and that to a function returning a Maybe<DbConnection> from which to pull authorised data. And do that without a single if(obj != null) in my code. Is this feasible, robust, reusable, thread-safe, etc.? Well, this Maybe of mine should allow the chaining, but I still have to see it at work in a production environment.


[1] Monads for Java/C++ programmers

[2] Monads in Java

[3] wikiBooks: Haskell/Understanding monads

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s