24 September 2008

typedefs are a Good Thing.

I often used typedefs in my C++ code, as a good practice, but it never revealed so useful.
Now I bring you an example describing how typedefs saved me.

My code is like one base class and 10000 subclasses. I happened that all these classes used the base class configured in some way (i.e. with a certain constructor).

Code was like:

class Base { Base() { some(); } }
class Sub1 : public Base {};
class Sub2 : public Base {};
...
class SubN : public Base {};


Problem is that all the SubX classes, have at least a function in the form
Base *fun();


All was fine, until it happened that this configuration should have changed, and the 10000 classes needed another configuration, BUT I shouldn't have broken the old one.

The quick change was to build another base class, Middle: public Base, with the new configuration, and then use it for all the SubX classes.
Well, if I wasn't using a typedef for the pointer, that would be a pain you-know-where :)

But, since there was a typedef:
BaseP fun();

I just changed the typedef and all went fine.

Well, now I've just to change 5000 classes with the new configuration :D It will be painful (well, not too much, thanks to regexes), but it wouldn't be if I used correctly typedefs :P

So, every time you use a type in a certain way, expecting it to have a certain role, typedef it. It will save you a lot of time (maybe) if things are gonna change.

Stay --sync

0 commenti:

Post a Comment