[erlang-questions] Use of logical "not" in `case`

zxq9@REDACTED zxq9@REDACTED
Fri Feb 9 10:31:35 CET 2018


Someone asked me an interesting question about readability of case statements, and I'd like some alternative opinions (because I can't decide myself).

When writing a case statement based on a boolean expression, like whether or not to take an action depending on whether or not a given value is a key in a map, I tend to put the value that causes something to happen first assuming that this will be the most interesting path.

For example:


foo(Status, Thingy, Assignments) ->
    case maps:is_key(Thingy, Assignment) of
        false ->
            Assignment = fomulate_assignment(Thingy),
            NewAssignments = maps:put(Thingy, Assignment, Assignments),
            {assigned, NewAssignments};
        true ->
            {Status, Assignments}
    end.


This isn't the best example case, but you get the idea. We care about the case where Thingy was not already assigned and have to do something there, and we just pass the values back in the case it already was. Here the false case came first -- it could have come second, that doesn't *really* matter to me, but I tend to put the interesting stuff up front.

Now compare:


foo(Status, Thingy, Assignments) ->
    case not maps:is_key(Thingy, Assignment) of
        true ->
            Assignment = fomulate_assignment(Thingy),
            NewAssignments = maps:put(Thingy, Assignment, Assignments),
            {assigned, NewAssignments};
        false ->
            {Status, Assignments}
    end.


The argument was that 'true' should always be the more interesting case (whenever there is a more interesting case) because that reads closer to the semantics of the check being done were we to describe it in conversation "If A is *not* a member of B, then [stuff]".

That makes sense to me. It sounds like a reasonable argument.

This isn't a big deal either way of course (I find them both equally readable), but I am curious if anyone has a strong opinion on the issue and why. Which would you prefer to encounter when reading a project to understand how it works on github?

-Craig



More information about the erlang-questions mailing list