Abstraction Functions and Representation Invariants CS/SWE 332 Paul Ammann Data Abstraction Abstract State (Client State) Representation State (Internal State) Methods (behavior) Constructors (create objects) Producers (return immutable object) Mutators (change state) Observers (report about state) This lecture is about state only 2 What is “State”? Key notion Definition: A state is an assignment of values to variables. Need to consider all possible values for each variable State space is cross product of possible values for each individual variable Java example: Variables: List list; int x; Possible States: list = list = list = list = etc. [], x = 5 null; x = 0 [“cat”, “dog”]; x = -8 [“cat”, 1, null]; x = 0 3 Motivation Why hide implementation from client? Makes reimplementation (maintenance) possible! Protects implementation from client Lecture covers two key notions Abstraction function Implemented by toString() in Java Representation Invariant Not standard in Java, but fits assertion mechanisms Is available in C# (VisualStudio Code Contracts) 4 Abstraction Function Abstract state Representation state What the implementation manipulates Examples given in class Abstraction function simply maps representation states to abstract states What the client sees Examples given in class Required for any implementation Difference here – we’re documenting it! Code examples: in-class exercises 5 Rep Invariant Rep invariant captures constraints on implementation variables English descriptions are fine “Why my code works” But needs to be coded to be effective Can check in Junit tests Code examples: in-class exercises 6