I have the following code in my dto class.
public void setBillDate(Date billDate) {
this.billDate = billDate;
}
And I get an error in s
In addition to the existing answers, I propose a new version based on Optional
class from Java 8.
public void setBillDate(Date billDate) {
this.billDate = Optional
.ofNullable(billDate)
.map(Date::getTime)
.map(Date::new)
.orElse(null);
}
Date is not immutable, i.e. your billDate can be changed after it has been set on your DTO object. Or, in code:
Date billDate = new Date();
dto.setBillDate(billDate);
billDate.setYear(1990);
// now, dto.getBillDate().getYear() == 1990
You can make your setter more secure:
public void setBillDate(Date billDate) {
this.billDate = (Date)billDate.clone();
}
Top answer number 37 is not the correct answer : nobody cares about NullPointerExceptions???
You should try this instead :
public void setBillDate(Date billDate) {
this.billDate = billDate == null ? billDate : new Date(billDate.getTime());
}
Consider using a clone as well. Don't forget null check.
public void setBillDate(Date billDate) {
this.billDate = billDate == null ? null : billDate.clone();
}
Date
is mutableUsing that setter, someone can modify the date instance from outside unintentionally
Consider this
class MyClass {
private Date billDate;
public void setBillDate(Date billDate) {
this.billDate = billDate;
}
}
now some one can set it
MyClass m = new MyClass();
Date dateToBeSet = new Date();
m.setBillDate(dateToBeSet); //The actual dateToBeSet is set to m
dateToBeSet.setYear(...);
//^^^^^^^^ Un-intentional modification to dateToBeSet, will also modify the m's billDate
To avoid this, you may want to Deep-copy before setting
public void setBillDate(Date billDate) {
this.billDate = new Date(billDate.getTime());
}
Date
is mutableand you are not creating a copy of Date
that came in to you are parameter. So if the client code will change the value of the Date
object, it will affect your class too.
Solution is to create a copy of Date
public setBillDate(Date billDate){
this.billDate = new Date(billDate.getTime());
}