SDSU CS 535 Object-Oriented Programming
Fall Semester, 2003
Class Invariants
Previous    Lecture Notes Index    Next    
© 2003, All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated 13-Nov-03

Reading Assignment

Object-Oriented Design Heuristics, Chapter three


Doc 15, Class Invariants Slide # 2
Class invariants

“Class invariants are predicates of (statements about) a class that should always be true”

John Farrell, http://c2.com/cgi/wiki?CodeClassInvariants

Examples are:

An instance variable is not nil
An instance variable is an ordered collection
An integer value has to be in a certain range


Doc 15, Class Invariants Slide # 3
Example

Stack

Instance variables: elements, top

elements – Array containing the element of the stack
top – An integer pointing to element that is currently the top of the stack


Stack>>isEmpty
   ^top = 0

Stack>>isFull
   ^top = elements size

Stack>>pop
   self isEmpty ifTrue: [invoke your empty stack policy].
   topElement := elements at: top.
   top := top – 1.
   ^topElement

Stack>>push: anObject
   self isFull ifTrue: [invoke your full stack policy].
   elements at: (top := top + 1) put: anObject.


Doc 15, Class Invariants Slide # 4
Class Invariants

Are to be true



In the middle of a message send to an object the class invariant may be false


Doc 15, Class Invariants Slide # 5
WordStream

Parent class: ReadStream

Inherited instance variables:






WordStream>>on: aCollection
   ^super on: (aCollection runsFailing: [:each | each isWordSeparator])



Copyright ©, All rights reserved.
2003 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA.
OpenContent license defines the copyright on this document.

Previous    visitors since 13-Nov-03    Next