jump to navigation

Three Paragraphs on Duck Typing
Tuesday, 22 August 2006

Posted by austin in: Ruby, trackback

Not counting my paragraphs, of course. In the course of the thread “Static typing ain’t so bad, after all…” on ruby-talk, David Vallner and Francis Cianfrocca came up with three great paragraphs on duck typing and why it makes so much sense:

David Vallner:

David Vallner: In dynamically typed languages, the type of an object isn’t its “class” or any other predictable concept, it’s just the protocol it adheres to during its lifetime. Most such languages also make no presumption that this protocol, or the behaviour of an object remains the same during its lifetime – which makes compile-time checks rather pointless.

Of course, you rarely use even this aspect of dynamic typing – in fact, I can’t come up with a single noncontrived example for it, these things just don’t occur in daily coding. But dynamic languages sure a heck faster to type, and the fact the compiler rarely bitches at all is very, very appealing to people that know what they’re doing most of the time.

Francis Cianfrocca:

That was a perceptive comment. The fact that there are so few true cases of objects that metamorphose in flight also accounts for the observed “magical” behavior that “duck-typing” seems to “just work” almost all of the time. (By magical, I mean unexpected for people like me with too many years of experience programming in statically-typed languages.) The intention of a well thought-out code path is generally easy to express without typing all the types along the way. It doesn’t break often, and when it does break, it doesn’t make a big mess.

This matters because when I write an API, I write it with an interface (protocol, to use David’s term) in mind. That interface might have the name of a class, say File. But if someone gives me something that acts like the portions of File that I use,(and I use sensible alternatives when possible, such as #<< instead of #write, then someone can give me something entirely different and I won’t care. But I don’t restrict the consumer of my library to only using File, and I handle it as best as I can because I expect that things will work the way that they should.

Comments

Sorry, comments are closed for this entry