#What are reasons to favor composition over inheritance?

1 messages · Page 1 of 1 (latest)

clear geode
#

Is composition creating particular object within particular class?

Why it's better to favor composition over inheritance? Is it because with inheritance is fixed what is inherited and is not dynamic as it is with encapsulating particular object instance variable, or...?

idle phoenixBOT
#

<@&987246841693360200> please have a look, thanks.

idle phoenixBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

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.

cerulean phoenix
#

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

stoic lava
cerulean phoenix
#

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

jolly lance
#

This explains it well with examples

clear geode
#

👍

clear geode
#

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

cerulean phoenix
#

and then tell me what remains unclear

#

otherwise id just repost

idle phoenixBOT
#

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 👍

clear geode
#

@cerulean phoenix Yeah, I think I understand what you meant with your comments. Sorry for late response