You do not need to explicitly set null in your setter, just use the value passed this way ...
public void setDate(Date date) { if (date != null) { this.date = new Date(date.getTime()); } else { this.date = date; } }
Personally, I would never allow null values to be in my Value objects, wherever they are, but this is just my rooted coding style.
My advice to someone is to give preference to objects of constant value, where you set all the values in the constructor and don't allow the input of zeros. This style may not be acceptable for all third-party libraries that expect a java bean getter / so keep in mind where this can be used effectively to simplify your code.
Edit
If the above code still gives you a warning and you should have the property “property not yet set”, another approach is to define a “null object” like this
public static final Date NO_DATE = new Date(Long.MIN_VALUE); public void setDate(Date date) { this.date = (date == null) ? NO_DATE : new Date(date.getTime()); }
Users of this class can reference an NO_DATE object like this, which is still doing for readable code.
if(toto.getDate() != NO_DATE) ...
Or encapsulate it in another method so that it is used
if(toto.hasDate()) ...
Of course, this does not bring much benefit compared to Java 8. Optional approach from @kij, but it works with any version of Java
source share