#What are reasons to favor composition over inheritance?
1 messages · Page 1 of 1 (latest)
<@&987246841693360200> please have a look, thanks.
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
inheritance is an "is" relationship. while composition is "has"
theres barely any actual problem ull encounter in real coding that logically requires an "is" relationship
almost all issues logically require "has"
composition is also by far more flexible, modular and less limited
especially java, being very interface driven, favors this approach
just look at ur past medium to bigger sized projects u created and count how often u used inheritance. likely between 0 and 3 times
then count how often u used fields. likely 100+ times
Technically, both can resolve the same problems, but while inheritance is easier to use than composition (in the sense that you don't need to duplicate code), unless the language has good syntax for composition. The problem of inheritance is that it's often misused and abused
thing is, nobody is saying u shouldnt use inheritance for a Dog to extend from animal
but in many cases, a taxidriver shouldnt be an extra class extending person
instead, u should add fields like profession/job to the person class and represent the taxi driver like that
now u can also switch jobs. or have multiple jobs at the same time
with inheritance in this situation, u will run into design nightmares
Let's discuss the tradeoffs between Inheritance and Composition
Access to code examples, discord, song names and more at https://www.patreon.com/codeaesthetic
0:00 Introduction
0:25 Inheritance
3:32 Composition
5:22 Abstracting with Inheritance
6:52 Abstracting with Interfaces
8:20 When to use Inheritance
This explains it well with examples
👍
Can you explain that?
It varies on framework and language too. Composition in Darts flutter framework is very different from Java. Javas Android framework is also very reliant on composition. It varies considerably from use case to use case.
I wouldn’t say one is necessarily better
please read the rest of what i posted, and also the examples
and then tell me what remains unclear
otherwise id just repost
Closed the thread due to inactivity.
If your question was not resolved yet, feel free to just post a message to reopen it, or create a new thread. But try to improve the quality of your question to make it easier to help you 👍
@cerulean phoenix Yeah, I think I understand what you meant with your comments. Sorry for late response