Thought about this use of interfaces. Accordingly, the question arose whether to use such code?

public interface IAnimal { int LegsCount { get; } } public interface ICat : IAnimal { string Voice { get; } } public abstract class FourLegsAnimal : IAnimal { public int LegsCount => 4; } public class DummyCat : FourLegsAnimal, ICat { public string Voice => "I am dummy cat"; } 

The code works, but I don’t know if there is a “smell” for such a code.

  • And why IAnimal can not immediately contain a string Voice ? - tCode
  • one
    @tCode, what about fish? - Alex Krass
  • @AlexKrass there are some kinds that make a sound, sort of like) - tCode
  • @AlexKrass, the fish are not animals? - koks_rs
  • one
    @koks_rs thought so too, but googled - animals written - tCode

1 answer 1

It seems to me, speaking of object orientation, it does not make sense to split into interfaces without the need for program design. Otherwise, you can get an infinite number of interfaces: IFourLegs , IHaveWhiskers , IDrinkWater , ILiveOnEarth , IVertebrate , ICarbonBasedLifeForm , IHavingNameInEnglish , IHavingSeparateGenders , and so on.

Think first about your hierarchy of objects, think about which groups you will group them and why, and based on this, build your interfaces.

It may make sense to start without any interfaces at all, write a prototype, and in the process of writing a prototype, thoughtfully add the necessary interfaces (and beat yourself on your fingers so as not to add unnecessary ones).

  • Yes, I think in general this way. Although it seems to me that such code is nice in the following case (perhaps initially I chose a not quite correct hierarchy) - LmTinyToon
  • What if the model has a hierarchy, and I want every class to implement an interface with "read-only" methods. And accordingly use these interfaces in gui objects. Gui objects will also have the same hierarchy. I think with such an approach, such a code would make sense (I'm afraid that I explained it too vaguely) - LmTinyToon
  • @LmTinyToon: Vooot, you already think in terms of application architecture. This is much better. If an interface is needed for an application, it makes sense. - VladD