Search code examples
c#oopinterfaceinformation-hiding

Is the purpose of an interface to hide information?


Given that interfaces are also used to help hide information, giving the user only a subset of the possible methods they are allowed to use, and, let's say, I have a Person class and interface IPerson.

Now in main, I'm allowed to do

IPerson testy = new Person();

or

Person testy = new Person();

So really I'm not restricted from using Person still. So how does the interface truly hide data?


Solution

  • Interfaces are not used to "hide" anything per se. It is used to establish a contract between the caller and the implementation. This contract promises that "these methods and properties will be here, and they will not change".

    Interfaces also opens up the nice possibility of varying implementation without the caller having to deal with it. This is essential in decoupled designs.

    Your question implies that your main wants to know everything about the Person class. What you actually get then is coupled code, which is harder to test. To "fix" this you have to change your mindset and think: main do not want to know everything about Person, it is only interested in IPerson and requires only the interface. No more, no less.