I have the following 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;
}
}
If you notice that setName and setId use the same check for their constructor fields. Is this redundant code that may cause problems in the future (for example, if someone edits the installer to allow 0 for id and instead prevent -1, but did not change the constructor)? Should I use a private method to check and share it between the designer and the installer, which seems too big if there are many fields.
Note. That is why I do not use setters in the constructor. stack overflow
Jimmy source
share