[erlang-questions] variable exported from case in OTP 18

Richard A. O'Keefe <>
Thu Oct 1 08:08:08 CEST 2015

On 29/09/2015, at 9:06 pm, Martin Koroudjiev <> wrote:
> test(Mode) ->
>    case Mode of
>        r -> {ok, FP} = file:open("warn.erl", [read]);
>        w -> {ok, FP} = file:open("warn.erl", [write])
>    end,
>    file:close(FP).

[Why is this considered worse than this rewrite?]
> test(Mode) ->
>    {ok, FP} =
>        case Mode of
>            r -> file:open("warn.erl", [read]);
>            w -> file:open("warn.erl", [write])
>        end,
>    file:close(FP).

You will get a diversity of opinions on this.
In general, I think that *avoiding* variable exports from
case, if, receive, &c can lead to contorted code.
In this specific instance, however, the original code
violates the "once and only once" principle.  I'd even
prefer to see

test(Mode) ->
    {ok, FP} = file:open("warn.erl", full_mode(Mode)),

full_mode(r) -> [read];
full_mode(w) -> [write].

The kind of thing that I'd call contorted is avoiding

    case foo(...)
      of {bar,X,Y} -> ...
       ; {ugh,Y,X} -> ...
    use(X, Y)

by writing

    {X,Y} = case foo(...)
              of {bar,X1,Y1} -> ..., {X1,Y1}
               ; {ugh,Y2,X2} -> ..., {X2,Y2}
    use(X, Y)

Stuffing things into a data structure just so that you can
*immediately* pull them out again is obfuscation in my book,
and renaming what are going to be the same variables is also

It's better to look for a somewhat larger refactoring, if you
want to avoid this annoyance.

More information about the erlang-questions mailing list