I have the following POJO:
public class Shipment() {
private LocalDate dateShipped; // Sometimes we know the date of shipment, sometimes we don't
private boolean wasItemShipped; // If we know the date of shipment, this value is true. If we don't know the date, it can be either true or false
}
I'm trying to design the best pattern for managing these two fields. The boolean should be true whenever the Date is not null. However when the Date is null, the boolean can be true or false. Here's a couple of approaches:
- Standard getter/setters
public void setDateShipped(LocalDate dateShipped) {
this.dateShipped = dateShipped;
}
public LocalDate getDateShipped() {
return dateShipped;
}
public void setWasItemShipped(boolean wasItemShipped) {
this.wasItemShipped = wasItemShipped
}
public boolean getWasItemShipped() {
return wasItemShipped;
}
This is a pretty normal approach. One downside to this approach is that when developers call setDateShipped() they need to also know to call setWasItemShipped(). This could become problematic if this code is found in multiple spots, or if we need to deserialize some incomplete JSON or something.
- Add logic into the setter of dateShipped
public void setDateShipped(LocalDate dateShipped) {
this.dateShipped = dateShipped;
if (dateShipped != null) {
setWasItemShipped(true);
}
}
- Add logic into the getter of wasItemShipped
public boolean getWasItemShipped() {
return dateShipped != null || wasItemShipped
}
Both of these approaches have the downside of adding logic to a POJO to mutate it in perhaps surprising ways. I feel like this could lead to frustration/bugs down the road.
Are there any other patterns for this type of operation?