Jim*_*mmy 5 java coding-style getter-setter
我有以下课程:
public class Project {
private int id;
private String name;
public Project(int id, String name) {
if(name == null ){
throw new NullPointerException("Name can't be null");
}
if(id == 0 ){
throw new IllegalArgumentException("id can't be zero");
}
this.name = name;
this.id = id;
}
private Project(){}
public int getId() {
return id;
}
public void setId(int id) {
if(id == 0 ){
throw new IllegalArgumentException("id can't be zero");
}
this.id = id;
}
public String getName()
return name;
}
public void setName(String name) {
if(name == null ){
throw new NullPointerException("Name can't be null");
}
this.name = name;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您注意到setName和setId与构造函数的字段共享相同的验证.这个冗余代码是否可能导致将来出现问题(例如,如果有人编辑setter以允许0为id并防止-1而不是更改构造函数)?.我是否应该使用私有方法进行检查并在构造函数和setter之间共享它,如果有很多字段,这似乎太多了.
注意:这就是为什么我不在构造函数中使用setter./sf/answers/342552311/
| 归档时间: |
|
| 查看次数: |
2057 次 |
| 最近记录: |