Thursday, July 23, 2015

If It Looks Like A Duck....

See that ^ .

Yeah, that duck up there typing. It's not some abstract visual metaphor for how I'm getting on with the Makers Academy Ronin course, rather a term we've been asked to look into.

What is 'Duck Typing'?

Well someone who knows what they're talking about might respond that in computer programming with object-oriented programming languages, duck typing is a layer of programming language and design rules on top of typing. Typing is concerned with assigning a type to any object. Duck typing is concerned with establishing the suitability of an object for some purpose.

Although I'm more partial to the description - if it walks like a duck and swims like a duck and quacks like a duck, I'll call it a duck!

Simply put the term Duck Typing in coding refers to the fact that you don't need a type in order to invoke an existing method on an object - if a method is defined on it, you can invoke it.

So how does this work in Ruby?

Say we have a class Duck

And a class Person

And we define these methods

If we call 'game' what will we see?

You may think that 'in_the_forest john' will not work as we've only defined the method 'in_the_forest' with '(duck)' as an argument. But Ruby doesn't care what the argument is, and so if, in our case, the new Person can quack and has feathers then Ruby goes with it - if it looks like a duck and quacks like a duck it must be a duck, right?

So our output reads -

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

Duck Typing saves time on writing code, as we only need to be concerned with ensuring that objects behave as demanded of them in a given context, rather than ensuring that they are of a specific type.

No comments:

Post a Comment