What is provable about Animal
? youYou don't provide code or return type, Presumablypresumably something like:
Is it still true for Cat
? Yes. (assuming you add the state changes).
What about that type checking statement in Cat
though? thisThis looks bad, itsit's not a LSP violation, but it does raise questions about whether Food has a violation in it. If it doesn't, then I shouldn't need to check the Type right?
Really, the code smell is pointing out that Food
should have some sort of FoodType
property or CanBeEatenBy(Animal animal)
method, rather than using SubTypes to identify the type.
I'm going to use c#C#, which has a "flaw" in that you cantcan't specify what exceptions might be thrown in the class defintiondefinition. That being the case, and respecting the normal rule about not using exceptions for logic, I will try to avoid all exceptions.
Obviously, this isntisn't the only way to do this, itsit's just a way to avoid your code smell and problems with exceptions.
public enum AnimalType
{
Omnivore,
Herbivore,
Carnivore
}
public class Food
{
public bool IsEdibleBy(Animal a)
{
return true;
}
}
public class EatenFood
{
public override bool IsEdibleBy(Animal a)
{
return false;
}
}
public class Animal
{
public readonly AnimalType Type = AnimalType.Omnivore;
public Food Eat(Food f)
{
if(f.IsEdibleBy(this))
{
return new EatenFood(f);
}
else
{
return f;
}
}
}
public enum AnimalType
{
Omnivore,
Herbivore,
Carnivore
}
public class Food
{
public bool IsEdibleBy(Animal a)
{
return true;
}
}
public class EatenFood
{
public override bool IsEdibleBy(Animal a)
{
return false;
}
}
public class Animal
{
public readonly AnimalType Type = AnimalType.Omnivore;
public Food Eat(Food f)
{
if(f.IsEdibleBy(this))
{
return new EatenFood(f);
}
else
{
return f;
}
}
}
What is proveableprovable?
public class Cat : Animal
{
public Cat() { this.Type = AnimalType.Carnivore; }
}
Public class Meat : Food
{
public override bool IsEdibleBy(Animal a)
{
return a.Type == AnimalType.Omnivore ||
a.Type == AnimalType.Carnivore;
}
}
public class Cat : Animal
{
public Cat() { this.Type = AnimalType.Carnivore; }
}
Public class Meat : Food
{
public override bool IsEdibleBy(Animal a)
{
return a.Type == AnimalType.Omnivore ||
a.Type == AnimalType.Carnivore;
}
}
Now you have avoided all exceptions and LSP questions, you can extend youyour food types indefinitely, although you may have issues if you add more AnimalType enums. It would be important to make sure that that list is complete at the start.