Java Reference
In-Depth Information
119
120
return 0 ; // If month is incorrect
121 }
122
123
/** Determine if it is a leap year */
public static boolean isLeapYear( int year)
isLeapYear
124
{
125
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0 );
126 }
127 }
The program does not validate user input. For instance, if the user enters either a month not in
the range between 1 and 12 or a year before 1800 , the program displays an erroneous calen-
dar. To avoid this error, add an if statement to check the input before printing the calendar.
This program prints calendars for a month but could easily be modified to print calendars
for a whole year. Although it can print months only after January 1800 , it could be modified
to print months before 1800 .
5.12.4 Benefits of Stepwise Refinement
Stepwise refinement breaks a large problem into smaller manageable subproblems. Each sub-
problem can be implemented using a method. This approach makes the program easier to
write, reuse, debug, test, modify, and maintain.
Simpler Program
The print calendar program is long. Rather than writing a long sequence of statements in one
method, stepwise refinement breaks it into smaller methods. This simplifies the program and
makes the whole program easier to read and understand.
Reusing Methods
Stepwise refinement promotes code reuse within a program. The isLeapYear method is defined
once and invoked from the getTotalNumberOfDays and getNumberOfDayInMonth meth-
ods. This reduces redundant code.
Easier Developing, Debugging, and Testing
Since each subproblem is solved in a method, a method can be developed, debugged, and tested
individually. This isolates the errors and makes developing, debugging, and testing easier.
When implementing a large program, use the top-down and/or bottom-up approach. Do
not write the entire program at once. Using these approaches seems to take more development
time (because you repeatedly compile and run the program), but it actually saves time and
makes debugging easier.
Better Facilitating Teamwork
When a large problem is divided into subprograms, subproblems can be assigned to different
programmers. This makes it easier for programmers to work in teams.
incremental development and
testing
K EY T ERMS
actual parameter 179
ambiguous invocation
method overloading
194
195
method signature
179
argument 179
divide and conquer 203
formal parameter (i.e., parameter)
modifier 179
parameter 179
pass-by-value 186
scope of a variable
179
information hiding
203
196
method 178
method abstraction
stepwise refinement
203
203
stub
205
 
Search WWH ::




Custom Search