Skip to content

Instantly share code, notes, and snippets.

@netojoaobatista
Last active August 29, 2015 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save netojoaobatista/ad555702f637b277239b to your computer and use it in GitHub Desktop.
Save netojoaobatista/ad555702f637b277239b to your computer and use it in GitHub Desktop.
Violating LSP principle
<?php
require_once 'Rectangle.php';
require_once 'Square.php';
require_once 'TestRectangleArea.php';
$r = new Rectangle();
$s = new Square();
// This will work.
// Rectangle behaves as expected
$t = new TestRectangleArea();
$t->testRectangleCalcArea($r);
// This will not work and will throw an exception
// In Math, Square is a Rectangle, but the object Square does not behave as Rectangle
$t->testRectangleCalcArea($s);
<?php
class Rectangle
{
private $height;
private $width;
public function getHeight()
{
return (int) $this->height;
}
public function getWidth()
{
return (int) $this->width;
}
public function setHeight($height)
{
$this->height = (int) $height;
}
public function setWidth($width)
{
$this->width = (int) $width;
}
}
<?php
require_once 'Rectangle.php';
class RectangleArea
{
public function calcArea(Rectangle $rectangle)
{
return $rectangle->getWidth() * $rectangle->getHeight();
}
}
<?php
require_once 'Rectangle.php';
class Square extends Rectangle
{
public function setWidth($width)
{
parent::setWidth($width);
parent::setHeight($width);
}
public function setHeight($height)
{
parent::setHeight($height);
parent::setWidth($height);
}
}
<?php
require_once 'Rectangle.php';
require_once 'RectangleArea.php';
class TestRectangleArea
{
public function testRectangleCalcArea(Rectangle $rectangle)
{
$w = 10;
$h = 5;
$rectangle->setWidth($w);
$rectangle->setHeight($h);
$recArea = new RectangleArea();
if ($recArea->calcArea($rectangle) !== ($w * $h)) {
throw new Exception('Você violou Liskov');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment