简体   繁体   中英

Nested Data Structures in Java (inner classes)

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, eg 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 (eg 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:

  • What is a good way to represent a nested data structure in a fully self-contained way?

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.

  1. You could use inner classes but make them implement public interface.
  2. One of the solutions I would recommend is to stay with your standard approach (public classes as fields) but prohibit developers from using those classes with aspect policies (here is short tutorial i found: http://www.jayway.com/2010/03/28/architectural-enforcement-with-aid-of-aspectj/ ). Using aspects you can do two things:
    • Prohibit use of your classes
    • Tell developers why they can't use it (using policy warning text)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM