Java Reference
In-Depth Information
variable with the private modifier. Then, we can safely refactor, as in
listing 9.3.
Listing 9.3
This is a better implementation for getAge
We calculate getAge based on the birthdate, saving us from managing ever-changing ages.
o Attributes are private
and wrapped.
private Date birthDate;
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date aBirthDate) {
this.birthDate = aBirthDate;
}
o The implementation of
getAge is hidden.
public int getAge(){
Date today = new Date();
int thisYear = today.getYear();
int birthYear = this.birthDate.getYear();
int age = thisYear - birthYear;
if (! hadBirthdayThisYear()) {
age = age - 1;
}
return age;
}
o Intermediate elements
are private.
private boolean hadBirthdayThisYear() {
Date today = new Date();
int thisMonth = today.getMonth();
int birthMonth = this.birthdate.getMonth();
int thisDay = today.getDate();
int birthDayOfMonth = this.birthdate.getDate();
if (birthMonth < thisMonth) {
return true;
} else if (birthMonth > thisMonth) {
return false;
}else if (birthDayOfMonth <= thisDay) {
return true;
}else {
return false;
}
}
Search WWH ::




Custom Search