Is there a way of telling when to use composition and when to use inheritance in your code.
Example: Let's say we have 4 classes called Computer
, MotherBoard
, Monitor
, Keyboard
. I can make computer
inherit from the other three classes and I can also declare MotherBoard
, Monitor
, Keyboard
in the field of computer
, thus for the second case using composition. Which way is better? Which way is preferred by most developers?
I prefer the inheritance in the following cases:
Otherwise, the composition is appropriate.
Note that in this case, the computer is composed of the components you have listed. As a shortcut, I sometimes ask myself the following:
Computer
have a Mouse
? If so, then use composition. Notice a computer can have no mouse.MacBook
a Computer
? If so, then use inheritance. ... but in general which way is preferred
In general, the decision should be based on the situation :)