[erlang-questions] feedback please

zxq9 zxq9@REDACTED
Thu Sep 24 07:39:44 CEST 2015

Ah, one thing worth pointing out... some people really hate case statements. I'm not religious about this, but very often I will do something slightly different than you might see in books: "name" my case statements by making them into function calls. (I *do* hate nested case statements, though, especially when there are a lot of them!)

Consider the way ask_action/0 was implemented earlier:

ask_action() ->
     Input = io:get_line("Which action do you need? (W)ithdrawl/(D)eposit? "),
     case Input of
         [$w | _] -> withdrawl;
         [$W | _] -> withdrawl;
         [$d | _] -> deposit;
         [$D | _] -> deposit;
         BadInput ->
             ok = io:format("You can't seem to '~tp' today...~n"
                            "Let's try that again...~n",

We might change this to...

ask_action() ->
    ask_action(io:get_line("Which action do you need? (W)ithdrawl/(D)eposit? ")).

ask_action([$w | _]) -> withdrawl;
ask_action([$W | _]) -> withdrawl;
ask_action([$d | _]) -> deposit;
ask_action([$D | _]) -> deposit;
ask_action(BadInput) ->
     ok = io:format("You can't seem to '~tp' today...~n"
                    "Let's try that again...~n",

The advantages here are not universal, but you will almost certainly see this caseless style of code occasionally. Sometimes it can be really useful, sometimes it can be annoying to read if the calls are always in-lined with huge compositions-as-arguments. For example, if we had removed ask_action/0 and included the user prompt in-line within get_balance/1 it would have been slightly more distracting to the eye. I favor verb-focused readability in the places I can have it; but not everyone does (and that wouldn't have been so bad in this case, anyway -- but there are cases where you can spend a few minutes working out what the hell is going on in the arguments to a function call, and this is super annoying to me, especially when you know that part the original author's reason for making some particular case into a function call was readability).

Anyway, I digress. Just be aware that matching allows you to move a case into a function call, and make the match on the head -- and this is a somewhat common technique to "name" case statements (it can often make the trace of a crashed process much easier to read/understand/fix).


More information about the erlang-questions mailing list