Inheritance / interface design issue
I would like to get the opinion of stackoverflow community on the following three design patterns. The first is implementation inheritance; the second is interface inheritance; the third is middle. My specific question is which is better?
Implementation inheritance:
class Base {
X x() const = 0;
void UpdateX(A a) { y_ = g(a); }
Y y_;
}
class Derived: Base {
X x() const { return f(y_); }
}
Interface inheritance:
class Base {
X x() const = 0;
void UpdateX(A a) = 0;
}
class Derived: Base {
X x() const { return x_; }
void UpdateX(A a) { x_ = f(g(a)); }
X x_;
}
middle ground:
class Base {
X x() const { return x_; }
void UpdateX(A a) = 0;
X x_;
}
class Derived: Base {
void UpdateX(A a) { x_ = f(g(a)); }
}
I know many people prefer interface inheritance to implementation inheritance. However, the advantage of the latter is that with a pointer to Base
, x () can be inlined and the address x_
can be statically calculated.
a source to share
I would say that no one technique is inherently better than the others. They are all useful in different scenarios depending on the context in which they are used.
If you implement the Composite Pattern and most of the classes will use the same implementation, then implementation inheritance will probably go. This allows you to refine the implementation for those classes that need it, and share the code for those who don't.
If you are implementing a visitor pattern where it is likely that the implementation of each class method will be completely different, then interface inheritance might make the most common sense. In this case, the base class implementation is likely to be used by only one class.
I see that your middle example is helpful if you are inheriting from a project that was not designed using object oriented methods. Perhaps you need to refactor it as you add new functionality and use it as a way to make legacy code interoperate with new code that uses object-oriented design. This is more of a compromise than a real "best practice", but we all have to get them to ship products ... If I can think of a more / more specific example, I'll post it.
a source to share