cs 261 – data structures preconditions, postconditions & assert
TRANSCRIPT
![Page 1: CS 261 – Data Structures Preconditions, Postconditions & Assert](https://reader036.vdocuments.net/reader036/viewer/2022082517/56649ef25503460f94c03614/html5/thumbnails/1.jpg)
CS 261 – Data Structures
Preconditions, Postconditions & Assert
![Page 2: CS 261 – Data Structures Preconditions, Postconditions & Assert](https://reader036.vdocuments.net/reader036/viewer/2022082517/56649ef25503460f94c03614/html5/thumbnails/2.jpg)
Preconditions
/* pre: size < SIZELIMIT pre: name != null; post: result >= MINRESULT*/int magic (int size, char *name)
{
assert(size < SIZELIMIT);
assert(name != null)
… DO STUFF …
assert(result >= MINRESULT);
return result;
}
preconditions are input conditions for the function
1. magic is only required to do it’s task if pre-conditions are satisfied
2. The caller knows that if he satisfies those conditions, magic will perform the task correctly
![Page 3: CS 261 – Data Structures Preconditions, Postconditions & Assert](https://reader036.vdocuments.net/reader036/viewer/2022082517/56649ef25503460f94c03614/html5/thumbnails/3.jpg)
Postconditions
/* pre: size < SIZELIMIT pre: name != null; post: result >= MINRESULT*/int magic (int size, char *name)
{
assert(size < SIZELIMIT);
assert(name != null)
… DO STUFF …
assert(result >= MINRESULT);
return result;
}
postconditions are output conditions for a function
1. magic guarantees the condition will hold when it completes. As developer, you must ensure this!
2. The caller is certain of what it will get , provided it has met preconditions
![Page 4: CS 261 – Data Structures Preconditions, Postconditions & Assert](https://reader036.vdocuments.net/reader036/viewer/2022082517/56649ef25503460f94c03614/html5/thumbnails/4.jpg)
Pre-conditions + Post-conditions
When combined….they define a contract!!!
Using pre and post conditions and CHECKING them helps you find and remove bugs and fulfill the contract!
pre post
![Page 5: CS 261 – Data Structures Preconditions, Postconditions & Assert](https://reader036.vdocuments.net/reader036/viewer/2022082517/56649ef25503460f94c03614/html5/thumbnails/5.jpg)
In practice….
• put pre-conditions in the header• put post-conditions in the header• during debugging, use asserts() to enforce them
To catch errors when recovery is generally not immediately possible
Useful during debugging, but we should replace for “Release”
![Page 6: CS 261 – Data Structures Preconditions, Postconditions & Assert](https://reader036.vdocuments.net/reader036/viewer/2022082517/56649ef25503460f94c03614/html5/thumbnails/6.jpg)
Bugs and Errors
1. Program Error: a bug, and should never occur
2. Run-time Error: can validly occur at any time during execution (e.g. user input is illegal) and should be recoverable
Replace these asserts with a reasonable error message
Write recovery code for these kinds of errors