I was reading about composition and I'm wondering if it violates the O in SOLID, and what should be done to fix the situation. In the article the author uses a Fruit and an Apple. At the end the writer admits it would be better as a "is-a" relationship rather than "has-a".
Suppose however, you decided to stick with composition and you constructed your Fruit class like this:
class Fruit { public void peel(){ //code to peel fruit. } } and Apple:
public void peel() { fruit.peel(); } If I updated my Fruit class, for example, a method called eat, I would then have to also update my Apple class to accomdate the new eat method.
Questions:
- Does this violate the O is SOLID? To me, it does because every time the
Fruitchanges, you have to update Apple to implement it. - Would providing a
getterfor theFruitand then calling the required method be better? If you were determined to make composition work, how would you handle updates?
Example:
Apple:
public Fruit getFruit(){ return this.fruit; } Client:
Fruit fruit = apple.getFruit(); fruit.eat(); Ideally you would refactor this to a is-a relationship and regardless of what type of fruit it is, the sub class can override eat().