I have Employee class and I am setting its properties,
Employee emp = new Employee();
if (id != null)
emp.setId(id);
if (name != null)
emp.setName(name);
if (dept != null)
emp.setDepartment(dept);
if (subDept != null)
emp.setSubDepartment(subDept);
My question is, can we avoid null checks for each property setter?
I can not use ternary operator, as in that case setter would be called even if value is null. I want to avoid setter call if value is null.
emp.setName(name!=null?name:null);
Actually, in your code, check null is not necessary: in every cases, since you just created the employee object, all his fields are null, then if, for example, id
is not null the setId
will set a not null value, if id
is null
then setId
will not change anything.
Obviously, these considerations only make sense if the constructor does not initialize the variables shown in any way.