From: Michael Witten Date: Tue, 7 Apr 2009 19:59:23 +0000 (-0500) Subject: Docs: Quick explanation of duck typing and a warning X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=c98e0e85db98f82e6cf495b56dc57b4df0e3d51d;p=p5sagit%2Fp5-mst-13.2.git Docs: Quick explanation of duck typing and a warning Signed-off-by: Michael Witten --- diff --git a/pod/perlboot.pod b/pod/perlboot.pod index afe9837..5a60d62 100644 --- a/pod/perlboot.pod +++ b/pod/perlboot.pod @@ -296,15 +296,24 @@ which results in: [but you can barely hear it!] Here, C has its own speaking routine, so C<< Mouse->speak >> -doesn't immediately invoke C<< Animal->speak >>. This is known as -"overriding". In fact, we didn't even need to say that a C was -an C at all, since all of the methods needed for C are -completely defined with C. - -But we've now duplicated some of the code from C<< Animal->speak >>, -and this can once again be a maintenance headache. So, can we avoid -that? Can we say somehow that a C does everything any other -C does, but add in the extra comment? Sure! +doesn't immediately invoke C<< Animal->speak >>. This is known as +"overriding". In fact, we don't even need to say that a C is +an C at all, because all of the methods needed for C are +completely defined for C; this is known as "duck typing": +"If it walks like a duck and quacks like a duck, I would call it a duck" +(James Whitcomb). However, it would probably be beneficial to allow a +closer examination to conclude that a C is indeed an C, +so it is actually better to define C with C as its base +(that is, it is better to "derive C from C"). + +Moreover, this duplication of code could become a maintenance headache +(though code-reuse is not actually a good reason for inheritance; good +design practices dictate that a derived class should be usable wherever +its base class is usable, which might not be the outcome if code-reuse +is the sole criterion for inheritance. Just remember that a C +should always act like an C). + +So, let's make C an C! First, we can invoke the C method directly: