4

Every time I have used the InternalsVisibleToAttribute when developing an API, it feels a bit smelly. Like the API is not being designed in a truly encapsulated way. A lot of the times this is out of time constraints - exposing the internal functionality in an elegant, encapsulated way takes time, and a lot of times only one other assembly is going to need it, making InternalsVisibleToAttribute seem like the correct solution.

Does InternalsVisibleToAttribute indicate a design smell, such as a case of refactoring gone wrong, or an indication that the two assemblies should not be separate?

Note: I understand the need to use InternalsVisibleToAttribute for unit testing. This question does not refer to unit testing.

5
  • 5
    I've never seen this used outside of unit testing. – Jon Raynor Aug 30 '16 at 16:54
  • Could you give us a non-unit-testing example of what you're talking about? – Jeff B Aug 30 '16 at 16:57
  • I disagree emphatically with your note. The unit under test is the class, not the method. If you're testing private methods, either the unit is too complex for testing and should be broken down, or you're testing at too fine-grained a level and your tests are going to be brittle. – Eric Stein Aug 30 '16 at 17:05
  • @EricStein you might be right, never personally used it for this purpose so I don't have an opinion. – Mr Anderson Aug 30 '16 at 17:07
  • @JeffBridgman here is an example for the .NET System.Web assembly: referencesource.microsoft.com/#System.Web/Properties/… – Mr Anderson Aug 30 '16 at 17:10
4

A typical usage for InternalsVisibleToAttribute is when you are a component or library vendor like Microsoft and produce components for other customers. Then you probably want to create a well restricted API to your clients and do not expose more than necessary to them (because every public API method gives a potential risk for a "breaking change" later when you distribute newer versions).

To deal with this case, you can make almost every initially "public" method of your component system internal, use InternalsVisibleToAttribute to expose the internal methods to other libs of your library system, and set only the external API methods to public.

So for this situation (besides unit testing) the usage of InternalsVisibleToAttribute is IMHO clearly not a code smell. For other cases - well, at least you should think twice about it before you use it, this is surely case dependent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.