接口应该放在单独的包中吗?

2022-01-13 00:00:00 interface packages java

我是一个团队的新手,该团队正在处理一个相当大的项目,其中包含许多组件和依赖项.对于每个组件,都有一个 interfaces 包,用于放置该组件的公开接口.这是一个好习惯吗?

I'm new to a team working on a rather large project, with lots of components and dependencies. For every component, there's an interfaces package where the exposed interfaces for that component are placed. Is this a good practice?

我通常的做法是接口和实现放在同一个包中.

My usual practice has always been interfaces and implementations go in the same package.

推荐答案

把接口和实现都放在一个普通的地方,好像没有问题.

Placing both the interface and the implementation is common place, and doesn't seem to be a problem.

以 Java API 为例——大多数类的接口及其实现都包含在同一个包中.

Take for example the Java API -- most classes have both interfaces and their implementations included in the same package.

java 为例.util 包:

它包含SetMapList等接口,同时也有HashSet、HashMapArrayList.

It contains the interfaces such as Set, Map, List, while also having the implementations such as HashSet, HashMap and ArrayList.

此外,Javadocs 旨在在这些条件下正常工作,因为它在显示包的内容时将文档分为 Interfaces 和 Classes 视图.

Furthermore, the Javadocs are designed to work well in those conditions, as it separates the documentation into the Interfaces and Classes views when displaying the contents of the package.

只为接口提供包实际上可能有点过分,除非有大量的接口.但是仅仅为了这样做而将接口分离到自己的包中听起来是不好的做法.

Having packages only for interfaces may actually be a little bit excessive, unless there are enormous numbers of interfaces. But separating the interfaces into their own packages just for the sake of doing so sounds like bad practice.

如果需要将接口的名称与实现区分开来,可以有一个命名约定以使接口更易于识别:

If differentiating the name of a interface from an implementation is necessary, one could have a naming convention to make interfaces easier to identify:

  • 在接口名称前加上 I. 这种方法适用于 .NET 框架中的接口.很容易看出 IList 是一个列表的接口.

  • Prefix the interface name with an I. This approach is taken with the interfaces in the .NET framework. It would be fairly easy to tell that IList is an interface for a list.

使用-able后缀.这种方式在Java API中经常看到,如<​​code>ComparableIterableSerializable 等等.

Use the -able suffix. This approach is seen often in the Java API, such as Comparable, Iterable, and Serializable to name a few.

相关文章