1 / 6

CS 261 – Data Structures

CS 261 – Data Structures. Preconditions, Postconditions & Assert. Preconditions . /* pre: size < SIZELIMIT pre: name != null; post: result >= MINRESULT */ int magic ( int size, char *name) { assert(size < SIZELIMIT); assert(name != null) … DO STUFF …

norris
Download Presentation

CS 261 – Data Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS 261 – Data Structures Preconditions, Postconditions & Assert

  2. Preconditions • /* • pre: size < SIZELIMIT • pre: name != null; • post: result >= MINRESULT • */ intmagic (int size, char *name) { assert(size < SIZELIMIT); assert(name != null) … DO STUFF … assert(result >= MINRESULT); return result; } preconditions are input conditions for the function magic is only required to do it’s task if pre-conditions are satisfied The caller knows that if he satisfies those conditions, magic will perform the task correctly

  3. Postconditions • /* • pre: size < SIZELIMIT • pre: name != null; • post: result >= MINRESULT • */ intmagic (int size, char *name) { assert(size < SIZELIMIT); assert(name != null) … DO STUFF … assert(result >= MINRESULT); return result; } postconditionsare output conditions for a function magic guarantees the condition will hold when it completes. As developer, you must ensure this! The caller is certain of what it will get , provided it has met preconditions

  4. 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! post pre

  5. 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”

  6. Bugs and Errors • Program Error: a bug, and should never occur • 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

More Related