0

我本质上是在制作一个预先计算其大部分字段的表格。所以,我有一堆方法依赖于以前的方法,或者应该返回 nil。目前我正在做一系列检查,我想删除它们。

(忽略计算,它们只是示例)

def age
  return unless dob  # Not so bad... 
  Date.today - dob
end

def age_at_start
  return unless dob && start_date  # Getting worse
  start_date - dob
end

def compensation
  return unless age_at_start && time_worked && salary && staff_rating  # Shoot me now
  some_calculation(age_at_start, time_worked, salary, staff_rating)
end
4

3 回答 3

1

It partially depends on what you're really doing, aside from the example--without context it's difficult to know what would be the most meaningful under the circumstances.

Can't do much better than:

def age
  Date.today - dob if dob
end

Same with this one--I wouldn't break out the guard clause yet:

def age_at_start
  dob && start_date ? start_date - dob : nil
end

Here I'd break out the guard clause, because (a) you can, and (b) IMO testing is easier:

def compensation
  some_calculation if can_be_compensated?
end

def can_be_compensated?
  age_at_start && time_worked && salary && staff_rating
end

If some_calculation is actually 'external' and needs the args, I might wrap it in a method that has access like your original and can_be_compensated?.

于 2012-06-05T01:29:09.847 回答
0
def age
  (Date.today - dob) if dob
end

def age_at_start
  (start_date - dob) if dob && start_date
end

def compensation
  some_calculation(time_worked, age_at_finish, salary, staff_rating) if age_at_start && time_worked && salary && staff_rating
end
于 2012-06-05T00:53:47.560 回答
0

当条件开始变得太长时,我总是遇到麻烦。曾经有帮助的事情是将其中一些包装成 individual methods。这条路线至少会为您提供几个可以在测试中存根的公共方法。

def age
  return unless dob
  Date.today - dob
end

def age_at_start
  return unless valid_age_at_start(start_date, dob)
  start_date - dob
end

def compensation
  return unless valid_compensation(age_at_start, time_worked, salary, staff_rating)
  some_calculation(time_worked, age_at_finish, salary, staff_rating)
end

def valid_age_at_start(start_date, dob)
  start_date && dob
end

def valid_compensation(age_at_start, time_worked, salary, staff_rating)
  age_at_start && time_worked && salary && staff_rating
end

或者您可以创建一个仅验证您的论点的方法:

def age
  return unless dob
  Date.today - dob
end

def age_at_start
  return unless valid_arguments?(start_date, dob)
  start_date - dob
end

def compensation
  return unless valid_arguments?(age_at_start, time_worked, salary, staff_rating)
  some_calculation(time_worked, age_at_finish, salary, staff_rating)
end

private

def valid_arguments?(*args)
  args.each do |arg|
    return false unless arg
  end
  return true
end

诚然,这两条路线仍然有点难看。

于 2012-06-05T01:11:56.690 回答