Search code examples
design-patternslanguage-agnosticoopobserver-pattern

Extending a class: doing this within the class or using observers?


I need to extend a class (in C++, but this question is language-agnostic I think), with functionality that can be implemented in two different ways:

  • by simply adding the logic to the class itself
  • by adding observer logic to the class and putting the logic in an observer, outside the class

There are advantages and disadvantages in both alternatives:

  • since the code might be used for other classes as well, it seems more logical to add the logic in an observer. Future classes then only need to support observers.
  • on the other hand, the impact of observers in calculation-intensive code is hard to foresee. New observers added later in the code, might have a negative impact in the calculation-intensive code.

Has anyone clear rules on when to add new functionality within the class, as opposed to putting it in an observer outside the class?


Solution

  • I think in this case (as with so many) - it depends. It's a case of knowing what's appropriate in in the context of the problem you're addressing.

    In a purist sense, you're probably right in thinking that the Observer model is potentially easier to extend and manipulate in the future. However that purist view rarely takes into account the pragmatic realities if actually having to work in a reasonable timescale.

    It may well be that the observer model serves you fine. But is the logic time critial, and is it likely to be expensive? If these are things that matter in your implementation, then you have to tale account of them.

    Unfortunately, only you can tell - and while it may work well in one situation, a conceptually similar situation may have different constraints, and perform poorly (or be totally impractical) with that same design.

    So, in answer to your question: no - I honestly don't think that anyone can say that there are clear rules.

    People may have preferences, and they be more, or mostly, applicable. But I doubt they're ever going to be universal.

    You're going to have to think about it - but that's what makes it fun!