"Internal" Modifier & OOP Principles
I have heard some people are against the use of 开发者_如何学Cinternal
modifier to hide classes and members from outside the assembly in which they are declared because it defeats the main principles of OOP. Is this really true?
Is this really true?
No, it is not true. Internal visibility modifier has its usages. There are classes which you don't want to be used outside of their containing assembly but still to be public inside the assembly. For example if you are designing an API, there might be classes that you don't want to expose to consumers of your API.
internal keyword allows developers to hide members of the assembly if it is used by another assembly. In .NET framework for example there are many types that are internal, meaning they are only required for the inner assembly usage and are not visible from outside the library. This is encapsulation on the assembly level.
Well people are free to have their opinions. I'm not sure how "internal" defeats the main principles of OOP.. perhaps a link would help me to evaluate their stance.
I use internal to hide types that I don't want anyone outside the assembly to use. This is pro-OOP in my opinion
- expose behavior but hide implementation.
- use the most restrictive access possible
e.g. I refactor some common code out of 2 public types ; this new type starts out as internal. Unless some client/test drives me to increase the visibility. Also I sometimes use it as a temp cheat to avoid writing tests for some types (all public types should have tests). It has served me well.
精彩评论