Saturday, 14 July 2007

Names matter

What is your favourite keyword in C++? Well mine is typedef.
The reason is simple: it is the mechanism by which you create new names for existing types. Some people may think that it is just a name aliasing mechanism but its not in fact. For example in the example below we have created two new types:

class Widget;
typedef std::list WidgetList;
typedef boost::shared_ptr WidgetPtr;

The real power of 'typedef' unleashes when you use it with a meaningful semantic naming convention: In the example, we have appended 'List' word to indicate that the type has a list interface i.e you can append, traverse, etc., and similarly 'Ptr' to indicate that the type is a
a smart pointer. Now this naming convention not only documents and simplifies the usage of the types in the system but also communicates their interface.

Using names to communicate the interface of software artifacts is a very powerful technique and is used by some very successful libraries , most notably STL. Template-based techniques in C++ is almost exclusively based on typdefs and some naming conventions

Having said that, i have to stress that sloppy use of typedefs can create a real mess in a codebase. Important point is agreeing on a naming convention and naming all new types created through typedefs accordingly.

No comments: