CS 535 Object-Oriented Programming Fall Semester, 2003 Class Invariants |
||
---|---|---|
© 2003, All Rights Reserved, SDSU & Roger Whitney San Diego State University -- This page last updated 13-Nov-03 |
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
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.
Class Invariants
Are to be true
WordStream
Parent class: ReadStream
Inherited instance variables:
WordStream>>on: aCollection ^super on: (aCollection runsFailing: [:each | each isWordSeparator])