DEV Community

loading...

Discussion on: What programming best practice do you disagree with?

Collapse
jckuhl profile image
Jonathan Kuhl

I've never fully understood getters and setters. If I have a field that has both a getter and a setter like so:

class Person {
   private String name;

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

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

Why not just make the field public? What's the point in making getters and setters and not just dealing with the field directly? I asked one instructor about this and he just said "it's better encapsulation" but I don't see it.

Collapse
rossdrew profile image
Ross

It allows you to validate and know when fields are accessed.

Thread Thread
michaeldober profile image
Michael Ober

Getters and Setters allow you to validate and normalize input. If this validation isn't needed then consider a public field.