Reputation: 1124
I show a Java method with validations following method declaration:
public Integer executeComputation(Integer a, Integer b) {
Validate.notNull(a);
Validate.notNull(b);
Validate.isTrue(b != 0);
return a/b;
}
Is it a good practice to translate this method call to ruby code as following:
def execute_computation(a,b)
raise 'a is nil' if a.nil?
raise 'b is nil' if b.nil?
raise 'zero division' if b == 0
a/b
end
This is a trivial example, but I feel that for Ruby it is too talkative. Yet I'm used to checking my parameters in public methods in Java to prevent some hard-to-find NPEs deep.
Can somebody explain how argument validations in Ruby work? Ideally some reference to literature.
Upvotes: 4
Views: 1591
Reputation: 74720
If you feel you need to do value validation and that's too talkative, use a module that makes it less talkative, like your commons module did.
module Validate
def self.not_zero val
raise ArgumentError, 'arg is zero' if val == 0
end
end
def execute_computation(a,b)
Validate.not_zero b
a/b
end
Upvotes: 1
Reputation: 15634
Ruby is a duck typed language. Java isn't. Confident Ruby code doesn't ever check for types of arguments. If you have to check types, it's a smell. Validation should be on the value and not on the type.
How about handing runtime exceptions NoMethodError: undefined method '/' for nil:NilClass
and/or TypeError: nil can't be coerced into Fixnum
and/or ZeroDivisionError: divided by 0
?
Upvotes: 1
Reputation: 1409
Better fail fast. Check types only if you have some strong restrictions that you want to satisfy. Besides Runtime exceptions will be thrown.
Upvotes: 1