Here is a quick demonstration of how the Maybe monad and the do keyword can simplify the chaining of methods. The following shows a succession of condition evaluations which must all succeed for the final function (process_json_entities) to be called:
For those of you who wonder, yes I know that WebMachine could do most of this stuff for me: using this awesome REST framework is not an option for my project.
Without the help of the maybe monad, I would have add to either nest case clauses (yuck!) or chain methods, each of them calling the next one in case of success of its condition.
There are two problems with the latter approach:
- the most obvious problem is that the overall sequence of calls would not be in one place but buried deeper and deeper in the succession of functions,
- the least obvious problem pertains to the classic issue of naming things: finding good names for a chain of methods, each of them testing a condition and calling the next one is very hard.
So what's inside each of these method? Let's look into the first, which is basically a blueprint for most of them:
Notice on line 4 and 7 how the return/1 and fail/1 method of the Maybe monad are used to influence the flow of the sequence in the encapsulating do. The values I'm passing to these two functions are purely arbitrary but it is not always the case. In the first example above, on line 5 the value passed to return/1 in extract_json_entities is assigned to JsonEntities, eventually passed to the actual processing function.
To make this work, besides a Rebar dependency, not much is needed besides the following directives:
Hopefully, this will whet your appetite and decide you to give Erlando a try!