Effective Java : Making a class as private nested class (Item 22) [duplicate]

This question already has an answer here:

If a package-private top-level class (or interface) is used by only
one class, consider making the top-level class a private nested class
of the sole class that uses it (Item 22)

Effective Java 2nd edition

Referring to the above item from effective Java. I understand that it will promote class inaccessible for other purposes. But I have two doubts on this,

  1. Doing this, we will be moving a class which does a different purpose into other class. For example, an UI class which needs an event listener which is used only by that class, has to be moved into that UI class as per the above recommendation. Then the UI class will be less cohesive by principle as it serves UI rendering and event listening.

  2. Referring to the same example above, if we move the classes used only once as an inner class, then we are closed for extension and open for modification, say we want to change a different listener or inject dynamic listeners then we may not be achieving without modifying the UI class. Hence how feasible is the above approach to do?


Source: oop

Leave a Reply