Why Favor Object Composition Over Class Inheritance? A Deep Dive

preview_player
Показать описание
Are you a programmer trying to understand the difference between object composition and class inheritance? In this video, We'll take a deep dive into why you should favor object composition over class inheritance in your code. After explaining what object composition and class inheritance are, we will explore what object composition and class inheritance are, and explore the advantages and disadvantages of each. You'll learn about the composition vs inheritance debate and why composition is often the better choice for achieving code reuse. We'll also take a look at the benefits of using composition over inheritance, and why it's important to understand this concept for better programming practices.⚡️❤️

My video covers a range of topics, from functional programming to C# programming and beyond. I provide C# tutorials to help you improve your skills and stay up-to-date with the latest dotnet trends. My video is perfect for programmers looking to improve their understanding of inheritance programming and composition programming. I also cover essential programming concepts, including OOP, C#, functional programming, and .NET. With Zoran Horvat, you'll have access to the best programming tutorials, ensuring that you have the skills you need to succeed.❤️

So, whether you're a beginner or an experienced programmer, this video will help you understand the difference between inheritance and composition and why you should favor composition over inheritance. Join me on Zoran Horvat's channel to learn more about object composition, OOP, C# programming, and functional programming. Don't forget to subscribe to my channel for more programming tutorials and tips!❤️

⭐ Learn more from video courses:

▬▬▬▬▬▬▬▬▬▬▬
⚡️ Have a look at our other Videos :

👉 Other videos on this channel you may be interested in watching:

⚡️Chapters:
▬▬▬▬▬▬▬▬▬▬▬
⌚ 0:00 Today's Topic: Composition vs Inheritance
⌚ 0:17 Why Favor Object Composition Over Class Inheritance?
⌚ 18:13 Outro
▬▬▬▬▬▬▬▬▬▬▬
#inheritance #composition #objectorientedprogramming #inheritence #compositionoffunctions #oop #csharp #dotnet #zoranhorvat
▬▬▬▬▬▬▬▬▬▬▬
⭐ CONNECT WITH ME 📱👨

▬▬▬▬▬▬▬▬▬▬▬
👨 About Me 👨
Hi, I’m Zoran, I have more than 20 years of experience as a software developer, architect, team lead, and more. I have been programming in C# since its inception in the early 2000s. Since 2017 I have started publishing professional video courses at Pluralsight and Udemy and by this point, there are over 100 hours of the highest-quality videos you can watch on those platforms. On my YouTube channel, you can find shorter video forms focused on clarifying practical issues in coding, design, and architecture of .NET applications.❤️
▬▬▬▬▬▬▬▬▬▬▬
⚡️RIGHT NOTICE:
The Copyright Laws of the United States recognize a “fair use” of copyrighted content. Section 107 of the U.S. Copyright Act states: “Notwithstanding the provisions of sections 106 and 106A, the fair use of a copyrighted work, including such use by reproduction in copies or phono records or by any other means specified by that section, for purposes such as criticism, comment, news reporting, teaching (including multiple copies for classroom use), scholarship, or research, is not an infringement of copyright." This video and our youtube channel, in general, may contain certain copyrighted works that were not specifically authorised to be used by the copyright holder(s), but which we believe in good faith are protected by federal law and the Fair use doctrine for one or more of the reasons noted above.

Рекомендации по теме
Комментарии
Автор

Send over the examples of your class designs that you wish me to review and, maybe, include in the future video on code redesign and refactoring.

zoran-horvat
Автор

Beautifully explained. I have seen so many explanations where they use the horrible idea of "composition is a "has a" and inheritance is an "is a"".... While this is partially true, it does not completely explain why favour composition. Following that logic you could always find an "is a" relation in any hierarchy

Love your explanation here: what problem were we trying to solve with inheritance? Movement? Ok, just have a class that represents that behaviour and use DI to use it on the "base" class. Just clear and beautiful

Many thanks for such a simple and elegant explanation

kzelmer
Автор

I'am not sure if I like the example, but the explanation is top notch. Thanks

bogdanzarzycki
Автор

Zoran is favorite YouTube Man. Keep going, please.

blom
Автор

Hi Zoran

Every time I learn something new, whenever you publish a new video.

Great to see. Thanks for sharing it.

akhilbandari
Автор

Thank you in advance, watching now but I'm sure the content will be awesome as always :)

LinuxUser
Автор

This is a very interesting video! Very useful information. I've been working with Unity for a while now, and since most of the objects, like items and characters, have repeated behaviors, instead of using inheritance, I've been using separated scripts for a defined behaviors, which makes it so much easier for design. Instead of finding a way to make inheritance work and be flexible, I can just make a behavior script and attach it to the object. I thought I was being a little lazy there, but it may have not been a bad idea after all.

hauntedcrowdev
Автор

Very explanatory and useful video. Thank you

e-k
Автор

Around 13:35 you keep adding different abilities to the Vehicle class (composition). Is this how we extend the functionality (Open-closed principle) of the vehicle class? I mean is that the procedure when we want to add more functionality to the vehicle class later on?

What I mean is I always thought composition means that we create separate class for ex "input", "engine" or "movement type" and next we create a "boat" class that as a movement type uses "water Movement" which ex detects if we are on water and can move, passes to it the value from the "input" and it performs the movement. For the car we use "Road movement" or whatever. That we create new classes that reuses the existing ones and basically are composed out of those.

Thanks for this video!

piotrw
Автор

Beautiful video ! ❤ how you provide insight. By the way, in the context of flying vehicles there’s air speed and ground speed, making things even more complex.

anonymous.youtuber
Автор

One thing that bothers me with videos that shows that says 'composition over inheritance' is they always show an example where they trip on the smallest problem and act likes there's no solution, or that it will become a mess.

It always the same thing. Here's a apple, its a fruit! At this level, its simple! But what if the apple has wings?

??? Then its NOT a fruit?

What I'm trying to say is that maybe there's an issue with your abstraction?

vincecas
Автор

Very well explained, as always! :) But there are multiple drawbacks in this approach! First: Nothing prevents you from calling one of the factory methods with wrong abilities (Maybe Inheritence can help out here ;)). Second: I now depend on multiple abilities that could either be set or not ("dont depend on things you dont need"), causing possible nullReferenceExceptions and confusion. Third: There IS code duplication!!!, when having multiple abilities, all of the same type (written after each other) -> When adding new Abilities i have to CHANGE (for example) GetAverageSpeed implementation (OpenClosedPrinciple violated). The Problem in the beginning of the implementation was that you tried to bound all the complexity to primitives. Why not just abtsract out that as well? Instead of defining "double topSpeed" define a class/record "Speed" and inherit from this aswell? For example "record Knots : Speed" aswell as "record Kmh : Speed". Also tackle the complexity in these ValueObjects by defining calculation of Average Speed in them? Vehicle can still expose GetAvgSpeed, but only needs to call its variant of "Speed.CalculateAverage". Or am i wrong? :) I know that all of the topics i meantined as a solution you are a master of! But my experience tell me that this example lacks of smarter implementation of inherent Objects :)

sotsch
Автор

Another case when inheritance brings lot of pain is injected deps, especially when you have 10+ descendants and add a new dep into the ctor of the base class

tkjyxrb
Автор

Hey Zoran, thanks for the great content. Using your last example, how would you model vehicle specific properties without having to bloat the Vehicle class with functionality related to a single vehicle type, while also publicly exposing functionality only appropriate for the specific type. For example an airplane can have different wings (biplane, tandem wing, low wing, mid wing...), while a flying drone might have 4, 8, .. propellers instead. A boat might have sea anchors of different types, while that does not apply to car... At the end we do not want a method named "ApplyLandingConfiguration()" on a Car object. Of course we could have but the Vehicle class might become very large and confusing, if using composition only. Thinking out loud, but the ideal solution seems more like a combination of inheritance and composition, and constant refactoring while we add more types and functionality?

colebq
Автор

Best Video about composition! I'm your new Fan and Sub

brandonjoaocastillo
Автор

I can't help quoting my attorney when I ask her a legal question: "it all depends".

brucerosner
Автор

Hey Zoran!
I'm so grateful that you have recorded this video. I still can't quite out my finger on converting inheritance to composition.

Could you recommend any reading on it (or one of your courses)? I might just be not fully understanding some concept of OOP that causes me to constantly try inheritance (I read a lot of books / tried creating bigger projects but still I am missing something).

I would really appreciate your help :)

piotrw
Автор

Amazing explanation. New sub here. Keep it up!

dzllz
Автор

Hi Zoran, I have a question.

So, let's say we create a Car.

var car = MovingAbility(120));
Console.WriteLine($"Average speed is: {car.GetAverageSpeed(120, 22, 3330)}");

What would you expect this to print out?
If it's a car, then it can not travel on air nor water, we can conclude the average speed would be 0 because the time needed would approach infinity to cover any of the two distances.

However, what if we want to look for car.GetAverageSpeed(120, 0, 0);

In this case, it should take into account that the car does not need to travel over water nor air and then print out the average speed. However, due to the nullability nature of the moving abilites, the totalHours will be null, hence rendering the GetAverageSpeed to be 0.

Is this a mistake in my reasoning or a potential issue?

lostinsarajevo
Автор

Unfortunately, in C++, you can have multiple inheritance, which means the Amphibian vehicle can inherit twice, once from Boat and once from GroundVehicle, then inside GetAverageSpeed it can call into the base classes.
The problems still arise later because, unlike members inside an object, base classes can not be swapped at runtime, you can not change the base class of an object to be something else, some other object instance.
Great video overall though!

TwinechoesEntertainment