In many of systems I have worked in, the class that represents a model is a POJO, and we map their fields to columns (in relational databases) or attributes (in some NoSQL databases). So, em many ORMs, it is mandatory to have accessors methods to take and bring data from/to database. However, the best practices in Object Oriented Programming say that we should not expose the intern structure of our objects. Instead, we must expose operations that change the internal state of objects e maintain the state consistency of this object
Let's give an example. Let's say we have a class Client. This class has an ID, the customer's name e its date of last change. We cannot change this data directly, but we want to persist them. If we want to modify the client's name, we must also change the ID and the last change date.
The ORM needs of following getters and setters methods, so that 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;
}
}
The way it is, anyone, besides the ORM, could change the ID and last change date, causing unwanted effects on the rest of the system.
Instead, if we wanted to respect the Oriented Object rules, we 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();
}
}
So, my question is: how we conciliate the best practices of Object Oriented Programming with the needs of getters and setters in ORMs frameworks?