Is there an elegant Java implementation of Joshua Bloch’s defensive copying techniques using the example below? The nullChecking is really the issue I think, but perhaps there is a much simpler way to achieve defensive copying.
public class Audit {
private Date dateCompleted;
...
public Audit() {
super();
}
//defensive copy of dateCompleted
public final Date getDateCompleted() {
if (dateCompleted != null){
return new Date(dateCompleted.getTime());
}else{
return null;
}
}
public final void setDateCompleted(Date dateCompleted) {
if (dateCompleted != null){
this.dateCompleted = new Date(dateCompleted.getTime());
}else{
this.dateCompleted = null;
}
}
...
}
Well you can have a convenience method in a utility class:
Then:
Static imports can hide the
DateUtilspart if you want.Alternatively, you can use Joda Time which mostly uses immutable types and is a much better API in general 🙂