Java Reference
In-Depth Information
2.5.1
Stepwise refinement: making coffee
We introduce the notion of stepwise refinement with this problem:
This discussion
is also present-
ed in activity
2-5.1, using
synchronized
animation.
Get coffee in the morning.
This statement says what to do; we want to replace it by a sequence of instruc-
tions, or statements, that say how to do it.
So how do we get coffee? If no one in the house has made coffee yet, we
have to make it. After that, we can pour coffee into a cup:
// Get coffee in the morning.
if ( coffee not made ) {
Make coffee.
}
Pour coffee into cup.
Note that we made the original task into a statement-comment , and we have
written its implementation underneath it. A statement-comment states what the
corresponding code does; it is often a big help when reading the code.
Note also that we use Java notation where appropriate. Some people prefer
to continue to write everything in stylized English —they call it pseudocode . We
prefer using programming notation whenever it is reasonable, so that the final
result is as close to being a program as possible.
We now work on refining the statement Make coffee . There are two choices:
real or instant, so we insert an if-else statement with those two choices:
// Get coffee in the morning.
if ( coffee not made ) {
// Make coffee.
if ( real coffee desired ) {
Brew coffee.
} else {
Make instant coffee.
}
}
Pour coffee into cup.
We now have two statements that could be refined further: Brew coffee and
Make instantcoffee . We can refine them in any order; they are independent. We
also have a choice of notation. If we continue to make each statement into a state-
ment-comment, the program becomes harder and harder to read. It exhibits too
much nested structure. Another choice is to introduce a method for a task and to
make an English statement into a procedure call. This allows the program to stay
short and simple. So let us create two methods:
Search WWH ::




Custom Search