I am trying to understanding a little best the Class Invariances used by Liskov Principle.
I know that some languages like D have native support to invariant, but, using asserts in PHP I've tried combining magic methods and assert:
<?php
class Person {
protected string $name;
protected string $nickName;
protected function testContract(){
assert(($this->name != $this->nickName));
}
public function __construct(string $name, string $nickName){
$this->name = $name;
$this->nickName = $nickName;
}
public function __set($name, $value){
$this->testContract();
$this->$name = $value;
}
public function __get($name){
$this->testContract();
return $this->$name;
}
}
class GoodPerson extends Person {
public function getFullName(){
return $this->name." ".$this->nickName. "!!!";
}
}
class BadPerson extends Person {
protected function testContract(){
assert(($this->name != ""));
}
}
$gp = new GoodPerson("João", "Joãozinho");
echo $gp->nickName;
echo $gp->getFullName();
$bp = new BadPerson("João", "João");
echo $bp->nickName;
- Can I use assert to create a Contract?
- Is BadPerson a valid example to Liskov's Class Invariance violation on inheritance ?
- Is GoodPerson a valid example to Liskov's Classe Invariance?