o9s
is a microblog
home archives search feed blogroll


Duck Typing

Duck typing comes from the phrase If it looks like a duck and quacks like a duck, it’s a duck”.

In Java you would do something like this.

interface BreathingOrganism {
  void breathe();
}

class Dog implements BreathingOrganism {
  public void breathe() {
    System.out.println("Breathing like a dog.");
  }
}

class Jellyfish implements BreathingOrganism {
  public void breathe() {
    System.out.println("How do I breathe?");
  }
}

You would then be able to use the code above like this.

BreathingOrganism jellyfish = new Jellyfish();
BreathingOrganism dog = new Dog();
BreathingOrganism[] organisms = new BreathingOrganism[] {jellyfish, dog};

for (BreathingOrganism organism: organisms) {
  organism.breathe();
}

In a dynamic language without strong typing and duck typing abilities (like Ruby), you could simply do the following.

class Dog
  def breathe
    p 'Breathe like a dog'
  end
end

class Jellyfish
  def breathe
    p 'How do I breathe?'
  end
end

And then use the code above like this.

organisms = [Jellyfish.new, Dog.new]
organisms.each do |organism|
  organism.breathe
end

The difference is that you don’t need to verbosely define the common interface. If you want to be thorough, you can make sure the method exists like this.

organism.breathe if organism.respond_to?(:breathe)
Posted on 2018-02-23   #ruby  






← Next post    ·    Previous post →