Code analysis “setters”(集合方法)有什么用?
也许是我做的选择地点的错误 对不起,我的英语不好 直到最近,我还认为为字段只设置一次的类编写setter和getter是没有意义的。我没有使用setters\getter,而是在Java中使用公共常量字段或final,并通过构造函数设置字段 但我最近遇到了一种情况,这种方法被证明是非常不舒服的。类也有许多字段5-7个字段 我第一次意识到getters的好处 而不是这样做:Code analysis “setters”(集合方法)有什么用?,code-analysis,setter,getter-setter,Code Analysis,Setter,Getter Setter,也许是我做的选择地点的错误 对不起,我的英语不好 直到最近,我还认为为字段只设置一次的类编写setter和getter是没有意义的。我没有使用setters\getter,而是在Java中使用公共常量字段或final,并通过构造函数设置字段 但我最近遇到了一种情况,这种方法被证明是非常不舒服的。类也有许多字段5-7个字段 我第一次意识到getters的好处 而不是这样做: class Human { public final int id; public final Stri
class Human {
public final int id;
public final String firstName;
public final String lastName;
public final int age;
public final double money;
public final Gender gender;
public final List<Human> children;
Human(int id, String firstName, String lastName, int age, double money, Gender gender, List<Human> children) {
// set fields here
}
}
class HumanReader {
Human read(Input input) {
int id = readId(input);
String firstName = readFirstName(input);
// ...
List<Human> children = readChildren(input);
return new Human(id, firstName, lastName, age, money, gender, children);
}
}
我开始使用下一个解决方案:
interface Human {
int getId();
String firstName;
// ...
List<Human> getChildren();
}
class HumanImpl implements Human {
public int id;
public String firstName;
// ...
public List<Human> children;
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
// ...
public List<Human> getChildren() {
return children;
}
}
class HumanReader {
Human read(Input input) {
HumanImpl human = new HumanImpl();
human.id = readId(input);
human.firstName = readFirstName(input);
// ...
human.children = readChildren(input);
return human;
}
}
我认为第二种解决办法更好。它没有复杂的构造函数和混乱的参数顺序
但是setter有什么用呢?我还是不明白。或者他们需要一致性?这里有一个非常简单的解释,想象一下这样一种情况:每次更改设置属性时,您都需要更改其他内容(可能是UI或数据)。实现这一点最简单的方法是在setter中进行 下面是一个很好的列表,列出了你为什么要使用它的原因
使用setter和getter的目的是封装对这些值的访问。所以如果 如果基础数据结构发生更改,则不必更改代码的其余部分。例如,假设您的人类类突然依赖于数据库 但是,尽管getter和setter提供了一个很小的保护来防止更改,但它们仍然在很大程度上反映了下面的数据结构,因此您仍然可能会遇到麻烦。最好的解决方案是尽量避免使用getter和setter,而是提供类的客户机实际需要的服务。也就是说,在人类类的情况下,考虑人类能够将自己呈现给接口。