tags:

views:

65

answers:

4

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!

+1  A: 

I think that it is unnecessary. I once read on a blog something like "If you need to protect your code from stupid people, ruby isn't the language for you."

Adrian
thats true. why validate your programmers=)
never_had_a_name
+6  A: 

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 responds_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.

JasonTrue
+1  A: 

If you want compiler/runtime-enforced code contracts, then Ruby isn't for you. If you want a malleable language and easy testability, then Ruby is.

Justice
+2  A: 

There's usually no need to validate that arguments are of a certain class. In Ruby, you're encouraged to use Duck Typing.

Andreas