Friday, August 24, 2007

Object oriented modelling in C - PART 2 - Encapsulation

You can achieve packaging of data with functions in C by making each class attribute (instance variable) a field in the C struct. You implement class methods as C functions that take as their first argument the pointer to the structure of attributes (the this pointer). You can further strengthen the association between the attributes and methods by a consistent naming convention for method names. The most popular convention that I adopt is to concatenate the structure name (class name) with the operation name. This altering of function names is part of name decorating (also known as name mangling) and is performed implicitly by most C++ compilers. Because name decorating eliminates method name clashes between different classes, it effectively partitions the flat C function namespace into separate namespaces nested within classes.

The next aspect I address by a coding convention is access control. In C, you can only indicate your intention for the level of access permitted to a particular attribute or a method. Conveying this intention through the name of an attribute or a method is better than just expressing it in the form of a comment at the declaration point. In this way, unintentional access to class members in any portion of the code will be easier to detect. Most OO designs distinguish the following three levels of protection:

  • private-accessible only from within the class
  • protected-accessible only by the class and its subclasses
  • public-available anywhere (de-fault in C)
Optionally, a class may provide a destructor, which is a method responsible for releasing the resources allocated during the lifetime of an object. Whereas there may be many ways of instantating a class (different constructors taking different arguments), there should be only one way of destroying an object.


No comments: