gpt4 book ai didi

java - 构造函数和 setter 中的验证字段是否被认为是错误的冗余代码?

转载 作者:搜寻专家 更新时间:2023-10-31 20:22:03 24 4
gpt4 key购买 nike

我有以下类(class):

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;
}

}

如果您注意到 setName 和 setId 与构造函数共享相同的字段验证。这个冗余代码是否会在将来引起问题(例如,如果有人编辑 setter 以允许 0 作为 id 并阻止 -1 而不是更改构造函数)? .我是否应该使用私有(private)方法进行检查并在构造函数和 setter 之间共享它,如果有很多字段,这似乎太多了。

注意:这就是我不在构造函数中使用 setter 的原因。 https://stackoverflow.com/a/4893604/302707

最佳答案

修改后的代码:

public class Project {

private int id;
private String name;

public Project(int id, String name, Date creationDate, int fps, List<String> frames) {

checkId(id);
checkName(name);
//Insted of lines above you can call setters too.

this.name = name;
this.id = id;

}

private Project(){}

public int getId() {
return id;
}

public void setId(int id) {
checkId(id);
this.id = id;
}

public String getName()
return name;
}

public void setName(String name) {
checkName(name);
this.name = name;
}

private void checkId(int id){
if(id == 0 ){
throw new IllegalArgumentException("id can't be zero");
}
}

private void checkName(String name){
if(name == null ){
throw new NullPointerException("Name can't be null");
}
}

}

关于java - 构造函数和 setter 中的验证字段是否被认为是错误的冗余代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12229457/

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