OOP Principles: Composition vs Inheritance

Dave Crabbe
27 Apr 201815:38

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

00:00

🐾 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.

05:01

πŸ€– 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.

10:04

πŸ”„ 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.

15:05

🧩 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

Object-oriented design is a programming paradigm that uses objects and classes to design applications and software. It focuses on creating reusable and modular code by encapsulating data and methods that operate on the data within objects. In the video, object-oriented design is the central theme, with discussions on how to structure classes and objects to solve problems effectively.

πŸ’‘Inheritance

Inheritance is a core concept in object-oriented programming that allows a class to inherit properties and methods from another class. It establishes a relationship between a base class (superclass) and a derived class (subclass). The video discusses inheritance as a design model, illustrating how it can be used to create classes like 'Animal' with subclasses 'Dog' and 'Cat', but also points out its limitations when dealing with more complex requirements.

πŸ’‘Composition

Composition is an alternative to inheritance that involves creating a new class by including objects from other classes. It is often referred to as a 'has-a' relationship, as opposed to inheritance's 'is-a' relationship. The video introduces composition as a strategy to avoid the pitfalls of inheritance, showing how a 'SuperBot' class can be created by composing objects from 'Robot', 'Dog', and 'CleanRobot' classes.

πŸ’‘Method Duplication

Method duplication occurs when the same method is implemented in multiple classes, leading to code redundancy and potential inconsistencies. The video script uses the example of adding an 'eat' method to both 'Dog' and 'Cat' classes to illustrate this issue, highlighting the need for a more efficient design approach like inheritance or composition.

πŸ’‘Tightly Coupled

In the context of the video, tightly coupled refers to the strong dependency between classes in an inheritance hierarchy. When classes are tightly coupled, changes in the superclass can have cascading effects on the subclasses. This is discussed as a potential downside of using inheritance, as it can lead to complex and hard-to-maintain code structures.

πŸ’‘Subclass

A subclass is a class that inherits properties and methods from another class, known as the superclass. The video uses subclasses 'Dog' and 'Cat' inheriting from a superclass 'Animal' to demonstrate how inheritance can simplify code by centralizing common methods like 'eat' in the superclass.

πŸ’‘Superclass

A superclass is a class from which other classes inherit properties and methods. In the video, 'Animal' is presented as a superclass with subclasses 'Dog' and 'Cat', emphasizing how superclasses can define common behaviors that are shared among their subclasses.

πŸ’‘Polymorphism

Although not explicitly mentioned in the script, polymorphism is an object-oriented concept that allows objects of different classes to be treated as objects of a common superclass. It is implicitly related to the discussion on inheritance, as it enables methods to be called in a way that is independent of the actual class of the object.

πŸ’‘Encapsulation

Encapsulation is the process of bundling data with the methods that operate on that data, and restricting access to some of an object's components. While not directly discussed in the script, encapsulation is a fundamental principle of object-oriented design that is inherently related to the creation of classes and objects.

πŸ’‘Class

A class is a blueprint for creating objects, defining the properties and methods that the objects will have. The video script frequently refers to classes such as 'Dog', 'Cat', 'Robot', and 'SuperBot', using them to explain how objects are created and how they can interact through methods like 'bark', 'meow', 'eat', 'move', 'clean', and 'play games'.

πŸ’‘Robot

In the script, 'Robot' is used as an example of a superclass with subclasses 'CleanRobot' and 'CookRobot'. The discussion around robots helps to illustrate the concept of inheritance and the challenges that arise when trying to extend functionality, such as needing a robot that can 'clean', 'move', 'bark', and 'play games'.

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

play00:00

this entire course has been about

play00:03

object-oriented design for software

play00:05

applications and we've talked about

play00:08

inheritance at length because

play00:10

inheritance occurs whenever an object is

play00:13

created but using inheritance as a

play00:16

design model may not be ideal when many

play00:20

students first study object-oriented

play00:22

languages they often think that using

play00:25

inheritance is the only way to create

play00:27

classes not so and in this video you're

play00:31

going to discover that a design model

play00:33

called composition may be your best

play00:36

strategy so we're going to use some

play00:39

examples of robots and animals however

play00:42

these represent much more complex

play00:44

classes that we might be asked to create

play00:47

when writing software for an

play00:49

organization because we're using an

play00:53

object-oriented programming language we

play00:56

first try to organize all our data into

play00:59

objects now not all problems will lend

play01:02

themselves to this type of repackaging

play01:05

and this is why object-oriented design

play01:08

sometimes falls into some criticism not

play01:13

all designs may always sort of fit this

play01:16

mold but for this video we're going to

play01:18

go full steam ahead into creating our

play01:21

first object-oriented project I

play01:24

encourage you to create all the modules

play01:27

and run the code along with the video so

play01:30

you can get a better feel of how this

play01:33

works in Python so our boss wants us to

play01:36

create many objects so we're going to

play01:39

start out by just a couple templates

play01:43

that we're going to use and we're going

play01:44

to create dogs that bark and cats that

play01:49

meow so we start our design by creating

play01:52

these classes

play01:57

here we have our two classes we want to

play02:01

be able to create dog objects that bark

play02:03

and cat objects that meow so we start by

play02:06

creating a couple classes which are very

play02:10

simply represented by the software so

play02:13

we've got Snoopy and we've got Garfield

play02:15

and if we want Snoopy to bark

play02:20

we just invoke the bark method and

play02:28

Garfield meows by using the meow method

play02:34

but now our boss has told us that well

play02:38

we want both these objects to also be

play02:42

able to eat so now we need to modify our

play02:45

templates and our design to create new

play02:48

dogs and cats that not only barking meow

play02:50

but that both eat so we can look at

play02:57

adding the eat method to both cat and

play03:00

dog but all of a sudden something

play03:04

something doesn't seem quite right what

play03:06

happens here is that we now have to

play03:08

duplicate methods in each of our classes

play03:10

and that's not really optimum the reason

play03:13

is we want to make sure that if we're

play03:16

creating these modules nice car these

play03:17

methods and these could be quite

play03:19

complicated they could get at a sink

play03:22

maybe I miss type 1 or perhaps I I make

play03:28

changes in one and I forget to make

play03:29

changes to the other we can sort of show

play03:35

that here where yes we could add those

play03:38

methods to each class but as you can see

play03:41

here we've already gotten that a sink

play03:42

we've made some typo error and it's not

play03:45

good to have the same method duplicated

play03:48

this way in multiple classes we look at

play03:51

solving this problem by using

play03:53

inheritance and so we're going to create

play03:57

an animal class with eating as a method

play04:01

we can now remove the eat method from

play04:06

dog and cat because they're going to

play04:08

become subclasses of an

play04:13

this is an inheritance relationship

play04:15

which we've worked at before an

play04:17

inheritance is what's sometimes called

play04:19

an is a relationship and it works

play04:22

whenever things are what are called

play04:24

tightly coupled to a superclass so a dog

play04:27

is a type of an animal a cat is a type

play04:31

of animal so that most of the properties

play04:35

of animals that are get inherited down

play04:37

to dog that's a good thing and there may

play04:40

be one or two differences that we

play04:43

specify at the subclass level now how we

play04:48

would do that in code is shown here so

play04:55

we have a class animal which is the

play04:58

super class and dog and cat become

play05:01

subclasses because they're based on

play05:03

animal now the advantage here is that we

play05:08

only have one eat method so there's no

play05:10

chance of it getting out of sync with

play05:13

anything else we simply need to maintain

play05:15

that one method and let's look at how we

play05:17

would get this to work so we'll create

play05:24

our Snoopy and as before Snoopy come

play05:29

back or Garfield cat meow but because of

play05:34

inheritance

play05:36

Snoopy can also eat

play05:43

boss now wants to create new types of

play05:47

objects and now we're going to create

play05:50

some robots some cook robots and some

play05:52

clean robots obviously robots that can

play05:55

cook or clean and to do that we would

play06:01

use the same model as before where we

play06:09

have these two templates and so my robot

play06:16

might be an instantiation of clean robot

play06:26

and it cleans by calling that method

play06:35

thing comes back and says well I forgot

play06:38

that these robots have to move so we've

play06:41

got to make sure that both those classes

play06:43

have the ability to move and if we look

play06:46

at that change we run into the same

play06:51

problem that we originally had with the

play06:53

dogs and cats that eat is that we could

play06:57

put move in both both these classes but

play07:01

that's not a good design decision we

play07:04

want to make sure that we only have to

play07:05

maintain one method so again we look at

play07:09

inheritance as solving our issue and so

play07:13

we look at creating a subclass removing

play07:20

move out of these subclasses creating a

play07:23

superclass called robot that has the

play07:26

move method and removing it from the

play07:30

subclasses and so a clean robot is a

play07:33

robot so this inheritance makes sense so

play07:38

as a review the inheritance design model

play07:41

creates subclasses based on super

play07:44

classes and how we would do this in code

play07:49

look something like this

play07:53

and so we'll look at our instantiation

play07:58

of this

play08:02

so we're creating Rosie which is a cook

play08:05

robot and Rosie can cook by using that

play08:08

method and Rosie can move by using the

play08:11

move the move method which Rosie

play08:14

inherits from the superclass robot and

play08:20

you're feeling pretty good about your

play08:23

object-oriented design paradigm you've

play08:26

got inheritance working really well and

play08:29

everything is fine and then your boss

play08:36

comes back a week later and says hey we

play08:40

need a robot that can clean move back

play08:44

and play games so we're going to create

play08:49

a a personal robot the reason for the

play08:52

barking is to keep away predators when

play08:55

you're not home play games to keep you

play08:57

entertained and then we said oh my

play08:59

goodness how do we do that and how do we

play09:03

make everything fall into pack this

play09:06

package which we have of our inheritance

play09:10

design system because I need a little

play09:12

bit here a little bit there how am I

play09:15

going to make this inheritance model

play09:17

work well you're not

play09:22

the type of things we want here in a

play09:26

short way we have a dog and then we're

play09:28

gonna look at the things that the dog

play09:30

has as properties what does it do

play09:33

well it can bark and it can eat the

play09:35

clean robot moves and cleans we want

play09:39

this super bot which moves cleans barks

play09:42

and plays games so are we gonna solve

play09:45

this well here's where a composition can

play09:49

come to a rescue and so what we're gonna

play09:53

do is we're gonna make each of these

play09:55

things these skills a class and then

play09:58

we're going to compose a new class by

play10:00

including objects from these other skill

play10:03

classes that we've created so let's look

play10:06

at how this works sometimes composition

play10:14

is referred to as a has a relationship

play10:18

so we have inheritance is a like a dog

play10:21

is an animal composition has a

play10:25

characteristics such as it can eat or a

play10:27

can bark how do we apply that well I

play10:34

start by making a very simple classes

play10:38

with these these characteristics so bark

play10:42

is in a class of dog and it can wolf and

play10:46

I'm not creating all the classes here

play10:48

just the ones that will create our super

play10:50

bot here we've got a robot that can move

play10:53

so we've defined the move method inside

play10:56

the robot class we've got our clean

play11:00

robot and it's got the clean method now

play11:04

you'll notice that none of these are

play11:06

using inheritance they're not there's

play11:09

nothing in here that shows their

play11:10

inherited on anything else so now what

play11:17

we want to do is create our super bot

play11:20

and our super bot has some of these

play11:25

skills if we look the move the clean and

play11:27

the bark which we've defined before

play11:31

because we've used these and other

play11:33

objects and the way to do this is

play11:36

to create an initialization overridden

play11:40

method here that creates objects inside

play11:44

it so this class has its own objects and

play11:47

it creates an object I've used oh one

play11:49

here for the first object it's created a

play11:52

robot object and what can a robot object

play11:54

do ah

play11:55

you can move it's created a dog object

play11:59

which can back and it's created a clean

play12:03

robot object that can vacuum again we're

play12:06

not using inheritance here we're using

play12:08

composition so we're creating our super

play12:11

bot and we're including objects which

play12:14

come from other classes now this class

play12:19

has something unique in it it can play

play12:21

games so it can play chess as one of the

play12:25

games so how are we going to use what

play12:33

else do we have to define in our super

play12:35

BOTS here we have to define these other

play12:38

characteristics that can do it can move

play12:40

bark and clean but we can get those from

play12:43

the objects that we've included in the

play12:46

super BOTS up here so we define a move a

play12:50

bark and a clean the move comes from

play12:53

this object up here gets from a robot

play12:56

and what we're doing is we're we're

play12:58

getting this move method we're calling

play13:01

this move method that comes from the

play13:03

robot class we're calling the bark

play13:06

method which comes from the dog class

play13:09

and so on so we still have to define

play13:12

these in here but we're calling them

play13:15

from these classes up here so if I want

play13:18

to change the way the bark works I do

play13:20

that up here and it gets changed down

play13:24

here because this is referring to

play13:27

objects based on this class now let's

play13:34

see how we use the super bot and let's

play13:37

see how this works

play13:40

here's our

play13:41

complete definition we want to create

play13:44

Henry Henry is our super bot and if we

play13:49

want to get Henry to move we simply need

play13:51

to call the move method and Henry moves

play13:54

Henry can also bark play games and clean

play13:59

and if we want to change the behavior we

play14:03

go up to the class where the method is

play14:05

defined we have to of course restart

play14:14

this based on our new definition so

play14:17

we're gonna create Henry again and now

play14:22

when Henry barks he exhibits the new

play14:26

behavior so this is called composition

play14:31

there is no one rule for what design

play14:35

method you should choose when you're

play14:37

solving problems the problem is is going

play14:39

to define how how you go about choosing

play14:44

a design model most people however feel

play14:47

that use composition when you can and

play14:51

use inheritance only when you must

play14:53

because there are a lot of gotchas with

play14:55

inheritance as soon as you inherit

play14:57

things from super classes you have no

play15:00

choice but to inherit everything from

play15:02

super classes and you can run into a lot

play15:05

of problems you can have names which

play15:07

clash which are the same as names which

play15:11

you have in your subclass which can

play15:13

cause issues you may inherit

play15:16

characteristics which may be undesirable

play15:20

compositions are actually simpler it can

play15:23

lead to fewer problems and most people

play15:27

choose composition as their sort of

play15:29

their default design paradigm when using

play15:33

object-oriented languages

Rate This
β˜…
β˜…
β˜…
β˜…
β˜…

5.0 / 5 (0 votes)

Related Tags
Object-Oriented DesignPython ProgrammingInheritanceCompositionSoftware DevelopmentClass DesignCode StructureProgramming ParadigmOOP ConceptsDesign Patterns