ale*_*xey 5 erlang refactoring functional-programming
考虑一下代码:
f(command1, UserId) ->
case is_registered(UserId) of
true ->
%% do command1
ok;
false ->
not_registered
end;
f(command2, UserId) ->
case is_registered(UserId) of
true ->
%% do command2
ok;
false ->
not_registered
end.
is_registered(UserId) ->
%% some checks
Run Code Online (Sandbox Code Playgroud)
现在假设有很多命令,它们最初都是调用is_registered.有没有办法概括这种行为(重构此代码)?我的意思是在所有命令中放置相同的案例并不是一个好主意.
我会去的
f(Command, UserId) ->
case is_registered(UserId) of
true ->
run_command(Command);
false ->
not_registered
end.
run_command(command1) -> ok; % do command1
run_command(command2) -> ok. % do command2
Run Code Online (Sandbox Code Playgroud)
我认为ctulahoops的代码读取得更好,如下所示:
run_command(Command, UserId) ->
case is_registered(UserId) of
true ->
Command();
false ->
not_registered
end.
run_command(some_function_you_define);
run_command(some_other_function_you_define);
run_command(fun() -> do_some_ad_hoc_thing_here end).
Run Code Online (Sandbox Code Playgroud)
这利用了函数是Erlang中的第一类实体的事实.您可以将它们传递给函数,甚至可以在调用中匿名定义它们.每个函数的名称可以不同.cthulahoops的方法要求所有命令函数都是预定义的,并且调用run_command(),它们的第一个参数消除歧义.