Say I have a class pet and it is composed of two variables:
Class Pet {
Category category; // be amphibian, fish, mammal, dog
Diet diet; //meat, vegetarian, omnivore
...
If category = dog I want to restrict diet to omnivore only (and vice versa). My actual problem is somewhat more complex, whats the best way to code this ? I started with nested enums and then inner builder class …
Is their a common pattern I can employ ?
You have this trouble because you are not taking advantage of inheritance here.
DogIS APet. So letDog extend Pet.Petwill have abstractsetDiet()andDogwill implement this with applying the diet rules applicable for Dog.Now, you can encapsulate the diet rules in their respective
enum(your current approach) or leverage inheritance which is natural. If you go composition approach, then you can’t leverage polymorphism. So it depends upon your business requirements to understand which one to use. If you make sure that you doesn’t violate LSV then inheritance seems to be a natural solution for this.