Only Use Inheritance If You Want Both of These

  Рет қаралды 11,696

Christopher Okhravi

Christopher Okhravi

Күн бұрын

Inheritance gives us hierarchical reuse of code AND subtype polymorphism. In this video I argue that we should only ever use it if we want BOTH.
/ christopherokhravi
📚 Recommended Reading:
geni.us/nlbA6 (Head First: Design Patterns)
geni.us/PsXmo (Design Patterns: Elements of Reusable Object-Oriented Software)
Watch next:
• The Only Time You Shou...
• Always Use Interfaces
• Depend on Abstractions...
00:00 Intro
00:21 Only Hierarchical Reuse
03:16 Only Subtype Polymorphism
05:37 Avoid Inheritance?
07:13 Couple To Abstractions
07:32 Example
08:36 Conclusion

Пікірлер: 101
@gurituna
@gurituna 22 күн бұрын
as a senior developer , it is very good explanation.
@user-vh8bm3fw9w
@user-vh8bm3fw9w 22 күн бұрын
I really love your videos! Not many people can explain it clearly and understandably. I like that even now, when I've got a PhD in computer science and don't write code on a regular basis. Greetings from the former Soviet union!
@motazabdelazeem3533
@motazabdelazeem3533 21 күн бұрын
Now I finally understand why Golang team provides composition and Interfaces and they refuses to add Inheritance to the language
@RagingMonkee
@RagingMonkee 22 күн бұрын
Great simple explanation of something I've seen done wrong hundreds of times.
@sarthikg
@sarthikg 21 күн бұрын
I had written some huge piece of code following inheritance. This video just made me realise how I would rewrite that code today if given a chance to do it. If 2 classes have to implement a method, i.e. be like something, it should do it through interfaces, and if they have to share some logic, they should do it through composition. Also, welcome back!
@ChristopherOkhravi
@ChristopherOkhravi 21 күн бұрын
Exactly this. Thank you for sharing! 😊🙏
@staystealth
@staystealth 22 күн бұрын
first time i've clearly understood when to use interfaces and object composition over inheritance. love your videos
@gerdsfargen6687
@gerdsfargen6687 21 күн бұрын
Best instructor ever. Chris is the best.
@itsahandle
@itsahandle 20 күн бұрын
We love your videos so much please never stop teaching ❤
@Happydrumstick93
@Happydrumstick93 22 күн бұрын
You are an unreasonably effective teacher! Keep up the great work!
@johnekare8376
@johnekare8376 22 күн бұрын
Great video as always! I really like your way of explaining these concepts. Not just in this video but in all I have seen from you so far. I feel your explanations are concise and to the point, without leaving room for ambiguity, which I really appreciate.
@ChristopherOkhravi
@ChristopherOkhravi 22 күн бұрын
Thank you very much for the feedback. Appreciated. 🙏😊
@adilsaju
@adilsaju 18 күн бұрын
Wow so clear explanation!! ❤
@nandishnan5680
@nandishnan5680 22 күн бұрын
Love your videos, as always very informative.
@ervingegprifti2612
@ervingegprifti2612 19 күн бұрын
I couldn't be happier with your videos. Thanks for your time and effort.
@loic1665
@loic1665 21 күн бұрын
Damn, this video is SO GOOD!! Your recent videos are one of the best contenet about programming!
@ChristopherOkhravi
@ChristopherOkhravi 21 күн бұрын
Thank you 🙏😊 I’m very happy to hear that the content is useful. Please feel free to share with others who you think might benefit from it. 😊
@loic1665
@loic1665 14 күн бұрын
I sure will!
@user-cd6ot9ur6h
@user-cd6ot9ur6h 15 күн бұрын
Fantastic explanation
@ratache
@ratache 21 күн бұрын
Tack så mycket.
@learn-web-dev
@learn-web-dev 22 күн бұрын
Awesome explanation!
@ipodtouch470
@ipodtouch470 22 күн бұрын
Great video man I think inheritance, composition, and interfaces are something that is taught everywhere but rarely do they teach you when and how to use it properly
@seppotaalasmaa3404
@seppotaalasmaa3404 21 күн бұрын
Thanks, very well explained.
@perian1983
@perian1983 20 күн бұрын
Another great one. Thanks!
@bogdanf6698
@bogdanf6698 22 күн бұрын
All my support for you man!❤
@ambassadorofserotonin8957
@ambassadorofserotonin8957 21 күн бұрын
Love your explanations
@rpo3ge
@rpo3ge 21 күн бұрын
First of all glad you’re back on the youtube stage 🎉 Second - how/where/when would you instantiate the list class for backpack and warehouse to use. Because backpack and warehouse are composed of things including the list class we should not be triggered/scared etc. that we’re tight coupling them? Would it also make sense to use composition with an interface rather than a concrete object. Not sure the list concept would ever change but the list could be a paper sheet and then turn out into Notes app on a tablet device 😊
@baay81
@baay81 21 күн бұрын
thanks for sharing
@shivankgoel1813
@shivankgoel1813 21 күн бұрын
due to your design pattern course i am able to grab all logics eaisly, thank you🙂
@PbPomper
@PbPomper 22 күн бұрын
Glad you're back! Composition over inheritance is something you usally learn the hard way :P
@ChristopherOkhravi
@ChristopherOkhravi 22 күн бұрын
😆
@thierrybakera4681
@thierrybakera4681 21 күн бұрын
@@ChristopherOkhravi, I really like ! But, can you give an example in which it is reasonable to use inheritance ? Because, in the last part of this video, just combined subtypes polymorphism and object composition ! Kindly ! 😊
@Igoryan481
@Igoryan481 22 күн бұрын
Thank you!
@shaharts8333
@shaharts8333 22 күн бұрын
Great work❤
@fabricehategekimana5350
@fabricehategekimana5350 20 күн бұрын
As Always, high quality content
@eahmedshendy
@eahmedshendy 21 күн бұрын
While watching, I thought to ask your perspective/thoughts about POP (Protocol Oriented Programming), but then you made a good lesson about it out of this talk.
@francescoleto2823
@francescoleto2823 22 күн бұрын
Thank you sir, amazing! 😊
@MenukaWeerasooriya
@MenukaWeerasooriya 21 күн бұрын
Anither great explanation ❤
@dripcode2600
@dripcode2600 21 күн бұрын
Yep and yep! Great video! Love this! #LoveThis
@Whatthetrash
@Whatthetrash 22 күн бұрын
Love your videos, mate! :)
@kevinfurst8163
@kevinfurst8163 20 күн бұрын
Love your vids❤
@eahmedshendy
@eahmedshendy 21 күн бұрын
I laughed when you whispered object composition, I just loved it haha.
@ChristopherOkhravi
@ChristopherOkhravi 21 күн бұрын
😊😊
@aditibhatnagar6970
@aditibhatnagar6970 21 күн бұрын
Nicely explained. Christopher, can you also share the downsides of going with inheritance incorrectly? This would help understand the implications of picking a wrong choice. Alternatively, what does one gain from going with object composition? If you've shared this in any other video, please point me to it. Thank you!
@hayeduce
@hayeduce 20 күн бұрын
I'd watch a vid about that too!
@divakukulza
@divakukulza 21 күн бұрын
I had been subclassing for a whilewithout deep thinking and reason. after studying design pattern, I can compose or confirm interface with makesense. thank you
@RatFace_MonkeyEar_FishEye
@RatFace_MonkeyEar_FishEye 22 күн бұрын
This man!
@professorfontanez
@professorfontanez 20 күн бұрын
5:37 Now in Java, you can also use Interfaces with default methods to get the best of both worlds. Like the Mandalorian would say: "This is the way!"
@ChristopherOkhravi
@ChristopherOkhravi 20 күн бұрын
100% agree. Imho there is 0 reason left to use inheritance now that we have default interface methods. Was actually thinking about doing a video on precisely this but haven’t figured out how to make it relevant for non C# programmers. Thanks for commenting! 😊🙏
@professorfontanez
@professorfontanez 20 күн бұрын
@@ChristopherOkhravi That's the beauty of this modeling. UML being language agnostic leaves the implementation detail up to the developers. It is their job to interpret the blueprint and build the code the best way the language used to implement allows you to. Years ago, you had to do it the way you show here (with the extra class) in Java because default interface methods were not possible. Today, it's a different thing. Now, we can take "creative license" liberty to deviate a bit from the model and implement it using just interfaces.
@mczn9499
@mczn9499 20 күн бұрын
interface default methods were introduced in java a long time ago, since version 8 if i remember correctly
@professorfontanez
@professorfontanez 20 күн бұрын
@@mczn9499 you'll be surprised how many people are still coding with older versions of Java.
@thestarinthesky_
@thestarinthesky_ 22 күн бұрын
You’re awesome ❤ awesome 👏
@MMMM-vc5oi
@MMMM-vc5oi 18 күн бұрын
It is true, appreciated, Christopher. I think you have experienced in game development, right? please make some videos about component based architecture and different software architectures like onion architecture, etc.
@theAIex2
@theAIex2 19 күн бұрын
Awesome explanation! But then if I understood correctly, you could achieve more or less the same using inheritance (given that you want both hierarchical reuse and subtyping) and using interface + composition. I also hear that you would favor the second approach, but then is there a specific case where you would choose inheritance (instead of interface + composition)?
@Rajmanov
@Rajmanov 22 күн бұрын
great
@johnconnor9787
@johnconnor9787 22 күн бұрын
Should we do object composition by putting an object through the constructor? Will in this case this be an example of dependency injection?
@ChristopherOkhravi
@ChristopherOkhravi 22 күн бұрын
Yes and yes 😊 The more nuanced answer is ofc that it depends. But if you use that as a general rule of thumb then it is a good rule of thumb 😊😊 Thank you for asking. 🙏
@FritsvanDoorn
@FritsvanDoorn 22 күн бұрын
I still find it difficult to actually use it. But practise makes perfect I think. Thank you for another super explanation.
@phanig398
@phanig398 18 күн бұрын
At 4:32, to make a case for hierarchical reuse of code, methods in sub classes need not always call the method/s in super class. Template design pattern is a classic example of hierarchical code re-use that uses inheritance effectively. What do you think?
@ChristopherOkhravi
@ChristopherOkhravi 17 күн бұрын
I completely agree. I have 5+ mins of deleted scenes from this video (because I think my execution was too poor) that I will release on my Patreon. In that clip I talked about Template Method Pattern (among other things) so I personally think you are spot on 😊🙏 Template Method for a a valid use case for inheritance. It could certainly still be argued that composition plus subtyping is a better solution but there’s nothing inherently problematic with Tenplate Method imho 😊😊 Thanks for the comment.
@christophem6373
@christophem6373 21 күн бұрын
Till now my view was, if you couldn't inherit from a class (because it sealed in C# for example) then use composition. I mean, composition was a workaround solution, not a "primary idea" in "factorisation" of code. But I still think taht if i need a spécial DIctionary, I implement a new class that inherit Dictionary...
@user-yi3ci7uj1x
@user-yi3ci7uj1x 21 күн бұрын
cool, I dig my code while watching
@Competitiveforlolz
@Competitiveforlolz 19 күн бұрын
So instead of using Traits as a code reuse for Subtypes (with an interface), you want to inject the implementation of another class instance, essentially the same implementation the Trait would describe, guess it streamlines the dependency overview.
@AlchemyOfDeathBand
@AlchemyOfDeathBand 21 сағат бұрын
Ok let's say we have this situation: I have a bunch of classes that share the exact same 3 methods. I need hierarchical reuse of code. I can either create a base class, and inherit from it, or create another class, then compose it and still duplicate the methods and delegate the calls? Sounds redundant. Or, I could have this new class (with the 3 methods) as a field of each of my initial classes, and when I'd want to access the method, I would access it through this field (violating the law of Demeter)? It sounds kind of confusing. I'd still go with inheritance here.
@zerg-zx5rx
@zerg-zx5rx 22 күн бұрын
One reason I might consider using inheritance is if the constructors are not accessible. For example, you need to extend the Activity class in Android.
@aj.arunkumar
@aj.arunkumar 20 күн бұрын
nice video... i have a question, is this topic related to liskov substitution in any way
@chrisjust7445
@chrisjust7445 12 күн бұрын
What are your thoughts about this scenario: In Java, interfaces can have default methods with implementation. Recently I refactored a library of classes representing specific types of web elements (for Selenium tests), and all those web elements have a base class with methods that are common to all the web elements and some of the web elements may override the implementation and others may use the default implementation. I saw that some web elements could be disabled and others cannot, so I extracted the IsDisabled() method into a default method of a new interface and had the web elements that can be disabled implement that interface, rather than copy & paste the same function in multiple classes. Would you consider that good or bad?
@SanjitMisra
@SanjitMisra 22 күн бұрын
Smashing explanation! Where is the furry one though 😺?
@carnicer78
@carnicer78 22 күн бұрын
thanks, very insightful however, in C++ using an interface is actually inheriting it - I mean that the title might be confusing. But of course, the fact of interfaces having or not a base method is something that occurs often and it's a very good criterium
@ChristopherOkhravi
@ChristopherOkhravi 22 күн бұрын
Ah. Good point. 🤔 Sometimes I get too stuck in C# which is what I do most of my thinking in. Thank you! 🙏😊
@ChikitoPOWA
@ChikitoPOWA 21 күн бұрын
Wouldn't a header file play the role of interface in C++?
@carnicer78
@carnicer78 21 күн бұрын
@@ChikitoPOWAin C++, the (java) interfaces are the so-called pure abstract classes, that is, classes with 0 methods implemented (except the default destructor) these pure-abstract classes are then inherited with either a base (shared) class, or directly implemented by several children classes
@carnicer78
@carnicer78 21 күн бұрын
@@ChristopherOkhraviooh C#, I see, now I understand why you said so haha 😄 (I write C++ for a living)
@carnicer78
@carnicer78 21 күн бұрын
back to your question, C++ classes (whether they are or not pure-abstract or not) are declared in the header files, and implemented in the .cpp file. I mean, not all header files describe interfaces (pure abstract classes). So it depends on whether the methods are implemented or not. Warning: some people implement some of the C++ methods directly in the header files. This is something I do not like at all and I never do. However, it is of course valid C++.
@BangsarRia
@BangsarRia 21 күн бұрын
@ChristopherOkhravi Not really off topic for those of us who listen to music while programming, who is your favorite Melodic Death Metal Band?
@ChristopherOkhravi
@ChristopherOkhravi 3 күн бұрын
Such a random question 😊😊 In my younger days there was a time when I listened to Soilwork 😊 But I’m not really a metal person 😊😊
@MagicPants647
@MagicPants647 20 күн бұрын
is object composition basically dependency injection? Instead of inheritance you’d just Inject a class instance into your other class and use its methods
@wooodser
@wooodser 21 күн бұрын
Can someone please explain what is 'hierarchical reuse of code'? What does it mean? I can't understand the first example at all...
@ErezAvidan1
@ErezAvidan1 17 күн бұрын
what about inheritance for data classes?
@angeloceccato
@angeloceccato 14 күн бұрын
Typescript have subtype polymorphism without inheritance, so only composition matter?
@TheHarpanOnly
@TheHarpanOnly 21 күн бұрын
Then, when do we need to do actual inheritance?
@alejandroioio6784
@alejandroioio6784 9 күн бұрын
😎
@N0Reaver
@N0Reaver 22 күн бұрын
Nice vid but is best to watch it at 1.75x ... better for the ears ;)
@adambickford8720
@adambickford8720 22 күн бұрын
Even if you have the perfect storm of needing both, as soon as that changes, you're still holding the inheritance baggage.
@ChristopherOkhravi
@ChristopherOkhravi 22 күн бұрын
I would agree 😊 But I can see how some would prefer the inheritance solution in some cases and so as long as it is a sensible use of inheritance o would not argue too much. Better to prioritize moving forward is what I’m thinking 😊 Thank you for commenting 🙏😊
@jimiscott
@jimiscott 21 күн бұрын
As opposed to? If you went the composition route, then you end up... 1. injecting behaviours into the superclass - these behaviours tend to know quite a lot about the class their being injected into. 2. they also tend to be quite limited and limiting in scope - what happens if you need multiple behaviours in a single compositional inheritance? How do you coordinate these? They get messy, quickly. Inheritance, with virtual/overridable methods give you the flexibility and the readability that compositional inheritance does not - though you do need to think about when to use traditional inheritance this closely.
@adambickford8720
@adambickford8720 21 күн бұрын
@@jimiscott It not a theory, this is a well understood topic. Composition gives you better control over your coupling. It can be slightly more effort but ime the gains of inheritance are fragile at best and a disaster at worst.
@jimiscott
@jimiscott 21 күн бұрын
@@adambickford8720 Whilst I agree that inheritance used wrongly can lead to complications, it should not be thrown out with the baby's bathwater. In our large (1M Lines) middleware/integration platform we have used inheritance to great affect to allow both ourselves and our partners to allow us/them to write add-ins to interface/integrate with different APIs/solutions. An example of this is that we allow our writer classes to be inherited and their methods overridden. These objects take a dynamic model and translate a dataset to a specific format (JSON, CSV, Xml, CSV, etc) - we have writer classes for each type of format. Each addin can (this is not always the case) inherit a writer class to implement it's own custom logic for a specific requirement. For example, an addin may need to encode some data into a specific base64 form when trying to send/upload/post images OR it may need to perform a series of API requests to translate a value/set of values to something specific to solution/service/API being integrated. Inheritance gives us the ability to override the specific method(s) to do this - furthermore we can maintain state much more easily than say if we used composition. Inheritance has given us the ability to rapidly develop these addins, they are succinct, can be easily tested and are maintainable.
@ramonennik2536
@ramonennik2536 21 күн бұрын
O my, just made this error last week... stupid me
@AloisMahdal
@AloisMahdal 20 күн бұрын
stupid you from last week is dead, long live smarter you of the future :)
@Robert-yw5ms
@Robert-yw5ms 21 күн бұрын
"Inheritence over composition" makes as much sense as "frying pan over sauce pan". They solve different problems and should be used differently. You even say it yourself at one point: "is a" vs "has a".
@Loutistic
@Loutistic 21 күн бұрын
Extremely controversial statements which violate SRP, and decline using of protected/private/abstract methods.
@ChristopherOkhravi
@ChristopherOkhravi 3 күн бұрын
Thank you for supplying an alternative perspective. Would you care to elaborate why you think this is controversial? My argument is not that you should do “two things” in a sense that it would violate SRP. The point is: Both hierarchical reuse of code and subtype polymorphism could be used for the same “feature” or “thing”, and inheritance is only a suitable solution if you need both of those to succinctly implement your one feature or thing. Otherwise inheritance is a worse solution than the alternative (which would be either composition or subtype polymorphism through interfaces). Please do feel free elaborate 😊 Thank you again 😊🙏
@user-ul9td3cd8q
@user-ul9td3cd8q 14 күн бұрын
One exception I can think of right now : sometimes I use inheritance to enforce identicalness across things, for exemple : Imagine a web application where every UI elements are defined with components called "blocks" (dozensss of them), it might make sense to inherit all different blocks from a parent class ("AbstractBlock" for exemple) even if blocks doesn't overwrite methods from the parent class, simply because when the day comes where you need to implement a feature inside ALL blocks, I would rather edit a single file than edit dozens of them ! (and maybe miss some blocks created in an un-merged branch). Or someone might not know that when you create a new block you need to implement X, Y and Z features. It's a lot less prone to human errors when the only thing to remember is "you need to extend from this class and that's it".
@TedFanat
@TedFanat 20 күн бұрын
hazza > izza)
@ChristopherOkhravi
@ChristopherOkhravi 20 күн бұрын
😆
@CSharp1991
@CSharp1991 21 күн бұрын
"just the fact that we want to reuse code, does not justify the use of inheritance" Nonsense. The sole purpose of inheritance is code reuse (reuse of procedures/methods), similar to how procedures serve the purpose of reusing sequences of operations. However, inheritance operates at a higher level. The connection between inheritance and polymorphism is coincidental. Initially, inheritance was the sole method for implementing polymorphism. Subsequently, polymorphism acquired its own implementation mechanism known as interfaces.
@silberwolfSR71
@silberwolfSR71 9 күн бұрын
You've not provided much context, so I'll assert my own: In languages like C# and Java, inheritance does more than just facilitate code reuse. The polymorphism manifesting from inheritance is not coincidental but an intended feature of these languages. As such, having a class inherit from another carries semantic meaning: it implies an is-a relationship; it implies substitutability. When you subclass a class, you make an implied promise to follow its contract. If you never cared about the contract and only about the code, it's easy to (knowingly or not) break the contract, which can lead to all sorts of hard to find bugs in other parts of the system. Composition is a more basic functionality that doesn't require inheritance yet still enables code reuse. It doesn't carry any unintended semantic meaning and encapsulates the implementation detail of code sharing (fully or partly, depending on whether you inject the component), making the class more robust (you can shield users of your class from changes to the "shared" implementation, maintaining their contract with your class independent of such changes).
@yapayzeka
@yapayzeka 21 күн бұрын
this beauty of explanation 😘🤌
@abdelaziz2788
@abdelaziz2788 17 күн бұрын
great
Command Pattern - Design Patterns (ep 7)
39:12
Christopher Okhravi
Рет қаралды 262 М.
This Is Why Managers Don't Trust Programmers...
28:04
Thriving Technologist
Рет қаралды 139 М.
小路飞姐姐居然让路飞小路飞都消失了#海贼王  #路飞
00:47
路飞与唐舞桐
Рет қаралды 89 МЛН
顔面水槽がブサイク過ぎるwwwww
00:58
はじめしゃちょー(hajime)
Рет қаралды 114 МЛН
Let's all try it too‼︎#magic#tenge
00:26
Nonomen ノノメン
Рет қаралды 54 МЛН
Who Will Eat The Porridge First The Cockroach Or Me? 👧vs🪳
00:26
Giggle Jiggle
Рет қаралды 15 МЛН
The Only Time You Should Use Polymorphism
13:55
Christopher Okhravi
Рет қаралды 85 М.
Factory Method Pattern - Design Patterns (ep 4)
27:21
Christopher Okhravi
Рет қаралды 530 М.
Liskov Substitution Principle (SOLID)
20:16
Christopher Okhravi
Рет қаралды 7 М.
The Flaws of Inheritance
10:01
CodeAesthetic
Рет қаралды 878 М.
So You Think You Know Git - FOSDEM 2024
47:00
GitButler
Рет қаралды 934 М.
Depend on Abstractions not Concretions (Framework)
11:56
Christopher Okhravi
Рет қаралды 14 М.
Event-Driven Architecture (EDA) vs Request/Response (RR)
12:00
Understanding Covariance and Contravariance
13:31
Christopher Okhravi
Рет қаралды 10 М.
Interview With A Sr JavaScript Dev | Prime Reacts
24:43
ThePrimeTime
Рет қаралды 150 М.
Why Does Scrum Make Programmers HATE Coding?
16:14
Thriving Technologist
Рет қаралды 485 М.
小路飞姐姐居然让路飞小路飞都消失了#海贼王  #路飞
00:47
路飞与唐舞桐
Рет қаралды 89 МЛН