never_had_a_name
never_had_a_name

Reputation: 93216

Validate arguments in 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!

Upvotes: 7

Views: 6427

Answers (5)

JasonTrue
JasonTrue

Reputation: 19624

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.

Upvotes: 10

Dave Rogers
Dave Rogers

Reputation: 53

I have found that validating that the input parameters meet your preconditions is a very valuable practice. The stupid person that its saves you from is you. This is especially true for Ruby as it has no compile time checks. If there are some characteristics of the input of your method that you know must be true it makes senes to check them at run time and raise errors with meaningful error messages. Otherwise, the code just starts producing garbage out for garbage in and you either get a wrong answer or an exception down the line.

Upvotes: 3

Zargony
Zargony

Reputation: 10135

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

Upvotes: 6

yfeldblum
yfeldblum

Reputation: 65445

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.

Upvotes: 1

Adrian
Adrian

Reputation: 15171

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

Upvotes: 1

Related Questions