When no other class ever needs to touch the (nested) class - should I always make it a (private) nested class?

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/393349

  •  26-02-2021
  •  | 
  •  

Question

And what is the recommended file structure?

The question is a bit similar to this one, but I'm looking for more explicit recommendations.

In theory I think it's a good concept to keep files short so you don't see other noise of nested classes where you're not interested in the implementation details at that point in time.

I think there are then two options left (but maybe I'm missing something).

Option A using partials and nested classes:

ClassA.cs

namespace Example
{
    public partial ClassA
    {
        [...]
    }
}

ClassA.Helpers.cs

namespace Example
{
    public partial ClassA
    {
        private class ClassB
        {
            [...]
        }

        private class ClassC
        {
            [...]
        }
    }
}

What I don't like here is the extra indention from the class - it makes it a bit harder to read, because your eye is used to scan for i.e. two indentions for class members.

Option B: don't make it a nested class, but make it an internal class within it's own namespace - so it doesn't pollute the main namespace:

ClassA.cs

namespace Example
{
    public class ClassA
    {
    }
}

Helpers/ClassB.cs

namespace Example.Helpers
{
    internal class ClassB
    {
    }
}   

Am I missing a third option? Are there any recommendations, defaults or guidelins

Was it helpful?

Solution

Bringing namespaces in for this is not right, namespaces are for big scope borders, typically on the module/assembly level. This is about keeping your scope tight, if you introduce a new namespace, that namespace will be visible outside the scope of the class which you do not want.

The partial class would be OK. I personally would just use a region named Classes within the parent class, that would get them out of the way for me without the need for an extra file in the project. If you do use a partial class, name the file MainClass.Classes.cs or something similar so it will be obvious the classes belong to MainClass and the files will be displayed in succession in the solution explorer.

OTHER TIPS

You're applying the Open Closed Principle to files. This is reasonable when your motivation for following the Open Closed Principle is to isolate proven tested files from change. By keeping your files small the amount of code that must be reviewed after a change is kept small.

Just keep in mind that just as extra indentation comes as a cost to readability so does having to jump through multiple files.

Licensed under: CC-BY-SA with attribution
scroll top