Java Reference
In-Depth Information
9.3
Mini-antipatterns: Organization and visibility
In the previous section, we examined commenting conventions that help us
describe structure. In this section, we'll address standards that alternately
ensure privacy and public utility as required. To understand our motivation,
consider the following treatment of an instance variable:
public SomeClass {
public int age;
public SomeClass() {
// code to correctly initialize age
}
}
public AnotherClass {
public void aMethod() {
SomeClass anInstance = new SomeClass();
Person person = new Person();
person.age = anInstance.age;
}
}
Two groups of programmers will cringe at this example. Purists will see that
we are directly accessing our instance variable. Database programmers will see
that we have implemented age as an integer attribute, meaning that for consis-
tency, we will have to update the database yearly on the person's birthday.
We'd probably want to change SomeClass to calculate the age based on the
birthday, but that would make all users of SomeClass.age change. Instead, we
should implement age with get and set access methods:
public SomeClass {
private int age;
public int getAge() {
return age;
}
public SomeClass() {
// code to correctly initialize age
}
}
In this case, we do not need a set , because the value is initialized in the con-
structor and won't change. The implementation for age is then hidden. Our
clients will access solely through the accessors, and we protect the instance
Search WWH ::




Custom Search