Friday, October 17, 2008

Duck Typing

There's this idiomatic expression "walks like a duck" in turn a shortened form of saying "if it walks like a duck, talks like a duck..." the implication being, it must be a duck.

In strictly typed languages, like Java, an object with duck-like behaviors ("quack quack") that isn't really a duck, might get frisked, then stopped by security, before getting through a functional gateway. This is called compile time checking, and involves declaring what types are accepted, as a part of the logic. Animals masquerading as other animals are likely a result of confusion, goes the theory, so let the compiler help you, by pointing out the error of your ways.

A scripting language like Python, in contrast, is more about checking at runtime, vs. design time, and there's no compiler as such, more just a translator, which takes us from a VHLL (very high level language) down to bytecodes, e.g. CLR in .NET / Mono etc.

In this paradigm, it's fine for animals to mask as ducks, without really being ducks, because all the function cares about is duck behavior, so if you walk, talk and quack like a duck, you're welcome into the inner sanctum, even if under the hood you're a platypus or something like that.