Unlock access to all the studying documents.
View Full Document
14
But the third function call might return true, or it might return false,
nobody really knows since the precondition has been violated.
Another Example
What values will be returnedWhat values will be returned
by these function calls ?by these function calls ? true
15
. . . crashing the computer.
Now, if I had written the is_vowel function, and the argument was a
Another Example
What values will be returnedWhat values will be returned
by these function calls ?by these function calls ?
16
Always make sure the
precondition is valid . . .
❐The programmer who
calls the function is
responsible for
17
On the other hand, if she keeps her end of the bargain, and calls the
function with a valid postcondition, then the function has a responsibility
of its own.
. . . so the postcondition becomes
true at the function’s end.
❐The programmer who
writes the function counts
THEN MY FUNCTION
WILL EXECUTE, AND WHEN
IT IS DONE, THE
18
Time for another quiz . . .
A Quiz
Suppose that you call a
function, and you neglect to
①You
②The programmer who
19
A Quiz
Suppose that you call a
function, and you neglect to
make sure that the
precondition is valid.
Who is responsible if this
inadvertently causes a 40-
day flood or other disaster?
①You
The programmer who
calls a function is
responsible for
ensuring that the
precondition is valid.
20
Well, there’s no way of getting around it: The programmer who calls a
function is responsible for making sure the precondition is valid.
On the other hand, careful
programmers also follow these rules:
❐When you write a function, you should
make every effort to detect when a
precondition has been violated.
21
On the other hand, careful
programmers also follow these rules:
❐When you write a function, you should
make every effort to detect when a
precondition has been violated.
22
Example
void write_sqrt( double x)
// Precondition: x >= 0.
// Postcondition: The square root of x has
23
Here are the primary advantages to using a method such as
One of the important advantages has to do with reimplementations.
Advantages of Using
Preconditions and Postconditions
❐Succinctly describes the behavior of a
function…
❐… without cluttering up your thinking with
details of how the function works.
24
Precondition
❐The programmer who calls
a function ensures that the
Postcondition
❐The programmer
who writes a
Summary
25
THE END
Presentation copyright 1997, Addison Wesley Longman
For use with
Data Structures and Other Objects Using C++
by Michael Main and Walter Savitch.