90 likes | 177 Views
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
E N D
Computer Science 340Software 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 • DBC leads to a better understanding of inheritance, and helps us apply it more effectively
Inheritance & DBC INVA PREA.R A Client R POSTA.R A a = new A(); a.R();
Inheritance & DBC INVA PREA.R A Client R POSTA.R INVB ? PREB.R B R POSTB.R A a = new B(); a.R();
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
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.Rlogically implies PREB.R
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
Another example • Stack example
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.