[erlang-questions] Must and May convention

Joe Armstrong <>
Wed Sep 27 11:08:02 CEST 2017


For several years I've been using a convention in my hobby
projects. It's what I call the must-may convention.

I'm wondering if it should be widely used.

What is it?

There are two commonly used conventions for handling bad arguments to
a function. We can return {ok, Val} or {error, Reason} or we can
return a value if the arguments are correct, and raise an exception
otherwise.

The problem is that when I read code and see a function like
'foo:bar(a,12)' I have no idea if it obeys one of these conventions or
does something completely different. I have to read the code to find
out.

My convention is to prefix the function name with 'must_' or 'may_'

If I see must_ in the name I know the arguments to the function must
be correct and that the function will return {ok,Val} | {error,Why}

If I see may_ in the name I know the arguments must be correct but if
they are not an exception will be generated, with meaningful data in
the exception so I can see what went wrong.

If a function follows neither of these conventions then it can do
whatever it feels like.

        - example -

  I have a library of interface functions,
  something like:

   must_read_file(F) ->
       case file:read_file(F) of
            {ok, Bin} ->
        Bin;
    {error, _} ->
        io:format("Could not read file ~p~n",[F]),
        exit({must,violation,read_file, F})
       end.

   may_read_file(F) -> file:read_file(F).

Now my source code becomes more readable

    test(F) ->
        Bin = must_read_file(F),
...

or
    test(F) ->
       case may_read_file(F) of
            {ok, B} ->
        ..
            {error, _} ->
    ..
end.

This turns out to be very convenient - I read many files
in my programs, so it's nice to know that must_read_file
will print a nice error message and terminate
if I give it a bad filename.

Note: I can get the program to crash by writing

   {ok, B} = file:read_file(F)

But I don't get a nice error message telling me the filename.

Any takers?

Cheers

/Joe


More information about the erlang-questions mailing list