你真的在java中使用你的反向域来命名包吗?

2022-01-14 00:00:00 namespaces java

很久以前,我一直认为,在java中,为包命名反转你拥有的域是愚蠢和尴尬的.

For a long time ago, I have thought that, in java, reversing the domain you own for package naming is silly and awkward.

您在项目中使用哪个包命名?

Which do you use for package naming in your projects?

推荐答案

一旦你理解了约定为什么存在,它就不应该感到愚蠢或尴尬.

Once you understand why the convention exists, it shouldn't feel silly or awkward in the least.

这个方案做了两个重要的事情:

This scheme does two important things:

  • 您的所有代码都包含在其他人不会与之发生冲突的包中.您拥有自己的域名,因此它是孤立的.如果我们没有这个约定,很多公司都会有一个实用程序".包,包含StringUtil"、MessageUtil"等类等等.如果你试图使用其他人的代码,这些很快就会发生冲突.

  • All of your code is contained in packages that no one else will collide with. You own your domain name, so it's isolated. If we didn't have this convention, many companies would have a "utilities" package, containing classes like "StringUtil", "MessageUtil" etc. These would quickly collide if you tried to use anyone else's code.

逆向"它的性质使得顶层的类目录布局非常狭窄.如果您展开一个 jar,您将看到com"、org"、net"等目录,然后在每个目录下显示组织/公司名称.

The "reverse" nature of it makes class-directory layout very narrow at the top level. If you expand a jar, you'll see "com", "org", "net", etc dirs, then under each of those the organization/company name.

(于 2021 年添加)如今,当这种类型的包命名用于第三方库时,这一点变得更加重要,这些库在构建过程中被引入,并且如果名称不是唯一的,则很容易发生冲突.如果每个人都遵守相同的约定,就不会发生意外碰撞.

(added in 2021) This is even more important nowadays when this type of package naming is used for third-party libraries which are pulled in transitively during builds and could easily conflict if the names were not unique. If everyone adheres to the same convention, there will be no accidental collisions.

(2021 年添加)相同的命名约定可用于应用商店中的应用程序 ID,以确保唯一性.

(added in 2021) The same naming convention can be used for application ids on an app store to ensure uniqueness as well.

我们通常不会扩展 jar,但在早期的 java 开发中,这很重要,因为人们使用扩展的 dir 结构来进行小程序.

We usually don't expand jars, but in early java development, this was important because people used expanded dir structures for applets.

但是,现在这很好,因为源代码目录结构具有非常自上而下"的结构.感觉.您从最通用的(com、org、net...)到不太通用的(公司名称)再到更具体的(项目/产品/lib 名称).

However, this is nice now as source code dir structures have a very "top-down" feel. You go from the most general (com, org, net...) to less general (company name) to more specific (project/product/lib name).

相关文章