Design by contract and class invariant

I'm reading about dbc ( http://en.wikipedia.org/wiki/Design_by_contract ) Can someone please give me a simple example of using class invariants with respect to inheritance?

+4
source share
3 answers

The design for contract concepts gets a little complicated when they are adapted to object-oriented languages.

A class invariant is a property guaranteed by each instance of a class when a method is called (for example, a general precondition for all methods), and that as a result, each method and constructor must ensure that they remain valid when they stop (as a general post-condition) .

They are good for expressing conditions of consistency. The Wallet class, which models the actual wallet, may have a class invariant that the contained amount is always positive.

Class invariants, like the rest of the contract, are inherited. New implementations of the methods should provide the same guarantees as the methods that they replace.

+3
source

In an inherited class, invariants must be at least equally strict , but they can be more strict . If the invariant is omitted in the derived class, the invariants of the base class are applied, of course.

eg:

 // Class invariant : sum should be > -1000 Account { public int sum; } // Class invariant : sum should be >= 0 AccountForKids : inheritsFrom Account { public int sum; } 

Accounting for children should not go below zero, but this, of course, is more than -1000.

In general: A derived class contract is always hounored when class invariants become more stringent.

+2
source

An invariant of a derived class must:

  • Check the invariants of any member variables introduced into the stupid class
  • Check base class invariant
+1
source

All Articles