Does it make sense to declare variables as private with getters/setters for class member definitions declared within a public class?
class Foo {
Strin开发者_如何转开发g 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 bar
by 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 to bar
? Maybe you don't want bar
to ever be set to null
. 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 set bar
to null
. If you mutate bar
directly, you couldn't do that. More drastically you may decide that bar
is 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.
If it's only for data access, not having getters/setters should be ok (some purists may disagree). And your class should be able to access private members of inner class so you can keep them private.
Make Foo an inner class and don't have getters/setters:
public class A {
private class Foo {
String bar;
}
public void method1() {
Foo foo = new Foo();
foo.bar = "x";
}
}
It is OK design because Foo is only visible within A - it's no worse than accessing private fields directly within a class instead of via the getter.
Please first answer: Why does method1
need to know about foo
's bar
? Why does method1
need to know that Foo
s even have bar
s in the first place?
精彩评论