Tuesday, 17 April 2012

Composition > Inheritance

In some cases composition is much better than inheritance.

Some classes in Kadu must emit signals after each change of its properties. When change is made to a lot of properties at once only one signal should be emitted (for performance reasons). So three classes got separate implementations of this behavior. Even worse, one of these classes was parametrized (it was template class). Qt does not support signals and slots on parametrized classes, so a workaround was created by adding virtual method emitUpdated that was reimplemented in every subclass to emit proper signal.

It was a lot of work. And it was error-prone.

Then a new simple class was born: ChangeNotifier. It has only one job - notify about changes. It support emitting only one signal per bulk of changes. It was added as member to these three classes mentioned above. A lot of duplicated code was removed. Strange emitUpdated method was also removed - ChangeNotifier is not parametrizedm, so it can emit signals without problems. Other classes just connect to ChangeNotifier signal instead of one of original class. And this class can be easily unit-tested and reviewed.

Really great. Next time I'll think twice before creating inheritance.

No comments:

Post a Comment