class Foo {
String bar;
// private String bar;
}
public class A {
public void method1() {
Foo foo = new Foo();
// foo.bar; or foo.getBar(); which is preferable
}
}
Does it make sense to declare variables as private with getters/setters for class member definitions (e.g. should bar be declared as private in Foo or should it be just declared as String bar)? I would prefer to remove them, sense they cannot be accessed outside this class anyway. What would be preferable?
Using getters and settings to access/mutate a private field member is standard OO practice. It allows the inner workings of the class to change while maintaining its public interface.
If you were to access/mutate
barby making it directly available as part of the public interface (by making it public) it may seem fine now but what happens when, months later, you decide you want to add some validation tobar? Maybe you don’t wantbarto ever be set tonull. How could you achieve that? If you use getters and setters, all you would need to do is change your setter to throw an exception if an attempt is made to setbartonull. If you mutatebardirectly, you couldn’t do that. More drastically you may decide thatbaris no longer required at all!Getters and setters do not imply that a field member of the same name and type exists internally of the class. They tell you only that the class has a property that can be accessed/mutated and dictate nothing about the way in which the class performs that internally. This gives you a great deal of flexibility.