开发者

Is grouping your verification code in one Ruby method a bad idea?

Imagine I have a class like this:

class A
   attr_accessor :a
   attr_accessor :b

   def check
      raise "a must meet some condition" if !condition(@a)
      raise "b must meet some condition" if !condition(@b开发者_Go百科)
   end

   def do_some_work
      check()
      # more work here
   end

   def do_some_more_work
      check()
      # other work here
   end
end

Is it bad practice to have the preconditions for the accessors inside another method, and not the current one?


It would be better to check when the assignment takes place. Fail fast.

class A
  attr_reader :a, :b

  def a=(new_a)
    raise "a must meet some condition" if !condition(@a)
    @a = new_a
  end

  def b=(new_b)
    raise "b must meet some condition" if !condition(@b)
    @b = new_b
  end

  def do_some_work
    # Do the work, knowing @a and @b are valid
  end

  # ...
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜