From
ljl8:
void date::prev()
{
if (day == 1) {
if (month == 1) {
--year;
month = 12;
day = length[month];
} else {
--month;
day = length[month];
}
} else {
--day;
}
}
|
void date::prev()
{
if (day > 1) {
--day;
} else {
if (month > 1) {
--month;
} else {
month = 12;
--year;
}
day = length[month];
}
}
|
Only need to write
day = length[month];
once,
if you write it in the right place:
void date::prev()
{
if (day == 1) {
if (month == 1) {
--year;
month = 12;
} else {
--month;
}
day = length[month];
} else {
--day;
}
}
void date::prev()
{
if (day == 1) {
if (month == 1) {
--year;
month = 12;
} else {
--month;
}
day = length[month];
} else {
--day;
}
}
An if/else
consists of two parts.
Write the smaller part (--day;)
on top,
to decrease the distance between the
if
and its
else.
I did the same thing to the other
if/else
too.
void date::prev()
{
if (day > 1) {
--day;
} else {
if (month > 1) {
--month;
} else {
month = 12;
--year;
}
day = length[month];
}
}
The number
31
should appear only in the array, not in the code.
From
an151:
void date::prev() // Move this date object into the past
{
if (day > 1) {
--day;
} else {
if (month > 1) {
--month;
day = length[month]; // last day of previous month
} else {
month = 12;
day = 31; // dec 31
--year;
}
}
}
void date::prev() // Move this date object into the past
{
if (day > 1) {
--day;
} else {
if (month > 1) {
--month;
day = length[month]; // last day of previous month
} else {
month = 12;
--year;
day = length[month]; // last day of previous month
}
}
}
Then remove the duplication as in the first example.
In all of the above examples,
we should call the static member function
date::monthsInYear
(exercise 4i)
that returns the number of months in the static data member
date::length:
void date::prev() // Move this date object into the past
{
if (day > 1) {
--day;
} else {
if (month > 1) {
--month;
} else {
month = monthsInYear();
--year;
}
day = length[month]; // last day of previous month
}
}