I.T. Discussion Community!
-Collapse +Expand
To/From Code
-Collapse +Expand Cross Ref Guide
-Collapse +Expand Members-Only
Sign in to see member-only pages.
   ► KBTo/From GuidesDelphi  Print This     

Code Contract (Delphi and Delphi Prism Cross Reference Guide)

By Mike Prestwood

Delphi versus Delphi Prism: A side by side comparison between Delphi and Delphi Prism.

OOP Details

More object oriented (OO) stuff.

Code Contract

[Other Languages] 

A.k.a. Class Contract and Design by Contracts.

A contract with a method that must be true upon calling (pre) or exiting (post). A pre-condition contract must be true when the method is called. A post-condition contract must be true when exiting. If either are not true, an error is raised. For example, you can use code contracts to check for the validity of input parameters, and results

An invariant is also a code contract which validates the state of the object required by the method.

Delphi:  "Code Contracts" Not Supported

Delphi does not offer built-in Design by Contract features. It does offer an Assert method which tests if an expression is true. If false, an EAssertionFailed exception is raised. Although you can use Assert in a similar manor as you would use a pre-condition contract, the Delphi help clearly says Assert is a debugging tool only and to not use it in production code.

//Although not intended as a code contract feature,
//Assert is useful for debugging.
method Cyborg.Walk(pPace);
Assert(pPace > 0);
Assert(pPace < 100);
  //Overloaded version with message.
Assert(FEnergyLevel >= 10, 'Energy level too low.');
Delphi Prism:  "Class Contracts" require, ensure

Prism supports class contracts with its require and ensure keywords. The require keyword is a pre condition that must be true when the method is called. The ensure keyword is a post condition that must be true when a method exits. With either, if the condition evaluates to false, then an assertion is generated.

The require and ensure keywords will expand the method body to list the preconditions; both sections can contain a list of Boolean statements, separated by semicolons.

Syntax Example:
method Cyborg.Walk(pPace);
pPace > 0;
  pPace < 100;
FEnergyLevel >= 10;

Follow PrestwoodBoards on: 

©1995-2020 PrestwoodBoards  [Security & Privacy]
Professional IT Services: Coding | Websites | Computer Tech