Hanno’s Coding Log: software development, geek stuff

Duck Typing, Generics and Templates…

Skunk Works has an article about how “The Future Won’t Be Statically Typed”.

There’s been many criticisms of duck typing but usually those voicing them don’t have an extensive experience of development using non statically typed languages or are Java fundamentalists.

Yeah. I agree with that. But I also think current dynamic languages are not the end of the story. Why is everybody thinking Types? Why not Interfaces? No, I don’t mean Java’s Interfaces — because they also rely on inheritance trees (or are the root of it). I think inheritance trees are the root of the problem.

Often it is argued, that Interfaces allow the same flexibility as duck typing. But that is not true. Consider the following scenario:

What do you do in Java if you use two libraries from two different vendors, who both make use of a type, defined by an interface, and also these two interfaces are exactly the same?
You either have to use generics, use a container/wrapper class of yourself with its own interface and inheritance tree, etc. etc.

Also generics are a problem: If I use something like vector<vendorAInterface>, I can’t use objects from vendor B’s library in the vector.

What if you could just declare your own interface with that exact same behavior and the compiler could automatically detect that the behavior is the same?
That would allow kind of duck typing and also allow before runtime checking. It also would give IDEs autocompletion hints.

Everybody talks “Design by Contract” but actually what is actually done is “Design by Typename”.

Do not specify what type your input objects should be — specify what they should be able to do.

One sidenote: C++ has duck typing: When you use template functions, you don’t have to specify the type, the compiler will automatically use the type from the parameters and check whether they fulfill the function’s needs.
Wonder why this doesn’t work on classes.

  • Digg
  • del.icio.us
  • MisterWong
  • Technorati
  • StumbleUpon
  • Yigg

Related posts

  • Update: the C++ case of course only works like duck typing if you have as many types in your template definition as parameters in the function.

You can follow any responses to this entry through the RSS 2.0 feed.

Stoppt die Vorratsdatenspeicherung! Jetzt klicken & handeln!Willst du auch bei der Aktion teilnehmen? Hier findest du alle relevanten Infos und Materialien: