-2

我一直想知道如何在代码设计方面改进这部分代码:

(我对使用不同的默认属性调用相同的函数特别感兴趣——大量的代码重复)

def follow_pages(number_of_pages = 5, sleep_interval = 5)
  process_pages true, number_of_pages, sleep_interval
end

def unfollow_pages(number_of_pages = 5, sleep_interval = 5)
  process_pages false, number_of_pages, sleep_interval
end

def process_pages(follow = true, number_of_pages = 5, sleep_interval = 5)
  number_of_pages.times do |page|

    sleep rand(sleep_interval)

    if follow
      follow_all_pages
    else
      unfollow_all_pages
    end

  end

end
4

1 回答 1

2

你可以这样做:

def follow_pages(*args)
  process_pages true, *args
end

def unfollow_pages(*args)
  process_pages false, *args
end

def process_pages(follow = true, number_of_pages = 5, sleep_interval = 5)
  ...
end

您基本上接受任何参数,为follow参数添加值并将其传递给 mainproess_page方法。我不确定它是否使代码更具可读性,但它绝对可以避免重复参数的默认值。

于 2012-04-26T10:40:35.407 回答