Perl and Duck Typing

April 10, 2007

I was just reading about duck typing on wikipedia.

Duck typing is a technique used in object oriented languages in order to identify the type of objects not based on which class they instantiate or inherit from, but based on which methods they implement. Or put in other words, duck typing is about not giving a damn about what an object *is*, and caring only about what an object *does*.

Duck typing brings languages closer to having true dynamic typing, with the flexibility that comes along.

Some languages use duck typing as their inner mechanism for method lookup: they know which methods every object implements and don't even care for the object's type. And with some other languages (Java for example) you can emulate duck typing by using introspection.

Which brings me to Perl...

Perl has introspection: you can call the 'can()' method on any object. So you can do duck typing. But I have difficulties seeing duck typing used on a larger scale in Perl.

The main issue is the lack of standard interfaces in Perl. To use duck typing to manipulate different objects *as if* they were related by way of a class hierarchy, they still need to implement the same interface. If you implement the objects' classes yourself, it will be fine. But if you fetch them from for example CPAN, you won't get any two similar interfaces... That's due to lack of naming conventions for Perl modules. Still, it may be better to write a couple of proxy classes to abstract away the difference between objects instanciating various classes, rather than having a monstruous if-elsif-elsif-elsif... in the middle of it.

Then, there is the issue of code robustness: how can you prevent someone to later on implement an object that quacks like a duck, walks like a duck, but is definitely NOT a duck? And what will happen when this object lands in a method that uses duck typing to manipulate objects? Probably nothing good...

Now I wonder how Perl6 will implement method lookups? Mmmm... nice reading ahead...

Comments

RSS feed for comments on this post.

The URI to TrackBack this entry is: http://lemonnier.se/erwan/blog/bblog/trackback.php/8/

Leave a Comment

Sorry, Comments have been disabled for this post