mituri

SOLID liskov subtitute principle

Feb 14th, 2021 (edited)
561
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Liskov subsitution principle */
  2.  
  3. /*
  4. derived(pochodne) objects must be subtitutable (zastępowalne) for their base
  5. in renderLargeRectangles() for square we passed setWidth(4) and next setHeight(5) overwrites width&height. This would work for rectangles but not for squares.
  6. So you cant really substitute square for rectangles
  7.  
  8. /* Projektując hierarchię klas, należy zrobić to tak, aby każda klasa pochodna mogła wykorzystywać wszystkie metody klasy bazowej bez konieczności ich przesłaniania. */
  9.  
  10. in GOOD soulution you can subtitute Square and Rectangle with Shape class
  11. */
  12.  
  13. class Rectangle {
  14.     constructor() {
  15.     this.width = 0;
  16.     this.height = 0;
  17.   }
  18.  
  19.   setColor(color) {
  20.     // ...
  21.   }
  22.  
  23.   render(area) {
  24.     // ...
  25.     console.log(area)
  26.   }
  27.  
  28.   setWidth(width) {
  29.     this.width = width
  30.   }
  31.  
  32.   setHeight(height) {
  33.     this.height = height
  34.   }
  35.  
  36.   getArea() {
  37.     return this.width * this.height
  38.   }
  39. }
  40.  
  41. class Square extends Rectangle {
  42.    setWidth(width) {
  43.     this.width = width;
  44.     this.height = width;
  45.   }
  46.  
  47.   setHeight(height) {
  48.     this.width = height;
  49.     this.height = height
  50.   }
  51. }
  52.  
  53. function renderLargeRectangles(rectangle) {
  54.     rectangles.forEach(rectangle => {
  55.     rectangle.setWidth(4);
  56.     rectangle.setHeight(5);
  57.    
  58.     const area = rectangle.getArea(); // BAD: returns 25 for Square, should be 20
  59.     rectangle.render(area)
  60.   })
  61. }
  62.  
  63. const rectangles = [new Rectangle(), new Rectangle(), new Square()];
  64. renderLargeRectangles(rectangles)
  65.  
  66.  
  67.  
  68. /* GOOD */
  69. class Shape {
  70.     setColor(color) {
  71.     //...
  72.   }
  73.  
  74.   render(area) {
  75.     //...
  76.   }
  77. }
  78.  
  79. class Rectangle extends Shape {
  80.     constructor(width, height) {
  81.     super();
  82.     this.width = width;
  83.     this.height = height;
  84.   }
  85.  
  86.   getArea() {
  87.     return this.width * this.height;
  88.   }
  89. }
  90.  
  91. class Square extends Shape {
  92.     constructor(length) {
  93.     super();
  94.     this.length = length;
  95.   }
  96.  
  97.   getArea() {
  98.     return this.length * this.length;
  99.   }
  100. }
  101.  
  102. function renderLargeShapes(shapes) {
  103.     shapes.forEach(shape => {
  104.     const area = shape.getArea();
  105.     shape.render(area);
  106.   })
  107. }
  108.  
  109. const shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)]
Add Comment
Please, Sign In to add comment