0

As I know, according to "composition over inheritance" rule, we should avoid reusing a method by inheritance, but how about class members? Suppose I have parent and child classes like the following:

public class Animal{
    protected String name;
    protected int _id;
    public String getName(){
        return name;
    }
    public int getId(){
        return _id;
    }
}

public class Cat extends Animal{
}

public class Dog extends Animal{
}

and I found I am reusing "name" and "_id" field by inheritance. Should I put all attributes into a separate class and let a child class uses it by composition like this:

public class AnimalData{
    public String name;
    public int _id;
}

public interface Animal{
    public AnimalData getAnimalData();
}

public class Cat implements Animal{
    public AnimalData animalData;
    public AnimalData getAnimalData(){
        return animalData;
    }
} 

public class Dog implements Animal{
    public AnimalData animalData;
    public AnimalData getAnimalData(){
        return animalData;
    }
} 

in order to obey "composition over inheritance" rule?

ggrr
  • 5,873

1 Answers1

5

There is nothing wrong with inheritance, and in in your case it is clearly the simplest solution. The second solution introduces complexity for no benefit. "Composition over inheritance" is just a rule-of-thumb to avoid over-reliance in inheritance - it does not say you shouldn't use inheritance when it is appropriate.

Furthermore, you are not even reducing the amount of inheritance in the second example. The question is if you need the subclasses "Cat" and "Dog" at all. It is easier to see if you use a more real world example. Say you have a Button. You realize than some instances of Button will have a popup-help, and some will not. Should you create a subclass ButtonWithPopupHelp which adds the popup-related functionality, or should you rather create a separate class PopupHelp, which contains the popup-specific functionality, and which can be attached to the button and perhaps other controls? If possible, the second options is preferable.

JacquesB
  • 61,955
  • 21
  • 135
  • 189