我应该如何构建 Java 应用程序,将类放在哪里? [英] How should I structure a Java application, where do I put my classes?
问题描述
首先,我知道如何构建 Java 应用程序.但我一直对把课程放在哪里感到困惑.有人支持以严格面向领域的方式组织包,其他人则按层分开.
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 strictly domain oriented fashion, others separate by tier.
我自己一直有问题
- 命名,
- 放置
所以,
- 您将域特定常量放在哪里(以及此类类的最佳名称是什么)?
- 您将基础设施和领域特定内容的类放在哪里(例如,我有一个 FileStorageStrategy 类,它将文件存储在数据库中,或者存储在数据库中)?
- 在哪里放置异常?
- 有什么标准可以参考吗?
推荐答案
我真的开始喜欢 Maven 的 标准目录布局.
I've really come to like Maven's Standard Directory Layout.
对我来说,一个关键的想法是有两个源代码根——一个用于生产代码,一个用于测试代码,如下所示:
One of the key ideas for me is to have two source roots - one for production code and one for test code like so:
MyProject/src/main/java/com/acme/Widget.java
MyProject/src/test/java/com/acme/WidgetTest.java
(这里,src/main/java 和 src/test/java 都是源码根).
(here, both src/main/java and src/test/java are source roots).
优点:
- 您的测试对您的测试类具有包(或默认")级别的访问权限.
- 通过将 src/test/java 作为源根目录删除,您可以轻松地仅将生产源打包到 JAR 中.
关于课程安排和课程包的一个经验法则:
One rule of thumb about class placement and packages:
一般来说,结构良好的项目将没有循环依赖.了解它们何时糟糕(以及何时不是),并考虑使用像 JDepend 或 SonarJ 可以帮助您消除它们.
Generally speaking, well structured projects will be free of circular dependencies. Learn when they are bad (and when they are not), and consider a tool like JDepend or SonarJ that will help you eliminate them.
这篇关于我应该如何构建 Java 应用程序,将类放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!