Search code examples
oopinheritancedesign-patternspolymorphismencapsulation

What would be the correct design here (encapsulation, polymorphism, inheritance)?


Assuming I have an interface and 3 or 4 classes that implement the interface. Now let's say I have another method but it is relevant only for one or two implementing classes.

So as I see it there are two approaches

  1. Declare the method in the interface, implement in all the classes. In classes that the method is not relevant - throw "not supported" exception.
  2. Declare the method only in the implementing classes where relevant but then you have to downcast the instance from interface type to the specific type in order to call the method. So would be your design here and why?

Solution

  • You should apply the interface segregation principle here, part of the SOLID principles. Instead of having one large interface, split the interfaces up into a few smaller interfaces. Implement the interfaces only in the classes that need it.