Skip to content

Instantly share code, notes, and snippets.

@zymsys
Created March 8, 2012 03:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zymsys/1998331 to your computer and use it in GitHub Desktop.
Save zymsys/1998331 to your computer and use it in GitHub Desktop.
Rectangle / Square LSP Example Violation in PHP
<?php
class Rectangle
{
private $_width;
private $_height;
public function getWidth()
{
return $this->_width;
}
public function setWidth($width)
{
$this->_width = $width;
}
public function getHeight()
{
return $this->_height;
}
public function setHeight($height)
{
$this->_height = $height;
}
}
class Square extends Rectangle
{
public function setWidth($width)
{
parent::setWidth($width);
parent::setHeight($width);
}
public function setHeight($height)
{
parent::setWidth($height);
parent::setHeight($height);
}
}
class LSPRectangeTest extends PHPUnit_Framework_TestCase
{
private function areaTest(Rectangle $rectangle)
{
$width = 5;
$height = 4;
$rectangle->setWidth($width);
$rectangle->setHeight($height);
$actualArea = $rectangle->getWidth() * $rectangle->getHeight();
$expectedArea = $width * $height;
$this->assertEquals($expectedArea, $actualArea);
}
public function testRectangleArea()
{
$rectangle = new Rectangle();
$this->areaTest($rectangle);
}
public function testSquareArea()
{
$square = new Square();
$this->areaTest($square);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment