Тёмный

Why COMPOSITION is Better Than INHERITANCE - Detailed Python Example 

ArjanCodes
Подписаться 240 тыс.
Просмотров 255 тыс.
50% 1

In this video, I explain the difference between composition vs inheritance, what the design principle "favor composition over inheritance" means in practical terms, and how you can use it to make better software design decisions.
The code I worked on in this video is available here: github.com/ArjanCodes/2021-co...
💡 Here's my FREE 7-step guide to help you consistently design great software: arjancodes.com/designguide.
🎓 Courses:
The Software Designer Mindset: www.arjancodes.com/mindset
The Software Designer Mindset Team Packages: www.arjancodes.com/sas
The Software Architect Mindset: Pre-register now! www.arjancodes.com/architect
Next Level Python: Become a Python Expert: www.arjancodes.com/next-level...
The 30-Day Design Challenge: www.arjancodes.com/30ddc
🛒 GEAR & RECOMMENDED BOOKS: kit.co/arjancodes.
A few interesting links to articles and books:
- Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides: amzn.to/3jllgyH
- Principles of Package Design: Creating Reusable Software Components by Matthias Noback: amzn.to/2NETK3l
- Clean Code: A Handbook of Agile Software Craftsmanship by Robert Martin: amzn.to/3qVZgNs
- The original Design Principles and Design Patterns article by Robert Martin: fi.ort.edu.uy/innovaportal/fi...
👍 If you enjoyed this content, give this video a like. If you want to watch more of my upcoming videos, consider subscribing to my channel!
💬 Join my Discord server here: discord.arjan.codes
🐦 Twitter: / arjancodes
🌍 LinkedIn: / arjancodes
🕵 Facebook: / arjancodes
👀 Code reviewers:
- 0xUnicorn
- Ryan Laursen
- Sybren A. Stüvel
🔖 Chapters:
0:00 Intro
1:11 Explanation of the example
3:57 Technique #1: inheritance
8:30 Problems with the inheritance technique
10:02 Technique #2: composition
18:48 Improvement: turn Commission into an abstract class
20:03 Limitations of this example
21:29 Final thoughts
#arjancodes #softwaredesign #python
Thumbnail photos used:
- Marius Masalar (unsplash.com/@marius)
- Alexander Schimmeck (unsplash.com/@alschim)
DISCLAIMER - The links in this description might be affiliate links. If you purchase a product or service through one of those links, I may receive a small commission. There is no additional charge to you. Thanks for supporting my channel so I can continue to provide you with free content each week!

Опубликовано:

 

4 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 420   
@ArjanCodes
@ArjanCodes 3 года назад
I'm curious if it helps the click rate if I add a background image with money to the thumbnail ;). Several times in the video, I relate back to concepts like cohesion and coupling. I did a separate video about that as well a while ago: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-eiDyK_ofPPM.html
@AndresTalks
@AndresTalks 3 года назад
Nice inheritance pun! I actually didn't saw that nice detail, but could also be due to the fact that whenever I see arjanCodes new video upload I insta-click it and smash the like button! have a good weekend Arjan!
@ArjanCodes
@ArjanCodes 3 года назад
Thank you Andrés, glad to be of service and wish you a great weekend too.
@iluvsyphonfilter
@iluvsyphonfilter 3 года назад
To be honest I didn't notice the money in the thumbnail before reading this comment
@python360
@python360 2 года назад
Clickbait-ey thumbnails suck, I tried using them but on balance, it's probably better not to drop to the level of the creators who do?
@v0id_d3m0n
@v0id_d3m0n Год назад
Did it work?
@MichaelFJ1969
@MichaelFJ1969 3 года назад
I really like how you make small incremental changes, and run/test the code after each iteration.
@ArjanCodes
@ArjanCodes 3 года назад
Glad you like the video, Michael!
@RyuhoKudo
@RyuhoKudo 2 года назад
@@ArjanCodes It would have been better if it was a unit test :)
@dansplain2393
@dansplain2393 9 месяцев назад
That is basically the best way to code. Small change. Review. Commit.
@AzureFlash
@AzureFlash 3 года назад
Counter-argument: I'd rather get an inheritance from a deceased relative than a composition, no matter how good at poetry they were.
@anhnhvn
@anhnhvn 2 года назад
Why not both? You can inherit a bunch of compositions :)?
@nomadvagabond1263
@nomadvagabond1263 2 года назад
@@anhnhvn that sucks haha
@Azurath100
@Azurath100 2 года назад
Depending on if they were popular, the compositions could be worth a great fortune.
@aarondewindt
@aarondewindt 2 года назад
@@Azurath100 Not from my relatives.
@izzikora6751
@izzikora6751 Год назад
That's cute
@ShlomoGottlieb
@ShlomoGottlieb 3 года назад
I love it that your videos are somewhat advanced, there are not a lot of these on RU-vid. Keep up the great work!
@michaelyost9820
@michaelyost9820 3 года назад
Been listening to the audio book of a Pragmatic Programmer and in the book they emphasize that "has a" is a lot better than "is a". Actually doing it in code is a different story. Seeing it here it makes a ton of sense! Thanks for the vid!
@ArjanCodes
@ArjanCodes 3 года назад
Thank you Michael, glad it was helpful!
@cristobaljvp
@cristobaljvp 3 года назад
Man your videos are so high quality! Sadly I don't think you're gonna grow fast 'cause advanced topics have a smaller audience. I really hope you keep the videos coming anyway. Thanks for the content!
@ArjanCodes
@ArjanCodes 3 года назад
Thanks - happy you like them! Fast growth is not my goal, to be honest. This is a topic I really like talking about, and already with my current subscriber number, I’m able to help way more people than when teaching a programming course at my local university. So that’s a win-win in my book.
@cabanford
@cabanford 3 года назад
@@ArjanCodes What a great answer and attitude.
@NateROCKS112
@NateROCKS112 3 года назад
To be honest, slightly more niche videos actually make channels blow up quicker.
@VivekYadav-ds8oz
@VivekYadav-ds8oz 2 года назад
This is not that advanced. This is something every programmer is supposed to research and know about.
@RoamingAdhocrat
@RoamingAdhocrat 2 года назад
@@VivekYadav-ds8oz So, going forward, every new programmer who reaches this stage and searches "composition vs inheritance" is likely to find this video.
@freacas
@freacas 3 года назад
Would love to see some creational patterns as the continuation of this video when that main() gets crowded because there are many parts to create before instantiating The Employee or when you need to decide which Employee to create during runtime. P.S. Please keep up this great work! In python you have either hello_world() tutorials or data science ML. Your videos are like a fresh air in Python world! ;]
@ArjanCodes
@ArjanCodes 3 года назад
Thanks, glad you enjoy the videos! It seems you have been reading my mind. I have just finished recording two videos about object creation, including a video about the factory pattern.
@MrCmon113
@MrCmon113 Год назад
Lesson 1: Hello world. Lesson 2: Using a three billion parameter transformer to optimize the hyperparameters in our novel PDE solver that's going to help us predict the temperature of my left butt cheek on the Sunday three weeks in the future.
@amitsinghsansoya4038
@amitsinghsansoya4038 2 года назад
Man! you are great with your videos, most of the people really don't include the incremental changes while making the code and sometimes it adds a lot of complexity when you are studying way complex things but in your video things start to make much sense as we do see the changes happening and it helps in understanding the stuff very well. Really awesome videos!!
@drooten
@drooten 2 года назад
Thank you for yet another quality topic while also getting to the point in ways that make sense and is easy to follow. I particularly like the code zooming you do, as it means I can watch these while on the bus to/from work, on my small phone.
@AdobadoFantastico
@AdobadoFantastico 2 года назад
Thanks I've been programming for a while and kind of understood but still wondered a lot about this. Your vid really elucidated things for me. Best explanation I've seen, 10/10 will share any time the topic comes up.
@reddit7372
@reddit7372 3 года назад
OOP composition has not been covered enough, so thank you for creating this video!
@ArjanCodes
@ArjanCodes 3 года назад
You’re most welcome!
@SaurabhSingh1987
@SaurabhSingh1987 Год назад
After appearing in so many coding interviews, now I understand the market expectation is highly improved for real hands-on even for lesser experience. great to have someone doing hands-on on screen and keeping us motivated!!
@WthyrBendragon
@WthyrBendragon Год назад
I generally find it helpful to approach my Object model from an RDBMS mindset. The Employee class might be better treated as a Personnel record containing only that information needed to identify a person. That person's relationship to the company, pay structure, and other factors are defined by other related data structures.
@Graham_Wideman
@Graham_Wideman Год назад
Yes, exactly this. Most of the problem with this example is that the original Employee class was used to contain pay records, (and presumably just for a particular time period, which is doubly mad.) Combining two data structures where the individual data structures have their own variants of course results in a combinatorial explosion. That's not the fault of inheritance per se, it's incorrectly modeling the problem domain.
@danyalt8221
@danyalt8221 10 месяцев назад
Great video, thanks Arjan!
@mauisam1
@mauisam1 3 года назад
Thank you! Finally a more advance level of Python programming and specifically dealing with classes. A lot of good information, I'll need to watch this again! I just subscribed!
@ArjanCodes
@ArjanCodes 2 года назад
Thank you Sam, glad you liked it!
@maroben225
@maroben225 2 года назад
Watching you is intellectually stimulating....what a relief to find such an amazing and ADVANCED content
@noblessetech
@noblessetech 2 года назад
I love your typing speed and sound of it. Amazing content. Subscribed!!
@fexofenadinaGenerica
@fexofenadinaGenerica 3 года назад
This is so great. Thank you for the explantation! As I aspiring software developer this kinds of videos are very important.
@pope-pylinux-vi
@pope-pylinux-vi 2 года назад
Thank you for such an excellent content. Wish I could give you multiple likes. A special thank you for the timestamps in your videos, it really makes things easier. You are great!
@ArjanCodes
@ArjanCodes 2 года назад
Thank you! Glad you enjoy the videos!
@dennissmith6867
@dennissmith6867 3 года назад
Crystal clear examples and explanations. Love your videos Arjan!
@ArjanCodes
@ArjanCodes 3 года назад
Glad you like ‘em Dennis!
@laurentverge5512
@laurentverge5512 2 года назад
Very nice content ! One more thing you could add to this codebase is a NoCommission class that returns 0 when get_payment is called. With this class there is no need for "Optional Commission" in the Employee class and the concept of "there is no commission" has now a concrete representation.
@TechandCodeInGreek
@TechandCodeInGreek 2 года назад
This channel is a treasure for advanced python! Thanks!
@nianeddavid7985
@nianeddavid7985 2 года назад
the only video I really understood. It is important to know the real problem before thinking how to write the code.
@cetilly
@cetilly 3 года назад
Another brilliant video. Thanks Arjan! I just love your content.
@ArjanCodes
@ArjanCodes 3 года назад
Thanks Chuck, always nice to hear from you and glad that you like the content!
@henrikolsen5
@henrikolsen5 Год назад
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.
@ArjanCodes
@ArjanCodes Год назад
I appreciate that!
@smann43231816
@smann43231816 2 года назад
The best Python videos I've seen so far. Thank you!
@ArjanCodes
@ArjanCodes 2 года назад
Glad you like them, Steve!
@jampk24
@jampk24 Год назад
This channel has been a game changer for my coding skills.
@ArjanCodes
@ArjanCodes Год назад
Thank you!
@k98killer
@k98killer 2 года назад
Really good explanation and example.
@nato.musica
@nato.musica 2 года назад
Arjan your channel is just great! Thanks for this material :)
@ArjanCodes
@ArjanCodes Год назад
Thanks so much, glad it was helpful!
@ishtiaquehussain
@ishtiaquehussain 2 года назад
This is super helpful! Learned a lot, thank you! I'm going to recommend your channel to my network. Keep up the good work!
@ArjanCodes
@ArjanCodes 2 года назад
Awesome, thank you!
@DonGioification
@DonGioification 2 года назад
Very happy I stumbled on your videos. I’m just finishing up my three year University course in software engineering and your videos are very interesting for me. Keep up the awesome work !
@ArjanCodes
@ArjanCodes 2 года назад
Congrats on finishing your university degree, and thanks - will definitely keep it up!
@madanielmadaniel
@madanielmadaniel 2 года назад
Thanks for a clear and concise explanation. 👍
@Wahlnetwork
@Wahlnetwork 3 года назад
Fantastic content, clear explanations, and great editing. Subscribed!
@ArjanCodes
@ArjanCodes 3 года назад
Thank you so much! And congrats on your own channel, those are really nice topics you cover.
@izvarzone
@izvarzone 2 года назад
why do ppl always write that?
@shadharris4275
@shadharris4275 3 года назад
Thank you for another great video Professor Arjan
@ArjanCodes
@ArjanCodes 3 года назад
You’re welcome, glad you liked it!
@magenertech9412
@magenertech9412 2 года назад
Great video. For those who want a simple sentence to sum up composition - Composition is dividing different class responsibilities to abstract interfaces stored inside the class as opposed to defining these responsibilities through inheritance.
@ravirockz7958
@ravirockz7958 2 года назад
You are just awesome. It really helpful to know more about the advanced topics on python. Please Keep sharing
@baloothebeardogretreiver8419
Best video on this topic I've seen.
@ArjanCodes
@ArjanCodes Год назад
Glad you think so!
@engcisco
@engcisco Год назад
Thank you, your videos are direct, simple and to the point. great explanation, I really enjoy your videos
@ArjanCodes
@ArjanCodes Год назад
Thanks Baher, happy you’re enjoying the content!
@Christina__V
@Christina__V 2 года назад
Found your video as i was looking for the basics. Bit too advanced for me but this is solid content. Keep up the good work
@f4bglv
@f4bglv Год назад
Excellent tutorial, very well done and directed. Thanks a lot!
@ArjanCodes
@ArjanCodes Год назад
Thank you Fabio, glad you liked the video!
@suryaya441
@suryaya441 Месяц назад
Brilliant video, thanks so much
@ArjanCodes
@ArjanCodes Месяц назад
Glad you enjoyed it
@pierocruz6191
@pierocruz6191 2 года назад
Amazing as always! Thank you for your content
@ArjanCodes
@ArjanCodes Год назад
Thank you Piero, glad you liked the video!
@AJ-et3vf
@AJ-et3vf 2 года назад
Awesome video! Thank you!
@ArjanCodes
@ArjanCodes Год назад
Thank you AJ, glad you liked the video!
@moizmansur
@moizmansur 3 года назад
Arjan, I love your videos. These are things I've always wanted to read from the books but they seem too intimidating. The way you explain them make them very understandable in a language I'm familiar with so thank you so much :)
@ArjanCodes
@ArjanCodes 3 года назад
Thanks! Happy that you like the videos!
@aliabedi6163
@aliabedi6163 3 года назад
Thank you so much for this video!
@ArjanCodes
@ArjanCodes 3 года назад
You are most welcome, Ali!
@learn9475
@learn9475 2 года назад
Thanks for the video, i have watched many videos on this topic but didnt get the clarity as to why use composition but this video has a clean and neat explanation
@ArjanCodes
@ArjanCodes 2 года назад
Thank you - glad it was helpful to you!
@jonathankirkegaard2784
@jonathankirkegaard2784 3 года назад
Good example. It's refreshing to see a little more detail than the usual "Shape" examples
@ArjanCodes
@ArjanCodes 3 года назад
Thanks Jonathan, glad you enjoyed it.
@lbb2rfarangkiinok
@lbb2rfarangkiinok 2 года назад
Really good content, thnx so much for your hard work on the videos.
@edwardkent1503
@edwardkent1503 Год назад
Great explanation! I would say the "favour composition over inheritance" concept is applicable to many other languages too. In my opinion, you're the stackoverflow hero of the youtube world! 😄
@ArjanCodes
@ArjanCodes Год назад
Wow, thank you!
@bhaskarthouti1482
@bhaskarthouti1482 2 года назад
Thank you!! Very well Explained.
@ArjanCodes
@ArjanCodes 2 года назад
Thank you, glad you liked it!
@69k_gold
@69k_gold 5 месяцев назад
It's important to understand the tradeoff between code deduplication and the speed of incremental code deduplication. Inheritance is useful when there is a clear vertical heirarchial pattern, where the top level parent appears in a lot of levels below Composition is useful in a horizontal hierarchy, where there are a lot of subclasses at a single level and the odds of one of them changing in the future is high So the best practice is a combination of both
@michaelhoffman8468
@michaelhoffman8468 2 года назад
This is probably the best and most important concept video regardless of the language is so critical for new programmers to learn.
@ArjanCodes
@ArjanCodes 2 года назад
Thanks, glad you liked it!
@JulioMartinsVerso
@JulioMartinsVerso 2 года назад
wonderful explanation, congrats
@ArjanCodes
@ArjanCodes 2 года назад
Glad you liked it, Julio!
@filippobuonco95
@filippobuonco95 5 месяцев назад
Thanks a lot for this amazing work! You are literally helping me reaching the next level of Python code!
@ArjanCodes
@ArjanCodes 5 месяцев назад
I'm happy to hear that my content has been helpful, Filipo!
@sachinjogi1995
@sachinjogi1995 3 года назад
Very well explained 😀! It'll be great if in future you also consider building complex application following the design principles. Something like Twitter clone etc, where you can understand how to think about software architecture, oop design etc in complex applications.
@ArjanCodes
@ArjanCodes 3 года назад
Thank you very much for the suggestion!
@Elite7555
@Elite7555 2 года назад
3:05 That's a perfect example for mixins: shared behaviour without class hirachy.
@abhishekkumar-gupta
@abhishekkumar-gupta 2 года назад
I really love your content and would really wish you continue making such videos.
@ArjanCodes
@ArjanCodes 2 года назад
Glad to hear you like the content, and I’m definitely continuing with these!
@CounterBarry
@CounterBarry 2 года назад
Thank you for this video. In a simple and understandable way, you have explained the concept of Composition.
@ArjanCodes
@ArjanCodes 2 года назад
Glad it was helpful!
@rulerofthumbs
@rulerofthumbs 3 года назад
Great content! Subscribed
@ArjanCodes
@ArjanCodes 3 года назад
Thank you - glad you like it!
@esra_erimez
@esra_erimez Год назад
The importance of this video simply cannot be overstated. Well done. Programmers embraced inheritance with reckless abandon.
@ArjanCodes
@ArjanCodes Год назад
Thank you!
@kaninchengaming-inactive-6529
I was skeptical at first but I think you convinced me
@andyanderson222
@andyanderson222 Год назад
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!
@ArjanCodes
@ArjanCodes Год назад
Thank you so much, Andy!
@dawid_dahl
@dawid_dahl 2 года назад
Great video!
@ArjanCodes
@ArjanCodes 2 года назад
Thanks!
@finja5451
@finja5451 2 года назад
thank you so so much for sharing your knowledge, great channel!
@ArjanCodes
@ArjanCodes 2 года назад
Thank you Josephine, glad you like the videos!
@floodu17
@floodu17 Год назад
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.
@ArjanCodes
@ArjanCodes Год назад
Thank you too!
@chriswysocki8816
@chriswysocki8816 2 года назад
excellent guideline.
@ArjanCodes
@ArjanCodes 2 года назад
Glad it was helpful!
@lowkeygaming4716
@lowkeygaming4716 Год назад
Thanks. This is so informative
@ArjanCodes
@ArjanCodes Год назад
Thanks so much, glad the content is helpful!
@TheFootballPlaya
@TheFootballPlaya 2 года назад
these are awesome videos. thank you so much
@ArjanCodes
@ArjanCodes 2 года назад
Thank you, happy to hear you liked it!
@mpete0273
@mpete0273 3 года назад
These are so good!
@ArjanCodes
@ArjanCodes 3 года назад
Thank you, Matt - glad you like 'em!
@robertbrummayer4908
@robertbrummayer4908 3 года назад
Great job
@utube999ify
@utube999ify 2 года назад
I am a tester by experience and looked at coding with that mindset. I am also old school procedural methods (think Basic with sub-routines or PL/SQL). When object oriented programming first hit I tried to follow the approach for inheritance in the book to mimic the complex applications I tested on. We went too deep with inheritance (as the examples in the early books used multiple layers), so it tainted my experience and I left it behind as too difficult for me to understand when dealing with large data volumes in structured databases. Nowadays, I am more open minded. I have more time on my hands to research and experience the design methods and changes in coding practice. I find your videos has taken the hard learning and presents the knowledge in a straight forward practical manner.
@mareged9978
@mareged9978 3 года назад
Love design patterns!!
@ArjanCodes
@ArjanCodes 3 года назад
Me too!!
@alexanderscott2456
@alexanderscott2456 3 года назад
Thank you for the high quality content. Subbed.
@ArjanCodes
@ArjanCodes 3 года назад
Thank you Alexander, glad you like the videos!
@alexanderscott2456
@alexanderscott2456 3 года назад
@@ArjanCodes I think you've touched on a completely under developed niche on RU-vid. There are so few good Python videos on good design principles. Also, RU-vid recommended me your channel because I was searching for Python design patterns. It was your introduction to Pydantic.
@JohnDoe-wq9pr
@JohnDoe-wq9pr 2 года назад
These videos are great reminders of concepts that were learned then long forgotten, due to various circumstances. I actually learned about design patterns in university using the same Design Patterns book by Grady Booch (so glad I decided to keep it). I just had a couple of thoughts for this type of comparison video for your consideration, as follows: - instead of changing the code that is already there, maybe have a side by side view that will allow the new code to be seen against the previous version, for improved clarity on the differences between the two - it would be nice to see a diagram that visually shows the structural difference between them Take these suggestions as you see fit. I look forward to seeing more of your videos either way.
@ArjanCodes
@ArjanCodes 2 года назад
Hi John, glad that you like the videos and thank you for your suggestions!
@RakeshMandava
@RakeshMandava 3 года назад
Good One - Thanks !!
@ArjanCodes
@ArjanCodes 3 года назад
You’re welcome! Glad you enjoyed it.
@nyashachiroro2531
@nyashachiroro2531 Год назад
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.
@ArjanCodes
@ArjanCodes Год назад
Thanks!
@yd_
@yd_ 2 года назад
Thanks for these videos, I think these are very important resources, especially in academia, where graduate students from non-computational background usually self-teach programming for data analysis, modelling, etc. As such, it's often the case that they write code that performs well, but isn't readable or extensible.
@ArjanCodes
@ArjanCodes 2 года назад
You're very welcome!
@gremblexyz
@gremblexyz Год назад
This is also a very useful use case for the structural subtyping stuff (Protocols).
@ArjanCodes
@ArjanCodes Год назад
Thanks so much, glad the content is helpful!
@natel2891
@natel2891 2 года назад
thank you for many interesting videos. You got my sub! The videos on youtube about Python are either too basic or just blah blah import...ML...data science. Your content really stands out and I have learned so much about software dev standards that can be applied to other languages not necessarily only Python.
@ArjanCodes
@ArjanCodes 2 года назад
Thank you Nate, glad the content is helpful to you,
@vxsniffer
@vxsniffer 2 года назад
very clear explanation ;-)
@user-hf5be1zu7s
@user-hf5be1zu7s 2 года назад
you are the best! thank you
@ArjanCodes
@ArjanCodes 2 года назад
You're welcome!
@TimWackrow
@TimWackrow Год назад
Would be great to include an example of aggregation vs composition
@masterull
@masterull 2 года назад
well done thnx!
@evadeflow
@evadeflow 2 года назад
It really caught my eye when you inherited from `ABC`, but also used the `dataclass` decorator. What sorcery is this?? I've clearly missed some recent developments in Python. Any chance you have vids/links that explain why one would do this? Also... your videos absolutely rock, man. I dunno if they hit other people's sweet spot for relevance to their own place within the IT ecosystem, but... your content is super-relevant to my own little corner of this crazy space we work in. Thank you!
@ruszkait
@ruszkait 3 года назад
Very nice explanation indeed. Two remarks: for testing you can use a unit test instead of just looking at the output - this would set a good example. The other comment: maybe you can show how you can use the decorator pattern to build up class hierarchies in runtime and override behavior. That would be simpler than the composition, because you do not have to know in your base class that you have a contract and an optional comission, but it would be much more flexible than the inheritance, because you can add up the layers of decoration in runtime (similar as you have done the dependency injection in runtime)
@ArjanCodes
@ArjanCodes 3 года назад
Thank you, glad you liked it! I try to strike a balance between using best practices in my examples while keeping things simple. That’s why I generally leave unit tests out of the examples if that’s not the focus. The decorator pattern is indeed a good suggestion for a video (I think it’s already somewhere on my list).
@ninjanape
@ninjanape 2 года назад
Thanks mate
@zdzichuWentyl
@zdzichuWentyl 2 года назад
Wow a piece of good work
@ArjanCodes
@ArjanCodes 2 года назад
Thank you! Glad you enjoyed it.
@zdzichuWentyl
@zdzichuWentyl 2 года назад
@@ArjanCodes yes indeed you explain in very accessible way good work best explained content I even seen not good work -> best work I have to subscribe
@Operaatoors
@Operaatoors Год назад
I know 100% for sure that this was not scripted, but I really love to see you struggle to find the correct place on 8:02 :D Very good "bad" example :) I had a feeling that this might come up but I didn't know if you really wanted to force your self in that stupid situation. I also did similar thing displaying strugle with WET code to my students, and I was suffering a lot :D
@flam1ngicecream
@flam1ngicecream 2 года назад
Really cool. As a C++ nerd, my brain was shouting "multiple inheritance!" but now I can use this method instead when I'm in a language like Java that forbids it.
@noimnotnice
@noimnotnice 2 месяца назад
I discovered this principle without knowing its name in my testing of automated trading strategies. Every building block naturally lends itself to be derived from a base strategy (e.g. setting stop losses). All strategies are then assembled as compositions by various building blocks. The key is that both inheritance and composition have their utility for different purposes.
@mahmoudelrabee2456
@mahmoudelrabee2456 2 года назад
Thank you 😍
@ArjanCodes
@ArjanCodes 2 года назад
You’re welcome!
@wlcrutch
@wlcrutch 2 года назад
I have been having my first dabblings in OO with java, coming from a mathematical/functional background. While I understand what inheritance IS, I haven’t ever been a fan of using it, mostly for the reasons you mention. It just isn’t how my brain works, so it’s nice to see this and feel validated 😃
@izvarzone
@izvarzone 2 года назад
but you still need it sometimes. Use both inheritance and composition, not only composition, where it make sense.
@izvarzone
@izvarzone 2 года назад
For example LinkGun would be Actor -> Inventory -> Weapon - > LinkGun with inheritance but then LinkGun would have many components of which it's made. In case you'd want make hybrid of Minigun and Link gun later, using components of both. Actor, Inventory and Weapon are abstract classes.
@cfossto
@cfossto Год назад
Here I was thinking I was good at Python. Thank you for this! Python have become fun again thanks to this video.
@ArjanCodes
@ArjanCodes Год назад
Great to hear!
@jackbotman
@jackbotman 4 месяца назад
The composition approach effectively forces you to simplify your objects into more reusable units Which is nice
@mystisification
@mystisification 2 года назад
Would you mind explaining why we couldn't use a Mixin here rather than composition?
@mario7501
@mario7501 Год назад
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
@iloulislam2866
@iloulislam2866 Год назад
Thanks!
@ArjanCodes
@ArjanCodes Год назад
You're welcome!
@mgrfans
@mgrfans 3 года назад
Superb videos. Good quality, well explained. Thank you so much for putting in the effort. By the way what is the extension that you are using for the python auto formatting?
@paul_devos
@paul_devos 3 года назад
This is the best video I've seen on the tradeoffs of Inheritance vs Composition. One question I'd have is could you manage the explosion of subclasses better with multiple inheritance? Perhaps that's just a nomenclature thing as you essentially have an explosion of parent (super) classes. Note: Most of my experience is for Data Engineering and web scraping. Where I might have a "data container" of attributes (10-12) I want as defaults for say, an http request, where each instance or new request adds or updates 5 new ones (e.g. API endpoint, persistence location, database destination, filename, etc) and then I add a few different methods if the user wants to add a 2nd API call to another endpoint to modify/enrich the current "state" and then persist. In function this would be similar to querying two database tables (via http requests), then joining/mapping the data, then persisting to a destination. For this scenario, I hadn't really considered composition altho the way you presented it I was using some of that "design" in that I use multiple parents with ABCs to get a subclass that is ultimately used. I had mostly hemmed and hawed on whether to use functions (passing in a large dictionary of 10-15 attributes or having 10-15 defaults) instead of classes. I'm still not sure I have done the design correctly. And I think the main problem I have is my final package seems where I am scraping a website and have 80+ API endpoints where 60 or so are more "functional" in design -- while 20 API endpoints need two different API calls for that sort of "join" to another data set (using a class here vs two function calls, persist in memory, join via say Pandas merge, then persist). So wanting to make it one package as it's for consumption of a single package so should it be composed of all classes? functions without classes? And the big thing is helping users with the default of all those default URL parameters (8-15 per HTTP request) and how to best manage that as each API call does have that many (or more) parameters needed to get a data request back. I will be watching more of your videos to see if you already have the right answer to this question. Thanks again for this content. Very helpful.
@ArjanCodes
@ArjanCodes 3 года назад
Hi Paul, glad you enjoyed the video! I would strongly advise against using multiple inheritance, as it leads to all kinds of issues, the most well-known one is the Diamond of Death (see en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem). I found I can solve most of my design problems with composition and careful use of inheritance, mainly in combination with abstract classes.
@paul_devos
@paul_devos 3 года назад
Thank you@@ArjanCodes will definitely work on becoming better at implementing composition instead.
@radeksmola3422
@radeksmola3422 Год назад
Hi Arjan, great video by the way. One question at you: What is the difference between composition in this video and dependency injection?
Далее
Do We Still Need Dataclasses? // PYDANTIC Tutorial
16:33
Composition over Inheritance
8:34
Просмотров 508 тыс.
Protocol Or ABC In Python - When to Use Which One?
23:45
The Ultimate Guide to Writing Functions
24:31
Просмотров 178 тыс.
More Python Code Smells: Avoid These 7 Smelly Snags
20:29
Only Use Inheritance If You Want Both of These
9:10
Просмотров 13 тыс.
Here’s a More Pythonic Factory Pattern
23:18
Просмотров 99 тыс.
8 Design Patterns | Prime Reacts
22:10
Просмотров 389 тыс.
Why Use Design Patterns When Python Has Functions?
23:23