views:

412

answers:

4

I've been thinking lately, would it be a good form of syntactic sugar in languages like Java and C#, to include a "duck" type as a method parameter type? This would look as follows:

void myFunction(duck foo) {
   foo.doStuff();
}

This could be syntactic sugar for invoking doStuff() via reflection, or it could be implemented differently. Foo could be any type. If foo does not have a doStuff() method, this would throw a runtime exception. The point is that you would have the benefits of the more rigid pre-specified interface paradigm (performance, error checking) when you want them, i.e. most of the time. At the same time, you'd have a simple, clean-looking backdoor to duck typing, which would allow you to cleanly make changes not foreseen in the initial design without massive refactoring. Furthermore, it would likely be 100% backwards compatible and mesh cleanly with existing language constructs. I think this might help cut down on the overengineered just-in-case programming style that leads to confusing, cluttered APIs. Do you believe that something like this would be a good or bad thing in static OO languages like C# and Java?

+5  A: 

The dynamic keyword supports these exact semantics and will be in C# 4.0.

It is not just for reflection, though. It is an implementation of dynamic dispatch which uses reflection only if no other mechanism is available.

This question also has lots of good information.

Bryan Watts
+1  A: 

Actually, that's very much like the "dynamic" type that will be part of C#4.

James Curran
+1  A: 

My short answer is "Yes, Duck Typing is something that would be a useful tool in OO languages. The C# team agrees, and is putting it into C# 4.0"

Long answer:

Duck Typing has its pros and cons... there are a lot of people who swear it off completely, but I'll tell you what: There are some very compelling reasons for using Duck Typing for things that can't be solved well in any other case.

See my post on an interface that took a Dictionary instead of an IDictionary where Duck Typing would have saved the day:

http://www.houseofbilz.com/archive/2008/09/22/why-you-really-need-to-think-about-your-interfaces.aspx

C# has SOME duck typing built in since 1.0! Take the foreach keyword, for instance. It is a common misconception that your type needs to be IEnumerable in order to use an object in a foreach loop. It turns out, in fact, that this is NOT true. You only need to implement GetEnumerator() and implementing the interface is not necessary (it IS good form, though). This is Duck Typing.

Brian Genisio
A: 

For some additional perspective(s) see this question: What are some advantages of duck-typing vs. static typing?

Ken Gentle