kabanek
kabanek

Reputation: 323

Nested classes and good practices

I'm considering using nested classes in my class. I have a class called ServerConfiguration and I have two classes closely related to it: a builder and a provider.

All of the classes are in separate places:

the question is if should I add them as nested (static) classes to the ServerConfiguration or keep it as is?

The ServerConfiguration class is very simple and adding 2 extra classes will make it more complicated. On the other hand, it's more readable to me to have code

private ServerConfiguration.Builder getBuilder()
    {
        return new ServerConfiguration.Builder();
    }

instead of

private Builder getBuilder()
    {
        return new Builder();
    }

what do you think?

Upvotes: 4

Views: 1181

Answers (1)

Ankita Agrawal
Ankita Agrawal

Reputation: 113

You should go ahead with making the class as inner class.

As per effective java

If a package-private top-level class or interface is used by only one class, consider making the top-level class a private static nested class of the sole class that uses it (Item 24). This reduces its accessibility from all the classes in its package to the one class that uses it. But it is far more important to reduce the accessibility of a gratuitously public class than of a package private top-level class: the public class is part of the package’s API.

Upvotes: 3

Related Questions