Play Video
1
Programming Languages: Static and Dynamic Typing
Programming Languages: Static and Dynamic Typing
::2012/05/01::
Play Video
2
10 - 9 - Duck Typing (728)
10 - 9 - Duck Typing (728)
::2013/03/29::
Play Video
3
CTO Message - Duck Typing
CTO Message - Duck Typing
::2011/04/06::
Play Video
4
Duck Typing in Ruby - tekniqal.com
Duck Typing in Ruby - tekniqal.com
::2009/03/06::
Play Video
5
3.7. Mixins and Duck Typing
3.7. Mixins and Duck Typing
::2012/03/05::
Play Video
6
13.- Curso de Python 3.X Polimorfismo y Duck Typing.
13.- Curso de Python 3.X Polimorfismo y Duck Typing.
::2014/02/15::
Play Video
7
19. Curso Python Exprés - Duck Typing
19. Curso Python Exprés - Duck Typing
::2014/11/15::
Play Video
8
Duck Typing
Duck Typing
::2014/11/04::
Play Video
9
Baby Duck Typing on Laptop Awwwwww!!!!!!
Baby Duck Typing on Laptop Awwwwww!!!!!!
::2014/02/04::
Play Video
10
Object Oriented Design in PHP   2 7  Duck Typing vs  Type Hinting
Object Oriented Design in PHP 2 7 Duck Typing vs Type Hinting
::2014/06/26::
Play Video
11
Ruby Conf 12 - Thinking in Objects by Josh Susser (Fixed)
Ruby Conf 12 - Thinking in Objects by Josh Susser (Fixed)
::2012/12/02::
Play Video
12
Polymorphism and duck typing
Polymorphism and duck typing
::2014/06/16::
Play Video
13
2.7 Duck Typing vs Type Hinting
2.7 Duck Typing vs Type Hinting
::2014/10/02::
Play Video
14
Juego Donald Duck Typing
Juego Donald Duck Typing
::2013/01/12::
Play Video
15
KharkivPy #4: Go: static duck typing
KharkivPy #4: Go: static duck typing
::2012/06/21::
Play Video
16
Object-Oriented Design in PHP Tutorial #8 - Duck Typing vs. Type Hinting
Object-Oriented Design in PHP Tutorial #8 - Duck Typing vs. Type Hinting
::2014/10/18::
Play Video
17
Ruby for Newbies - Part 6 - Duck Typing
Ruby for Newbies - Part 6 - Duck Typing
::2012/08/12::
Play Video
18
Duck Typing Brandon
Duck Typing Brandon
::2010/10/02::
Play Video
19
Juego Donald Duck Typing
Juego Donald Duck Typing
::2014/10/25::
Play Video
20
duck typing
duck typing
::2009/05/24::
Play Video
21
Advanced Python or Understanding Python
Advanced Python or Understanding Python
::2012/08/22::
Play Video
22
♥ Disney Mickey
♥ Disney Mickey's Typing Adventure - Donald Duck Trouble With Magic
::2014/01/07::
Play Video
23
Go for Pythonistas
Go for Pythonistas
::2014/02/06::
Play Video
24
RedDotRuby 2014 - Safety Nets: Learn to Code With Confidence by Christophe Philemotte
RedDotRuby 2014 - Safety Nets: Learn to Code With Confidence by Christophe Philemotte
::2014/07/23::
Play Video
25
Interface Segregation Principle Promo
Interface Segregation Principle Promo
::2014/04/18::
Play Video
26
Disney Mickey
Disney Mickey's Typing Adventure Donald Duck Trouble With Magic New Game Episode for kids in English
::2014/08/14::
Play Video
27
Disney Mickey
Disney Mickey's Typing Adventure Donald Duck Trouble With Magic New Game Episode for kids in English
::2014/11/19::
Play Video
28
Advanced Python or Understanding Python
Advanced Python or Understanding Python
::2007/10/08::
Play Video
29
♥ Disney Mickey Mouse Kindergarten - Donald Duck
♥ Disney Mickey Mouse Kindergarten - Donald Duck's Dancing Moves (Ages 4-6)
::2014/01/20::
Play Video
30
Oregon Duck - This is SportsCenter
Oregon Duck - This is SportsCenter
::2009/12/01::
Play Video
31
Donald Duck Cartoons Full Episodes ღ♥ English Compilation ღ♥ Part 8 ✔
Donald Duck Cartoons Full Episodes ღ♥ English Compilation ღ♥ Part 8 ✔
::2014/09/09::
Play Video
32
Sesame Street: Elmo
Sesame Street: Elmo's Ducks
::2009/05/01::
Play Video
33
Ruby Essentials for Beginners (Part 01)
Ruby Essentials for Beginners (Part 01)
::2013/03/21::
Play Video
34
F**k YOU CEE LO GREEN (official "SOUNDS LIKE"Parody) DUCK POO
F**k YOU CEE LO GREEN (official "SOUNDS LIKE"Parody) DUCK POO
::2010/09/30::
Play Video
35
Play Doh Disney Donald Duck vs Make Minion Kids Modeling Cartoons Character
Play Doh Disney Donald Duck vs Make Minion Kids Modeling Cartoons Character
::2014/11/09::
Play Video
36
Duck You Undo! for iPhone
Duck You Undo! for iPhone
::2009/04/07::
Play Video
37
Disney
Disney's Mickey Mouse and Donald Duck Funny Farting Game
::2014/01/07::
Play Video
38
Rabid Duck Takes Typing Lessons!
Rabid Duck Takes Typing Lessons!
::2011/03/21::
Play Video
39
Baby duck takes an upside-down nap
Baby duck takes an upside-down nap
::2014/07/13::
Play Video
40
WHY OFFICE JOBS SUCK? - One Late Night
WHY OFFICE JOBS SUCK? - One Late Night
::2013/05/09::
Play Video
41
Jan Stępień - Embrace the static. Cherish the functional. Remain a Rubyist.
Jan Stępień - Embrace the static. Cherish the functional. Remain a Rubyist.
::2013/04/10::
Play Video
42
Weird Game Madness! Episode 22: One Duck
Weird Game Madness! Episode 22: One Duck
::2014/03/10::
Play Video
43
AGDQ 2014: Duck Tales speedrun by DXTR (7:41)
AGDQ 2014: Duck Tales speedrun by DXTR (7:41)
::2014/02/16::
Play Video
44
Let
Let's play Super Duck Punch (2): Suddenly horses everywhere
::2013/03/23::
Play Video
45
Bass eat baby Duck lure..Part 3 "Get Crushed" Tamiami Canal
Bass eat baby Duck lure..Part 3 "Get Crushed" Tamiami Canal
::2014/08/16::
Play Video
46
Kids math games: Park Math by Duck Duck Moose [ages: 3+, iPad, iPhone]
Kids math games: Park Math by Duck Duck Moose [ages: 3+, iPad, iPhone]
::2013/05/29::
Play Video
47
Meet Jenya Bolotov - The Human Platypus
Meet Jenya Bolotov - The Human Platypus
::2014/11/18::
Play Video
48
Programming in Go: Concurrency Tips
Programming in Go: Concurrency Tips
::2012/11/08::
Play Video
49
BRAND NEW CASTLE SIEGE MINIGAME: #REVIVEASF FAMILY DUCK w/ Kat and Midg3tKnight
BRAND NEW CASTLE SIEGE MINIGAME: #REVIVEASF FAMILY DUCK w/ Kat and Midg3tKnight
::2014/07/01::
Play Video
50
Programming in Go: Creating Applications for the 21st Century
Programming in Go: Creating Applications for the 21st Century
::2012/11/08::
NEXT >>
RESULTS [51 .. 101]
From Wikipedia, the free encyclopedia
Jump to: navigation, search

In computer programming with object-oriented programming languages, duck typing is an alternative to typing. In duck typing, an object's suitability for some purpose is determined by the presence of certain methods and properties (with appropriate meaning), rather than the actual type of the object. The name of the concept refers to the duck test, attributed to James Whitcomb Riley (see history below), which may be phrased as follows:

When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.[1]

In duck typing, a programmer is only concerned with ensuring that objects behave as demanded of them in a given context, rather than ensuring that they are of a specific type. Instead of specifying types formally, duck typing practices rely on documentation, clear code, and testing to ensure correct use.

Concept examples[edit]

Consider the following pseudo-code for a duck-typed language:

function calculate(a, b, c) => return (a+b)*c

example1 = calculate (1, 2, 3)
example2 = calculate ([1, 2, 3], [4, 5, 6], 2)
example3 = calculate ('apples ', 'and oranges, ', 3)

print to_string example1
print to_string example2
print to_string example3

In the example, each time the calculate function is called, objects without related inheritance may be used (numbers, lists and strings). As long as the objects support the "+" and "*" methods, the operation will succeed. If translated to Ruby or Python, for example, the result of the code would be:

9
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
apples and oranges, apples and oranges, apples and oranges,

Thus, duck typing can work the same as polymorphism, but without inheritance. The only restriction that function calculate places on its arguments is that they implement the "+" and the "*" methods.

The duck test can be seen in the following example (in Python). As far as the function in_the_forest is concerned, the Person object is a duck:

class Duck:
    def quack(self):
        print("Quaaaaaack!")
    def feathers(self):
        print("The duck has white and gray feathers.")
 
class Person:
    def quack(self):
        print("The person imitates a duck.")
    def feathers(self):
        print("The person takes a feather from the ground and shows it.")
    def name(self):
        print("John Smith")
 
def in_the_forest(duck):
    duck.quack()
    duck.feathers()
 
def game():
    donald = Duck()
    john = Person()
    in_the_forest(donald)
    in_the_forest(john)
 
game()

In statically typed languages[edit]

Certain usually statically typed languages such as Boo and the version 4 release of C# have extra type annotations[2][3] that instruct the compiler to arrange for type checking of classes to occur at run-time rather than compile time, and include run-time type checking code in the compiled output.

Other statically typed languages like F# support static duck typing, where the type is verified to have the specific method signatures during compilation.

Comparison with other type systems[edit]

Structural type systems[edit]

Duck typing is similar to but distinct from structural typing. Structural typing is a static typing system that determines type compatibility and equivalence by a type's structure, whereas duck typing is dynamic and determines type compatibility by only that part of a type's structure that is accessed during run time.

The OCaml, Scala, and Go languages use structural type systems.

Protocols and Interfaces[edit]

Protocols and interfaces can provide some of the benefits of duck typing but duck typing is distinct in that no explicit interface is defined. For example, if a third party Java library implements a class you are not allowed to modify, you cannot use an instance of the class in place of an interface you have defined yourself, whereas duck typing would allow this. Again, all of an interface must be satisfied for compatibility.

Templates or generic types[edit]

Template, or generic functions or methods apply the duck test in a static typing context; this brings all the advantages and disadvantages of static versus dynamic type checking in general. Duck typing can also be more flexible in that only the methods actually called at run time need to be implemented, while templates require implementation of all methods that cannot be proven unreachable at compile time.

Examples include the languages C++ and D with templates, which developed from Ada generics.

Criticism[edit]

One issue with duck typing is that it forces programmers to have a much wider understanding of the code they are working with at any given time. For instance, in Python, one could easily create a class called Wine, which expects a class implementing the "press" attribute as an ingredient. However, a class called Trousers might also implement the press() method. With duck typing, in order to prevent strange, hard-to-detect errors, the developer needs to be aware of each potential use of the method "press", even when it's conceptually unrelated to what they are working on. By way of contrast, in a strongly and statically typed language that uses type hierarchies and parameter type checking, it's much harder to supply an unexpected object type to a class. For example, in a language like Java, the ambiguity in the above reuse of the method name press() would not be a problem unless one of the two classes was deliberately defined as a child of the other.

Proponents of duck typing, such as Guido van Rossum, argue that the issue is handled by testing, and the necessary knowledge of the codebase required to maintain it.[4][5]

Criticisms around duck typing tend to be special cases of broader points of contention regarding dynamically typed versus statically typed programming language semantics.

History[edit]

Alex Martelli made an early (2000) use of the term in a message to the comp.lang.python newsgroup:

In other words, don't check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need to play your language-games with.

Implementations[edit]

In C#[edit]

In C# 4.0 the compiler and runtime collaborate to implement dynamic member lookup. Parameter duck is declared dynamic in method InTheForest of class Program.

using System;
 
namespace DuckTyping 
{    
    public class Duck 
    {
        public void Quack()    { Console.WriteLine("Quaaaaaack!"); }
        public void Feathers() { Console.WriteLine("The duck has white and gray feathers."); }
    }
 
    public class Person 
    {
        public void Quack()    { Console.WriteLine("The person imitates a duck."); }
        public void Feathers() { Console.WriteLine("The person takes a feather from the ground and shows it."); }
    }
 
    internal class Program 
    {
        private static void InTheForest(dynamic duck) 
        {
            duck.Quack();
            duck.Feathers();
        }
 
        private static void Game() 
        {
            Duck donald = new Duck();
            Person john = new Person();
            InTheForest(donald);
            InTheForest(john);
        }
 
        private static void Main() 
        {
            Game();
        }
    }
}

In Cobra[edit]

In addition to static typing, Cobra allows one to declare objects of type 'dynamic' and send any message to them. At run-time the message passing will either succeed or throw an exception. The 'dynamic' type is the default for object variables and method arguments when a type has not been explicitly declared for them. This feature was inspired by Objective-C.[6]

In CFML[edit]

The web application scripting language CFML allows function arguments to be specified as having type any. For this sort of argument, an arbitrary object can be passed in and method calls are bound dynamically at runtime. If an object does not implement a called method, a runtime exception is thrown which can be caught and handled gracefully. In ColdFusion 8, this can be picked up as a defined event onMissingMethod() rather than through an exception handler. An alternative argument type of WEB-INF.cftags.component restricts the passed argument to be a ColdFusion Component (CFC), which provides better error messages should a non-object be passed in.

Other CFML application servers such as Railo work analogously to ColdFusion's CFML implementation.

In Dart[edit]

class Duck {
    quack() => print("Quack, quack!");
    fly()   => print("Flap, Flap!");
}
 
class Person {
    quack() => print("I'm Quackin'!");
    fly()   => print("I'm Flyin'!");
}
 
inTheForest(mallard) {
    mallard.quack();
    mallard.fly();
}
 
main() {
    inTheForest(new Duck());
    inTheForest(new Person());
}

In Common Lisp[edit]

Common Lisp includes an object-oriented system (Common Lisp Object System, or shorter CLOS) providing classes with multiple inheritance and generic functions that can specialize on multiple arguments. The combination of CLOS and Lisp's dynamic typing make duck typing a common programming style in Common Lisp.

With Common Lisp one also does not need to query the types, since at runtime an error will be signaled when a generic function is not applicable. The error can be handled with the Condition System of Common Lisp. Methods are defined outside of classes and can also be defined for specific objects.

;; We describe a protocol for 'duck-like' objects. Objects with methods for
;; these three generic functions may be considered 'ducks', for all intents
;; and purposes -- regardless of their superclass.
(defgeneric quack (something))
(defgeneric feathers (something))
 
;; Implementation of the protocol for class DUCK.
(defclass duck () ())
 
(defmethod quack ((a-duck duck))
  (print "Quaaaaaack!"))
 
(defmethod feathers ((a-duck duck))
  (print "The duck has white and gray feathers."))
 
;; But we can also implement it for PERSON, without inheriting from DUCK.
(defclass person () ())
 
(defmethod quack ((a-person person))
  (print "The person imitates a duck."))
 
(defmethod feathers ((a-person person))
  (print "The person takes a feather from the ground and shows it."))
 
;; IN-THE-FOREST does not need to be polymorphic. Its 'duck' argument is
;; anything that implements the duck protocol above.
(defun in-the-forest (duck)
  (quack duck)
  (feathers duck))
 
;; GAME can also just be a regular function.
(defun game ()
  (let ((donald (make-instance 'duck))
        (john (make-instance 'person)))
    (in-the-forest donald)
    (in-the-forest john)))
 
(game)

The usual development style of Common Lisp (by using a Lisp REPL like SLIME) allows also the interactive repair:

? (defclass cat () ())
#<STANDARD-CLASS CAT>
? (quack (make-instance 'cat))
> Error: There is no applicable method for the generic function:
>          #<STANDARD-GENERIC-FUNCTION QUACK #x300041C2371F>
>        when called with arguments:
>          (#<CAT #x300041C7EEFD>)
> If continued: Try calling it again
1 > (defmethod quack ((a-cat cat))
        (print "The cat imitates a duck."))

#<STANDARD-METHOD QUACK (CAT)>
1 > (continue)

"The cat imitates a duck."

This way software can be developed by extending partially working duck typed code.

In Java[edit]

In Java duck typing may be achieved with reflection.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
 
public class DuckTyping {
 
    interface Walkable  { void walk(); }
    interface Swimmable { void swim(); }
    interface Quackable { void quack(); }
 
    public static void main(String[] args) {
        Duck d = new Duck();
        Person p = new Person();
 
        as(Walkable.class, d).walk();   //OK, duck has walk() method
        as(Swimmable.class, d).swim();  //OK, duck has swim() method
        as(Quackable.class, d).quack(); //OK, duck has quack() method
 
        as(Walkable.class, p).walk();   //OK, person has walk() method
        as(Swimmable.class, p).swim();  //OK, person has swim() method
        as(Quackable.class, p).quack(); //Runtime Error, person does not have quack() method
    }
 
    @SuppressWarnings("unchecked")
    static <T> T as(Class<T> t, final Object obj) {
        return (T) Proxy.newProxyInstance(t.getClassLoader(), new Class[] {t},
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        return obj.getClass()
                            .getMethod(method.getName(), method.getParameterTypes())
                            .invoke(obj, args);
                    } catch (NoSuchMethodException nsme) {
                        throw new NoSuchMethodError(nsme.getMessage());
                    } catch (InvocationTargetException ite) {
                        throw ite.getTargetException();
                    }
                }
            });
    }
}
 
class Duck {
    public void walk()  {System.out.println("I'm Duck, I can walk...");}
    public void swim()  {System.out.println("I'm Duck, I can swim...");}
    public void quack() {System.out.println("I'm Duck, I can quack...");}
}
 
class Person {
    public void walk()  {System.out.println("I'm Person, I can walk...");}
    public void swim()  {System.out.println("I'm Person, I can swim...");}
    public void talk()  {System.out.println("I'm Person, I can talk...");}
}

In Groovy[edit]

In Groovy, the Java-derived scripting language, the above Java example can be greatly simplified because Groovy uses duck typing by default when calling a method.

class Duck
{
	def walk() { println "I'm a Duck, I can walk..." }
	def swim() { println "I'm a Duck, I can swim..." }
	def quack() { println "I'm a Duck, I can quack" }
}
 
class Person
{
	def walk() { println "I'm a Person, I can walk..." }
	def swim() { println "I'm a Person, I can swim..." }
	def talk() { println "I'm a Person, I can talk..." }
}
 
def d = new Duck()
def p = new Person()
 
d.walk()	// Ok, duck has walk() method
d.swim()	// Ok, duck has swim() method
d.quack()	// Ok, duck has quack() method
 
p.walk()	// Ok, person has walk() method
p.swim()	// Ok, person has swim() method
p.quack()	// Runtime error, no quack() method

In JavaScript[edit]

var Duck = function(){
    this.quack = function(){alert('Quaaaaaack!');};
    this.feathers = function(){alert('The duck has white and gray feathers.');};
    return this;
};
 
var Person = function(){
    this.quack = function(){alert('The person imitates a duck.');};
    this.feathers = function(){alert('The person takes a feather from the ground and shows it.');};
    this.name = function(){alert('John Smith');};
    return this;
};
 
var inTheForest = function(duck){
    duck.quack();
    duck.feathers();
};
 
var game = function(){
    var donald = new Duck();
    var john = new Person();
    inTheForest(donald);
    inTheForest(john);
};
 
game();

In Lua[edit]

Lua supports duck typing as part of the Metatable weak-typing system. Any reference to a table's member function is checked dynamically at run-time. If an object does not implement the requested function, a run-time error is produced. If a data member is requested but does not exist, a nil value is returned.

local duck_mt = {}
local duck_methods = {}
duck_mt.__index = duck_methods
 
function duck_methods:quack()
    print "Quaaaaaack!"
end
 
function duck_methods:feathers()
    return "The duck has white and gray feathers."
end
 
local function new_duck()
    return setmetatable({}, duck_mt)
end
 
local person_mt = {}
local person_methods = {}
person_mt.__index = person_methods
 
function person_methods:quack()
    print "The person imitates a duck."
end
 
function person_methods:feathers()
    return "The person takes a feather from the ground and shows it."
end
 
function person_methods:get_name()
    return self.firstname .. " " .. self.lastname
end
 
local function new_person(t)
    return setmetatable(t or {}, person_mt)
end
 
local function in_the_forest(duck)
    duck:quack()
    print(duck:feathers())
end
 
local donald = new_duck()
local john = new_person {firstname="John", lastname="Smith"}
in_the_forest(donald)
in_the_forest(john)

In Objective-C[edit]

Objective-C, a cross between C and Smalltalk, allows one to declare objects of type 'id' and send any message to them (provided the method is declared somewhere), like in Smalltalk. The sender can test an object to see if it responds to a message, the object can decide at the time of the message whether it will respond to it or not, and if the sender sends a message a recipient cannot respond to, an exception is raised. Thus, duck typing is fully supported by Objective-C.

#import <Foundation/Foundation.h>
 
@interface Duck : NSObject 
- (void)quack;
@end
 
@implementation Duck
- (void)quack { NSLog(@"Quaaaack!"); }
@end
 
@interface Person : NSObject
- (void)quack;
@end
 
@implementation Person
- (void)quack { NSLog(@"The person imitates a duck."); }
@end
 
@interface Dog : NSObject
- (void)bark;
@end
 
@implementation Dog
- (void)bark { NSLog(@"Baaaaark!"); }
@end
 
void inTheForest(id duck) {
    if ([duck respondsToSelector:@selector(quack)]) {
        [duck quack];
    }
}
 
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        inTheForest([[Duck alloc] init]);
        inTheForest([[Person alloc] init]);
        inTheForest([[Dog alloc] init]);
    }
    return 0;
}

In Perl[edit]

Perl looks for method definitions in package set with bless function.

use strict;
 
package Duck;
 
sub hatch {
        bless \(my $self), shift;
}
sub quack {
        print "Quaaaaaack!\n";
}
sub feathers {
        print "The duck has white and gray feathers.\n";
}
 
package Person;
 
sub accept_birth {
        bless \(my $self), shift;
}
sub quack {
        print "The person imitates a duck.\n";
}
sub feathers {
        print "The person takes a feather from the ground and shows it.\n";
}
 
package main;
 
sub in_the_forest
{
        my $duck = shift;
        $duck->quack();
        $duck->feathers();
}
 
my $duck = Duck->hatch();
my $person = Person->accept_birth();
 
in_the_forest( $duck );
in_the_forest( $person );

Output:

Quaaaaaack!
The duck has white and gray feathers.
The person imitates a duck.
The person takes a feather from the ground and shows it.

In PHP[edit]

PHP leans towards the Java convention of using inheritance and the user land type system (type hinting method arguments or using instanceof class or interface) in favour of duck typing. Below is an example of duck typing:

<?php
class Duck {
    function quack() { echo "Quack", PHP_EOL; }
    function fly() { echo "Flap, Flap", PHP_EOL; }
}
 
class Person {
    function quack() { echo "I try to imitate a duck quack", PHP_EOL; }
    function fly() { echo "I take an airplane", PHP_EOL; }
}
 
function in_the_forest($object) {
    $object->quack();
    $object->fly();
}
 
in_the_forest(new Duck);
in_the_forest(new Person);

Output:

Quack
Flap, Flap
I try to imitate a duck quack
I take an airplane

In PowerShell[edit]

This is the concept example from the beginning of the page.

Function calculate($a, $b, $c) {
    return ($a+$b)*$c
}
 
calculate 1 2 3
"$(calculate (1, 2, 3) (4, 5, 6) 2)"
calculate 'apples ' 'and oranges, ' 3

In Python[edit]

Duck typing is heavily used in Python, with the canonical example being file-like classes (for example, cStringIO allows a Python string to be treated as a file).

class Duck:
	def quack(self):
		print "Quack, quack!"
	def fly(self):
		print "Flap, Flap!"
 
class Person:
	def quack(self):
		print "I'm Quackin'!"
	def fly(self):
		print "I'm Flyin'!"
 
def in_the_forest(mallard):
	mallard.quack()
	mallard.fly()
 
in_the_forest(Duck())
in_the_forest(Person())

Output:

Quack, quack!
Flap, Flap!
I'm Quackin'!
I'm Flyin'!

According to the EAFP principle, instead of checking to see if some purportedly Duck-like object has a quack() method (using if hasattr(mallard, "quack"): ...) it's usually preferable to wrap the attempted quack with proper exception handling:

try:
    mallard.quack()
except (AttributeError, TypeError):
    print("mallard can't quack()")

or, a more common use of the principle is to just let the exception "bubble up", that is, to let the exception be raised, and let whatever function or method called the code in question to deal with it (or if nothing deals with it, to let the exception be raised to the user). This gives better feedback on bad input, and avoids masking bugs.

In Ruby[edit]

class Duck
  def quack
    puts "Quaaaaaack!"
  end
 
  def feathers
    puts "The duck has white and gray feathers."
  end
end
 
class Person
  def quack
    puts "The person imitates a duck."
  end
 
  def feathers
    puts "The person takes a feather from the ground and shows it."
  end
end
 
def in_the_forest(duck)
  duck.quack
  duck.feathers
end
 
def game
  donald = Duck.new
  john = Person.new
  in_the_forest donald
  in_the_forest john
end
 
game

Output:

Quaaaaaack!
The duck has white and gray feathers.
The person imitates a duck.
The person takes a feather from the ground and shows it.

In Smalltalk[edit]

Duck typing is fundamental to Smalltalk. Variables have no data type, and can hold any object. Behavior is triggered by messages sent between objects. Any arbitrary string can be sent to any object as a message. The receiving object checks its method list for a matching behavior. This is the only approximation of type-checking in the language.

Moreover, a message with no matching method is not necessarily an error. In this case, the receiving object triggers its own doesNotUnderstand: method, inherited from Object. The default implementation raises an error, but this can be overridden to perform arbitrary operations based on the original message.

References[edit]

  1. ^ Heim, Michael (2007). Exploring Indiana Highways. Exploring America's Highway. p. 68. ISBN 978-0-9744358-3-1. 
  2. ^ Boo: Duck Typing
  3. ^ Anders Hejlsberg Introduces C# 4.0 at PDC 2008
  4. ^ Bruce Eckel. "Strong Typing vs. Strong Testing". mindview. 
  5. ^ Bill Venners. "Contracts in Python. A Conversation with Guido van Rossum, Part IV". Artima. 
  6. ^ "Cobra - Acknowledgements". cobra-language.com. Retrieved 2010-04-07. 

External links[edit]

Wikipedia content is licensed under the GFDL License
Powered by YouTube
LEGAL
  • Mashpedia © 2014