Thoughts on type aliases/synonyms

programming-languages

I'm going to try my best to frame this question in a way that doesn't result in a language war or list, because I think there could be a good, technical answer to this question.

Different languages support type aliases to varying degrees. C# allows type aliases to be declared at the beginning of each code file, and they're valid only throughout that file. Languages like ML/Haskell use type aliases probably as much as they use type definitions. C/C++ are sort of a Wild West, with typedef and #define often being used seemingly interchangeably to alias types.

The upsides of type aliasing don't invoke too much dispute:

  • It makes it convenient to define composite types that are described naturally by the language, e.g. type Coordinate = float * float or type String = [Char].
  • Long names can be shortened: using DSBA = System.Diagnostics.DebuggerStepBoundaryAttribute.
  • In languages like ML or Haskell, where function parameters often don't have names, type aliases provide a semblance of self-documentation.

The downside is a bit more iffy: aliases can proliferate, making it difficult to read and understand code or to learn a platform. The Win32 API is a good example, with its DWORD = int and its HINSTANCE = HANDLE = void* and its LPHANDLE = HANDLE FAR* and such. In all of these cases it hardly makes any sense to distinguish between a HANDLE and a void pointer or a DWORD and an integer etc..

Setting aside the philosophical debate of whether a king should give complete freedom to their subjects and let them be responsible for themselves or whether they should have all of their questionable actions intervened, could there be a happy medium that would allow the benefits of type aliasing while mitigating the risk of its abuse?

As an example, the issue of long names can be solved by good autocomplete features. Visual Studio 2010 for instance will alllow you to type DSBA in order to refer Intellisense to System.Diagnostics.DebuggerStepBoundaryAttribute. Could there be other features that would provide the other benefits of type aliasing more safely?

Best Answer

Two features come to my mind:

Portability. In languages like C, where datatypes like int are platform specific, an alias like DWORD makes it easier to ensure you are really using a 32bit signed integer everywhere, when this is the requirement for your program, even when you port the program to a plattform where int is e.g. 16bit unsigned and therefore DWORD has to be an alias for signed long.

Abstraction. In your program, you might use a lot of integer and floating point numbers for different purposes. By creating aliases like SPEED, HEIGHT, TEMPERATURE, it's relatively easy to change one of those e.g. from float to double and leave the others as they are.

Related Topic