[英]How could this code be improved
我正在寻找一种避免两次声明return_with_nok
的方法,但仍然会return_with_nok
两种情况。 有没有一种方法可以编写比当前代码更详细的代码?
def receive_notification(params)
if some_condition
case params[:case]
when 'case2'
... logic...
when 'case2'
... logic...
end
else
return_with_nok
end
else
return_with_nok
end
end
这是您要做什么?
def receive_notification(params)
return 'c' unless params.is_a?(Hash)
case params[:case]
when 'case1'
'a'
when 'case2'
'b'
else
'c'
end
end
编辑
您的新示例似乎仍然在不属于该逻辑的逻辑下处于end
,无论如何,我宁愿通过使用保护子句而不是条件句来按如下方式对其进行重构。
def receive_notification(params)
return return_with_nok unless some_condition
case params[:case]
when 'case2'
..logic..
when 'case2'
..logic..
else
return_with_nok
end
end
有一种方法可以使这种方法比原始的原始代码丑陋得多:
case some_condition && params[:case]
when ...
else
# ...
end
如果可以将条件组合成一个奇异的值,则可以将其放入case
语句中。 对于那些不熟悉&&
评估方式的人来说,可能很难遵循。
我主张即使是以一些冗长的代价为代价,也应使用最少混乱的选项。
解决该问题的另一种方法是提前解决它,将逻辑扁平化:
return ... unless (some_condition)
case (...)
# ...
end
您将有一个重复的函数调用,这可能是逻辑结构如何的问题。 真的要看
通过在您的case
添加明确的回报并依靠失败来满足您的要求吗?
def receive_notification(params)
if some_condition
case params[:case]
when 'case1'
... logic...
return something1
when 'case2'
... logic...
return something2
end
end
return_with_nok
end
有点奇怪,但是您可以这样做:
params[:case] = 'else' unless some_condition
或类似这样,因此您无需更改用户参数:
kase = some_condition ? params[:case] : 'else'
case kase
#...
然后,如果条件不匹配,您将最终进入else。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.