invariant Blocks

Learn about invariant() blocks for object consistency.

invariant() blocks for object consistency

The in and out blocks of constructors guarantee that the objects start their lives in consistent states, and the in and out blocks of member functions guarantee that those functions themselves work correctly. However, these checks are not suitable for guaranteeing that the objects are always in consistent states. Repeating the out blocks for every member function would be excessive and error prone.

The conditions that define the consistency and validity of an object are called the invariants of that object. For example, if there is a one-to-one correspondence between the orders and the invoices of a customer class, then an invariant of that class would be that the lengths of the order and invoice arrays would be equal. When that condition is not satisfied for any object, then the object would be in an inconsistent state.

Get hands-on with 1200+ tech skills courses.