How to reconcile good Object Orientation practices and ORM frameworks for getters and setters?

Asked

Viewed 111 times

1

In many of the systems I have worked on or had contact with, the class representing a model is usually a POJO, which we map your attributes for columns (for relational banks) or attributes (for some Nosql banks). Thus, in many Orms, it is mandatory to have terms access methods (getters and setters) to bring and take data to the database. But good object-oriented practices tell us that we should not expose the internal structure of our objects by exposing, instead operations that change the internal state of the objects and maintain the consistency of the state of that object.

Let’s take an example. Let’s say we have the Client class. This class has an identifier, the client name and the date of the last change. We cannot change this data, but we want to persist. If we want to change the name, we also have to change the id and last change date.

The ORM needs getters and setters methods, so we have:

@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public Date lastChange() {
    return this.lastChange;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public void setString(String name) {
    this.name = name;
  }

  public void setLastChange() {
    this.lastChange = latChange;
  }

}

As it stands, anyone other than the ORM itself could alter the object ID, causing unwanted effects on the rest of the system.

On the contrary, if we were to change using the class to respect the object orientation rules, we would have something like this:

@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Client(Long id, String name) {
    this.id = id;
    this.name = name;
    this.lastChange = new Date();
  }

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public void changeName(String name) {
    this.name = name;
    this.id = newIdFromClient();
    this.lastChange = new Date();
  }

  private Long getNewIdFromClient() {
    return (new Random()).nextLong();
  }

}

My question is:

How to reconcile these good practices with the needs of Orms frameworks?

1 answer

0

  • And how would you do for the other properties? Works the same way? What if the framework doesn’t follow the JPA standard?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.