I'm ashamed to ask this, but it has been bugging me for years. I'm a senior develloper in a big corporation, since 2013.
I work in JAVA JEE (mostly on the backend) and Android devellopment (JAVA).
We have tons of "Value Objects", "DTOs" and such. Eachs times they have private properties and getter/setters. Each property will have a getter/setter.
public class UserVo {
private String name;
private String email;
private String password;
public UserVo(String name, String email, String password) {
this.name = name;
this.email = email;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
When I was asking why not make them public I was told "It's because of encapsulation, like this the values are safe and cannot be modified directly" yes they can, you can just do myObject.setMyProperty(a value);
So why? why do we put getter and setter on every property of those objects? why not use public properties?
I've been on multiples big projects, those things are everywhere. Usually you get an entity from the databse then you convert it into a "VO" the "VO" is the exact same object as the entity, same properties, same getter/setter.
Or sometimes people want to move data in something more readable than a list or multiple variables and create their own "VO" with some private properties and getters/setters for each of them.
And if someone make them with public fields, then the wich hunt begins, everyone is laughting saying "oooh you don't know about encapsulation?", "NEVER make public fields!", "Have you been to school?". Frankly everyone does it but nobody know why.
Oh and I know that the Value Object pattern say that they are immutable, but in real life, they aren't, at least they weren't on the 7 projects where I worked.
Common architecture on all my project is :
.................
Dao and Managers -> they return entities
.................
Value objects that have the same structure than your entities (sometimes they name them DTOs)
.................
View controllers (JAVE JEE) / Activity or Fragments (Android)
.................
Layer isolation is an other subject it's just to show you where we use value objects, the VOs are then used in the view layer (and modified according to the user actions) and then sent back to the managers that will build entities and persist them.
Any thought on the subject? Thanks.
Aucun commentaire:
Enregistrer un commentaire