I am using C++ , but as far as I understand most OO principles are cross language.
In most of the articles that I have read and liked about inheritance the advice are about :
- not to use it for the purpose of code reuse.
- inherit interface not implementations.
- use "interfaces" (pure abstract class ) as base class.
- prefer composition over inheritance ,and so on known articles about the abuse of inheritance.
- prefer to work with interfaces for testability.
Examples:
Meyers effective C++ : Item 20: Avoid data members in the public interface.
Trying to improve my OO abilities and understanding I am reading this book: Head First Object-Oriented Analysis and Design and seen this usage in many other real life examples , where they put all common derived class attributes in the base classes.
In the book there is an example of guitar and mandolin classes , where base class have all the common members and the derived class have only the unique data.
I have seen these pattern in many other examples and in real life work.
The question is about the conflict between those two things, all the guidelines I stated, and contradicting examples from real life (or as examples of that book):
Maybe public interfaces has more strict "rules" from regular inner classes?
Or maybe those examples are bad, and I should continue to use inheritance only for interfaces (abstract classes with no members)?
I know that these are all recommendations and not state laws but I feel that I am missing something in my understanding .
Edit: The question is on the design stage, not the mess going on evolving code... If I try to design new classes and notice the same members between two classes with the same interfaces, should I put them in the base class?
Edit: added the example from the book that confused me, why inherit members?
Edit: this core guideline shows the problem I discussed and tries to solve it , but I think ,the solution is too complex.
"... For example, center has to be implemented by every class derived from Shape....How can we gain the benefit of stable hierarchies from implementation hierarchies and the benefit of implementation reuse from implementation inheritance"
am I confused between interfaces and regular classes inheritance ? so public interfaces has more strict "rules" from regular inner classes ?
maybe it's just me, but I don't get what's the question or what are you struggling with. Would you mind rewording the question so it makes clear what's confusing you. If it'sAvoid data members in the public interface.
it only means that it's preferable to define members as protected or private and then define accessors and/or modifiers in the public section (interface), so no derived class can bypass the rules implemented in the abstract class