How should I structure a Java application, where do I put my classes?

后端 未结 10 1446
轻奢々
轻奢々 2020-12-24 05:17

First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a str

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 05:52

    Short answer: draw your system architecture in terms of modules, drawn side-by-side, with each module sliced vertically into layers (e.g. view, model, persistence). Then use a structure like com.mycompany.myapp.somemodule.somelayer, e.g. com.mycompany.myapp.client.view or com.mycompany.myapp.server.model.

    Using the top level of packages for application modules, in the old-fashioned computer-science sense of modular programming, ought to be obvious. However, on most of the projects I have worked on we end up forgetting to do that, and end up with a mess of packages without that top-level structure. This anti-pattern usually shows itself as a package for something like 'listeners' or 'actions' that groups otherwise unrelated classes simply because they happen to implement the same interface.

    Within a module, or in a small application, use packages for the application layers. Likely packages include things like the following, depending on the architecture:

    • com.mycompany.myapp.view
    • com.mycompany.myapp.model
    • com.mycompany.myapp.services
    • com.mycompany.myapp.rules
    • com.mycompany.myapp.persistence (or 'dao' for data access layer)
    • com.mycompany.myapp.util (beware of this being used as if it were 'misc')

    Within each of these layers, it is natural to group classes by type if there are a lot. A common anti-pattern here is to unnecessarily introduce too many packages and levels of sub-package so that there are only a few classes in each package.

提交回复
热议问题