2012-02-15 59 views
2

我想将这三种方法合并为一种,但此时无法将我的大脑包裹在其中。复杂的事实是1/3需要稍微不同的呼叫。他们都很相似,我知道有更好的方法,但现在超出我的技能水平。通过一个额外的变量传递(获取,检查或处理),我可以把它变成一个,如何做到这一点避开了我。将三种类似的方法合并为一种方法

如果你想将这些重构成一种方法,你会怎么做?

def fetch(subjects = current_subjects, queues = QUEUES) 
    subjects.each do |s| 
    queues.each { |x| fetch_results(x, s) } unless queue.nil? 
    end 
end 

def check(subjects = current_subjects, queues = QUEUES) 
    subjects.each do |s| 
    queues.each { |x| check_results(s["#{x}_recent"]) } unless queue.nil? 
    end 
end 

def process(subjects = current_subjects, queues = QUEUES) 
    subjects.each do |s| 
    queues.each { |x| process_results(s["#{x}_recent"]) } unless queue.nil? 
    end 
end 

编辑:一种解决方案是接近我早先想,但我没有说清楚,我想在what传递作为一个很小的阵列,这可能是扩张的,并且可以用于指示是否提取,检查或处理这些信息或其组合。因此,本质上,我试图用一种方法循环三件事:

  • 一个动作什么:I.E.,取,检查或处理。
  • 任何数量的科目。
  • 任何数量的队列,这是一个常数。

此外,其他的解决方案在这里:

http://refactormycode.com/codes/2002-three-into-one

+0

侧面说明:队列是一个枚举,所以相应地将其命名为:_queues_。 – tokland 2012-02-15 23:00:43

回答

2

@Lucapette提出了一种自顶向下的解决方案(我认为它在大多数情况下非常有效)。然而,@托尼正确地指出,方法可能会发展,因此它可能太僵化。替代解决方案是自下而上的方法:

def iter_queues(subjects, queues) 
    subjects.each do |subject| 
    (queues || []).each { |queue| yield(queue, subject) } 
    end 
end 

def fetch(subjects = current_subjects, queues = QUEUES) 
    iter_queues(subjects, queues) { |q, s| fetch_results(q, s) } 
end 

同上其他方法。顺便说一句,这双each也可以写成:

subjects.product(queues).each { ... } 
+0

嗯,伟大的思想思考相似:)但我想我喜欢双倍每个更好 – pguardiario 2012-02-15 23:29:32

+0

我也是,说实话:-p – tokland 2012-02-15 23:35:46

0

你为什么要把它们重构为一个单一的功能?他们现在很相似,但如果他们稍后发展并变得与众不同呢?每个功能都有自己的目的,应该作为单独的功能。

+0

一个很好的观点,但没有必要重复的意义。它可以去任何一个方面。 – blueblank 2012-02-15 22:34:31

+1

现在干起来,使代码更简单。如果一个或多个进程稍后发生变化,则提取该进程。没有意义,只是在“假设”的情况下保持排列不整齐的代码。 – Pavling 2012-02-16 00:07:00

1
def execute(what, subjects = current_subjects, queue = QUEUES) 
    subjects.each do |s| 
    queue.each { |x| send("#{what}_results", s["#{x}_recent"]) } unless queue.nil? 
    end 
end 

是一种方法。当然,命名取决于你。

+0

与我之前的想法类似,但没有得到。第一个'fetch'需要一个稍微不同的调用,所以我需要改变它或者解决它我猜,谢谢。 – blueblank 2012-02-15 22:33:52

1

我可能会做这样的事情:

def with(subjects,queues) 
    subjects.each do |subject|  
     queues.each do |queue| 
      yield subject, queue 
     end 
    end 
end 

with(my_subjects, my_queues){|s, q| fetch_results(q, s)} 
+0

好吧,我的想法在下面;-)注意''与'也可以写'subjects.product(队列)。每个(块)' – tokland 2012-02-15 23:22:15

相关问题