2

Consider the following hierarchy in C++ notation:

class A
    {
    public:
        virtual void doStuff()=0;
        virtual void doOtherStuff()=0;
    };

class B:public A
    {
    public:
        void doStuff();
        void doOtherStuff();
    };

class C:public A
    {
    public:
        void doStuff();
        void doOtherStuff();
    };

Now, assume that the code for doStuff is identical in B and C. What is the best practice of

  • implementing doStuff in a class D:public A and let B and C derive from A
  • Let the real task be performed in a function that is called from doStuff in both B and C

Somehow the latter seems more clean, is it? It should be noted that there are other methods in B and C with common implementations as well, and that in the underlaying model, the concept of D does not exist.

  • 1
    Option one seems a lot cleaner. You would call an external method from all the methods that should actually implement it? That sounds like a lot of code duplication and unnecessary complexity. A common base class is a good way to group shared functionality. – Jeroen Vannevel Jan 10 '14 at 16:18
  • @JeroenVannel But does it make sense to say that B objects is substitutable for D objects? The latter avoids the more or less artificial construct D (no such thing exists in the underlaying model). – user877329 Jan 10 '14 at 16:24
  • You would create a separate class as well except you would just basically create a helper class and call its functions, right? A class shouldn't rely on another class to do the things it can do perfectly fine itself. And yes, it does make sense to say that B is substitutable with D: after all, B contains all functionality that's held in D. – Jeroen Vannevel Jan 10 '14 at 16:29
  • It's not clear from your question what varies, so it's hard to suggest what the best encapsulation is. For example, are you suggesting a class D because there are other implementors of A that wouldn't want the common doStuff() implementation? – neontapir Jan 10 '14 at 16:35
  • @neontapir Exactly: There might be other implementations of A that do not share the implementation of doStuff. – user877329 Jan 10 '14 at 16:40
1

I would create a class E to hold the shared implementation of doStuff

class E : class A
{
override doStuff() {}
}

and have classes B and C inherit from E. This allows you to maintain the inheritance if B and C still need to be types derived from A, but allows A and other derivations to not share the same implementation and B and C

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.