1

Say I define an interface IAnimal which has a pure virtual (abstract) method called eat like this:

class IAnimal
{
   virtual void eat(Food*) = 0;
};

In the future I inherit form IAnimal and create different animals. and eventually I find out that some animals need not only food to eat but also other things. Say in my context, (it is easy to imagine it is a game), Dogs can eat if there is a Food and a Plate. Mans can eat if there is a Food, Plate, Table and Chair. Does this mean that it is wrong to use inherit from IAnimal? Can we say that Dog and Man are not animals as you can not use them interchangeably.

6

Trying to come up with an accurate taxonomy of the real-world objects you want to represent with a class hierarchy is usually not that productive. Your interfaces should represent functionality or behavior rather than ontological categories, because that's what interfaces are: one or more functions you can call.

In other words, name the interface IEater instead of IAnimal, and this problem simply disappears, since anything that has an eat() method is clearly capable of eating.

Regarding your examples of additional objects, it's possible that eat(Food, Plate) is a special case of the more general eat(Food, Plate, Table, Chair), but it's also possible that these are two completely different kinds of eating that shouldn't be lumped together. That depends entirely on what eating means in the context of your application. If they are completely different, don't be afraid to choose more explicit and descriptive names like IPlateEater or IEaterWithTableManners.

  • So you suggest to have completely different interfaces for different type of "Eaters". I think if you cannot interchange the implementations such as for Man eat(food) cannot make sense, then this means Man cannot be derived from IAnimal, or IEater. – Narek Aug 20 '15 at 12:32
  • @Narek If I'm reading your comment correctly, yes I would agree with that. – Ixrec Aug 20 '15 at 19:28

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.