Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I don't feel `.is_a?(Class)` is ever idiomatic ruby. You should always be coding to an interface, not an implementation. This prevents things like mocks and duck typing, making testing more difficult and adding complexity when you want to add AnotherEnemy that doesn't share the same inheritance tree.

I try to avoid using `.is_a?(Class)` in all of my ruby code when possible. `.respond_to?` is much more responsible way of probing whether an object has the interface you are looking for.



> I try to avoid using `.is_a?(Class)` in all of my ruby code when possible. `.respond_to?` is much more responsible way of probing whether an object has the interface you are looking for.

#is_a?(class) is a much more specific check of semantics than #respond_to?(method_name). is_a? is the more cautious approach (least likely to produce false positives at the expense of being most likely to produce false negatives) whereas respond_to? is the less cautious approach (least likely to produce false negatives while most likely to produce false positives.)


Are you coming from java? That's my background (at least one of them), and felt that way too. Interface === API contract == safe.

But that really isn't the only way to do things. Read up on http://en.wikipedia.org/wiki/Duck_typing


> Are you coming from java?

Well, java was one of the languages I used before Ruby, but I've done more Ruby than Java.

> Read up on http://en.wikipedia.org/wiki/Duck_typing

I am well aware of duck typing, and rarely use either #is_a? or #respond_to?

That doesn't change that, if you have a reason to use that type of inquiry to check interfaces, #is_a? is the more safe of the two (more likely to reject an object that provides the semantics of concern and less likely to accept one that does not) and #respond_to? is the less safe (more likely to accept an object that does not provide the semantics of concern and less likely to reject one that does.)


Exactly, you got it. is_a? and respond_to? are code smells.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: