Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private nested static class - Good or bad practice?

Would it be considered a bad practice to nest a private static class inside of a non-static class?

public class Outer
{
    private static class Inner
    {


    }
}

The idea here is that all instances of 'Outer' would share access to the static state. Another way to do it might be to just let the Inner class be non-static and use a static instance of it:

public class Outer
{
    private static innerInstance = new Inner(); 

    private class Inner
    {


    }
}

Similar effect. What are the pros / cons or other considerations with this approach?

I must admit that I almost never use nested classes, whether static or not, but I am interested in this particular concept..

like image 488
Sean Thoman Avatar asked Nov 10 '11 01:11

Sean Thoman


People also ask

Is it good practice to use nested class?

Nested Class can be used whenever you want to create more than once instance of the class or whenever you want to make that type more available. Nested Class increases the encapsulations as well as it will lead to more readable and maintainable code.

Is nested classes bad?

They're not "bad" as such. They can be subject to abuse (inner classes of inner classes, for example). As soon as my inner class spans more than a few lines, I prefer to extract it into its own class. It aids readability, and testing in some instances.

Can a nested class be private?

Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass , a nested class can be declared private , public , protected , or package private.

What are the advantages disadvantages of nested classes?

And the benefit of it is you can have less number of objects created at runtime which wouldn't be the case with other types of nested classes. Disadvantage The only disadvantage I can think of is a static nested class has access to both the protected and private members of the outer class.


1 Answers

Both approaches are entirely valid.

I wish developers would use private nested classes more often. In conjunction with c#'s partial keyword, it makes writing very complex classes much more maintainable. Imagine needing to build a class that has the complexity of a small application - much easier when you actually can build an entire private application, with classes that are totally internal to your complex outer class!

One very common case I've seen is enumerables - these can be quite complex, especially when you start building custom iterators that can be chained, like LINQ. Hiding the complexity inside the individual classes is the very definition of encapsulation.

like image 145
Rex M Avatar answered Sep 27 '22 20:09

Rex M