1

Let's say I have a main class A and another class B.
In the B class the user can change some settings and variables of the program that belongs to A, I want to be able to apply these changes to the A class, should I use inheritance and apply the changes to the father of B which is A or should I use composition and pass the instance of A to class B and change the variables of A in this manner?
which one is best practice and why?
note : If it helps in anyway, I'm writing a gui application and A is my main window and B is a setting window opened from A.

  • 1
    If instances of A can be replaced by B, then you can use the decorator pattern via inheritance. Otherwise I would tend towards composition. – lealand Apr 3 '15 at 20:19
  • This SE thread may be helpful – radarbob Apr 7 '15 at 1:07
10

Inheritance is "is-a", composition is "has-a". Is it the case that "a B is-an A", or it is the case the "a B has-an A for some reason"?

It is obvious that setting window is-not-a main window, but is an external actor. So it should have an A passed in.

EDIT: Since you told what A and B is, that is, windows, you should separate domain from presentation; that is, not even B should be passed an A (no, those are just views), but B's model should be passed A's model. But treat this just as an additional note, as original question was about inheritance vs. composition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.