Wednesday, February 21, 2007

Method Calling -- "What's my motivation?"

Sure, you don't really need to know what class a Ruby object belongs to. After all, Ruby is a dynamic language, and instead of relaxing in the knowledge that strict typing means expected methods will always be there, Ruby informs us to relax in the knowledge of duck typing instead.

What I want to know is: what do you do when the expected duck has no bill?

In other words: what do you do when you end up either calling or about to call a method that ain't there?

Seems to me there are two major scenarios:

1) Duck typing -- call the method and hope for the best.

If you call a method that doesn't exist on an object, you end up with a halted program and the message:
NoMethodError: undefined method

So, if you would like to call a method on an object and guard against it not existing at run-time, you can do the following:
begin
   obj.some_unknown_method
rescue NoMethodError
   puts "Glad I used a rescue"
end

2) Probe for the method before calling.

This is very un-Ruby-like as far as I can tell. However, it is possible using the the respond_to? method to see if the desired method does, in fact, exist in the object:
Object.new.respond_to?("respond_to?") => true
Object.new.respond_to?("nonexistent") => false

So, two alternatives that are relatively tight would be:
obj.call_it unless ! obj.respond_to?("call_it")
obj.call_it if obj.respond_to?("call_it")

No comments: