Optional VS Duck Typing (Python)


 0.1   Type Checking  

Duck typing offers much flexibility in programming, but it lacks of compiling time type s
afety checking. As a result, even obvious type errors cannot be detected at compiling tim
e by an interpreter or compiler for a duck typing language. This problem can be well illu
strated by the following example in Python, 
   1  def SomeFunction(a, b):
   2      return a * b
   4  SomeFunction( 'abc', 'def' )  # Running time error!
Since not all the execution paths can be covered by testing, some bugs caused by such sim
ple 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 compili
ng 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 spe
cified, 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 fun
ctions, 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 multipl
ication. But the second call is not,  because it attempts to do string-string multiplicat
ion,  which is not a valid operation. Because such function specialization and type check
ing 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 documentation
s for a function, or the implementation of the function, it may be very difficult to gues
s 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 exp
licit parameter type specification is also very helpful in creating bindings for C/C++ fu
nctions, because this will guarantee that the parameters passed to the functions are of t
he expected types, so it can save a lot of boilerplate codes for type checking (and conve
rsion in some cases).