Why COMPOSITION is Better Than INHERITANCE - Detailed Python Example

Why COMPOSITION is Better Than INHERITANCE - Detailed Python Example

ArjanCodes

2 года назад

252,214 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

Daniel C
Daniel C - 23.09.2023 08:25

Should the saying be "favor AGGREGATION over inheritance" instead? All the meaningful examples I have seen use aggregation instead of composition to replace inheritance.

Ответить
Phil Adams
Phil Adams - 03.09.2023 09:51

So this is similar logic to how you design database tables or normalize the tables to clean up a messy database. Best to separate each thing to its own table then join them when needed (like composition)

Ответить
KeepingItSimple
KeepingItSimple - 02.09.2023 07:47

It's good simple explanation, though, I have a question when you said there are two issues with the design.
1. It has duplication like commission, contracts landed which is correct and we are violating DRY.
2. The class has lot of responsibility, like storing personal data, but isn't the class has only one responsibility which is to compute pay. It has no other behavior.

Ответить
Hussein Allaw
Hussein Allaw - 27.08.2023 16:16

Thanks for the video, isn't this the bridge design pattern?

Ответить
Caleb Parks
Caleb Parks - 24.08.2023 09:39

This example is too trivial to be exemplary. Plus, you go back to using inheritance at the end by using an "abstract" commission.

Ответить
Danyal T
Danyal T - 12.08.2023 19:09

Great video, thanks Arjan!

Ответить
djtomoy
djtomoy - 24.06.2023 01:58

Huh?

Ответить
Andy Anderson
Andy Anderson - 04.06.2023 22:00

Great explanation! I hope one day my code will become as clean as every example at this channel) Thanks, Arjan! Your videos helps a lot!

Ответить
Amrut Umrankar
Amrut Umrankar - 01.06.2023 15:12

Its me or everyone is loving the way typing sounds

Ответить
Lance Dubois
Lance Dubois - 26.05.2023 21:10

Definetely in love with your video. I am a beginner and I am new to OOP, I was trying to figure out how organise my classes in the programm I am currently so I clicked on your video by curiosity. You really well- explained it (timing, choice of words). Thank you very much for your content.

Ответить
bartosak
bartosak - 24.05.2023 22:31

We could even add more flexibility creating a Protocol "GetPaymentProtocol" and employee could have list of that protocol so in compute_pay we could use simple sum of all protocol based classes

Ответить
Llkc
Llkc - 12.05.2023 16:08

yes, composition AND (instead of inheritance) dependency injection. Then you have the best of both worlds.

Ответить
Nikolai Kalashnikov
Nikolai Kalashnikov - 05.05.2023 22:49

Since when does Python have types ? ...Someone finally realized that having a compiler or interpreter do type checking is far superior to guessing & praying that someone passed the correct type into the method, function, &/or constructor of your Framework or Library ? LOL

Ответить
Angel GamePlay
Angel GamePlay - 02.05.2023 23:13

But the Employee class on composition method still have the same issue with responsibility, the only diference is that instead of directly input the values, you created separated classes, but a the end of the day, you have all the information inside the same class. I think that is better to have it literaly separated, for example, to be accesible with the employee ID though other classes, but not in the same. That allows you to pick up only the needed information, remaining any other unknown.

Ответить
Manas
Manas - 24.04.2023 07:47

Thumbnail definition of dadjoke

Ответить
Finn Jensen
Finn Jensen - 21.04.2023 22:00

You also could have created a Payment Interface which the Employee could retrieve an Array of implementations of. GetPayment would then iterate over all payment implementions and add up the payment. This would remove the necessity of Optional and open up for more payment options.

Ответить
Shirkit
Shirkit - 19.04.2023 14:29

Why do OOP at all? Honestly, overcomplicating as always is what OOP does.

Ответить
Arcus Cerebellumus
Arcus Cerebellumus - 11.04.2023 00:01

hmm... I had a thought, listening to this.

It seems like with an abstract class called simply `Pay`, it would be possible to make an attribute with a list of `Pay` objects inside an `Employee` class and cycle through them on compute_pay(). That way you can add things like overtime, single time bonuses, penalties, etc. pretty much indescriminantly and the `Emploee` doesnt even need to destinguish between `Pay` cubclasses, like it does now with commission and contract, for example.

Now what I'm curious about is, would this break anything conceptually? I'm sure that I'm missing some design flaws in this approach... or just misunderstanding how ABC work :|

Ответить
jampk24
jampk24 - 06.04.2023 22:06

This channel has been a game changer for my coding skills.

Ответить
Hareesh Mohan
Hareesh Mohan - 17.03.2023 20:35

What keyboard are you are using? It is just singing!!

Ответить
Dima Trushin
Dima Trushin - 09.03.2023 14:13

"Prefer composition over inheritance" -- said that guy using abstract classes...

Ответить
Xcoder112
Xcoder112 - 06.03.2023 18:09

The real reason why composition is better than inheritance is because it reflects the real world. In the real world we build stuff by composition. We put components together which themselves are made out of components to form objects. Your house has a door, your door has a door knob, your door knob has a key cylinder, inside your key cylinder are driver pins.

And just because two things are operated in the same way does not mean they are related but only that they share the same interface, e.g. a piano and an electrical keyboard are not related at all, yet they both have the same key system and if you know how to play one, you also know how to play the other one. Inheritance creates a strong is-a relationship that simply does not hold true most of the time in the real world.

You might say a front door and a room door are both doors but what does that mean to be both doors? They are operated the same? That only means they share the same interface. They both have a body, a knob, and hinges? That only means they are composed out of the same three components, wich in fact they are not as your room door probably has a different door knob than your front door, so one component is not the same, it may just operated partly the same and share a common interface.

The idea of inheritance is to put common properties and behaviors into a case class and use inheritance to create specialized sub-classes of it but why do objects share common properties and behaviors in the first place? Because they have common interfaces and are made out of the same components, none of this is inheritance. That's why people often struggle to correctly press the real word into an inheritance structure. The result are poor inheritance structures that lead to lots of design problems and bad code.

I utterly gave up on inheritance. I never use it unless I have to as some API forces me to go that route. Some people will argue that there are situations where inheritance works best, I disagree. At best it may safe you some typing work but that's pretty much it. Since I stopped using inheritance altogether, my code got way cleaner, way more robust, and way easier to test and extend in the future.

Ответить
Jorge Escobar
Jorge Escobar - 16.02.2023 09:10

I watched like 3 python courses that cover OOP, Besides @classmethod, @property and @staticmethod I had never seen all those decorators used or mentioned.

Ответить
edgeeffect
edgeeffect - 31.01.2023 20:44

It's a rare opportunity to say "we've got a good thing in PHP", so I'll go for it...
We've got a good thing in PHP, we have `interfaces` which are basically the same as abstract base classes - but like "he" says in PEP 20: "Explicit is better than implicit".

Ответить
ΙΟΡΔΑΝΗΣ ΠΕΛΕΖΙΚΗΣ
ΙΟΡΔΑΝΗΣ ΠΕΛΕΖΙΚΗΣ - 27.01.2023 21:52

Great video!

Ответить
r0di
r0di - 27.01.2023 00:50

the second option is basically combining both composition and inheritance. depending on how you conceptualize your classes you can reduce the combinatorial number of cases.

Ответить
Henrik Olsen
Henrik Olsen - 25.01.2023 12:11

Great content, presentation and personality. Solid content. Your students are lucky to have you, and we here are too - thanks again for making this. Much appreciated. Feels like actually studying again instead of more or less random quality Python content.

Ответить
Baloo The Bear Dog Retreiver
Baloo The Bear Dog Retreiver - 22.01.2023 05:03

Best video on this topic I've seen.

Ответить
GrimChu
GrimChu - 18.01.2023 03:28

I THINK the Composition style is the way I'm currently using. It feels like the most logical design pattern, inheritance feels like you need to complicate stuff unnecessary often times.

Ответить
cfossto
cfossto - 16.01.2023 21:31

Here I was thinking I was good at Python. Thank you for this! Python have become fun again thanks to this video.

Ответить
ProtFox
ProtFox - 14.01.2023 08:00

Composition seems like a way of abstracting away inheritance, as you're still using inheritance, but the way it's used is more extensible
I find myself using composition a lot without thinking, as that's the way I learned OOP, though I learned it as a part of inheritance

Ответить
Mario
Mario - 14.01.2023 01:54

I think it would be even neater to use lambdas to define contracts and commissions. Then pass them as parameters which get called by the Base class

Ответить
KaninchenGaming -inactive-
KaninchenGaming -inactive- - 13.01.2023 17:00

I was skeptical at first but I think you convinced me

Ответить
DRSNova
DRSNova - 13.01.2023 02:17

If you pick a language that does not support multiple inheritance, then yes, of course you run into those problems. In C++, you could just go "class SalariedEmployee : public EmployeeWithCommission, public EmployeeWithBonus", both virtual children of an Employee base class - or something to that effect.

I'm not saying that composition might not be beter in this case, but I also think it's silly to dismiss things that have worked - and still work - for the use cases they are good for just because you have a never, shinier tool in your toolbox now.

Ответить
Steven Bliss
Steven Bliss - 11.01.2023 11:35

OOP has been crazy overused, but sadly also rarely well understood. Most programmers are DELUSIONAL (in their ability) MORONS!!!!!!!!!!!!!

Ответить
Pablo Napan
Pablo Napan - 10.01.2023 09:39

Question: What was the reasoning for separating salaried employee class into with-commission and without-commission? The original class doesn't show that there are employees with and without commission

Ответить
Todd Hasken
Todd Hasken - 08.01.2023 23:29

I will get flamed by the purists but while the original code had duplication and separation issues, it was also extremely simple for anyone to follow and understand exactly what was happening with each employee without bouncing around references, which are most likely going to be in various files.

Ответить
Fred .Flintstone
Fred .Flintstone - 08.01.2023 18:18

I know the difference between composition and inheritance and that I should favor composition. But should I always favor composition over inheritance? If not, when if ever should I use inheritance?

Ответить
Antonio Dourado
Antonio Dourado - 07.01.2023 18:07

That's cool but the red squiggle under the first dataclass decorator is driving me insane =P

Ответить
Daniel J. Rodriguez
Daniel J. Rodriguez - 07.01.2023 05:01

Thank you for your detailed example. The tip about thinking in terms of "is-a" vs. "has-a" really helped me grasp the advantage of composition vs. inheritance.

Also, the link for the "Design Principles and Design Patterns" article by Robert Martin appears to be broken. Is it possible to access the article elsewhere? If so it will be helpful to update the link.

Ответить
Esra Erimez
Esra Erimez - 06.01.2023 18:10

The importance of this video simply cannot be overstated. Well done. Programmers embraced inheritance with reckless abandon.

Ответить
DDC Tech Institute
DDC Tech Institute - 05.01.2023 08:52

The statement is pretty clear, FAVOUR COMPOSITION OVER INHERITANCE, it doesn't say do away with inheritance completely as they're cases where inheritance is most suitable. Also don't forget that most inheritance cases can be modeled as composition. 💕

Ответить
Jan Kučera
Jan Kučera - 04.01.2023 06:12

superclasses suck

Ответить
estranho konsta
estranho konsta - 03.01.2023 13:10

The content of the video may have been ok, but i must say that your title is really bad. This is the kind of title that promotes ignorance and is taken then by rookies as an absolute truth since they normally remember the title much easily than the content and arguments.

Composition is not better than inheritance.
They both have their advantages and disadvantages.
It is ok to compare them with certain goals or situations, but that doesn't mean that those goals are automatically better than one another. We use principles as references, we do do teach religion.

Laying out such a title in such a form is very bad practice.
That is how blind dogmatism is marketed.

Ответить
Nyasha Chiroro
Nyasha Chiroro - 30.12.2022 19:41

One of the best videos on inheritance vs composition. I'm definitely going to try and port this knowledge to Golang since it's big on composition and I can see why now. It's now very very cleary.

Ответить
User Name
User Name - 29.12.2022 07:36

Dank je! :-)

Ответить
nuynobi
nuynobi - 28.12.2022 22:48

This seemed like a good use case for mixins, ie cooperative multiple inheritance. Is there a good reason you didn't even mention that as an option?

Ответить