Thoughts on type aliases/synonyms?

Posted by Rei Miyasaka on Programmers See other posts from Programmers or by Rei Miyasaka
Published on 2011-06-16T19:12:30Z Indexed on 2011/06/23 8:29 UTC
Read the original article Hit count: 278

Filed under:

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?

© Programmers or respective owner

Related posts about programming-languages