Sunday, 22 December 2013

Using multiple inheritance to decrease compile time

When working on a modest-scale project, long compile times can be both a blessing (coffee breaks, anyone?) or an annoyance (staring at the screen with a long face). Most of the time, long compile times are an indication of poor design. Here's a tip on using multiple inheritance to decrease the compile time and improve maintainability.

Very often, a parent (interface) class is written like this:

class Shape
{
public:
    virtual void draw();
protected:
    double area;
    double line_width;
    Colour line_colour;
}

class Square : public Shape
{
public:
    void draw();
protected:
     double x1, y1, x2, y2;
}

class Circle : public Shape
{
public:
    void draw();
protected:
    double x, y, radius;
}


This kind of design, unfortunately, has its drawbacks. Whenever changes are made to the "common" protected members, say by adding the member Colour fill_colour, user code must recompile, although they never use the protected members anyway. In fact, any changes to the Colour class will require user code to recompile - makes no sense!

This can be resolved by separating the common properties in another class, and let the interface be purely an interface. For example:

class Shape
{
public:
    virtual void draw();
}

struct ShapeCommon
{
    double area;
    double line_width;
    Colour line_colour;
}

class Square : public Shape, protected ShapeCommon
{
    //...
}


This way, any changes to the collection of classes will not require user code to recompile.

No comments:

Post a Comment