4

Condition constructions are easy to write when you have a simple condition and a possibly complicated body:

if simple_condition_expressed_in_one_liner
  complicated_body_that_may_be_long
  complicated_body_that_may_be_long
  complicated_body_that_may_be_long
end

but sometimes, you have a complicated condition and a simple body like this:

if condition1 and
condition2 and
condition3 and
some_more_complicated_condition_that_cannot_be_written_on_a_single_line and
still_some_more_complicated_condition_that_cannot_be_written_on_a_single_line
  simple_body
end

In such case, is there a good way to write it?

4

4 回答 4

5

我总是尝试重构为更小的描述性方法。

使用您的示例,而不是:

until (print "Username : "; gets.chomp == "user") and
      (print "Password : "; gets.chomp == "pa$$word")
  puts "Error, incorrect details"
end

我会使用:

def correct_user
  print "Username : "
  gets.chomp == "user"
end

def correct_password
  print "Password : "
  gets.chomp == "pa$$word"
end

until correct_user and correct_password
  puts "Error, incorrect details"
end
于 2013-04-08T16:14:21.927 回答
2

我个人把整个条件语句放到一个单独的方法中。这可能听起来很像已经建议的内容,但我将整个事情放入一个方法中,而不是分解它。

simple_body if complicated_condition

def complicated_condition
  condition1 and
  condition2 and
  condition3 and
  some_more_complicated_condition_that_cannot_be_written_on_a_single_line and
  still_some_more_complicated_condition_that_cannot_be_written_on_a_single_line
end

我可能会也可能不会将条件分解为更多方法,具体取决于条件是什么以及我以后是否会最终使用这些方法(太多的方法只用于一个目的开始变成代码味道)。

它使代码可读(我可以浏览代码并查看它在做什么)和可维护(如果需要我可以更改条件并且我确切地知道它在哪里)。

如果我把它放到一个类中,我会把这个方法放在下面,private因为“外部”没有理由需要使用它。

编辑: 如果条件需要在条件中使用变量时的值,也许考虑传入binding方法。

opt = :mysql
simple_body if complicated_condition(binding)

opt = :oracle
simple_body if complicated_condition(binding)

def complicated_condition(b)
  condition1 and
  condition2 and
  condition3 and
  some_more_complicated_condition_that_cannot_be_written_on_a_single_line and
  still_some_more_complicated_condition_that_cannot_be_written_on_a_single_line and
  eval('opt', b) == :mysql
end
于 2013-04-08T16:36:44.497 回答
1

您应该考虑将其拆分为单独的方法。阅读代码时很难在脑海中映射条件:

if(condition1 and condition2 and ...)

相对:

if(isValidCondition())..
于 2013-04-08T15:52:19.970 回答
0

Early returns might be a candidate when making the complex_condition a method call.

simple_body if complex_condition

def complex_condition
  condition1 or return # or return unless condition1 
  condition2 or return
  condition3 or return
  condition4 or return
  condition5
end

def condition4
  some_more_complicated_condition_that_cannot_be_written_on_a_single_line
end

def condition5
  still_some_more_complicated_condition_that_cannot_be_written_on_a_single_line
end

I really appreciate your thoughts, feel free to comment!

于 2013-04-13T19:25:37.400 回答