Search code examples
oopinheritanceencapsulation

How to design a generic class so functionality is limited based on the derived type?


If I have a Cat and Dog class that implement PetBase. And they each hold an object called Owner. And Owner holds an object called Emotion. How would I limit accessing certain properties or functions or function parameters on the Emotion class based on whether it belongs to a Cat or Dog? Like so:

Dog d = new Dog();
d.Owner.Emotion.SetFearLevel(10); // dog owners can have a fear level from 1-10 so let the user decide.
Cat c = new Cat();
c.Owner.Emotion.SetFearLevel(); // all cat owners have the same fear level so I don't want the user to be able to pass in a parameter but still be able to call SetFearLevel(). How do I enforce this?

In this example, I want to restrict the Cat owners from being able to pass in a parameter to SetFearLevel(), but give the Dog owners the flexibility to be as afraid as they want (ie. be able to pass in a parameter to SetFearLevel()).

What do I have to change in the design?

[EDIT]

It was a toss up between Jordao's and DavidFrancis's answers. In the end, I went with DavidFrancis's design due to the tree structure nature of the app.


Solution

  • SetFearLevel is a different signature so you need 2 different subtypes of a base Emotion type.
    Then you would need a separate owner subtype for each pet type.
    Return types can usually be Covariant (ie a subtype) so each owner subtype can return the specific Emotion subtype that applies to that owner.