Tim*_*imH 48 ruby coding-style
为了更简洁地写,而不是这样做:
test_value = method_call_that_might_return_nil()
if test_value
do_something_with test_value
end
Run Code Online (Sandbox Code Playgroud)
我一直在条件中分配:
if test_value = method_call_that_might_return_nil()
do_something_with test_value
end
Run Code Online (Sandbox Code Playgroud)
这是不好的风格?更简洁的语法:
do_something_with test_value if test_value = method_call_that_might_return_nil()
Run Code Online (Sandbox Code Playgroud)
根据Matz(http://redmine.ruby-lang.org/issues/show/1141),正如另一个SO问题所讨论的那样,不允许在1.9中保持这种状态.
鉴于分配和比较可能混淆,这是否使得阅读代码变得太难?
Dev*_*ons 32
在条件语句中使用赋值显然是GOOD样式.如果这样做,请将条件括在括号中.
# bad (+ a warning)
if v = array.grep(/foo/)
do_something(v)
# some code
end
# good (MRI would still complain, but RuboCop won't)
if (v = array.grep(/foo/))
do_something(v)
# some code
end
# good
v = array.grep(/foo/)
if v
do_something(v)
# some code
end
Run Code Online (Sandbox Code Playgroud)
Jör*_*tag 28
一个有点普遍的习惯是使用and
,看起来像这样:
tmp = method_call_that_might_return_nil and do_something_with tmp
Run Code Online (Sandbox Code Playgroud)
另一种可能性是#nil?
明确地调用,这样意图就会变得更加清晰; 特别是很明显,你实际上是想分配而不是比较:
unless (tmp = method_call_that_might_return_nil).nil?
do_something_with tmp
end
Run Code Online (Sandbox Code Playgroud)
简洁的代码不一定是更好的代码.当Concision改进了从作者到未来维护者的预期代码行为的通信时,它很有用.我认为我们中的很多人来自于我们在if
块中意外分配的背景(当我们想要进行相等比较时)我们更喜欢样式,其中绝对清楚的是赋值是指,而不是比较..nil?
已经提到的成语具有该属性,并且我认为它比在if
条件中具有裸分配更清晰.但实际上,我没有看到为分配提供额外代码行的危害.
执行此操作的函数式编程方法是使用andand
.这是一种链接方法调用的可读方式,因此中间的nil会阻止链.所以你的例子是这样的:
method_call_that_might_return_nil.andand.tap {|obj| do_something_with obj}
## or, in the common case: ##
method_call_that_might_return_nil.andand.do_something
Run Code Online (Sandbox Code Playgroud)