Wednesday, August 22, 2007

Duck Typing Explained.

One rule:
  1. Don't check/assert the type of any argument or part of an argument to a method/function
One suggestion:
  1. Make it easy to see what method calls/parameter accesses are made on arguments.

Create and debug your function/method with the argument types you have in mind.
Future users might substitute arguments of a different type but compatible method/parameter signatures, for just those methods used on the arguments.



For example: Create an assembler as if it is taking in a file object, and calling readline to get a line then assembling that line, in a loop, for all lines in the file.


To test the assembler you could:
  • Generate pseudo-random assembler statements.
  • Write them to a tmp file
  • Close the file.
  • Reopen the file for reading.
  • And pass the file object to the assembler function.

You could instead:
  • Add a readline method to the pseudo-random assembler generator.
  • And pass this object to the unchanged assembler function.
This would be 'Duck Typing' as, to the assembler, the code generator looks as file-like as it needs.



With Python, Duck typing is a doddle. Tutorials state that checking the type of objects should not normally be done. It is standard practice.


In some statically and manifestly typed languages such as C++, objective C and Java, you can it seems get part or all of this behaviour, (by using Templates in C++ for example), but functions/methods have to be explicitly written to support this behaviour from the outset, and the means by which such behaviour is accessed is not the 'normal' way one would write functions/methods if the behaviour were not considered.



Duck typing's power is rarely seen unless normal coding practices allow it to be later applied to method/function calls without having to know up-front of the need.

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete