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: ua-cam.com/video/eiDyK_ofPPM/v-deo.html
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!
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!
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!
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.
@@VivekYadav-ds8oz So, going forward, every new programmer who reaches this stage and searches "composition vs inheritance" is likely to find this video.
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! ;]
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.
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.
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.
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.
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.
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!
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!!
This video is great. What is not mentioned in it is that it also conforms the single responsibility principle to separate different kind of responsibilities into different interfaces/classes to provide a flatter structure instead of having a fat class or a very deep inheritance relationship that doing everything, which also make it improves the cohesion of the class. I did find it is quite interesting that when people are talking about a good design pattern from one aspect, its goodness will also make it to conform the other coding principles automatically. Great job 👍
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.
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!!
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
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.
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.
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.
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.
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.
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.
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!
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.
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.
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.
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!
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! 😄
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 :)
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.
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
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.
I'm not sure that it would be a very bad design or not, but it would it be interesting to see if Multiple Inheritance (Mixins) were used to solve this problem. What are your thoughts on it?
An inheritance without abstract methods (or virtual functions if you wish) is a different form of a composition it is a "horizontal"composition. The main difference is the following: 1) In case A is a member of B you create a hierarchy in the interface of B: x = B() x.method_of_B() x.a.method_of_A() 2) In case A is a base class of B you merge the two interfaces together: x = B() x.method_of_B() x.method_of_A() So you can do something like that def EmployeeType(PersonalData, Contract, Commission): class Employee(PersonalData, Contract, Commission): ## implementation of the class return Employee to create a specific type of Employee and then use type alias Employee1 = EmployeeType(PersonalData1, Contract1, Commission1) to use it in a convenient way like that dude = Employee1() However, all the methods of PersonalData, Contract, and Commission will be available in Employee interface. If this is meaningful and what you want, this is a right solution. If the interface of Employee has excess methods, then you should not do this, because "horizontal" composition means that you really do want to merge the interfaces together. This technique is called "Policy based design". It is useful when you want to construct a class with an interface merged from several independent ones and you want to control these peaces.
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.
I'm curious, is there a good reason to have separate abstract base classes for Commissions and for Contracts? They are both defined identically by the end of the refactoring, and you even call the concrete commissions class ContractCommission which is a mighty confusing name given that its implementation is independent of Contract. It seems to me like there should be only one type of abstract class, a Contract. And Employee, rather than taking a single Contract + optional Commission, can just take an arbitrary collection of Contracts and sum up their pays.
But even though they have similar interfaces, they are fundamentally different things. For example, it wouldn't make any sense for an Employee to have an arbitrary collections of Contracts (what does it mean for an Employee to have both an HourlyContract and a SalariedContract?), but it may make sense to have an Employee with an HourlyContract and an arbitrary collection of Commissions. I would say that's enough reason to keep them as separate classes. But definitely adding a collection of Commissions to Employee could make sense, and maybe improve naming between Contract and Commission to avoid confusion.
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)
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).
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
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 !
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 😃
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.
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. 💕
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.
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.
Hi Arjan, great video!. Just one question: in 17:19 you relate to hours_worked like this: henry_contract.hours_worked. Why not henry.contract.hours_worked ? Can you share why first approach over second one?
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.
I would perhaps add a NullCommission class instead of making the commission optional with None; it would clean up the code a little bit, since you wouldn't need to check for nulls
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.
I am revisiting this as this is an important concept. I notice though that the inheritance you set up is not how it is done. The compute pay should be its own class. You would then inherit from multiple base classes. This is true OOP under C/C++. Unfortunately, most languages today only allow for inheriting from one base class. This is because so many people cannot get the inheritance setup up correctly. Composition makes it a lot easier when it comes to data classes like you have been using. When it comes to behavioral things like building a window system, then inheritance is the way to go.
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.
In 13:57, I would usually verify "if self.comission", not "if self.commision is not None". Is there a advantage in the longer version that I'm not aware? The diference is that in the shorter comission can be something, but also representing False.
Since self.commission is set to None by default, and since self.commission only affects the salary if the default is overwritten, then it is cleaner to check exactly for 'not the default value'. Hence 'if self.commission is not None'. Though I'd argue that it is even better to check 'if isinstance(self.commission, Commission)' since, strictly speaking, a commission can only be paid if self.commission is an instance of Commission. A commission cannot be guaranteed to be paid just because self.commission is not None. Then it could in principle be anything else than None.
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 clicked because of the cute thumbnail, and the great content ;) Halfway through, just wanted to comment- watching the inheritance demo gave me an increasingly nauseated feeling. Looking forward to cleanliness of composition. I find often, with a modicum of intuition in the domain, you can really follow your gut about whether you're using a good pattern for a given objective.
Thanks, glad you like it! You're right - the intuition is something you develop over time as you gain more experience. Often, I find I don't explicitly think about design patterns or principles anymore, they just "emerge" when I write code.
@@ArjanCodes That's really cool to hear. Like great musicians or athletes who make it look natural. It is definitely a skill and an art to give clear and concise explanations of the concepts though! Satisfying and elucidating to watch, even when you sort of know where it's going already. Big ups for that! :)
Hey, Arjan! Isn't this an example of Aggregation instead of Composition since the object creation isn't a responsibility of the classes that are using it rather is used by passing references? Just asking, I am learning Aggregation vs Composition very recently. I can be wrong. BTW, Huge Fan!
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?
I know, this is just an example, but the redundancy issue you mentioned for yearly bonus, etc. can be solved easily by multiple inheritance I think. I'm still not saying, that this should be a way to go for this situation. I feel, that inheritance has more reason for statically typed languages. In a duck typed language that story is different. Also, it probably matters, if inheritance means "extension" or "specification". Not arguing, just sharing thoughts. It is actually really interesting to see, how different languages address these different issues. I'm more of a C++ guy, and when people ask, why C++ is difficult, I usually answer that it is not because of memory and stuff. It is because you have (multiple) inheritance, composition, templates, concepts, crazy things like CRTP. And the difficult thing to know is, which is better used for a certain problem. As always, thanks for the vid.
Another thought. If you have n of these features, and that gives 2^n different "types", then an important question is if you are going to use all of them, or you know, that only 3 specific types will be ever used. Maybe 2 more added later. The best applied design probably depends on this. Also, it is rather important if you "depend" on the parent functions (like in your example) or not (like personal data mentioned in the end). Inheritance is probably not such a problem in the second case. The advantage of inheritance in my eyes is that it also "copies" the interface of a class. If I do composition and want to make that functionality public, I have to write the function that calls the function of the component. If no additional logic is added, it is just a boilerplate code. My python background is not the best, maybe there is a @delegate decorator or something like traits in PHP. But I'm curious on your opinion.
Great series of videos, I have been watching from first in the series til here (with giving thumbs up :P). I am pretty new to pattern design and design principle space, so my questions might sound noobish. 1. Is it the Bridge pattern that you are implementing with this example? 2.Is Composition a type of design principle or a type of other stuffs? Like Bridge pattern belongs to design patter, what composition belongs to? I just want to know what other good 'principle' are out there for me to learn that sits the same level as Composition. Again, thanks for these great videos, its really good and please keep it up!
For question 1, if it's not bridge, could you specify what is the difference? I just started learning and I think the best way to master them is to identify the similarity and differences between different designs
Instead of inheriting broad classes from a single ABC create multiple smaller ABCs encapsulating some data and use a broader class to encapsulate specific implementations of these smaller ABCs
The Go language is sometimes criticized over its lack of support for inheritance. However after watching this video, I believe the language's developers were wise to focus on composition. (with interfaces to handle abstract methods)
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: ua-cam.com/video/eiDyK_ofPPM/v-deo.html
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!
Thank you Andrés, glad to be of service and wish you a great weekend too.
To be honest I didn't notice the money in the thumbnail before reading this comment
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?
Did it work?
Counter-argument: I'd rather get an inheritance from a deceased relative than a composition, no matter how good at poetry they were.
Why not both? You can inherit a bunch of compositions :)?
@@anhnhvn that sucks haha
Depending on if they were popular, the compositions could be worth a great fortune.
@@Azurath100 Not from my relatives.
That's cute
I really like how you make small incremental changes, and run/test the code after each iteration.
Glad you like the video, Michael!
@@ArjanCodes It would have been better if it was a unit test :)
That is basically the best way to code. Small change. Review. Commit.
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!
Thank you Michael, glad it was helpful!
I love it that your videos are somewhat advanced, there are not a lot of these on UA-cam. Keep up the great work!
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!
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.
@@ArjanCodes What a great answer and attitude.
To be honest, slightly more niche videos actually make channels blow up quicker.
This is not that advanced. This is something every programmer is supposed to research and know about.
@@VivekYadav-ds8oz So, going forward, every new programmer who reaches this stage and searches "composition vs inheritance" is likely to find this video.
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! ;]
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.
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.
the only video I really understood. It is important to know the real problem before thinking how to write the code.
OOP composition has not been covered enough, so thank you for creating this video!
You’re most welcome!
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.
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.
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.
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!
Thank you Sam, glad you liked it!
The importance of this video simply cannot be overstated. Well done. Programmers embraced inheritance with reckless abandon.
Thank you!
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!!
This video is great. What is not mentioned in it is that it also conforms the single responsibility principle to separate different kind of responsibilities into different interfaces/classes to provide a flatter structure instead of having a fat class or a very deep inheritance relationship that doing everything, which also make it improves the cohesion of the class. I did find it is quite interesting that when people are talking about a good design pattern from one aspect, its goodness will also make it to conform the other coding principles automatically. Great job 👍
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.
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!!
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
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.
3:05 That's a perfect example for mixins: shared behaviour without class hirachy.
This is probably the best and most important concept video regardless of the language is so critical for new programmers to learn.
Thanks, glad you liked it!
This channel has been a game changer for my coding skills.
Thank you!
Watching you is intellectually stimulating....what a relief to find such an amazing and ADVANCED content
I love your typing speed and sound of it. Amazing content. Subscribed!!
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.
Thank you very much for the suggestion!
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.
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.
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.
Fantastic content, clear explanations, and great editing. Subscribed!
Thank you so much! And congrats on your own channel, those are really nice topics you cover.
why do ppl always write that?
Good example. It's refreshing to see a little more detail than the usual "Shape" examples
Thanks Jonathan, glad you enjoyed it.
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.
Thank you too!
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!
Thank you! Glad you enjoy the videos!
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.
I appreciate that!
I was skeptical at first but I think you convinced me
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.
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.
Thank you@@ArjanCodes will definitely work on becoming better at implementing composition instead.
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!
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! 😄
Wow, thank you!
The composition approach effectively forces you to simplify your objects into more reusable units
Which is nice
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 :)
Thanks! Happy that you like the videos!
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.
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
Thank you - glad it was helpful to you!
This is so great. Thank you for the explantation! As I aspiring software developer this kinds of videos are very important.
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.
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
Thank you, your videos are direct, simple and to the point. great explanation, I really enjoy your videos
Thanks Baher, happy you’re enjoying the content!
I'm not sure that it would be a very bad design or not, but it would it be interesting to see if Multiple Inheritance (Mixins) were used to solve this problem. What are your thoughts on it?
An inheritance without abstract methods (or virtual functions if you wish) is a different form of a composition it is a "horizontal"composition. The main difference is the following:
1) In case A is a member of B you create a hierarchy in the interface of B:
x = B()
x.method_of_B()
x.a.method_of_A()
2) In case A is a base class of B you merge the two interfaces together:
x = B()
x.method_of_B()
x.method_of_A()
So you can do something like that
def EmployeeType(PersonalData, Contract, Commission):
class Employee(PersonalData, Contract, Commission):
## implementation of the class
return Employee
to create a specific type of Employee and then use type alias
Employee1 = EmployeeType(PersonalData1, Contract1, Commission1)
to use it in a convenient way like that
dude = Employee1()
However, all the methods of PersonalData, Contract, and Commission will be available in Employee interface. If this is meaningful and what you want, this is a right solution. If the interface of Employee has excess methods, then you should not do this, because "horizontal" composition means that you really do want to merge the interfaces together. This technique is called "Policy based design". It is useful when you want to construct a class with an interface merged from several independent ones and you want to control these peaces.
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.
You're very welcome!
I'm curious, is there a good reason to have separate abstract base classes for Commissions and for Contracts? They are both defined identically by the end of the refactoring, and you even call the concrete commissions class ContractCommission which is a mighty confusing name given that its implementation is independent of Contract.
It seems to me like there should be only one type of abstract class, a Contract. And Employee, rather than taking a single Contract + optional Commission, can just take an arbitrary collection of Contracts and sum up their pays.
But even though they have similar interfaces, they are fundamentally different things. For example, it wouldn't make any sense for an Employee to have an arbitrary collections of Contracts (what does it mean for an Employee to have both an HourlyContract and a SalariedContract?), but it may make sense to have an Employee with an HourlyContract and an arbitrary collection of Commissions.
I would say that's enough reason to keep them as separate classes. But definitely adding a collection of Commissions to Employee could make sense, and maybe improve naming between Contract and Commission to avoid confusion.
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)
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).
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
This channel is a treasure for advanced python! Thanks!
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 !
Congrats on finishing your university degree, and thanks - will definitely keep it up!
Thank you for this video. In a simple and understandable way, you have explained the concept of Composition.
Glad it was helpful!
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 😃
but you still need it sometimes. Use both inheritance and composition, not only composition, where it make sense.
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.
You are just awesome. It really helpful to know more about the advanced topics on python. Please Keep sharing
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. 💕
Would you mind explaining why we couldn't use a Mixin here rather than composition?
Thanks a lot for this amazing work! You are literally helping me reaching the next level of Python code!
I'm happy to hear that my content has been helpful, Filipo!
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.
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.
Thanks!
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!
Thank you so much, Andy!
This is super helpful! Learned a lot, thank you! I'm going to recommend your channel to my network. Keep up the good work!
Awesome, thank you!
Excellent tutorial, very well done and directed. Thanks a lot!
Thank you Fabio, glad you liked the video!
Crystal clear examples and explanations. Love your videos Arjan!
Glad you like ‘em Dennis!
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
Arjan your channel is just great! Thanks for this material :)
Thanks so much, glad it was helpful!
The best Python videos I've seen so far. Thank you!
Glad you like them, Steve!
Hi Arjan, great video!. Just one question: in 17:19 you relate to hours_worked like this: henry_contract.hours_worked. Why not henry.contract.hours_worked ? Can you share why first approach over second one?
Both works, there is no better one. I however, prefer henry.contract.hours_worked
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.
Would be great to include an example of aggregation vs composition
Great content. What was the keyboard you were using? Liked the sound of it.
Here I was thinking I was good at Python. Thank you for this! Python have become fun again thanks to this video.
Great to hear!
I would perhaps add a NullCommission class instead of making the commission optional with None; it would clean up the code a little bit, since you wouldn't need to check for nulls
Good suggestion!
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.
Hi Arjan, great video by the way. One question at you: What is the difference between composition in this video and dependency injection?
Really good content, thnx so much for your hard work on the videos.
This is also a very useful use case for the structural subtyping stuff (Protocols).
Thanks so much, glad the content is helpful!
great video
I like the way you've walked through the code changes
unrelated - what's the song playing at the end of the video?
Shazam is stumped
I am revisiting this as this is an important concept. I notice though that the inheritance you set up is not how it is done. The compute pay should be its own class. You would then inherit from multiple base classes. This is true OOP under C/C++. Unfortunately, most languages today only allow for inheriting from one base class. This is because so many people cannot get the inheritance setup up correctly. Composition makes it a lot easier when it comes to data classes like you have been using. When it comes to behavioral things like building a window system, then inheritance is the way to go.
Great video, thanks Arjan!
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.
Hi John, glad that you like the videos and thank you for your suggestions!
Another brilliant video. Thanks Arjan! I just love your content.
Thanks Chuck, always nice to hear from you and glad that you like the content!
Thanks for a clear and concise explanation. 👍
In 13:57, I would usually verify "if self.comission", not "if self.commision is not None". Is there a advantage in the longer version that I'm not aware? The diference is that in the shorter comission can be something, but also representing False.
Since self.commission is set to None by default, and since self.commission only affects the salary if the default is overwritten, then it is cleaner to check exactly for 'not the default value'. Hence 'if self.commission is not None'. Though I'd argue that it is even better to check 'if isinstance(self.commission, Commission)' since, strictly speaking, a commission can only be paid if self.commission is an instance of Commission. A commission cannot be guaranteed to be paid just because self.commission is not None. Then it could in principle be anything else than None.
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.
Thank you Nate, glad the content is helpful to you,
@ArjanCodes clicked because of the cute thumbnail, and the great content ;)
Halfway through, just wanted to comment- watching the inheritance demo gave me an increasingly nauseated feeling. Looking forward to cleanliness of composition.
I find often, with a modicum of intuition in the domain, you can really follow your gut about whether you're using a good pattern for a given objective.
Thanks, glad you like it! You're right - the intuition is something you develop over time as you gain more experience. Often, I find I don't explicitly think about design patterns or principles anymore, they just "emerge" when I write code.
@@ArjanCodes That's really cool to hear. Like great musicians or athletes who make it look natural. It is definitely a skill and an art to give clear and concise explanations of the concepts though! Satisfying and elucidating to watch, even when you sort of know where it's going already. Big ups for that! :)
Hey, Arjan! Isn't this an example of Aggregation instead of Composition since the object creation isn't a responsibility of the classes that are using it rather is used by passing references?
Just asking, I am learning Aggregation vs Composition very recently. I can be wrong. BTW, Huge Fan!
Best video on this topic I've seen.
Glad you think so!
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?
Could you please make a django series with design pattern and scalable architecture..it would be kindly helpful for learners
Hi! Django is definitely on the table for a future video or video series.
I know, this is just an example, but the redundancy issue you mentioned for yearly bonus, etc. can be solved easily by multiple inheritance I think. I'm still not saying, that this should be a way to go for this situation. I feel, that inheritance has more reason for statically typed languages. In a duck typed language that story is different. Also, it probably matters, if inheritance means "extension" or "specification". Not arguing, just sharing thoughts. It is actually really interesting to see, how different languages address these different issues. I'm more of a C++ guy, and when people ask, why C++ is difficult, I usually answer that it is not because of memory and stuff. It is because you have (multiple) inheritance, composition, templates, concepts, crazy things like CRTP. And the difficult thing to know is, which is better used for a certain problem. As always, thanks for the vid.
Another thought. If you have n of these features, and that gives 2^n different "types", then an important question is if you are going to use all of them, or you know, that only 3 specific types will be ever used. Maybe 2 more added later. The best applied design probably depends on this. Also, it is rather important if you "depend" on the parent functions (like in your example) or not (like personal data mentioned in the end). Inheritance is probably not such a problem in the second case. The advantage of inheritance in my eyes is that it also "copies" the interface of a class. If I do composition and want to make that functionality public, I have to write the function that calls the function of the component. If no additional logic is added, it is just a boilerplate code. My python background is not the best, maybe there is a @delegate decorator or something like traits in PHP. But I'm curious on your opinion.
Great series of videos, I have been watching from first in the series til here (with giving thumbs up :P). I am pretty new to pattern design and design principle space, so my questions might sound noobish.
1. Is it the Bridge pattern that you are implementing with this example?
2.Is Composition a type of design principle or a type of other stuffs? Like Bridge pattern belongs to design patter, what composition belongs to? I just want to know what other good 'principle' are out there for me to learn that sits the same level as Composition.
Again, thanks for these great videos, its really good and please keep it up!
For question 1, if it's not bridge, could you specify what is the difference? I just started learning and I think the best way to master them is to identify the similarity and differences between different designs
I really love your content and would really wish you continue making such videos.
Glad to hear you like the content, and I’m definitely continuing with these!
Instead of inheriting broad classes from a single ABC create multiple smaller ABCs encapsulating some data and use a broader class to encapsulate specific implementations of these smaller ABCs
There are more classes in this example than all the classes I implemented on python my entire life...
I’m going for a Guinness record ;).
Thank you so much for this video!
You are most welcome, Ali!
Composition combined with inheritance = mind blown
The Go language is sometimes criticized over its lack of support for inheritance. However after watching this video, I believe the language's developers were wise to focus on composition. (with interfaces to handle abstract methods)
Amazing as always!
Thank you for your content
Thank you Piero, glad you liked the video!
Really good explanation and example.