Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better: Function overriding or passing a function pointer for event handling

So, I'm writing code for a class that will go into a library that will be used by others. This class will intercept and process incoming messages (details are not important but it's using the activemq-cpp library). The outline of this consumer class is

class MessageConsumer {
    ...
    public:
        void runConsumer();
        virtual void onMessage(const Message* message);
}

where runConsumer() sets up the connection and starts listening and onMessage() is called when a message is received.

My questions is this: People who'll use this code will each have their own way of processing the different messages. How can I keep MessageConsumer generic but offer this flexibility, while keeping their code simple?

Two options:

  • Should they inherit a new class from MessageConsumer and write their own onMessage()?
  • Should they pass a pointer to a message handling function to MessageConsumer?

What do you think, which option is better and why?

Thanks!

like image 662
recipriversexclusion Avatar asked Feb 26 '23 21:02

recipriversexclusion


2 Answers

In one approach, clients are allowed to register a callback and then the MessageConsumer invokes the registered callback. This is something like an observer/broadcast design pattern.

The second approach, where clients have to inherit and override MessageConsumer would be something like Strategy design pattern.

Basic design goals suggest to use the weakest relationship to promote loose coupling. Since inhertiance is a stronger relationship as compared to a simple association, everything else being the same Approach 1 is preferred.

From Herb's article

"Inheritance is often overused, even by experienced developers. Always minimize coupling: If a class relationship can be expressed in more than one way, use the weakest relationship that's practical. Given that inheritance is nearly the strongest relationship you can express in C++ (second only to friendship), it's only really appropriate when there is no equivalent weaker alternative."

But as James points out, it is tough to comment unless the overall design constraints are known clearly.

like image 190
Chubsdad Avatar answered Feb 28 '23 09:02

Chubsdad


Inheritance will make your library more OO-friendly and may improve readability. But really, the choices are about the same since the compiler will check that the user has supplied the function (assuming you declare a pure virtual handler in the base class), and the underlying mechanism will be accomplished via a pointer anyway (virtual table in the case of inheritance).

like image 37
chrisaycock Avatar answered Feb 28 '23 09:02

chrisaycock