views:

39

answers:

2

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?

+1  A: 

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!

Ragster
+1  A: 

A popular way to extend functionality is the Extension Interface pattern, as described in POSA1.

Another pattern you might consider is the Proxy pattern. If the logic is discrete, you can chain proxy objects to each other and solely refer to them through an interface. This should allow you to spread the logic out nicely over several independent and interchangeable objects.

It's kind of hard for me to give more advice on the design, given that I don't know a whole lot about your situation. But I hope this helps.

Mike
Although I don't think this solves my question, but I see other uses for the Extension interface pattern in my application. Thanks.
Patrick