有没有更好的方法来处理这个?

时间:2011-07-11 15:46:01

标签: coding-style if-statement nested

我现在已经遇到过几次这种特殊模式,为了让它正常工作,必须声明flag变量有点烦人。有没有更简单的方法来安排我只是没有看到的代码?

flag = true
if x.is_okay?
  some_stuff_that_needs_x_to_be_okay
  if some_condition_that_depended_on_x
    actually_important_stuff
    flag = false
  end
end

if flag
  do_something_when_important_stuff_did_not
end

1 个答案:

答案 0 :(得分:0)

这是没有flag变量的一种方法。如果do_something_when_important_stuff_did_not是一个简单的语句,例如方法调用,那是合理的。

if x.is_okay?
  some_stuff_that_needs_x_to_be_okay
  if some_condition_that_depended_on_x
    actually_important_stuff
  else
    do_something_when_important_stuff_did_not()
  end
else
  do_something_when_important_stuff_did_not()
end