Guidelines for Class Design, Part 2

More on Encapsulation

Immutable classes

Unintended side effects


Contracts

Invariants

Invariants are associated with a class. To prove that an invariant is true, you must check:

Examples

Preconditions and Postconditions

Preconditions and postconditions are associated with specific methods of a class.

Examples:

OCL Expressions

To express constraints on a UML diagram with notes, use steroetypes, along with the boolean expressions:
  <<invariant>>
  denominator > 0

  <<precondition>>
  size() > 0

  <<postcondition>>
  size() < position
To express constraints in text form in OCL, use keywords context, along with inv, pre, or post:
  context Fraction inv:
      GetDenominator() > 0

  context Tournament inv:
      self.getMaxNumPlayers() > 0

  context Temperature::Convert(ns) pre:
      ns == 'c' || ns == 'C' || ns == 'f' || ns == 'F' || ns == 'k' || ns == 'K'

  context LinkedList::Delete(p) post:
      size() >= 0
Note that for invariants, you can use a special keyword self, which represents any instance of a class.

Also note that the invariants illustrated in these last examples are presented with method calls rather than direct member data. This is because it's something the user can verify (remember, user doesn't have access to private data


Throwing Exceptions