Constructor vs setter validations
Posted
by
Jimmy
on Programmers
See other posts from Programmers
or by Jimmy
Published on 2012-09-01T14:24:15Z
Indexed on
2012/09/01
15:48 UTC
Read the original article
Hit count: 417
java
I have the following class :
public class Project {
private int id;
private String name;
public Project(int id, String name, Date creationDate, int fps, List<String> frames) {
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;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I have three questions:
Do I use the class setters instead of setting the fields directly. One of the reason that I set it directly, is that in the code the setters are not final and they could be overridden.
If the right way is to set it directly and I want to make sure that the name filed is not null always. Should I provide two checks, one in the constructor and one in the setter.
I read in effective java that I should use
NullPointerException
for null parameters. Should I useIllegalArgumentException
for other checks, like id in the example.
© Programmers or respective owner