in Blocks for Preconditions
This lesson defines contract programming and then explains the working of in blocks in contract programming.
We'll cover the following
Contract programming #
Contract programming is a software design approach that treats parts of software as individual entities that provide services to each other. This approach realizes that software can work according to its specifications as long as the provider and the consumer of the service both obey a contract.
D’s contract programming features involve functions as units of software services. Similar to unit testing, contract programming is also based on assert
checks.
Contract programming in D is implemented by three types of code blocks:
-
Function
in
blocks -
Function
out
blocks -
Struct and class invariant blocks
in
blocks #
The correct execution of functions usually depends on whether the values of their parameters are valid. For example, a square root function may require that its parameter cannot be negative. A function that deals with dates may require that the number of the month must be between 1 and 12. Such requirements of a function are called its preconditions.
We have already seen such condition checks in the assert and enforce chapter. Conditions on parameter values can be enforced by assert
checks within function definitions:
Get hands-on with 1400+ tech skills courses.