Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate arguments in Ruby?

Tags:

ruby

I wonder if one should validate that the arguments passed to a method is of a certain class.

eg.

def type(hash = {}, array = [])
  # validate before
  raise "first argument needs to be a hash" unless hash.class == Hash
  raise "second argument needs to be an array" unless array.class == Array

  # actual code
end

Is it smart to do this or is it just cumbersome and waste of time to validate all passed in arguments?

Are there circumstances when you would like to have this extra security and circumstances when you won't bother?

Share your experiences!

like image 822
never_had_a_name Avatar asked Aug 05 '10 02:08

never_had_a_name


1 Answers

I wouldn't recommend this specific approach, as you fail to accommodate classes that provide hash or array semantics but are not that class. If you need this kind of validation, you're better off using respond_to? with a method name. Arrays implement the method :[], for what it's worth.

OpenStruct has hash semantics and attribute-accessor method semantics, but won't return true for the condition hash.class==Hash. It'll work just like a hash in practice, though.

To put it in perspective, even in a non-dynamic language you wouldn't want to do it this way; you'd prefer to verify that an object implements IDictionary<T>. Ruby would idiomatically prefer that, when necessary, you verify that the method exists, because if it does, the developer is probably intending their object to act alike. You can provide additional sanity with unit tests around the client code as an alternative to forcing things to be non-dynamic.

like image 79
JasonTrue Avatar answered Oct 21 '22 15:10

JasonTrue