Java Reference
In-Depth Information
Writing a procedure call
Suppose you have to write a program segment to carry out some task, and
you believe that a call to a certain method can be used for it. In such a situation,
try to rewrite the task so that it is the same as the specification of the method, but
with expressions instead of parameters. The call will then be easy to write.
For example, suppose we want to:
Activity
2-2.6
Draw a rectangle with top-left corner (20, 40) and
lower-right corner (40, 70) .
Here is method drawRect again:
/** Draw a rectangle with top-left corner at pixel (tx, ty) with
height h and width w. */
public void drawRect( int tx, int ty, int w, int h) { … }
The specification is not written in the same form as the desired task. So, we
rewrite the task. The specification of drawRect uses the width and height of the
rectangle, so we figure out the formulas for them and rewrite the task as:
Draw rectangle with top-left corner (20, 40) ,
height 70+1-40 , and width 40+1-20 .
Because this rewritten task has the same form as the specification of
drawRect , we can easily write it in Java as the call
drawRect(20, 40, 40 +1-20, 70+1-40);
Some programmers would look at the original task and immediately write
the call
drawRect(20, 40, 21, 31);
They have saved two steps. They didn't rewrite the specification, and they cal-
culated the width and height of the rectangle in their heads. You may do the same
thing as long as you don't make a mistake!
As you will soon see, one of the hardest parts of programming is to find and
correct mistakes. This process is called debugging . To debug, you run the pro-
gram with various test cases, detect errors in the output, find the programming
errors, and fix them. Often, more time is spent debugging than writing the pro-
gram in the first place. Obviously, if you don't put mistakes in a program, debug-
ging is much easier. You can approach this goal by developing a program in small
steps that you know are correct, even if this approach seems to take more time.
Above, we took the small step of rewriting the task so that it looked similar
to the specification of the method we wanted to call. We left to the computer the
task of calculating the width and height from their formulas. Both of these choic-
es helped eliminate potential errors.
Search WWH ::




Custom Search