gpt4 book ai didi

java - 有效 Java 项目 14 : You can’t change the representation without changing the API

转载 作者:行者123 更新时间:2023-12-01 23:27:03 25 4
gpt4 key购买 nike

这取自 Joshua Bloch 的《Effective Java》-

第 14 条(或第三版中的第 16 条):在公共(public)类中,使用访问器方法,而不是公共(public)字段

//像这样的退化类不应该是公共(public)的!

class Point {
public double x;
public double y;
}

因为这些类的数据字段是直接访问的,所以这些类不提供封装的好处(第 13 项)。

You can’t change the representation without changing the API

作者最后一句是什么意思?该语句在同一项目中多次使用。请提出建议。

术语“导出的 API”或“API”应按照作者在书中的建议进行解释

An exported API consists of the API elements that are accessible outside of the package that defines the API.

最佳答案

嗯,这相当简单,假设是 Point 类。

class Point {
public double x;
public double y;
}

现在,x 和 y 本质上是 2d 平面中点的表示。如果决定使用它,它将如下所示,例如:

Point p;
p.x = 5;
p.y = 10;

由于 x 和 y 声明为公开,因此每个人都可以访问它们,因此如果有一天您决定将点表示切换为 2D 平面上的半径和角度,例如

class Point {
public double r;
public double angle;
}

上面的代码也必须更改,这意味着使用您的 Point 对象的客户端将必须重新编译他们的代码。因此,通过将 x 和 y 声明为公共(public),您可以限制自己,因为这些声明现在是 Point API 的一部分。

但是更好的方法是将点的内部表示封装到私有(private)点状态中并仅公开所需的功能:

class Point {
private double x;
private double y;

// Computes norm2 of the point
public double norm2() {
return Math.sqrt(x*x + y*y);
}
}

现在,使用 Point 类的人将只能使用公共(public) API,在这种情况下 norm 方法,其方式与此类似:

Point p;
// Init coordinates
double norm = p.norm();

最后,如果您想更改内部表示形式,客户端代码将不会受到您的更改的影响,与前面的示例相反。

关于java - 有效 Java 项目 14 : You can’t change the representation without changing the API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46406119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com