UltraMaster
UltraMaster

Reputation: 1124

Validating method arguments for nil

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

Answers (3)

Matt
Matt

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

Chirantan
Chirantan

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

hahcho
hahcho

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

Related Questions