Pavel Petrashov
Pavel Petrashov

Reputation: 1262

How to guarantee update field whe other field is updated?

I have class

public class Order {
  private LocalDateTime creationDate;
  private Date creationDateAsDate;
 }

The creationDate is an existing field in the Order. The creationDateAsDate is a new field for some functionality.

I need to set and save this new field in all places where I save the old field. Unfortunately, I am working with legacy code, and I have 5 places where creationDate field is set. Now I see 2 solutions:

  1. call creationDateAsDate setter in all places where creationDate setter is called.
  2. call creationDateAsDate setter in the creationDate setter.

I don't like both variants. Can someone answer how to do this? It might be one of my variants, or something else.

Upvotes: 1

Views: 192

Answers (3)

Nikolas
Nikolas

Reputation: 44368

I would recommend updating both setters which is no wrong (that's the reason they exist) calling a common private method to avoid infinite recursion.

public void setCreationDate(LocalDateTime creationDate) {
    Date creationDateAsDate = Date.from(creationDate.atZone(ZoneId.systemDefault())
                                                    .toInstant());
    updateDates(creationDate, creationDateAsDate);
}
public void setCreationDateAsDate(Date creationDateAsDate) {
    LocalDateTime creationDate = LocalDateTime.ofInstant(
            creationDateAsDate.toInstant(), 
            ZoneId.systemDefault());
    updateDates(creationDate, creationDateAsDate);
}
private void updateDates(LocalDateTime creationDate, Date creationDateAsDate) {
    this.creationDate = creationDate;
    this.creationDateAsDate = creationDateAsDate;
}

Upvotes: 2

Hooman
Hooman

Reputation: 134

You could add a third method (e.g. setCreationDateAsDateAndcreationDate) and call it whenever you want both to be updated. (as classes should be open for extension, but closed for modification). Then put both setters in it,

or

you could call the new setter method from setCreationDateAsDate and setCreationDate (where you create the other property within setters, and then call the third setter setCreationDateAsDateAndcreationDate while passing both of dates as arguments to it)

Upvotes: 0

seenukarthi
seenukarthi

Reputation: 8624

Since these are private variables remove one of the variables for example private Date creationDateAsDate and the setter for the vaiable.

Implement getter method as follows.

public Date getCreationDateAsDate(){
 // convert the creationDate to date and return.
}

REF: Converting between java.time.LocalDateTime and java.util.Date for converting LocalDateTime to Date

Upvotes: 0

Related Questions