Flock the Duck

You know, duck typing is really easy. It's a simple concept for a simple job. Do you know why it's so hard for people to learn it? Do you know why it took me so long to understand it? Because it's a simple concept hiding behind a stupid phrase. Walks like a duck, talks like a duck, acts like a duck. Flock the duck! Really - Remove the stupid phrase and the stupid euphemism and what you get is something that's really easy to understand.

So what is duck typing? Duck typing is a concept where you pass an object reference, and only an object reference, into a CFC. It has nothing to do with variables; it has to do with object references.

Inside the CFC, you're going to have some code that's going to make use of an object reference that's been passed in. You can pass in 10 different object references, and as long as they have the same method that the CFC is going to be making use of, then it's duck typing.

So let's do a really simple example. Let's say you have a CFC that's trying to make use of the FlocktheDuck() method. You can pass in a reference to the orangeduck CFC that contains FlocktheDuck(). You can pass in a reference to the mallardduck CFC that contains a FlocktheDuck() method. You can pass in a reference to the rubberduck CFC, as long as it contains a FlocktheDuck() method. As long as these references that you are passing in contains the FlocktheDuck() method, then the CFC that you're passing them into will use the FlocktheDuck() method, and that's Duck Typing. What the FlocktheDuck() method actually does depends on the object reference being passed in - and we don't care what it is! Because it's all the same method name using the same method variables. What it returns we also don't care about, because it's going to return something. But it has the same method name and the same method arguments.

That's it. Simple. To the point. Now all you have to do is hide it behind a stupid phrase, and no one knows what you're talking about.

Comments
Jason Daiger's Gravatar Well said. The duck phase has never really made a whole lot of sense even though I get the idea. Reality is, if you pass in a Car CFC and it has the FlocktheDuck() method the function should work. But we all know are car isn't a duck.
# Posted By Jason Daiger | 2/21/06 9:06 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.9. Contact Blog Owner
House of Fusion | ColdFusion Jobs @ House of Fusion | Fusion Authority