Reputation: 13256
I'm working on some MonoTouch code that I derived from one of the samples (this is not a MonoTouch specific question) and the sample code declares a private class inside another class. I've not seen private classes used much in c# and I'm at a loss as to when it might make sense. I can see how a class that is only referenced within another class could be declared private but isn't this going to cause more grief than it's worth? Doesn't this break a number of the SOLID principles?
Right now I'm finding it confusing just trying to navigate the source because of the private class definition. I guess this could be mitigated somewhat by declaring a partial class to contain the private class and separating them into separate files that way but is this really a good approach?
Upvotes: 0
Views: 584
Reputation: 668
I'm not sure but I think Single Resposibilty can be broken by nested classes, since a class can now have more resasons to change. The definition is not very clear at Single Resposibilty... Anyway I think ms does also use nested classes in .net, so maybe c# is missing some features in terms of encapsulation here. I think nested classes can be fixed with not doing nested classes and writing a analyzer. Nested classes are often used to get access to private members of the wrapping class.
Upvotes: 1
Reputation: 37770
Usually, nested types (either class or struct, including enumerations) are used for some kind of contextual data and/or behavior, which doesn't have any sense without its context.
E.g., you could make nested types for some interop API, when you don't want to provide access to that API from external code, or you're using some kind of helper data container, which provides functionality, useful only for surrounding class.
So, even making these types internal
can bring confusion to other developers (especially, where a single project is being edited by several people).
I don't see, how SOLID is broken here - nesting the type is just a limiting of type scope. It is not an extending of functionality of the surrounding class.
Upvotes: 3
Reputation: 36072
I've used private classes in situations where an API says "you must implement and provide to us an implementation of this interface when we ask you for it" and there is no other use or consumer of that class other than the use of the API interface.
In this situation, the interface provides public or cross-functional access so there is no need for access to the implementation.
Upvotes: 2
Reputation: 8503
Why would the SRP be broken? You separate a responsibility that is only accessed inside a class into a nested class.
Most other principles do not apply to private members or private nested classes.
Upvotes: 1