DEV Community

Discussion on: Do we really need getters/setters?

Collapse
 
awwsmm profile image
Andrew (he/him)

Getters and setters are used when data needs to be encapsulated and/or validated. For instance, if you wanted to get someone's age, you should have something like

public int setAge (int newAge) throws IllegalArgumentException {
  if (newAge < 0 || newAge > 150) throw new IllegalArgumentException("invalid age!");
  this.age = newAge;
  return this.age;
}

rather than just having a public int age field. There are other situations where you might want encapsulation, without necessarily providing validation. For instance

private String myPassword;

public boolean checkPassword (String password) {
 ...
}

public void setPassword (String newPassword, String oldPassword) {
 ...
}

In this case, we want to provide a method for setting a new password, and checking against the current one. If you had a public field, this sensitive information could leak.

Collapse
 
katieadamsdev profile image
Katie Adams

Seconding this. Encapsulation is very important for protecting sensitive data.

Collapse
 
andsmile profile image
Andrii

Yeah, I totally understand why it is theoretically needed.

But have you ever had such validation in setters?
or was it in some validation 'business' logic outside domain class?

regarding 'password' use case:

yes, of course, you should use setters where it is really needed, but in 99% you can have public fields without any problem.

Collapse
 
awwsmm profile image
Andrew (he/him)

It's unusual, for sure, but so is directly getting and setting any state of a particular object, I'd say. The user usually doesn't interact directly with objects, but with some UI layer which then manipulates the objects, and -- as you say -- the validation is usually performed in that UI layer.

This might occur when trying to create objects without user input, like when reading serialized objects from a database. If your object schema has changed, you'll need to validate it before you can deserialize it. Slightly different from a setter, but the same general idea.

You're right that it's uncommon, but it's necessary.