4

我正在编写我的第一个“API jar”,它将成为开源库并由(可能)其他开发人员使用。我已经阅读了Joshua Block 关于有效 API 设计的论文,他谈到的其中一件事——否则我永远不会想到——是他的最小化访问最大化信息隐藏的概念。基本上,您只希望您的 API 开发人员能够访问他们将使用的 Java 对象,并且您不希望您的 API 开发人员能够访问您的库的任何“胆量”。

在我作为 Java 开发人员的几年中,除了public. 此外,我也从未使用过嵌套类。所以我坐在这里想知道如何在我的 Java API 中实现这种“信息隐藏”最佳实践?我认为私有的,可能是嵌套的,类是答案。但是从哪里开始呢?

  • 每个.java源文件至少需要 1 个public类才能编译。因此,对我来说,要创建一个类private(并且非嵌套),我需要“将它与一个类捆绑在一起。对我来说,这只有在/类密切相关时才public有意义。但是如果我的 API 有一部分只是由与任何其他类似物无关的类(用于可访问性最小化目的)组成?publicprivateprivatepublic
  • 你什么时候让一个private类嵌套,什么时候让它不嵌套?还是只是偏好问题?
4

3 回答 3

4

包私有的类(即没有任何可见性修饰符)仅对同一包的类可见。这是一种让 API 的其他几个类可见的方法,但外部世界不可见。

嵌套的私有类对于创建非公共类也很有用,而且它们的范围更窄:它们只对封闭类可见。

我建议查看Guava 的源代码,以了解出色的 API 设计。您会看到各种将内部隐藏到外部的技术。

于 2012-12-22T13:11:08.607 回答
3

Personally, I don't believe in private. I use protected instead whenever feasible to allow for some of the major benefits of OO design.

Basically the 'information hiding' principle is not bad as a guideline. However, in practice one should not blindly follow it in all cases. - For the pure principle you would, as others suggested, need to define a set of interfaces as public and hide all the rest of your lib away with package-private classes, factory methods, and the like. Given that Java's package-private visibility has some issues that render it somewhat useless in many cases (- classes within your lib will want to cooperate across packages -) this in turn seems to prevent such an approach.

Besides, there are always at least two types of users of an API: the basic users, who will use the objects and methods you provide, and the users with complex requirements, who will want to modify the API's behavior (at least) by inheritance, which a lot of 'hidden' stuff will successfully prevent.

Don't be shy to make those things public for which it may make sense, make things protected which are not really needed to be public, and make only those things private which may cause harm if directly accessed by anything but their directly related code.

Another note: The hiding-principle has as a major purpose to simplify the use of your code by others and to imply and encourage the correct use thereof. But remember that documentation is another important means to achieve this; and documentation will be needed for a library anyway. - If you have 100 public methods and your docs state which 10 of those are needed for a use case the user of your lib will probably get along with that just as well as he would if only those 10 were visible to him.

于 2012-12-22T15:57:12.393 回答
1

我相信私下。我从事框架类工作已经有一段时间了,Joshua 正确地告诉你应该尽可能地隐藏。其背后的原因是您暴露的所有内容都将被使用。而且一旦使用,你就无法在不破坏客户端代码的情况下更改它。客户可以访问所有非私有的内容!基本上你应该使用包私有类,只允许在有用的地方继承,并且只公开那些对于使你的库有用的绝对必要的类。在扩展功能时,“接口隔离原则”是您的朋友。

于 2012-12-22T16:37:02.030 回答