I've been scratching my head for a long time on a problem and I still don't know what would be the best solution. Since the application domain is very technical, I'll illustrate my problem with a simple example.
Suppose I have the following interfaces:
public interface Animal {
public void feed(AnimalFood food);
}
public interface AnimalFood {
// some methods
}
And the two following classes implementing the interfaces:
public class DogFood implements AnimalFood {
// some methods
}
public class CatFood implements AnimalFood {
// some methods
}
public class Dog implements Animal {
public void feed(AnimalFood food){
// can only eat dog food
}
}
public class Cat implements Animal {
public void feed(AnimalFood food){
// can only eat cat food
}
}
This means that everytime I feed a Dog
or a Cat
instance, I'll have to validate if the received instance of DogFood
or CatFood
and throw an exception if this is not the right kind of food.
This smells bad to me, and I am pretty sure to violate the Liskov substitution principle!
Is there a design pattern, or what would be an elegant way to manage this situation?
It appears you are using Java. If so you can use generics to restrict the type of the parameter in feed
public interface Animal<T extends AnimalFood> {
void feed(T food);
}
public class Dog implements Animal<DogFood> {
public void feed(DogFood food){
// can only eat dog food
}
}
public class Cat implements Animal<CatFood> {
public void feed(CatFood food){
// can only eat cat food
}
}