Verifying object invariants and pre- and post-conditions
D supports contract programming, which can help you ensure an object's state is always valid and object methods are passed with correct parameters and returns valid values, including while using class inheritance. Here, we'll see how to use these features and why they work the way they do.
How to do it…
Perform the following steps:
When writing an
interface
,class
, orstruct
, addin
andout
blocks to methods, right after the signatures, and also addinvariant
blocks to the aggregate.Put assertions in the
in
blocks to verify your preconditions.Put assertions in the
out
blocks to verify your postconditions. Theout
block may take an argument to access the method's return value.Add the
body
keyword before your method's body but after itsin
andout
blocks (if it has them).In child classes, also use
in
contracts to reassert your input requirements, even if they are the same as the parent class.Put assertions in the
invariant
blocks to verify...