Skip to content

Instantly share code, notes, and snippets.

@stolen
Last active February 21, 2018 16:38
Show Gist options
  • Save stolen/8537619 to your computer and use it in GitHub Desktop.
Save stolen/8537619 to your computer and use it in GitHub Desktop.
Erlang refactoring proposal
-module(no_deep_case).
-export([deep/1, no_deep/1]).
deep(X) ->
case x:do_something(X) of
{ok, Result1} ->
case x:do_something_else(X, Result1) of
{ok, Result2} ->
case x:final_action(Result2) of
ok ->
{ok, Result2};
Error ->
Error
end;
Error ->
Error
end;
Error ->
Error
end.
success({ok, _}) -> true;
success(_) -> false.
value({ok, Value}) -> Value.
no_deep(X) ->
Ret1 = x:do_something(X),
Ret2 = success(Ret1) andalso x:do_something_else(X, value(Ret1)),
Ret3 = success(Ret2) andalso x:final_action(value(Ret2)),
case {success(Ret1), success(Ret2), Ret3} of
{false, _, _} ->
Ret1;
{true, false, _} ->
Ret2;
{true, true, ok} ->
{ok, value(Ret2)};
{true, true, Error} ->
Error
end.
@yhafri
Copy link

yhafri commented Feb 21, 2018

deep__(X) ->
    try
        {ok, Result1} = x:do_something(X),
        {ok, Result2} = x:do_something_else(X, Result1),
        ok            = x:final_action(Result2),
        {ok, Result2}
    catch _:{badmatch, Err} -> Err end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment