![Page 1: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/1.jpg)
Assertions
Prasun Dewan
Comp 114
![Page 2: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/2.jpg)
Assertions
• Declare some property of the program
• Potentially useful for– specification– testing– formal correctness – documentation
![Page 3: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/3.jpg)
Compile time vs. runtime properties
• Some assertions language supported– Compile time
• String s = nextElement()
– Runtime• ((String) nextElement())
– Asserting type properties of object.– Assertions describe runtime properties
![Page 4: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/4.jpg)
Application-independent vs. dependent• Language can provide us with fixed number
of application-independent assertions.• Cannot handle
– First character of String is a letter.– Letter concept not burnt into language.
• Class Character defines it
– Innumerable assertions about letters possible• Second elements of string is letter.• Third element of string is letter.
• Need mechanism to express arbitrary assertions
![Page 5: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/5.jpg)
Assertions vs. Exceptions
• Wrong assertion results in exception.
• Wrong class cast leads to class cast exception.
![Page 6: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/6.jpg)
Reasons for exceptions
• User error– Programmer cannot prevent it
• Internal error– Programmer can prevent
• Assertions catch internal errors.
![Page 7: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/7.jpg)
Reasons for assertions
• Why catch internal errors via assertions?
• Alternative: Make test runs and look at output.
![Page 8: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/8.jpg)
Finite test runs
• Some errors not exhibited in test runs.– Inconsistent string not printed because of user
option.
![Page 9: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/9.jpg)
Late detection
• Output produced much after the cause– Storing an inconsistent string causes
erroneous output when the string is matched not when it is stored.
![Page 10: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/10.jpg)
Complex output
• May not know what the output is, but know the relationship between input and output– (123.345 * 789.123 ) / 123.345 == 789.123– Number is divisible by a prime factor
![Page 11: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/11.jpg)
No manifestation in output
• Some errors have to do with efficiency.– Storing duplicate items in a set.
• Not exhibited in output
![Page 12: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/12.jpg)
Example Assertion
{ y = 10/x; z = 5}
assert (y == 10/x) & (z == 5)
Our own mathematical syntax to be mapped to
Java later
![Page 13: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/13.jpg)
Definition• Example
{ y = 10/x; z = 5}
assert (y == 10/x) & (z == 5)
• Statement regarding– State of program (variable values)
– Program counter (currently executing statement)
• PC implicit by putting assertion next to a statement– Specifies Boolean expression involving selected program
variables
– Assertion fails if boolean expression false
– Not all program variables named• X unnamed above
• Does not care about unnamed variables
![Page 14: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/14.jpg)
Role of Assertions• Debugging
– Exception thrown if assertion fails
• Documentation// detailed prime factor computation code
….
assert (number % prime) == 0
• Specification – Assertion defined desired result of the code to be
implemented
• Formal correctness– Can prove if assertion met by code.
– Need assertions regarding language constructs
![Page 15: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/15.jpg)
Recording Variables
{X = X + 1}assert ???
• Cannot say:{X = X + 1}assert X == X + 1;
• Introduce recording variable{oldX = X; X = X + 1}assert X = oldX + 1
• Special variables needed to make assertions sometimes
![Page 16: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/16.jpg)
Preconditions and Postconditions
assert (x !=0)
{ y = 10/x; z = 5}
assert (y == 10/x) & (z == 5)
• Precondition– What is expected before
statement(block) execution
• Postcondition– What is guaranteed
after statement(block) if precondition met
• Together define a contract
![Page 17: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/17.jpg)
Alternative syntax
pre (x !=0)
post (y == 10/x) & (z == 5)
{ y = 10/x; z = 5}
• Both conditions placed before statement block.
![Page 18: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/18.jpg)
Incorrect precondition?
x = 0;pre (x !=0)post (y == 10/x) & (z == 5){ y = 10/x; z = 5}
• Precondition may not be satisfied by previous incorrect statement.
• Yet it is a correct precondition
![Page 19: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/19.jpg)
Alternative precondition
pre (x > 0)
post (y == 10/x) & (z == 5)
{ y = 10/x; z = 5}
• Some assertions imply others– x > 0 x !=0
• Implied assertion is considered weaker.
• Can always replace precondition with a stronger one.
• Prefer weakest precondition– Requires fewest assumptions.– Statement can be used in more
contexts– Better documentation
![Page 20: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/20.jpg)
Alternative postcondition
pre (x != 0)
post (z == 5)
{ y = 10/x; z = 5}
• Some assertions imply others– y == 10/x & (z == 5) => z == 5
• Can always replace postcondition with a weaker one
• Prefer strongest postcondition– More detailed documentation
– Can be used in more contexts• Can be followed by statements with
stronger preconditions.
![Page 21: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/21.jpg)
Comp 114
• pre arrays, loops, procedures
• {Take Comp 114}• post objects,
inheritance, trees, recursion, assertions, composite, iterator, visitor pattern
• pre arrays, loops, procedures, objects, inheritance
• {Take Comp 114}• post recursion
Too strong
Too weak
![Page 22: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/22.jpg)
Course Analogy
• Preconditions– Declared course prerequisite
• Post conditions– Advertised objectives
• Stronger precondition– Does not allow some students to enroll
• Weaker post conditions– Does not allow enrollment in future courses
![Page 23: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/23.jpg)
Strongest Postcondition?
pre (x !=0)
post (y == 10/x) & (z == 5)
{ y = 10/x; z = 5}
• Says nothing about x.
![Page 24: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/24.jpg)
Strongest Postcondition
pre (x !=0)
post (y == 10/x) & (z == 5) & (x != 0)
{ y = 10/x; z = 5}
• Strongest post condition given the precondition
• The stronger the pre condition, stronger the post condition.
![Page 25: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/25.jpg)
Alternative weakest/strongest pair
pre (x > 0)
post (y == 10/x) & (z == 5) & (x > 0) & (y > 0)
{ y = 10/x; z = 5}
Stronger precondition
Stronger postcondition
![Page 26: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/26.jpg)
Multiple valid pairs
• Weakest precondition relative to post condition.• Strongest post condition relative to pre condition.• A statement not associated with a unique pair that
is best.• Strengthening the precondition strengthens the
post condition• What is the “right pair?”
![Page 27: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/27.jpg)
Two approaches
• Start with a precondition– Find the strongest postcondition we can prove.
• Start with a post condition– Find the weakest precondtion for it.
![Page 28: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/28.jpg)
Theoretical specification point of view
• Specify the result needed as a post condition.
• Identify the weakest precondition needed to obtain the result.
• Write a program that satisfies the pair.
![Page 29: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/29.jpg)
Reality specification point of view
• Based on what you can assume you change your expectations.
• Iterative process.
![Page 30: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/30.jpg)
Debugging/specification/ documentation point of view
• Precondition of a statement should be weakest one necessary for “correct” operation of program.– Correct means no exception.
• A statement that is not equivalent should not have the same pre and post condition
![Page 31: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/31.jpg)
Debugging/specification/ documentation point of view
pre (x >0)
post (y == 10/x) & (z == 5) & (x > 0)
{ y = 10/x; z = 5}
pre (x >0)
post (y == 10/x) & (z == 5) & (x > 0)
{ y = 10/x; z = 5; x = abs(x) + 1}
Statements are not equivalent
![Page 32: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/32.jpg)
Debugging/ specification/ documentation point of view
pre (x !=0)
post (y == 10/x) & (z == 5) & (x != 0)
{ y = 10/x; z = 5}
Best pre and post conditions
![Page 33: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/33.jpg)
Proving programs correct point of view
• Precondition can be stronger than one that is the best one for the statement from debugging/specification/documentation point of view
• Allows us to derive pre and post conditions of containing statement/program
![Page 34: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/34.jpg)
Program correctness proof
pre
post (x == 1)
{x = 1}
pre (x == 1)
post (y == 10/x) & (z == 5) & (x == 1)
{ y = 10/x; z = 5}
![Page 35: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/35.jpg)
Program correctness proof
pre
post (y == 10/x) & (z == 5) & (x == 1)
{x = 1; y = 10/x; x= 5}
![Page 36: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/36.jpg)
Changeable assertions
• What we assert about a statement (to prove program correct) may depend on what is executed before it.
• Need facilities to change assertions easily.
• Proxies explained later address this.
![Page 37: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/37.jpg)
Weakest possible condition
• Implied by anything
• true
• p true
• If p is true then true is true.
• But true is always true.
• So p can be any boolean expression.
![Page 38: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/38.jpg)
Strongest possible condition
• Implies anything• false• false p• If false is true then p is true• But false is never true.• So any p is implied.• “I will give you a million dollars when hell
freezes over”
![Page 39: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/39.jpg)
Important equivalence
• P Q !P | Q
• P true !P | true true
• false Q !false | Q true
![Page 40: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/40.jpg)
Asserting false
switch c {
case ‘a’: …
case ‘b’: …
default: assert false
}
Unreachable statement
![Page 41: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/41.jpg)
Invariant
pre (x !=0)
post (y == 10/x) & (z == 5) & (x != 0)
{ y = 10/x; z = 5}
• True before and after statement
![Page 42: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/42.jpg)
Separately declared
inv (x !=0)
post (y == 10/x) & (z == 5)
{ y = 10/x; z = 5}
• List invariant separately
![Page 43: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/43.jpg)
Invariants for debugging purposes• Should never be false
– False strongest invariant of all statements.– But not best for a reachable statement as it does
not convey useful information– Never assert it for reachable statements if
assertion not done for program proofs.
• Should never involve recording variables– recording variables describe how program
variables change– invariants describe how these variables do not
change
![Page 44: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/44.jpg)
Loop Invariant
sum = 0;j = 0;while (j < n) { j++; sum = sum + j;}
• Holds true before and after each loop iteration, that is, before and after each execution of loop body.
![Page 45: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/45.jpg)
Loop Invariant
inv (sum = 0 j k) & (j <= n ) & (j >= 0)
sum = 0;j = 0;while (j < n) { j++; sum = sum + j;}
• Holds true before and after each loop iteration, that is, before and after each execution of loop body.
![Page 46: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/46.jpg)
Method assertions
invariant x != 0post (y == 10/x) & (z == 5) & (x != 0)void m () { y = 10/x; z = 5;}
• Preconditions, postconditions, invariants associated with method body
![Page 47: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/47.jpg)
Class assertions
public class C {int x =0;int y = 1;public void incrementXAndY () { incrementX(); incrementY();}public int getX() { return x;}public int getY() { return y;}incrementX() { x++;}incrementY() { y++;}}
• Preconditions, postconditions, invariants shared by all public methods of class
![Page 48: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/48.jpg)
Class assertionsinv y == x + 1public class C {int x =0;int y = 1;public void incrementXAndY () { incrementX(); incrementY();}public int getX() { return x;}public int getY() { return y;}incrementX() { x++;}incrementY() { y++;}}
• Preconditions, postconditions, invariants shared by all public methods of class
![Page 49: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/49.jpg)
Expressing Assertions• Natural language
– All array elements are not odd.– All array elements are either odd or positive.– Easy to read but ambiguous.
• Programming language– Library or language constructs– Executable, unambiguous but language-dependent and
awkward• Useful for debugging• Specification cannot be done before language decided.
• Mathematical language– Uambiguous, time tested, convenient but not executable
![Page 50: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/50.jpg)
Propositional Calculus• Logic operators
• not, and, or• We will use Java syntax.
• Quantifiers– Universal ( )– Existential ( )
• Propositional variables• Program• Others: Recording, Quantifier
• Propositions– Boolean expressions involving operators, variables, and
quantifiers
• Simple/quantified propositions– Do not use/use quantifiers
![Page 51: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/51.jpg)
Propositional Algebra
• Calculus based on algebra
• Algebra defines– Arithmetic operations– Relations operations– We will use Java syntax
![Page 52: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/52.jpg)
Example Propositions• Simple propositions
– True– False– X > 6– (X > 6 ) & (Y < 2)
• Quantified j: 0 <= j < b.size() : b.elementAt(j) != null
• All elements of B are not null j: 0 <= j < b.size(): b.elementAt(j) != null
• At least one element of B is not null.
![Page 53: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/53.jpg)
Quantified Propositions• Sub-proposition
– Simple or quantified proposition in terms of quantifier
• Domain– A collection of values used in
sub-proposition evaluation– b.elementAt(0), …
b.elementAt(B.size() – 1
• Domain description– Describes domain using
quantified variable
• Quantified j: 0 <= j < b.size():
b.elementAt(j) != null j: 0 <= j < b.size():
b.elementAt(j) != null
• General form:– Qx:D(x):P(x) – Q is either or
quantifier– X is quantified variable– D(x) is domain description– P(x) is sub-proposition
![Page 54: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/54.jpg)
Expressing Assertions in Java
• Write your own code.
• Libraries
• Language support– Does not support quantifiers– Works for 1.4– You have 1.3
![Page 55: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/55.jpg)
Assertion Failed Exception
• Thrown when assertion fails• Unchecked because internal error• Can subclass it for specific
assertions• Will use message in examples
package assertions;public class AnAssertionFailedException extends RuntimeException { public AnAssertionFailedException () {}; public AnAssertionFailedException (String initValue) { super (initValue); }}
![Page 56: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/56.jpg)
Assert methods
• Used for simple assertions
package assertions;import java.util.Enumeration;public class AnAsserter { public static void assert (boolean proposition, String message) throws AnAssertionFailedException { if (!proposition) throw new AnAssertionFailedException (message); }
public static void assert (boolean proposition) throws AnAssertionFailedException {
assert (proposition, “”);}
}
![Page 57: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/57.jpg)
Using assert
• Must write our boolean expression that is passed to assert– public static int sum (int from, int to) { … }
• Must code pre/post conditions and invariants as assert calls
//inv (sum = 0 j k) & (j <= n ) & (j >= 0)
sum = 0;j = 0;while (j < n) { j++; sum = sum + j;}
![Page 58: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/58.jpg)
Using assert
• Must write our boolean expression that is passed to assert– public static int sum (int from, int to) { … }
• Must code pre/post conditions and invariants as assert calls
sum = 0;
j = 0;
//inv (sum = 0 j k) & (j <= n ) & (j >= 0)
while (j < n) {
AnAsserter.assert (j <= n && j >= 0 && sum == sum(0, j))
j++;
sum = sum + j;
AnAsserter.assert (j <= n && j > =0 && sum == sum(0, j))
}
![Page 59: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/59.jpg)
Class and Method Invariants
• Class invariant– Encode them as invariants of
all public methods.
• Method invariant– Put assert at start and end of
public methods
//inv y = x + 1public class C {int x =0;int y = 1;public void incrementXAndY () { incrementX(); incrementY();}public int getX() { return x;}public int getY() { return y;}incrementX() { x++;}incrementY() { y++;}}
![Page 60: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/60.jpg)
Class and Method Invariants
• Class invariant– Encode them as
invariants of all public methods.
• Method invariant– Put assert at start and
end of method
//inv y = x + 1public class C {
int x =0;int y = 1;void assertClassInvariant{
AnAsserter.assert (y == x + 1);}public void incrementXAndY () { assertClassInvariant(); incrementX(); incrementY(); assertClassInvariant();}public int getX() { assertClassInvariant(); ??? return x;}
…}
Cannot put something after return and return may have side effects
(return x++)
![Page 61: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/61.jpg)
Class and Method Invariants//inv y = x + 1public class C {
int x =0;int y = 1;void assertClassInvariant{
AnAsserter.assert (y == x + 1);}void internalIncrementXAndY () { incrementX(); incrementY();}public void incrementXAndY () { assertClassInvariant(); internalIncrementXAndY(); assertClassInvariant();}int internalGetX() { return x;}public int getX() { assertClassInvariant(); int retVal = internalGetX(); assertClassInvariant(); return retVal;}
…}
Asserting proxy method
• Can define another proxy method that asserts and calls the real method– Keeps asserting code
separate
– Useful for functions
– Useful when multiple exit points
![Page 62: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/62.jpg)
Multiple exit points
• Can define another proxy method that asserts and calls the real method– Keeps asserting code
separate
– Useful for functions
– Useful when multiple exit points
char assignGrade (int score) {if (score >= 50) {
grade = ‘P’;return;
} elsegrade = ‘F’;
}
char assertingToGrade (int score) { assignGrade(score);
assert (grade == ‘F’ || grade == ‘P’);}
![Page 63: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/63.jpg)
Quantified Assertions
• Syntax– Qx:D(x):P(x) j: 0 <= j < b.size(): b.elementAt(j) != null j: 0 <= j < b.size(): b.elementAt(j) != null
• Goal:– Write general boolean functions that take as arguments
encoding of the elements of domain and return true iff proposition is true
– Will write separate functions for universal and existential quantifer
![Page 64: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/64.jpg)
Goal
• Need to fill the …
package assertions;import java.util.Enumeration;public class AQuantifier { public static boolean forAll (…) { … } public static boolean thereExists (…) { … }}
![Page 65: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/65.jpg)
Problem with inaccessible variables
• Syntax– Qx:D(x):P(x) j: 0 <= j < b.size(): b.elementAt(j) != null j: 0 <= j < b.size(): b.elementAt(j) != null
• How to describe D(x) and P(x)?– Cannot pass expression string as variables involved
have no meaning to library– Will pass one argument describing the domain
• Collection of elements– Another argument describing the subproposition to be
evaluated for each domain element.
![Page 66: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/66.jpg)
How to describe domain?
• Syntax– Qx:D(x):P(x) j: 0 <= j < b.size(): b.elementAt(j) != null j: 0 <= j < b.size(): b.elementAt(j) != null
• Domain can be– Array, Vector, StringHistory, …
• Need a common interface to describe elements– java.util.Enumeration
![Page 67: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/67.jpg)
Describing the domain
AnAsserter.assert(AQuantifier.forAll(B.elements(), …, "Some element of B is null");
AnAsserter.assert(AQuantifier.thereExists(b.elements(), …, "All elements of B are null");
Need to fill …
package assertions;import java.util.Enumeration;public class AQuantifier { public static boolean forAll ((Enumeration domain, …) { while (domain.hasMoreElements()) … } public static boolean thereExists ((Enumeration domain, …) {
while (domain.hasMoreElements()) … }}
![Page 68: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/68.jpg)
How to describe Subproposition
• Syntax– Qx:D(x):P(x) j: 0 <= j < b.size(): b.elementAt(j) != null j: 0 <= j < b.size(): b.elementAt(j) != null
• Cannot pass expression string as variables involved have no meaning to library
• But can pass function that evaluates it.– boolean isNotNull(Object element) {
return element != null; }
• Function will be evaluated for each domain element by our libraries
![Page 69: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/69.jpg)
Subproposition as a function
AnAsserter.assert(AQuantifier.forAll(B.elements(), isNotNull), "Some element of B is null");
AnAsserter.assert(AQuantifier.thereExists(b.elements(), isNotNull), "All elements of B are null");
package assertions;import java.util.Enumeration;public class AQuantifier { public static boolean forAll (Enumeration domain, (object boolean) subProposition) { while (domain.hasMoreElements()) if (!subProposition (domain.nextElement()) return false; return true; } public static boolean thereExists ((Enumeration domain, (object boolean) subProposition) {
while (domain.hasMoreElements()) if (!subProposition (domain.nextElement()) return true; return false; }}
![Page 70: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/70.jpg)
How to describe Subproposition• Cannot pass expression string.• But can pass function that
evaluates it.– boolean isNotNull(Object element) {
return element != null;
}
• Java does not support function parameters
• But allows object parameters– Object = data + functions
• All subproposition objects implement same interface
• A subproposition object visits each element
package visitors;import assertions.ElementChecker;public class ANonNullChecker implements ElementChecker { public boolean visit(Object element) {
return (element != null); }}
package assertions;public interface ElementChecker { public boolean visit (Object element);}
![Page 71: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/71.jpg)
Describing the subproposition
AnAsserter.assert(AQuantifier.forAll(b.elements(), new ANonNullChecker()), "Some element of B is null");
AnAsserter.assert(AQuantifier.thereExists(b.elements(), new ANonNullChecker()), "All elements of B are null");
package assertions;import java.util.Enumeration;public class AQuantifier { public static boolean forAll (Enumeration domain, ElementChecker subProposition) { while (domain.hasMoreElements()) if (!subProposition.visit(domain.nextElement())) return false; return true; } public static boolean thereExists (Enumeration domain, ElementChecker subProposition) { while (domain.hasMoreElements()) if (subProposition.visit(domain.nextElement())) return true; return false; }}
Call
Callback
![Page 72: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/72.jpg)
Calls vs. Callbacks
• Calls– calls from reusing class to reused class
• Callbacks– calls from reused class to reusing class.– not to implement a symbiotic relationship– done to service calls
![Page 73: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/73.jpg)
Subproposition accessing vars other than domain elements j: 0 <= j < b.size(): b.elementAt(j) != a.elementAt(0) j: 0 <= j < b.size(): b.elementAt(j) != a.elementAt(0)
package visitors;import assertions.ElementChecker;public class ANonNullChecker implements ElementChecker { public boolean visit(Object element) {
return (element != null); }}
AnAsserter.assert(AQuantifier.forAll(b.elements(), new ANonNullChecker()), "Some element of B is null");
No constructor
![Page 74: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/74.jpg)
Subproposition accessing vars other than domain elements j: 0 <= j < b.size(): b.elementAt(j) != a.elementAt(0) j: 0 <= j < b.size(): b.elementAt(j) != a.elementAt(0)
package visitors;import assertions.ElementChecker;public class AnInequalityChecker implements ElementChecker {
Object testObject;public AnInequalityChecker(Object theTestObject) {
testObject = theTestObject;}public boolean visit(Object element) {
return !element.equals(testObject);}
}
AnAsserter.assert(AQuantifier.forAll(b.elements(), new AnInequalityChecker(a.elementAt(0))), "Some element of b is equal to a.elementAt(0)");
Each external var becomes constructor parameter
![Page 75: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/75.jpg)
Visitor Pattern• Some collection C of elements of type T• Visitor interface
– public interface ElementChecker { public boolean visit (Object element);}– public interface V {public T2 m (T p);}
• One or more traverser methods that use collection and visitor interface to pass one or more collection elements to the method.
– public static boolean forAll (Enumeration domain, ElementChecker subProposition) {…subProposition.visit(domain.nextElement());
– traverser1 (C c, V v) { …v.m(element of C)…}• Implementation of interface whose constructors take as arguments external
variables that need to be accessed by the visitor methodpublic class AnInequalityChecker implements ElementChecker {
Object testObject;public AnInequalityChecker(Object theTestObject) {…}public boolean visit(Object element) {…};
}public class AV1 implements V { public AV1 (T1 p1, … Tn pN) { …} public T2 m (T p) { … }}
• Client passes traverser visitor implementation and collection– AQuantifier.forAll(b.elements(), new AnInequalityChecker(a.elementAt(0)));– traverser1(c, new AV1(a1,.. aN));
![Page 76: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/76.jpg)
Visitor Pattern
Collection Interface C with elements of type T
element1: T element1: T
component
Visitor Interface
Visitor Class 1
implements
Visitor Class 2
uses
Traverser 2
Traverser 1
![Page 77: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/77.jpg)
Example of Visitor Pattern
Enumeration
Object Object
component
ElementChecker
ANonNullChecker
implements
AnInequalityChecker
uses
thereExists()
forAll()
![Page 78: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/78.jpg)
Nested Assertions
j: 0 <= j < b.size(): k: 0 <= k < b.elementAt(j).size(): b.elementAt(j).elementAt(k) != null
package visitors;import assertions.ElementChecker;public class ANonNullChecker implements ElementChecker { public boolean visit(Object element) {
return (element != null); }}
package visitors;import assertions.ElementChecker;public class AForAllChecker implements ElementChecker { public boolean visit(Object element) { Enumeration children = ( (Vector) element).elements(); return AQuantifier.forAll(children, new ANonNullChecker())); }}
AnAsserter.assert(AQuantifier.forAll(b.elements(), new AForAllChecker(), "Some leaf-level element of b is null”);
Visiting Hierarchical Structures
(Trees)
![Page 79: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/79.jpg)
Example of Pattern in Everyday Applications
• Program tree
• A visitor for printing all nodes.
• Another for type checking.
• Yet another for generating code
• Do not want to put all of this code in tree class.
• In any case, printing should not be in tree.
![Page 80: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/80.jpg)
Java 1.4 Assertion Support• AssertionError exception
= AnAssertionFailedException
• assert <boolean expression>= AnAsserter.assert(<boolean expression>, “”);
• assert <boolean expression>: <value>= AnAsserter.assert(<boolean expression>, string representation of
<value>
• Compile option determine if assert is keyword– javac –source 1.4 models/ACounter.java
• Assertions can be dynamically turned on or off for package or Class– java –da:bus.uigen –ea models.ACounter
• No support for quantifiers.
![Page 81: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/81.jpg)
Error vs. Exception• Java assertion failure results in AssertionError
• Subclass of Error rather than RunTimeException
• Reasoning: – Convention dictates that RunTimeException
should be caught– Should “discourage programmers from
attempting to recover from assertion failures.”• Might do custom reporting, mail error report etc.
– Decision was controversial
![Page 82: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/82.jpg)
Modularizing assertion code
• How to not clutter regular with assertion code.
• How to turn off/change library-based assertion code?
![Page 83: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/83.jpg)
Proxy Methods
• Can define another proxy method that asserts and calls the real method– Keeps asserting code
separate
– Useful for functions
– Useful when multiple exit points
char assignGrade (int score) {if (score >= 50) {
grade = ‘P’;return;
} elsegrade = ‘F’;
}
char assertingToGrade (int score) { assignGrade(score);
assert (grade == ‘F’ || grade == ‘P’);}
![Page 84: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/84.jpg)
Proxy classes
• Put assertion code in special classes that are proxies for real classes.
• Factory, factory selectors and factory methods can be used to choose between proxy and regular classes.
![Page 85: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/85.jpg)
Counterpackage models;public class ACounter implements Counter {
int counter = 0;public void add (int amount) {
counter += amount;}public int getValue() {
return counter;}
}
![Page 86: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/86.jpg)
Asserting Proxy Class
package models;import assertions.AnAsserter;public class ACheckedCounter extends ACounter {
public void add (int amount) {int oldCounter = counter;super.add(amount);AnAsserter.assert(counter == oldCounter + amount,
"New counter:" + counter + " != old counter:" + oldCounter + " + amount:" + amount);
}}
![Page 87: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/87.jpg)
Example of Proxy Pattern
ACounter Counterimplements
AChecked Counter
IS-A implements
![Page 88: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/88.jpg)
Proxy Pattern
Real Subject Class
Subject Interface
implements
Proxy Class
IS-A implements
![Page 89: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/89.jpg)
Proxies in everyday apps• Proxy is a stand-in for real subject.• Adds to one or more method implementations• Web proxies
– Cache data– Redirect to nearest server
• Proxy may – Log– Cache (remote proxy)– Provide access control– Assert
![Page 90: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/90.jpg)
Asserting Proxy Class
package models;import assertions.AnAsserter;public class ACheckedCounter extends ACounter {
public void add (int amount) {int oldCounter = counter;super.add(amount);AnAsserter.assert(counter == oldCounter + amount,
"New counter:" + counter + " != old counter:" + oldCounter + " + amount:" + amount);
}}
Alternative way of doing
proxy?
![Page 91: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/91.jpg)
Delegating Proxy
• Proxy HAS-A reference to the Subject and not IS-A Subject.
• Proxy is called delegator and subject is called delegate
![Page 92: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/92.jpg)
Delegating Proxy-based Counterpackage models;import assertions.AnAsserter;public class ADelegatingCheckedCounter implements Counter {
Counter counter; public ADelegatingCheckedCounter (Counter theCounter) {
counter = theCounter;}public void add (int amount) {
int oldVal = counter.getValue();counter.add(amount);int newVal = counter.getValue();AnAsserter.assert(newVal == oldVal + amount,
"New counter:" + newVal + " != old counter:" + oldVal + " + amount:" + amount);
}public int getValue() {
return counter.getValue();}
}
![Page 93: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/93.jpg)
Example of Delegating Proxy
ACounter Counterimplements
AChecked Counter
HAS_A implements
![Page 94: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/94.jpg)
Delegating Proxy
Real Subject Class
Subject Interface
implements
Proxy Class
HAS_A implements
![Page 95: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/95.jpg)
Inheritance vs. Delegation
Real Subject Class Subject Interfaceimplements
Proxy Class
HAS-A implements
Real Subject Class Subject Interfaceimplements
Proxy Class
IS-A
![Page 96: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/96.jpg)
OMT (Object Modeling Technique)
Real Subject Class Subject Interfaceimplements
Proxy Class
HAS-A implements
Real Subject Class Subject Interfaceimplements
Proxy Class
IS-A
![Page 97: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/97.jpg)
Added notation of implements
Real Subject Class Subject Interfaceimplements
Proxy Class
HAS-A implements
Real Subject Class Subject Interfaceimplements
Proxy Class
IS-A
![Page 98: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/98.jpg)
Inheritance vs. Delegation
Reused Class Reused Interface
Reusing Class Reusing Interface
Reused Class Reused Interface
Reusing Class Reusing Interface
![Page 99: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/99.jpg)
Inheritance vs. Delegation: Instances
Reused Class
Reusing Class
Reused Class
Reusing Class
instance
instance
instance
Physical component
![Page 100: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/100.jpg)
Asserting Proxy Class
package models;import assertions.AnAsserter;public class ACheckedCounter extends ACounter {
public void add (int amount) {int oldCounter = counter;super.add(amount);AnAsserter.assert(counter == oldCounter + amount,
"New counter:" + counter + " != old counter:" + oldCounter + " + amount:" + amount);
}}
![Page 101: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/101.jpg)
Delegating Proxy-based Counterpackage models;import assertions.AnAsserter;public class ADelegatingCheckedCounter implements Counter {
Counter counter; public ADelegatingCheckedCounter (Counter theCounter) {
counter = theCounter;}public void add (int amount) {
int oldVal = counter.getValue();counter.add(amount);int newVal = counter.getValue();AnAsserter.assert(newVal == oldVal + amount,
"New counter:" + newVal + " != old counter:" + oldVal + " + amount:" + amount);
}public int getValue() {
return counter.getValue()b;}
}
![Page 102: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/102.jpg)
Inheritance vs. Delegation: Init methods/Constructor
Reused Class
Reusing Class
Reused Class
Reusing Class
declares
Constructor/init (delegate, …)
declares
Constructor/init (…)
![Page 103: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/103.jpg)
Inheritance vs. Delegation: Super calls
Reused Class
Reusing Class
Reused Class
Reusing Class
declares Reused method m
Reused method m
declares
declaresMethod n
super.m()
Method n
delegate.m()
declares
![Page 104: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/104.jpg)
Asserting Proxy Class
package models;import assertions.AnAsserter;public class ACheckedCounter extends ACounter {
public void add (int amount) {int oldCounter = counter;super.add(amount);AnAsserter.assert(counter == oldCounter + amount,
"New counter:" + counter + " != old counter:" + oldCounter + " + amount:" + amount);
}}
![Page 105: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/105.jpg)
Delegating Proxy-based Counterpackage models;import assertions.AnAsserter;public class ADelegatingCheckedCounter implements Counter {
Counter counter; public ADelegatingCheckedCounter (Counter theCounter) {
init(theCounter);}public void add (int amount) {
int oldVal = counter.getValue();counter.add(amount);int newVal = counter.getValue();AnAsserter.assert(newVal == oldVal + amount,
"New counter:" + newVal + " != old counter:" + oldVal + " + amount:" + amount);
}public int getValue() {
return counter.getValue();}
}
![Page 106: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/106.jpg)
Inheritance vs. Delegation: Reused Methods
Reused Class
Reusing Class
Reused Class
Reusing Class
declares Reused method m
Reused method m
declares
m stub
delegate.m()
declares
Delegation is more work!
![Page 107: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/107.jpg)
public abstract class AnAbstractTitleToCourseMapper implements TitleToCourseMapper {public AnAbstractTitleToCourseMapper() {
fillCourses();}abstract RegularCourse getRegularCourse();abstract FreshmanSeminar getFreshmanSeminar();void fillCourses() {
RegularCourse introProg = getRegularCourse ();FreshmanSeminar legoRobots = getFreshmanSeminar();...
}public String getTitle() {
return titleToCourseMapper.getTitle();}...
}
Abstract class
![Page 108: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/108.jpg)
Concrete course userpublic class ATitleToCourseMapper extends AnAbstractTitleToCourseMapper {
RegularCourse getRegularCourse() {return new ARegularCourse();
}FreshmanSeminar getFreshmanSeminar() {
return new AFreshmanSeminar();}
}
![Page 109: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/109.jpg)
Delegate classpublic class ATitleToCourseMapperDelegate implements TitleToCourseMapper {
CourseFactory delegator;public ATitleToCourseMapperDelegate(CourseFactory theDelegator) {
delegator = theDelegator;fillCourses();
}void fillCourses() {
RegularCourse introProg = delegator.getRegularCourse ();FreshmanSeminar legoRobots = delegator. getFreshmanSeminar(); ...
}public String getTitle() {
return titleToCourseMapper.getTitle();}...
}
![Page 110: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/110.jpg)
Concrete course user
public class ATitleToCourseMapperDelegator implements TitleToCourseMapper, CourseFactory {
public RegularCourse getRegularCourse() {return new ARegularCourse();
}public FreshmanSeminar getFreshmanSeminar() {
return new AFreshmanSeminar();}public String getTitle() {
return titleToCourseMapper.getTitle();}...
}
![Page 111: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/111.jpg)
Inheritance vs. Delegation: Callbacks
Reused Class
Reusing Class
Reused Class
Reusing Class
declaresReused
method m
Reused method m
declares
declaresMethod n
this.n()
declaresMethod n
with possibly
more access
delegator.n()
Abstract or OverriddenMethod n
![Page 112: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/112.jpg)
Calls vs. Callbacks
• Calls– calls from reusing class to reused class
• Callbacks– calls from reused class to reusing class.– not to implement a symbiotic relationship– done to service calls
![Page 113: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/113.jpg)
Inheritance vs. Delegation: Constructors/Init methods for callbacks
Reused Class
Reusing Class
Reused Class
Reusing Class
declares
declares Constructor/init (delegator, …)
Constructor/init (…)
![Page 114: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/114.jpg)
Access problems
• Occur with callbacks.
• And if reusing class accesses variables of reused class
![Page 115: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/115.jpg)
Inheriting String Databasepackage collections;public class AStringDatabase extends AStringHistory implements StringDatabase {
public void deleteElement (String element) {shiftUp(indexOf(element));
}public int indexOf (String element) {
int index = 0;while ((index < size) && !element.equals(contents[index]))
index++;return index;
}void shiftUp (int startIndex) {
int index = startIndex ;while (index + 1 < size) {
contents[index] = contents[index + 1];index++;
}size--;
}public boolean member(String element) {
return indexOf (element) < size;}public void clear() {
size = 0;}
}
![Page 116: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/116.jpg)
Delegating String Setpackage collections;import enums.StringEnumeration;public class ADelegatingStringDatabase implements StringDatabase {
AStringHistory stringHistory = new AStringHistory();public void deleteElement (String element) {
shiftUp(indexOf(element));}public int indexOf (String element) {
int index = 0;while ((index < stringHistory.size) && !
element.equals(stringHistory.contents[index])) index++;
return index;}void shiftUp (int startIndex) {
int index = startIndex ;while (index + 1 < stringHistory.size) {
stringHistory.contents[index] = stringHistory.contents[index + 1];index++;
}stringHistory.size--;
}
Class as type and accessing
non public variables in
same package
Instantiating delegate rather than
getting reference from constructor.init
method
![Page 117: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/117.jpg)
Delegating String Set
public boolean member(String element) {return indexOf (element) < stringHistory.size;
}public void clear() {
stringHistory.size = 0;}public int size() {
return stringHistory.size();}public String elementAt (int index) {
return stringHistory.elementAt(index);}public StringEnumeration elements() {
return stringHistory.elements();}public void addElement(String element) {
stringHistory.addElement(element);}
}
Large number of forwarding
stubs
![Page 118: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/118.jpg)
Access issues• Callbacks methods
– must be given public access if interface types the delegator.
– can be given protected or default access– but requires class types, delegator and delegator
class in same package
• May need to give access to reused class variables also– through public methods– or putting delegate and delegator in same
package, giving them protected/default access and using class as type
![Page 119: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/119.jpg)
Cons of Delegation
• Need to instantiate multiple classes.
• Need to compose instances.
• Need to define stub methods
• Access problems
![Page 120: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/120.jpg)
Pros of Delegation
Reused Class Reused Interface
Reusing Class Reusing Interface
Reused Class Reused Interface
Reusing Class Reusing Interface
![Page 121: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/121.jpg)
Substituting Reused Class
Reused Class 2 Reused Interface
Reusing Class 2 Reusing Interface
Reused Class 2 Reused Interface
Reusing Class Reusing Interface
![Page 122: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/122.jpg)
Substituting Reused Class
• Another implementation of reused interface– in inheritance requires another implementation
of reusing class that duplicates methods of original reusing class.
– In delegation simply requires a different object to be passed to constructor
![Page 123: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/123.jpg)
New Inheriting Proxy Class
package models;import assertions.AnAsserter;public class ACheckedCounter2 extends ACounter2 {
public void add (int amount) {int oldCounter = counter;super.add(amount);AnAsserter.assert(counter == oldCounter + amount,
"New counter:" + counter + " != old counter:" + oldCounter + " + amount:" + amount);
}}
![Page 124: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/124.jpg)
Orginal Delegating Proxypackage models;import assertions.AnAsserter;public class ADelegatingCheckedCounter implements Counter {
Counter counter; public ADelegatingCheckedCounter (Counter theCounter) {
counter = theCounter;}public void add (int amount) {
int oldVal = counter.getValue();counter.add(amount);int newVal = counter.getValue();AnAsserter.assert(newVal == oldVal + amount,
"New counter:" + newVal + " != old counter:" + oldVal + " + amount:" + amount);
}public int getValue() {
return counter.getValue();}
}
![Page 125: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/125.jpg)
Reused Class
Reusing Class 1
Reused Class
Reusing Class 2
Reusing Class 2
Reusing Class 1
Multiple Reusing Classes• Inheritance
– each possible combination of reusing classes bound at compile time
– Duplicates code
• Delegation– can be changed
dynamically
![Page 126: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/126.jpg)
AConsoleControllerAndViewAndJOptionViewAConsoleControllerAndView
ACounterJOptionView
Delegation-based MVC
ACheckedCounter
ACounterController ACounterConsole View
![Page 127: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/127.jpg)
Inheritance-based MVCACounter
ACounterWithConsoleAndJOptionViewAndController
ACounterWithConsoleView
ACounterWithConsoleAndJOptionView
No facades or notification needed
![Page 128: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/128.jpg)
Controller with Console View
package views;import models.ACounter;public class ACounterWithConsoleView extends ACounter {
void appendToConsole(int counterValue) {System.out.println("Counter: " + counterValue);
}public void add (int amount) {
super.add(amount);appendToConsole(getValue());
}}
![Page 129: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/129.jpg)
Controller with Console and JOption View
package views;import models.ACounter;import javax.swing.JOptionPane;public class ACounterWithConsoleAndJOptionView extends ACounterWithConsoleView {
void displayMessage(int counterValue) {JOptionPane.showMessageDialog(null, "Counter: " +
counterValue);}public void add (int amount) {
super.add(amount);displayMessage(getValue());
}}
![Page 130: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/130.jpg)
Controller with Console and JOption View and Controller
package controllers; import views.ACounterWithConsoleAndJOptionView;import java.io.IOException;public class ACounterWithConsoleAndJOptionViewAndController extends ACounterWithConsoleAndJOptionView implements CounterWithConsoleViewAndController {
public void processInput() {while (true) {
int nextInput = Console.readInt();if (nextInput == 0) return;add(nextInput);
}}
}
![Page 131: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/131.jpg)
AConsoleControllerAndView
Alternative: Delegation-based Configuration
AnObservableCounter
ACounterController ACounterConsole View
ACounterJOptionView
![Page 132: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/132.jpg)
Alternative: Inheritance-based MVCACounter
ACounterWithConsoleViewAndController
ACounterWithConsoleView
New class
![Page 133: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/133.jpg)
Controller with Console and View and Controller
package controllers; import views.ACounterWithConsoleAndJOptionView;import java.io.IOException;public class ACounterWithConsoleViewAndController extends ACounterWithConsoleView implements CounterWithConsoleViewAndController {
public void processInput() {while (true) {
int nextInput = Console.readInt();if (nextInput == 0) return;add(nextInput);
}}
}
Only difference between it and previous inheriting
controller
![Page 134: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/134.jpg)
Inheritance vs. Delegation: Distribution
Reused Class
Reusing Class
Reused Class
Reusing Class
instance
instance
instance
Data and methods of both
classes at one location
Can be in two different locations
(client/server)
![Page 135: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/135.jpg)
Reused Class 1
Reusing Class
Reused Class 1
Reusing Class
Reused Class 2
Reused Class 1
Reusing multiple classes• In Java reusing
multiple classes through inheritance not an option.
• Can always have multiple instance variables
![Page 136: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/136.jpg)
Pros and Cons of Delegation• Can change reused class
without changing reusing class.
• Multiple reusing classes can share reused class variables simultaneously.
• Variables and methods of reusing and reused class can be on separate computers.
• Works in single inheritance languages
• Need to instantiate multiple classes.
• Need to compose instances.
• Need to define stub methods
• Access problems
Need to weigh pros and cons
When benefits of delegation don’t apply use inheritance
That is why inheritance exists.
![Page 137: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/137.jpg)
Inheritance is a bad idea• If reusing class has “with” in its name:
– ACounterWithConsoleView
• If more than one way to do inheritance– Controller can be subclass of view– Or vice versa
• If some of the inherited methods are not used:– AStringHistory extends Vector
• Adds methods to add and access string elements rather than object elements
• addString(), stringAt()
– does not use removeElement() etc
• If reusing class should not be used wherever shared class is used– even if all methods are reused.
![Page 138: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/138.jpg)
Inheritance is a bad ideapublic ACartesianPoint implements Point { int x, y; public APoint(int theX, int theY) { x = theX; y = theY;} public int getX() { return x } public int getY() { return y } public double getRadius() { return Math.sqrt(x*x + y*y); } .public double getAngle() { return Math.atan(y/x);}}
public ASquare extends ACartesianPoint implements Square { int sideLength; public ASquare (int theX, int theY, int theSideLength) { x = theX; y = theY; sideLength = theSideLength} public int getSideLength() {return sideLength};}
public ASquare implements Square { Point center; int sideLength; public ASquare( Point theCenter, int theSideLength) { center = theCenter;sideLength = theSideLength; } public int getX() {return center.getX();} public int getY() {return center.getY();} public int getRadius() {return center.getRadius();} public int getAngle() {return center.getAngle();} public int getSideLength() {return sideLength;}}
ASquare IS-NOT-A
ACartesianPoint!
![Page 139: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/139.jpg)
Inheritance vs. Delegation in Popular Software: Toolkits
Widget Class
Widget User
Widget Class
Widget User
declares
declares
super call
delegate call
declares
declaresAction Performed
Action Performed
Action Performed
Action Performed
Java 1.0
Later versions
![Page 140: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/140.jpg)
Inheritance vs. Delegation in Popular Software• Main problem with inheritance based widgets
– Widget users could not be subclass of any other class because of multiple inheritance
• Multiple objects can receive events from same widget.
• Widget implementation can be switched• Observer concept supports both approaches
– Inherited Observer class vs. Delegated PropertyChangeSupport
• Threads support both approaches– Inheritable Thread class vs. Implemented Runnable
Interface
![Page 141: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/141.jpg)
The Importance of Being Earnestpublic class ABankAccount implements BankAccount {
int currentBalance = 0;public static final int MIN_BALANCE = 100;public ABankAccount (int initialBalance) {
currentBalance = initialBalance;}public void deposit (int amount) {
currentBalance += amount;}public boolean withdraw (int amount) {
int minNecessaryBalance = MIN_BALANCE + amount;if (minNecessaryBalance <= currentBalance) {
currentBalance -= amount;return true;
}else return false;
}public int getCurrentBalance () {
return currentBalance;}public boolean safeWithdraw (int amount) { AnAsserter.assert(amount > 0, "amount < 0"); boolean retVal = withdraw(amount); AnAsserter.assert(currentBalance >= MIN_BALANCE, "currentBalance < MIN_BALANCE"); return retVal;}
}
![Page 142: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/142.jpg)
Usage
![Page 143: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/143.jpg)
Usage
![Page 144: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/144.jpg)
Usage
Integer.MAX_INT
![Page 145: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/145.jpg)
Usage
![Page 146: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/146.jpg)
Usage
![Page 147: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/147.jpg)
Safe Usage
![Page 148: Assertions Prasun Dewan Comp 114. Assertions Declare some property of the program Potentially useful for –specification –testing –formal correctness –documentation](https://reader030.vdocuments.us/reader030/viewer/2022032800/56649d3a5503460f94a15112/html5/thumbnails/148.jpg)
Integer Overflow
and Security
• Google for “integer overflow security”