Inheritance, in the context of OOP, refers to the method of basing a class (called a subclass) on another class (called a superclass). Python, in particular, allows the developer to inherit from more than one superclass, with a pretty convoluted reference hierarchy. Composition, on the other hand, refers to the method of embedding the class to be based on as a instance attribute of the new class. These 2 methods sport a very distinct syntax across all programming languages and are based on two very different programming philosophies.
So, the big question is - inheritance or composition? Well, the answer is, it depends. The first thing to consider is the programming language in question. Some programming languages offer one and some the other, while others offer clearer syntax for one than the other. But when it comes to high level, widely used programming languages like all the C based languages and a few others, it helps to have a simple guideline to follow when a decision has to be made.
Here are a few general strengths and weaknesses of inheritance and composition that can be helpful in making the choice:
- It is easier to change the interface of a back-end class (composition) than a superclass (inheritance).
- It is easier to change the interface of a front-end class (composition) than a subclass (inheritance).
- Composition allows you to delay the creation of back-end objects until (and unless) they are needed, as well as changing the back-end objects dynamically throughout the lifetime of the front-end object.
- It is easier to add new subclasses (inheritance) than it is to add new front-end classes (composition).
- The delegation approach of composition will often have a performance cost as compared to inheritance's single invocation
No comments:
Post a Comment