Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. When writing an interface, class, or struct, add in and out blocks to methods, right after the signatures, and also add invariant blocks to the aggregate.

  2. Put assertions in the in blocks to verify your preconditions.

  3. Put assertions in the out blocks to verify your postconditions. The out block may take an argument to access the method's return value.

  4. Add the body keyword before your method's body but after its in and out blocks (if it has them).

  5. In child classes, also use in contracts to reassert your input requirements, even if they are the same as the parent class.

  6. Put assertions in the invariant blocks to verify...