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
精彩评论