5 ms·
At least in Java, storing a date/time as a primitive improves immutability and is a good pattern. You don't expose the underlying long value publicly so you en
by rdwallis 14y ago
At least in Java, storing a date/time as a primitive improves immutability and is a good pattern.
You don't expose the underlying long value publicly so you end up with something like the following:
private long primitiveDate;
public Date getDate() {
return new Date(primitiveDate);
}
-----
This prevents calling methods from doing something stupid like:
o.getDate().setTime(123455L)
to modify a date that shouldn't be editable.
- taftster 14y agoOr possibly better: private Date date; public Date getDate() { return new Date(date.getTime()); }
- rdwallis 14y agoYour code solves the external side effects problem but using the primitive also allows the time to be finalized eg: private final long creationTime = System.currentTimeMillis(); so it still has advantages over making the field a Date object.