Tuesday, September 4, 2007

Object Oriented Typing

The concept of type is more or less important in a language, depending on whether the language is strongly or weakly (or not at all) typed.

In strongly typed languages, the compiler prevents you from mixing different kinds of data together. This is limiting, but can be very helpful when you want to avoid putting a string, say, into the floating point value for the altitude of an airplane’s automatic pilot.

In OO languuages, type is a synonym for class, at least as a first cut. In fact, class and type are quite distinct. A more nuanced understanding of type is one of the things that distinguishes a shallow from a deep understanding of OO design and programming.

Type defines the properties and behaviors shared by all objects of the same type (class).

OO languages can run the range of un-typed, weakly typed, or strongly typed.

The advantage of strongly typed languages is that the compiler can detect when an object is being sent a message to which it does not respond. This can prevent run-time errors. The other advantages of strong typing are:

  • earlier detection of errors speeds development
  • better optimized code from compiler
  • no run-time penalty for determining type

The disadvantages of strong typing are:

  • loss of some flexibility
  • more difficult to define collections of heterogenous objects

C++ maintains strong class typing. An object may only be sent a message containing a method that is defined in the object’s class, or in any of the classes that this object inherits from. The compiler checks that you obey this.
Objective C support strong typing, but it also allows for weak typing. A special type, id, can be used for object handles. An id can be a handle to any class of object, thus it has no typing information, and the compiler can’t check if you are sending proper messages. This is done instead at run-time.

No comments: