4
\$\begingroup\$

I am working on some code which checks whether or not to unlink a file on the basis of the class:

File.unlink(file.path) if file.is_a? File

I think it would be more idiomatic to check whether the object responds to the unlink message:

File.unlink(file.path) if file.respond_to? :unlink

Is there any good reason to prefer the is_a? approach?

\$\endgroup\$
  • \$\begingroup\$ I love my static type checker. \$\endgroup\$ – ChaosPandion Oct 14 '13 at 3:00
  • \$\begingroup\$ can you provide some more context ? This kind of code is usually avoidable with a different OO design. I recommend that you read Some of Avdi Grimm's talks about "confident code" that provide nice insights on how to code comfortably in a duck-typing environment. \$\endgroup\$ – m_x Oct 22 '13 at 7:25
  • \$\begingroup\$ +1 to the different design, that's on the cards. The existing code does this is_a? hack. I thought that perhaps respond_to? would be a more idiomatic approach in the interim. \$\endgroup\$ – Duncan Bayne Oct 22 '13 at 21:50
5
\$\begingroup\$

Given that on some file systems a directory is simply a File with special attributes (or to put it another way a specialized file), does it really matter? Unlink it if it can be unlinked if that is what you want to do. If it can't be unlinked, why would you bother? And why would you care what it is? If you care what it is, then use is_a? If the inode can be unlinked, unlink it.

\$\endgroup\$
  • \$\begingroup\$ Assume that the codebase in question is sufficiently weird that it's possible the 'file' isn't even vaguely related to the filesystem - neither a directory or a file :-/ \$\endgroup\$ – Duncan Bayne Oct 22 '13 at 21:49
  • \$\begingroup\$ Then you are asking about nodes and trees? But no, still so you care what it is, if it responds to the behavior, then simply do the behavior. \$\endgroup\$ – vgoff Oct 23 '13 at 0:17
  • \$\begingroup\$ that's what I was thinking, hence the change to respond_to? \$\endgroup\$ – Duncan Bayne Oct 23 '13 at 2:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.