Created
March 8, 2012 03:11
-
-
Save zymsys/1998331 to your computer and use it in GitHub Desktop.
Rectangle / Square LSP Example Violation in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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