computer science 340 software design & testing

9
1 Computer Science 340 Software Design & Testing Inheritance & Design By Contract

Upload: baxter-mcgee

Post on 02-Jan-2016

28 views

Category:

Documents


0 download

DESCRIPTION

Computer Science 340 Software Design & Testing. Inheritance & Design By Contract. Inheritance & DBC. Our previous treatment of DBC ignored inheritance Now that you’ve had time to internalize DBC, let’s throw inheritance into the mix - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Computer Science 340 Software Design & Testing

1

Computer Science 340

Software Design & Testing

Inheritance & Design By Contract

Page 2: Computer Science 340 Software Design & Testing

2

Inheritance & DBC

• Our previous treatment of DBC ignored inheritance

• Now that you’ve had time to internalize DBC, let’s throw inheritance into the mix

• DBC leads to a better understanding of inheritance, and helps us apply it more effectively

Page 3: Computer Science 340 Software Design & Testing

3

Inheritance & DBC

Client A R

INVA

PREA.R

POSTA.R

A a = new A();a.R();

Page 4: Computer Science 340 Software Design & Testing

4

Inheritance & DBC

Client A R

INVA

PREA.R

POSTA.R

B R

INVB

PREB.R

POSTB.R

?

A a = new B();a.R();

Page 5: Computer Science 340 Software Design & Testing

5

Inheritance & DBC

• Conceptually, B’s implementation must honor A’s contract; otherwise, clients will break when using a B instead of an A

• B can provide a “better” implementation than A, but not a “worse” one

• What do “better” and “worse” mean?– Square root example

Page 6: Computer Science 340 Software Design & Testing

6

Subclasses can be less strict, but not more strict

• B can be less strict on clients than A, but not more strict

• B can weaken R’s pre-conditions– PREB.R can place fewer requirements on clients

than PREA.R, but not more– PREB.R <= PREA.R

– PREA.R logically implies PREB.R

Page 7: Computer Science 340 Software Design & Testing

7

Subclasses can do more,but not less

• B’s behavior must be consistent with A’s contract• B can do better than A, but not worse

• B can strengthen R’s post-conditions, but not weaken– POSTB.R can promise more to clients than POSTA.R, but not less– POSTB.R >= POSTA.R

– POSTB.R logically implies POSTA.R

• B can strengthen A’s class invariants, but not weaken– INVB can promise more to clients than INVA, but not less– INVB >= INVA

– INVB logically implies INVA

Page 8: Computer Science 340 Software Design & Testing

8

Another example

• Stack example

Page 9: Computer Science 340 Software Design & Testing

9

Liskov Substitution Principle

• Let q(x) be a property provable about objects x of type T. Then q(y) should be true for objects y of type S where S is a subtype of T.