Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is duck typing different from the old 'variant' type and/or interfaces?

I keep seeing the phrase "duck typing" bandied about, and even ran across a code example or two. I am way too lazy busy to do my own research, can someone tell me, briefly:

  • the difference between a 'duck type' and an old-skool 'variant type', and
  • provide an example of where I might prefer duck typing over variant typing, and
  • provide an example of something that i would have to use duck typing to accomplish?

duck typing illustration courtesy of The Register

I don't mean to seem fowl by doubting the power of this 'new' construct, and I'm not ducking the issue by refusing to do the research, but I am quacking up at all the flocking hype i've been seeing about it lately. It looks like no typing (aka dynamic typing) to me, so I'm not seeing the advantages right away.

ADDENDUM: Thanks for the examples so far. It seems to me that using something like 'O->can(Blah)' is equivalent to doing a reflection lookup (which is probably not cheap), and/or is about the same as saying (O is IBlah) which the compiler might be able to check for you, but the latter has the advantage of distinguishing my IBlah interface from your IBlah interface while the other two do not. Granted, having a lot of tiny interfaces floating around for every method would get messy, but then again so can checking for a lot of individual methods...

...so again i'm just not getting it. Is it a fantastic time-saver, or the same old thing in a brand new sack? Where is the example that requires duck typing?

like image 421
Steven A. Lowe Avatar asked Nov 14 '08 03:11

Steven A. Lowe


People also ask

What is the difference between static and dynamic typing duck typing?

Static Typing is opposite to Dynamic Typing. In Static Typing, type checking is performed during compile time. It means that the type of a variable is known at compile time.

What is the advantage of duck typing?

Advantages of Duck Typing advantage is that it leads to fewer lines of code. This makes it look cleaner; thus making your code easier to read and faster to write. practices, it really is useful functionality!

What is duck typing explain with an example?

Duck Typing is a type system used in dynamic languages. For example, Python, Perl, Ruby, PHP, Javascript, etc. where the type or the class of an object is less important than the method it defines. Using Duck Typing, we do not check types at all. Instead, we check for the presence of a given method or attribute.

What is duck typing languages?

Duck Typing is a term commonly related to dynamically typed programming languages and polymorphism. The idea behind this principle is that the code itself does not care about whether an object is a duck, but instead it does only care about whether it quacks.


2 Answers

In some of the answers here, I've seen some incorrect use of terminology, which has lead people to provide wrong answers.

So, before I give my answer, I'm going to provide a few definitions:

  1. Strongly typed

    A language is strongly typed if it enforces the type safety of a program. That means that it guarantees two things: something called progress and something else called preservation. Progress basically means that all "validly typed" programs can in fact be run by the computer, They may crash, or throw an exception, or run for an infinite loop, but they can actually be run. Preservation means that if a program is "validly typed" that it will always be "Validly typed", and that no variable (or memory location) will contain a value that does not conform to its assigned type.

    Most languages have the "progress" property. There are many, however, that don't satisfy the "preservation" property. A good example, is C++ (and C too). For example, it is possible in C++ to coerce any memory address to behave as if it was any type. This basically allows programmers to violate the type system any time they want. Here is a simple example:

    struct foo {     int x;     iny y;     int z; }  char * x = new char[100]; foo * pFoo = (foo *)x; foo aRealFoo; *pFoo = aRealFoo; 

    This code allows someone to take an array of characters and write a "foo" instance to it. If C++ was strongly typed this would not be possible. Type safe languages, like C#, Java, VB, lisp, ruby, python, and many others, would throw an exception if you tried to cast an array of characters to a "foo" instance.

  2. Weakly typed

    Something is weakly typed if it is not strongly typed.

  3. Statically typed

    A language is statically typed if its type system is verified at compile time. A statically typed language can be either "weakly typed" like C or strongly typed like C#.

  4. Dynamically typed

    A dynamically typed language is a language where types are verified at runtime. Many languages have a mixture, of some sort, between static and dynamic typing. C#, for example, will verify many casts dynamically at runtime because it's not possible to check them at compile time. Other examples are languages like Java, VB, and Objective-C.

    There are also some languages that are "completely" or "mostly" dynamically typed, like "lisp", "ruby", and "small talk"

  5. Duck typing

    Duck typing is something that is completely orthogonal to static, dynamic, weak, or strong typing. It is the practice of writing code that will work with an object regardless of its underlying type identity. For example, the following VB.NET code:

    function Foo(x as object) as object     return x.Quack() end function 

    Will work, regardless of what the type of the object is that is passed into "Foo", provided that is defines a method called "Quack". That is, if the object looks like a duck, walks like a duck, and talks like a duck, then it's a duck. Duck typing comes in many forms. It's possible to have static duck typing, dynamic duck typing, strong duck typing, and weak duck typing. C++ template functions are a good example of "weak static duck typing". The example show in "JaredPar's" post shows an example of "strong static duck typing". Late binding in VB (or code in Ruby or Python) enables "strong dynamic duck typing".

  6. Variant

    A variant is a dynamically typed data structure that can hold a range of predefined data types, including strings, integer types, dates, and com objects. It then defines a bunch of operations for assigning, converting, and manipulating data stored in variants. Whether or not a variant is strongly typed depends on the language in which it is used. For example, a variant in a VB 6 program is strongly typed. The VB runtime ensures that operations written in VB code will conform to the typing rules for variants. Tying to add a string to an IUnknown via the variant type in VB will result in a runtime error. In C++, however, variants are weakly typed because all C++ types are weakly typed.

OK.... now that I have gotten the definitions out of the way, I can now answer your question:

A variant, in VB 6, enables one form of doing duck typing. There are better ways of doing duck typing (Jared Par's example is one of the best), than variants, but you can do duck typing with variants. That is, you can write one piece of code that will operate on an object regardless of its underlying type identity.

However, doing it with variants doesn't really give a lot of validation. A statically typed duck type mechanism, like the one JaredPar describes gives the benefits of duck typing, plus some extra validation from the compiler. That can be really helpful.

like image 176
Scott Wisniewski Avatar answered Nov 10 '22 01:11

Scott Wisniewski


The simple answer is variant is weakly typed while duck typing is strongly typed.

Duck typing can be summed up nicely as "if it walks like a duck, looks like a duck, acts like a duck, then it's a duck." It computer science terms consider duck to be the following interface.

interface IDuck {   void Quack(); } 

Now let's examine Daffy

class Daffy {   void Quack() {     Console.WriteLine("Thatsssss dispicable!!!!");   } } 

Daffy is not actually an IDuck in this case. Yet it acts just like a Duck. Why make Daffy implement IDuck when it's quite obvious that Daffy is in fact a duck.

This is where Duck typing comes in. It allows a type safe conversion between any type that has all of the behaviors of a IDuck and an IDuck reference.

IDuck d = new Daffy(); d.Quack(); 

The Quack method can now be called on "d" with complete type safety. There is no chance of a runtime type error in this assignment or method call.

like image 36
JaredPar Avatar answered Nov 10 '22 00:11

JaredPar