Consider the following case –
I have a class (Fruits), which has some methods such as PackTheFruit(), CutTheFruit(), CleanTheFruit(). This class can not be modified.
I also have a set of classes which would contain an object of fruit type. In some of the classes I want to have access to PackTheFruit() method but not in all.
I have thought creating two interfaces, which would be implemented by Fruits class. One would expose PackTheFruit() and one would expose the other methods only and each class would have an object of the these interface type instead depending on if they need to have access to that method or not.
The problem in this solution is that, when ever I add another method to the Fruits class I will have to update the interfaces. That would be a bad design in my eyes at least.
I depends what these operations are doing. Let’s assume that packing consists of adding fruits to a basket up to a maximum weight, then you will need to know the weight of a fruit in order to make it packable. If you want to pack different kinds of fruits it would be better to have a separate packer class. It feels strange to have fruits packing themselves.
If you add new interfaces for new functionalities, you will not have to change existing interfaces. This is called Interface segregation principle (ISP) and is one of the five SOLID principles of Object-Oriented Design.
Note: Having an
IPackerinterface allows you to implement different kinds of packers. An implementation might mix different kinds of fruits within a package, while another one might sort the fruits.