CSC/ECE 517 Fall 2007/wiki1 5 sl

From Expertiza_Wiki
Revision as of 18:35, 12 September 2007 by Ljhaywar (talk | contribs)
Jump to navigation Jump to search

Duck Typing

The term “duck typing” comes from the common American analogy of the duck test. This test can be summed up with the following phrase:

If it walks like a duck and quacks like a duck, I would call it a duck.[1]

Java Example

Take the following code snippet:

Class ImaginaryNumber extends Object {

 public int realPart;
 public int imaginaryPart;
 public int getRealPart() {

return realPart; }

 public int getImaginaryPart() {

return imaginaryPart; } }


class MyMath {

 public boolean Equals(Object a, Object b)
 {   
    // this will create a compile-time error in Java
    return (a.getRealPart() == b.getRealPart());
 }

}


In a non-duck typed language, such as Java, the Equals() method above has two parameters a and b. It is required that these parameters have a specific type, in this case “Object”. A compile-time error will be generated even if two ImaginaryNumber objects are passed to the method. This occurs in spite of the fact that ImaginaryNumber has definitions for all of the methods called in Equals() and that ImaginaryNumber is a subclass of Object. In order to correct this error, Equals() would have to be changed to take two ImaginaryNumber objects as parameters.

Ruby Example

In a duck typed language, such as Ruby, the Equals() method below would require parameters to have a defined type. A runtime error would be generated only if a non-ImaginaryNumber object was passed to the Equals() method. As long as only objects of type ImaginaryNumber are passed to the Equals() method, no error will ever be generated. The equivalent Ruby code is shown below.

class ImaginaryNumber

 def initialize(realPart, imaginaryPart)
   @realPart = realPart
   @imaginaryPart = imaginaryPart
 end
 attr_reader :realPart, :imaginaryPart

end

class MyMath

 def self.equals(a, b)
   a.realPart == b.realPart
 end

end



Duck Typing Static Typing Advantages Concise and elegant code

Less restrictive Safer (errors are caught at compile time)

Interfaces can ensure that certain methods are always defined Disadvantages Potential errors at runtime (code cannot be monitored at runtime)

No guarantee that required methods are implemented in subclasses More verbose code is required to check for errors

Other Examples and Discussion

For a more detailed example using Boo, a language that uses both static typing and duck typing, see http://boo.codehaus.org/Duck+Typing. For a real-world example of duck-typing in C#, visit http://haacked.com/archive/2007/08/19/why-duck-typing-matters-to-c-developers.aspx

References

[1] http://en.wikipedia.org/wiki/Duck_test

    http://en.wikipedia.org/wiki/Duck_typing