Erlang:简单重构
考虑一下代码:
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
现在假设有很多命令,并且它们一开始都被调用is_registered。 有什么方法可以概括这种行为(重构此代码)?我的意思是,在所有命令中放置相同的大小写并不是一个好主意。
Consider the code:
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
Now imagine that there are a lot of commands and they are all call is_registered at first.
Is there any way to generalize this behavior (refactor this code)? I mean that it's not a good idea to place the same case in all the commands.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我会和
I'd go with
我认为 ctulahoops 的代码重构后读起来更好:
这利用了函数是 Erlang 中的一流实体这一事实。您可以将它们传递到函数中,甚至可以在调用中匿名内联定义它们。每个函数可以有不同的命名。 cthulahoops 的方法要求预定义所有命令函数并调用 run_command(),并通过第一个参数消除歧义。
I think ctulahoops' code reads better refactored like so:
This takes advantage of the fact that functions are first-class entities in Erlang. You can pass them into functions, even define them anonymously inline in the call. Each function can be named differently. cthulahoops' method requires that all your command functions be predefined and called run_command(), disambiguated by their first argument.
另外,交互式重构工具 Wrangler 可能是您的朋友。
Also Wrangler, an interactive refactoring tool, might be your friend.
我更喜欢使用异常。它将允许针对成功案例进行编程,并减少缩进级别的使用。
I like the use of exceptions better. It would allow programming for the successful case, and it decrease the use of indentation levels.
我更喜欢这种方式,它提供了更大的灵活性:
I prefer this way, it gives more flexibility: