[NAME]
ALL.misc.comparison.typing

[TITLE]
Optional VS Duck Typing (Python)

[DESCRIPTION]


 0.1   Type Checking  


Duck typing offers much flexibility in programming, but it lacks of compiling time type
safety checking. As a result, even obvious type errors cannot be detected at compiling
time by an interpreter or compiler for a duck typing language. This problem can be well
illustrated by the following example in Python,
     
   1  def SomeFunction(a, b):
   2      return a * b
   3  
   4  SomeFunction( 'abc', 'def' )  # Running time error!
     
Since not all the execution paths can be covered by testing, some bugs caused by such
simple typing errors may go undetected.

But such error can be easily detected with type inference and function specialization in
an optional typing language such as Dao. For example, the following will raise a
compiling error for the second function call,
     
   1  routine SomeFunction( a, b )
   2  {
   3      return a * b
   4  }
   5  SomeFunction( 123, 456 )      # No error.
   6  SomeFunction( 'abc', 'def' )  # Compiling time error!
     
In this example, even though the parameter types of SomeFunction() are not explicitly 
specified, but at its call sites, the types of the arguments for the calls can be
inferred. Using these type information, Dao interpreter will specialize SomeFunction() 
into two functions, one for int and int parameters, the other for string and string 
parameters.

The first call is valid because the specialized function will do integer-integer
multiplication. But the second call is not, because it attempts to do string-string
multiplication, which is not a valid operation. Because such function specialization and
type checking is done at compiling time, such errors can be easily detected at compiling 
time.

 0.2   Explicit Typing  


Another problem with duck typing is that explicit types cannot be specified to make codes
clearer and more readable. For example, in Python, without looking into the
documentations for a function, or the implementation of the function, it may be very
difficult to guess what are the correct parameter types for the function.

But in Dao with optional typing, one can write a function in the following way,
     
   1  routine SomeFunction( a :float, b :float )
   2  {
   3      return a * b
   4  }
     
This will make it clear that this function will accept two floats as parameters. Such
explicit parameter type specification is also very helpful in creating bindings for C/C++
functions, because this will guarantee that the parameters passed to the functions are of
the expected types, so it can save a lot of boilerplate codes for type checking (and
conversion in some cases).