out Blocks and Expression-based Contracts

This lesson explains the use of out blocks for postconditions and the expression-based contract. Furthermore, it teaches how to disable contract programming in D.

out blocks for postconditions #

This contract involves guarantees that the function provides. Such guarantees are called the function’s postconditions. An example of a function with a postcondition would be a function that returns the number of days in February: The function can guarantee that the returned value would always be either 28 or 29.

The postconditions are checked inside the out blocks of functions.

Because the value that a function returns by need not be defined as a variable inside the function, there is usually no name to refer to the return value. This can be seen as a problem because the assert checks inside the out block cannot refer to the returned variable by name.
D solves this problem by providing a way of naming the return value right after the out keyword. That name represents the very value that the function is in the process of returning:

int daysInFebruary(int year)
out (result) {
    assert((result == 28) || (result == 29));

} do {
    return isLeapYear(year) ? 29 : 28;
}

Although result is a reasonable name for the returned value, other valid names may also be used.
Some functions do not have return values or the return value need not be checked. In that case, the out block does not specify a name:

out {
    // ...
}

Similar to in blocks, the out blocks are executed automatically after the body of the function is executed.
An assert check that fails inside the out block indicates that the contract has been violated by the function.
As it has been obvious, in and out blocks are optional. Considering unittest blocks as well (which are also optional), D functions may consist of up to four blocks of code:

  • in: optional

  • out: optional

  • do: mandatory, but the do keyword may be skipped if no in or out block is defined

  • unittest: optional and technically not a part of a function’s definition but commonly defined right after the function

Here is an example that uses all of these blocks:

Get hands-on with 1200+ tech skills courses.