OOP Principles: Composition vs Inheritance
Summary
TLDRThis course video discusses object-oriented design, focusing on inheritance and composition in Python. It explains that while inheritance is useful for creating subclasses, it can lead to problems when duplicating methods across classes. Composition, however, offers a more flexible solution by building classes through reusable components. The video walks through examples using animals and robots, illustrating how composition can simplify design, allowing for greater modularity and fewer issues compared to inheritance. The key takeaway is to favor composition over inheritance when possible for more maintainable and scalable code.
Takeaways
- 🧠 **Inheritance vs. Composition**: The script discusses the difference between using inheritance and composition in object-oriented design, suggesting that while inheritance is a common approach, composition might often be a better strategy.
- 🐶 **Starting with Simple Classes**: It begins with creating simple classes for dogs and cats that can bark and meow, respectively, to illustrate the basics of object-oriented programming.
- 🍽️ **Adding Functionality**: The script then addresses the challenge of adding a new method ('eat') to existing classes, which leads to duplication of code and potential for errors.
- 🔄 **Inheritance as a Solution**: To solve the duplication issue, inheritance is introduced as a way to create a superclass ('Animal') with a shared method ('eat'), which is inherited by subclasses ('Dog' and 'Cat').
- 🤖 **Expanding to More Complex Classes**: The concept is further expanded to include more complex classes like robots with methods for 'clean' and 'cook', and the same inheritance pattern is applied.
- 🔧 **Inheritance Limitations**: The script highlights the limitations of inheritance, such as the difficulty of managing a class that needs to inherit multiple behaviors (like a robot that needs to 'clean', 'move', 'bark', and 'play games').
- 🔄 **Composition to the Rescue**: Composition is introduced as a solution to the limitations of inheritance, allowing a class to include objects from other classes to gain their behaviors.
- 👾 **Creating a 'Super Bot'**: An example is given of creating a 'Super Bot' class that includes objects from 'Robot', 'Dog', and 'Clean Robot' classes to achieve multiple behaviors without inheritance.
- 🛠️ **Flexibility in Design**: The script emphasizes the importance of choosing the right design model based on the problem at hand, suggesting that composition provides more flexibility and should be the default choice when possible.
- ⚖️ **Balance Between Inheritance and Composition**: It concludes with the advice that while inheritance has its place, it should be used judiciously due to its potential to introduce complexity and maintenance challenges.
Q & A
What is the main focus of the video transcript?
-The main focus of the video transcript is on object-oriented design, specifically comparing the use of inheritance and composition in designing software applications.
Why might inheritance not be an ideal design model in some cases?
-Inheritance might not be ideal because it can lead to duplication of methods, and making changes in one subclass could result in inconsistencies or errors in others. It also forces subclasses to inherit everything from the superclass, which may not always be desirable.
What problem does the video illustrate using the example of dogs and cats?
-The video illustrates the problem of method duplication in the example of dogs and cats. Initially, both dog and cat classes have separate methods for eating, barking, and meowing, which leads to duplicated code and potential errors if the methods become out of sync.
How is inheritance used to solve the problem of duplicated methods in the dog and cat example?
-Inheritance is used by creating a superclass called 'Animal' that contains the common 'eat' method. Dog and Cat then become subclasses that inherit the 'eat' method from Animal, avoiding duplication.
What issue arises when designing robots with the inheritance model?
-When adding new behaviors like 'move' to multiple robot classes (such as cook robot and clean robot), the same problem of method duplication occurs. Each robot class needs to implement the 'move' method, which leads to redundancy.
How does the video suggest resolving the robot design problem using inheritance?
-The video suggests creating a superclass called 'Robot' that contains the common 'move' method. Subclasses like cook robot and clean robot inherit the 'move' method from the Robot superclass, eliminating method duplication.
What challenge does the creation of a personal robot pose in the inheritance model?
-The personal robot needs to combine behaviors from different classes, such as moving, cleaning, barking, and playing games. This makes the inheritance model difficult to use effectively because it requires mixing multiple behaviors that don't fit neatly into a single inheritance hierarchy.
What is composition, and how is it different from inheritance?
-Composition is a design model where objects are composed of other objects to share behaviors, rather than inheriting them from a superclass. It is based on a 'has a' relationship, unlike inheritance, which is based on an 'is a' relationship. Composition allows more flexibility by assembling objects with desired behaviors.
How is composition applied to solve the problem of the personal robot in the video?
-Composition is applied by creating individual classes for each behavior, such as barking, moving, and cleaning. These behaviors are then combined in a 'super bot' class, where each method (e.g., move, bark) refers to the corresponding behavior from its respective class, avoiding the rigidity of inheritance.
What is the general advice given about when to use inheritance versus composition?
-The general advice is to use composition when possible and inheritance only when necessary. Composition tends to be simpler and less prone to problems, while inheritance can lead to unwanted dependencies and complexities due to forced inheritance of all behaviors from the superclass.
Outlines
🐾 Object-Oriented Design and Inheritance
The script introduces the concept of object-oriented design in software applications, emphasizing the use of inheritance. It discusses the common misconception among students that inheritance is the only way to create classes in object-oriented languages. The video aims to demonstrate that composition might be a better design strategy. Using examples of robots and animals, it illustrates how object-oriented programming requires organizing data into objects. It points out the limitations of object-oriented design and the need to adapt to different design models. The script encourages viewers to create modules and run code to understand object-oriented design in Python. It introduces the creation of dog and cat classes with methods to bark and meow, respectively, and then extends these classes to include an 'eat' method, leading to the realization that duplicating methods across classes is not optimal.
🤖 Inheritance and Its Pitfalls
This section delves into the use of inheritance to solve the problem of method duplication. It suggests creating a superclass 'Animal' with an 'eat' method to avoid duplication in subclasses 'Dog' and 'Cat'. The script then transitions to the creation of robot classes, 'CleanRobot' and 'CookRobot', and the need to add a 'move' method to both. It highlights the issue of maintaining consistency across duplicated methods and how inheritance can streamline this process by centralizing the 'eat' and 'move' methods in superclasses. The narrative then takes a turn as the boss requests a robot that can clean, move, and play games, complicating the inheritance model and prompting a discussion on the limitations of inheritance.
🔄 The Power of Composition
The script introduces composition as an alternative to inheritance, illustrating it with the concept of a 'SuperBot' that can move, clean, bark, and play games. It explains that composition involves creating individual classes for specific behaviors (like 'Move', 'Clean', 'Bark') and then combining these into a new class. The 'SuperBot' class includes objects from these behavior classes, allowing it to utilize their methods without direct inheritance. This approach is shown to be more flexible and maintainable, as changes to a method in one class do not require changes across all subclasses. The script concludes by advocating for the use of composition over inheritance whenever possible, due to its simplicity and reduced potential for issues.
🧩 Choosing Between Inheritance and Composition
The final paragraph summarizes the discussion on inheritance and composition, emphasizing the importance of choosing the right design model based on the problem at hand. It points out the potential issues with inheritance, such as name clashes and the inheritance of undesirable characteristics. In contrast, composition is presented as a simpler and more problem-specific approach, leading to fewer complications. The script concludes by suggesting that most developers prefer composition as a default design strategy in object-oriented programming, reserving inheritance for situations where it is truly necessary.
Mindmap
Keywords
💡Object-Oriented Design
💡Inheritance
💡Composition
💡Method Duplication
💡Tightly Coupled
💡Subclass
💡Superclass
💡Polymorphism
💡Encapsulation
💡Class
💡Robot
Highlights
Object-oriented design is not always ideal for all problems, and inheritance is not the only way to create classes.
Composition may be a better design strategy than inheritance for certain scenarios.
Using examples of robots and animals to illustrate complex class creation in software.
Object-oriented programming languages encourage data organization into objects, but not all problems fit this mold.
Inheritance can lead to duplication of methods across classes, which is not optimal.
Creating a superclass with a method that subclasses can inherit reduces duplication and potential errors.
Inheritance is an 'is a' relationship, useful when subclasses are tightly coupled to a superclass.
Subclasses inherit properties from their superclass, which can be beneficial for code reuse.
When a new requirement arises that doesn't fit the inheritance model, composition can be a solution.
Composition is a 'has a' relationship, allowing an object to include objects from other classes.
Creating individual classes for specific behaviors or skills can be beneficial for composition.
A composed class can include objects from other classes to achieve multiple behaviors without inheritance.
Using composition allows for changes in behavior to be made in one class without affecting others.
Inheritance can cause issues with name clashes and undesirable inherited characteristics.
Composition is often simpler and can lead to fewer problems in object-oriented design.
The choice between composition and inheritance should be guided by the specific problem at hand.
Many developers prefer composition as a default design paradigm due to its flexibility and simplicity.
Transcripts
this entire course has been about
object-oriented design for software
applications and we've talked about
inheritance at length because
inheritance occurs whenever an object is
created but using inheritance as a
design model may not be ideal when many
students first study object-oriented
languages they often think that using
inheritance is the only way to create
classes not so and in this video you're
going to discover that a design model
called composition may be your best
strategy so we're going to use some
examples of robots and animals however
these represent much more complex
classes that we might be asked to create
when writing software for an
organization because we're using an
object-oriented programming language we
first try to organize all our data into
objects now not all problems will lend
themselves to this type of repackaging
and this is why object-oriented design
sometimes falls into some criticism not
all designs may always sort of fit this
mold but for this video we're going to
go full steam ahead into creating our
first object-oriented project I
encourage you to create all the modules
and run the code along with the video so
you can get a better feel of how this
works in Python so our boss wants us to
create many objects so we're going to
start out by just a couple templates
that we're going to use and we're going
to create dogs that bark and cats that
meow so we start our design by creating
these classes
here we have our two classes we want to
be able to create dog objects that bark
and cat objects that meow so we start by
creating a couple classes which are very
simply represented by the software so
we've got Snoopy and we've got Garfield
and if we want Snoopy to bark
we just invoke the bark method and
Garfield meows by using the meow method
but now our boss has told us that well
we want both these objects to also be
able to eat so now we need to modify our
templates and our design to create new
dogs and cats that not only barking meow
but that both eat so we can look at
adding the eat method to both cat and
dog but all of a sudden something
something doesn't seem quite right what
happens here is that we now have to
duplicate methods in each of our classes
and that's not really optimum the reason
is we want to make sure that if we're
creating these modules nice car these
methods and these could be quite
complicated they could get at a sink
maybe I miss type 1 or perhaps I I make
changes in one and I forget to make
changes to the other we can sort of show
that here where yes we could add those
methods to each class but as you can see
here we've already gotten that a sink
we've made some typo error and it's not
good to have the same method duplicated
this way in multiple classes we look at
solving this problem by using
inheritance and so we're going to create
an animal class with eating as a method
we can now remove the eat method from
dog and cat because they're going to
become subclasses of an
this is an inheritance relationship
which we've worked at before an
inheritance is what's sometimes called
an is a relationship and it works
whenever things are what are called
tightly coupled to a superclass so a dog
is a type of an animal a cat is a type
of animal so that most of the properties
of animals that are get inherited down
to dog that's a good thing and there may
be one or two differences that we
specify at the subclass level now how we
would do that in code is shown here so
we have a class animal which is the
super class and dog and cat become
subclasses because they're based on
animal now the advantage here is that we
only have one eat method so there's no
chance of it getting out of sync with
anything else we simply need to maintain
that one method and let's look at how we
would get this to work so we'll create
our Snoopy and as before Snoopy come
back or Garfield cat meow but because of
inheritance
Snoopy can also eat
boss now wants to create new types of
objects and now we're going to create
some robots some cook robots and some
clean robots obviously robots that can
cook or clean and to do that we would
use the same model as before where we
have these two templates and so my robot
might be an instantiation of clean robot
and it cleans by calling that method
thing comes back and says well I forgot
that these robots have to move so we've
got to make sure that both those classes
have the ability to move and if we look
at that change we run into the same
problem that we originally had with the
dogs and cats that eat is that we could
put move in both both these classes but
that's not a good design decision we
want to make sure that we only have to
maintain one method so again we look at
inheritance as solving our issue and so
we look at creating a subclass removing
move out of these subclasses creating a
superclass called robot that has the
move method and removing it from the
subclasses and so a clean robot is a
robot so this inheritance makes sense so
as a review the inheritance design model
creates subclasses based on super
classes and how we would do this in code
look something like this
and so we'll look at our instantiation
of this
so we're creating Rosie which is a cook
robot and Rosie can cook by using that
method and Rosie can move by using the
move the move method which Rosie
inherits from the superclass robot and
you're feeling pretty good about your
object-oriented design paradigm you've
got inheritance working really well and
everything is fine and then your boss
comes back a week later and says hey we
need a robot that can clean move back
and play games so we're going to create
a a personal robot the reason for the
barking is to keep away predators when
you're not home play games to keep you
entertained and then we said oh my
goodness how do we do that and how do we
make everything fall into pack this
package which we have of our inheritance
design system because I need a little
bit here a little bit there how am I
going to make this inheritance model
work well you're not
the type of things we want here in a
short way we have a dog and then we're
gonna look at the things that the dog
has as properties what does it do
well it can bark and it can eat the
clean robot moves and cleans we want
this super bot which moves cleans barks
and plays games so are we gonna solve
this well here's where a composition can
come to a rescue and so what we're gonna
do is we're gonna make each of these
things these skills a class and then
we're going to compose a new class by
including objects from these other skill
classes that we've created so let's look
at how this works sometimes composition
is referred to as a has a relationship
so we have inheritance is a like a dog
is an animal composition has a
characteristics such as it can eat or a
can bark how do we apply that well I
start by making a very simple classes
with these these characteristics so bark
is in a class of dog and it can wolf and
I'm not creating all the classes here
just the ones that will create our super
bot here we've got a robot that can move
so we've defined the move method inside
the robot class we've got our clean
robot and it's got the clean method now
you'll notice that none of these are
using inheritance they're not there's
nothing in here that shows their
inherited on anything else so now what
we want to do is create our super bot
and our super bot has some of these
skills if we look the move the clean and
the bark which we've defined before
because we've used these and other
objects and the way to do this is
to create an initialization overridden
method here that creates objects inside
it so this class has its own objects and
it creates an object I've used oh one
here for the first object it's created a
robot object and what can a robot object
do ah
you can move it's created a dog object
which can back and it's created a clean
robot object that can vacuum again we're
not using inheritance here we're using
composition so we're creating our super
bot and we're including objects which
come from other classes now this class
has something unique in it it can play
games so it can play chess as one of the
games so how are we going to use what
else do we have to define in our super
BOTS here we have to define these other
characteristics that can do it can move
bark and clean but we can get those from
the objects that we've included in the
super BOTS up here so we define a move a
bark and a clean the move comes from
this object up here gets from a robot
and what we're doing is we're we're
getting this move method we're calling
this move method that comes from the
robot class we're calling the bark
method which comes from the dog class
and so on so we still have to define
these in here but we're calling them
from these classes up here so if I want
to change the way the bark works I do
that up here and it gets changed down
here because this is referring to
objects based on this class now let's
see how we use the super bot and let's
see how this works
here's our
complete definition we want to create
Henry Henry is our super bot and if we
want to get Henry to move we simply need
to call the move method and Henry moves
Henry can also bark play games and clean
and if we want to change the behavior we
go up to the class where the method is
defined we have to of course restart
this based on our new definition so
we're gonna create Henry again and now
when Henry barks he exhibits the new
behavior so this is called composition
there is no one rule for what design
method you should choose when you're
solving problems the problem is is going
to define how how you go about choosing
a design model most people however feel
that use composition when you can and
use inheritance only when you must
because there are a lot of gotchas with
inheritance as soon as you inherit
things from super classes you have no
choice but to inherit everything from
super classes and you can run into a lot
of problems you can have names which
clash which are the same as names which
you have in your subclass which can
cause issues you may inherit
characteristics which may be undesirable
compositions are actually simpler it can
lead to fewer problems and most people
choose composition as their sort of
their default design paradigm when using
object-oriented languages
浏览更多相关视频
Fundamental Concepts of Object Oriented Programming
DAY 07 | PHP AND MYSQL | VI SEM | B.CA | CLASS AND OBJECTS IN PHP | L1
Interfaces vs Abstract Classes
Java Inheritance | Java Inheritance Program Example | Java Inheritance Tutorial | Simplilearn
Class Inheritance | Godot GDScript Tutorial | Ep 17
OOPS CONCEPTS - JAVA PROGRAMMING
5.0 / 5 (0 votes)