Type system – Understanding safe and unsafe typing

computer-keyboard-keys

A language is type-safe if operations and type conversions results are not allowed.  An unsafe condition consists of the following C fragment:

int x = 4 ;
char y [ ] = “37″ ;
char * z = x + y;

The variable z is now pointing to an address of the undefined content. Suppose the compiler for y has a memory space of 3 bytes reserved, starting at address 100, as follows:

Variable points to address content
y 100 ’3 ‘
101 ’7 ‘
102 ‘ \ 0 ‘
103 ?
z 104 ?

What is the address where z is pointing to, is unpredictable. Perhaps random data, or the result of a previous calculation. If the program contents pointed to z, attempts to inspect it will probably crash or produce any result.

A language which allows calculations with pointers is not type safe. Hence, many languages use no pointers, but references (for example, Java and Perl).

The only way to create a reference is to take data that already exists to address (and initialize): a reference can only point to existing valid data.

Duck typing

In object oriented programming, a method of an object calls, checks the compiler (or interpreter), the type of that object. The type of an object is the class of an object.

Example : suppose we have created an object with the following declaration: my object = new Object ( ). When the compiler encounters the following statement : mijnObject.start ( ), the compiler knows that its object is of type Object.

Then the compiler checks if the Object class has indeed a start () method. If this is not the case, then an error is generated. The way you can use an object, therefore, depends on the type of that object .

However, this is not necessary. If the operations are allowed on an object, this depends only on the object itself, this points to duck typing. With duck typing the compiler looks at the object itself, and not the class (type) to which it belongs.

Examples of programming languages with duck typing are JavaScript, Python and Ruby.

About the Author