Java Reference
In-Depth Information
4.4 Methods with Conditional Execution
We introduced a great deal of information about methods in Chapter 3, including how
to use parameters to pass values into a method and how to use a return statement to
have a method return a value. Now that we've introduced conditional execution, we
need to revisit these issues so that you can gain a deeper understanding of them.
Preconditions and Postconditions
Every time you write a method you should think about exactly what that method is
supposed to accomplish. You can describe how a method works by describing the
preconditions that must be true before it executes and the postconditions that will be
true after it has executed.
Precondition
A condition that must be true before a method executes in order to guarantee
that the method can perform its task.
Postcondition
A condition that the method guarantees will be true after it finishes executing,
as long as the preconditions were true before the method was called.
For example, if you are describing the task of a person on an automobile assembly
line, you might use a postcondition like, “The bolts that secure the left front tire are
on the car and tight.” But postconditions are not the whole story. Employees on an
assembly line depend on one another. A line worker can't add bolts and tighten them
if the left tire isn't there or if there are no bolts. So, the assembly line worker might
have preconditions like, “The left tire is mounted properly on the car, there are at
least eight bolts in the supply box, and a working wrench is available.” You describe
the task fully by saying that the worker can make the postcondition(s) true if the pre-
condition(s) are true before starting.
Like workers on an assembly line, methods need to work together, each solving its
own portion of the task in order for them all to solve the overall task. The precondi-
tions and postconditions describe the dependencies between methods.
Throwing Exceptions
We have seen several cases in which Java might throw an exception. For example, if
we have a console Scanner and we call nextInt , the program will throw an excep-
tion if the user types something that isn't an int . In Appendix D we examine how
you can handle exceptions. For now, we just want to explore some of the ways in
which exceptions can occur and how you might want to generate them in your own
code.
 
Search WWH ::




Custom Search