views:

81

answers:

1

Say you are doing a calculator in a dynamic language (Python etc...) and you have an add method.

def Add(x, y)
    print x + y

Now if you were to pass in anything but a number that would be wrong, so you need some datatype checking.

Is Duck Typing about objects as opposed to parameters like the above example?

Could anyone explain further?

Edit

By objects I mean:

Person.Quack()
Duck.Quack()

With no care about what gets passed into methods.

+2  A: 

Duck typing is about not caring what the objects you're working with are as long as they support the necessary operations. So if + is string concatenation then passing strings to Add would be fine. If dates support the + operation then passing dates would be fine as well.

Amuck
+1 The example Add method will work nicely for strings. With respect to `+`, many many types will work.
S.Lott
This is what I read/understood however what happens when you don't want them to use a date. In the case of a calculator you'd be forced to check data types. Thus voiding Duck Typing.
Finglas
@Dockers: Why check data types? Why can't the calculator work with dates and strings?
S.Lott
Because its meant to be a numeric calculator. Imagine the spec was to produce a simple calculator and if the user entered anything other than digits 0 - 9 they get a friendly error message.
Finglas
Then you need to validate the input before it gets to this method.
Amuck