Friday, November 15, 2002


My work lately led me quite naturally to the seminal book, Generative Programming: Methods, Tools, and Applications. I read most of the book yesterday in one sitting (yikes!) and although I found much of it tough going, I want to share one key insight I got. I have always had a lot of trouble understanding the Smalltalk argument as put forth on places like Wiki when I used to be there and indeed the real  advantage of late binding languages. I always viewed the safety of static type checking as a given. Well, in Chapter 6 on Generic Programming, in the area of Overloading and Parametric versus Subtype Polymorphism, is the example that lays it bare before my eyes and makes me see it.

Consider writing a function for squaring a number. In pseudo-code, it looks like:

sqr(x)
return x * x

In a dynamically typed language, such as Smalltalk, this pseudo-code code can be typed in almost "as- is":

sqr: x
^x * x

However, if we want to implement it in a statically typed language; we have to declare the type of x and the return type, for example in C++:

int sqr(int x)
{ return x * x; }

This only works for int types; it is more "special" than the pseudo-code or Smalltak, which understands the message "*", or for any type including the operation "*." In C++, you could have a whole series of squaring functions for different types, but you would eventually come to the solution: a function template:

template <class T>
T sqr(T x)
{ return x * x;}
 

Of course, the compiler will automatically generate a concrete function for each parameter type. The interesting thing to note that the sqr() template will work, not only for number types, but for any type providing the operation "*", just as the Smalltalk implementation of sqr().  However, there a difference between these implementations and here's my revelation: The sqr() template is statically type-checked and no run-time errors of the type "operation * are not found" are possible, whereas the Smalltalk version is dynamically type-checked and a runtime error is possible (no suprise there; thats been my main objection to dynamic languages in general). But, on the other hand, the Smalltalk version if more flexible of x is not fixed at compile-time and objects of different types can be passed to sqr:. Wow, thats pretty more powerful and certainly leads to the rapid Refactoring that they have always talked about. This example is also a good one of just taking the proble semantics and "just typing it in."

 



9:28:31 AM