Search code examples
c++eventsmessaging

Does using this "shortcutting function" is a good practice?


I have a event based communication system, and this is the simplifed version of it:

class A: contains elements derived from class B

class B: has a pointer to its owner A

So when a B wants to communicate with other B-s, it calls A's Broadcast() method:

  • m_owner->Broadcast();

But I was wondering:

  • Should I make a protected Broadcast() method for B, which is just this:
    • m_owner->Broadcast();

Pros:

  • Instead of m_owner->Broadcast() I can write just Broadcast()

    • this makes the code cleaner.

Cons:

  • There will be +1 function calling in the procedure.

    • But this can be avoided by making the method inline

Is this a good practice? Why yes and why not?


Solution

  • In a situation that you have described, it probably indeed does not make much difference.

    But in future you may find that you will need to add extra code to each place where Broadcast is called, for example logging or mutex locking. In this case, a separate function will be really useful.

    Also you mention that you have classes derived from B. If this is a derived class that calls m_owner->Broadcast(), and m_owner is a base class field, then this is not a good pattern. Derived classes should better access parent's protected functions, not directly data members.