amana2
Posts by :
Liskov Substitution Principle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
// Example of violation of LSP class Rectangle { public int setWidth(int a) { width = a; } public int setHeight(int a) { height = a; } public int area { return (width * height); } } class Square extends Rectangle { public int setWidth(int a) { width = height = a; } public int setHeight(int a) { width = height = a; } } class RectangleTest { /* * This test fails for objects of class Square because they do not * respect the semantics of the setWidth and setHeight operations * in the superclass. */ @Test public void testArea(Rectangle r) { r.setWidth(2); r.setHeight(5); assert(r.area() == 2*5); } } /* * "Fixing" the test method through violation of OCP: */ @Test public void testArea(Rectangle r) { if (r instaceOf Rectangle) { r.setWidth(2); r.setHeight(5); assert(r.area() == 2*5); } } /* * As we have seen, the problem is not easy to solve, but most * important, it is originated by a wrong understanding of the * generalization relation. No matter how similar two objects look * in the real world, the generalization is applied to their computer * representation (e.g. class). Consequently, it only makes sense to * use generalization when the subclass will correspond to the semantics * of the superclass. Otherwise, it is better to use two separate classes. * * We could even force their relation in some cases by using a more * complex class structure, but we must bear in mind that having those * classes related may not be worth the complexity. */ public abstract class Rectangle { public int area { return (width * height); } } class PureRectangle extends Rectangle { public int setWidth(int a) { width = a; } public int setHeight(int a) { height = a; } } class Square extends Rectangle { public int setSide(int a) { width = height = a; } } /* * Now, client classes of the Rectangle class can only expect the semantics * of the area operation of the subclasses of Rectangle to be consistent with * the Rectangle specification. * * On the other hand, clients of each subclass will not have any problem with * semantics of the other subclass. */ |