Home > Mobile >  Best pattern in Java for managing inferred POJO attributes?
Best pattern in Java for managing inferred POJO attributes?

Time:09-08

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:

  1. 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.

  1. Add logic into the setter of dateShipped
public void setDateShipped(LocalDate dateShipped) {
  this.dateShipped = dateShipped;
  if (dateShipped != null) {
    setWasItemShipped(true);
  }
}
  1. 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?

CodePudding user response:

You may checkout Observer and Observable, but that's too complicated. On the other hand there is no formal documentation that strictly says 'no logic inside setters'. So you can go ahead and implement your second approach, and retrofit if needed in future.

CodePudding user response:

I prever Logic in the setter. Ist also helps debugging,as your variables represent the State Office your object and you don‘t Need the getter for getting your Objekts State. And you can use wasItemShipped in other methods too without mich thinking and making your class More complicated.

To ne it Feels More Natural and intuitive to have Logic in the setter Rather the getter

  • Related