Reputation: 5253
In our application methods often return nested data structures. We represent them as DTOs, where one DTO may contain other DTOs or Lists thereof. The methods in question primarily supply the GUI with things-to-show.
So far the "inner" DTOs are objects of regular public classes. Developers are tempted to reuse these inner DTOs in various other DTO classes. While this looks like a welcome application of code-reuse, it creates unnecessary dependencies between only loosely releted methods.
One way to avoid this, is to "flatten" the DTOs such that there is no nesting at all and all attributes are simple scalar types. However, in many situations this seems unnatural, e.g. when there is a 1:n relationship beween outer and inner DTO and navigating such a DTO would become more cumbersome.
So we thought, we could make the "inner" DTOs instances of inner classes (of the outer DTO's class). This should lessen the dependencies at the cost of less code-reuse.
But then we noticed, that the methods of the inner classes are not accessible from outside (e.g. the method returning such a DTO) unless we make the inner class public. But then anyone could create an instance of this inner class (though it would be less tempting).
So the basic question is:
Upvotes: 3
Views: 3185
Reputation: 26
Upvotes: 0
Reputation: 533660
You can do what you suggest. If you want to prevent others creating instances you can make the constructors package local or private. If the classes are also public, you can access the methods anywhere, but only construct them where you have allowed.
Upvotes: 4