(Java)包组织有最佳实践吗?

2022-01-13 00:00:00 package naming-conventions java

不久前,我在这里看到一个关于 java 包的细粒度组织的问题.例如my.project.utilmy.project.factorymy.project.service

A little while ago, I saw a question answered here regarding the fine-grained organization of java packages. For example, my.project.util, my.project.factory, my.project.service, etc.

我现在找不到,所以我还是问这个问题.

I can't find it now, so I may as well ask the question.

关于 Java 中的包组织以及其中的内容是否有最佳实践?

Are there best practices with regards to the organization of packages in Java and what goes in them?

您如何在 Java 项目中组织类?

How do you organize your classes in your Java project?

例如,我正在与几个人合作的一个项目有一个名为 beans 的包.它开始是一个包含简单 bean 的项目,但最终(由于经验不足和缺乏时间)包含所有内容(几乎).我通过将一些工厂类放在工厂包中(具有创建 bean 的静态方法的类)对它们进行了一些清理,但是我们还有其他执行业务逻辑的类和其他执行简单处理(不使用业务逻辑)的类,例如检索来自属性文件的代码消息.

For instance, a project I'm working on with a few people has a package called beans. It started out being a project containing simple beans, but has ended up (through poor experience and lack of time) containing everything (almost). I've cleaned them up a little, by putting some factory classes in a factory package (classes with static methods that create beans) but we have other classes that do business logic and others that do simple processing (not with business logic) like retrieving a message for a code from a properties file.

感谢您的想法和意见.

推荐答案

包组织或包结构通常是一个激烈的讨论.下面是一些关于包命名和结构的简单指南:

Package organization or package structuring is usually a heated discussion. Below are some simple guidelines for package naming and structuring:

  • 遵循 java 包命名约定
  • 根据功能角色和业务角色构建您的软件包
    • 根据功能或模块分解您的包.例如com.company.product.modulea
    • 可以根据软件中的层进行进一步细分.但是,如果您的包中只有几个类,请不要太过分,那么将所有东西都放在包中是有意义的.例如com.company.product.module.webcom.company.product.module.util
    • 避免过度结构化,IMO 避免对异常、工厂等进行单独包装,除非有迫切需要.

    经过一些实验和试验,您应该能够提出一个您感到满意的结构.不要拘泥于一种惯例,要对变化持开放态度.

    After a few experiments and trials you should be able to come up with a structuring that you are comfortable with. Don't be fixated on one convention, be open to changes.

相关文章