Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

DBC: basic design by contract

Part of HandlingErrorsCategory

Description

Implements specialized square_root used in doc example (with updated code to reflect dmd >= 0.102) and one-based lookup table.

Example

import std.stdio;
import std.math;

/* compile with dmd test.d */

void main ()
{
  long rc = GetMaxChapInBook(3);
  writefln("rc: ", rc);

  rc = square_root(16);
  writefln("rc: ", rc);
}


/* Specialized sqrt that requires an integer
 * that is an actual squared value (e.g. 1,4,9,16,etc)
 * Corresponds to DBC documentation with casts so that
 * it will compile with dmd >= 0.102
 * http://www.digitalmars.com/d/dbc.html
 */
long square_root(long x)
in 
{
  assert(x >= 0);

}
out (result)
{
  assert((result * result) == x);
}
body
{
  return cast(long)std.math.sqrt(cast(double)x);
}


/* One-based lookup table. An index of 0 or > 9 is rejected.
 * The return value rc is constrained to be between 1 and 50.
 * Note that "result" used in doc isn't reserved word or required.
 * Could also be done with enum??
 */
ushort GetMaxChapInBook(in ushort bk)
in { assert((bk >= 1) && (bk <= 9)); }

out (maxChap) { assert((maxChap >= 1) && (maxChap <= 50)); }

body {
  return chapsInBook[bk];
}


ushort[] chapsInBook = [
  0,  50, 40, 27, 36, 34, 24, 21,  4, 31     // 0-9
];

Source

Posted by Lynn
Date/Time Mon Oct 11, 2004 8:22 am