Re: Design by Contract
| From: | Yasuo Ohgaki | Date: | Sat, 14 Feb 2015 22:53:55 +0000 |
| Subject: | Re: Design by Contract | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-82705@lists.php.net to get a copy of this message | ||
Hi Robert,
D and PHP differs a lot with respect to types. D is very strongly typed
while PHP is very weakly typed.
Therefore, we need a little different approach.
On Sat, Feb 14, 2015 at 8:06 PM, Robert Stoll <php@tutteli.ch> wrote:
> The theory is actually quite simple. Roughly it says that if you use a
> type hint of a certain class then you can rely on all pre/post-conditions
> of this class even if a sub-class is passed. Hence the sub-class cannot
> have more restrict conditions. Consider the following (no longer sure which
> syntax is the one you intend to use, so I just use pre and post):
>
> class A{
> function foo($x){
> pre($x > 100);
> }
> }
>
> class B extends A{
> function foo($x){
> pre($x > 50); // less restrictive, that's fine
> }
> }
>
> class C{
> function foo($x){
> pre($x > 150); //more restrictive that's not allowed
> }
> }
>
> function foo(A $a){
> $a->foo(101); // that is ok as long as LSP is not violated
> }
>
> foo(new A()); //that's fine
> foo(new B()); //fine as well
> foo(new C()); //nope, C violates LSP and thus will result in an error
>
Correct. D does not allow to change parents contract. D does fancy check
for "overridden" methods
so that child cannot change parent behavior. I agree this is correct for
type safety.
Since D is strongly typed, D has "overloading" and D user can get around
with the previous restriction
easily.
e.g. foo(x, y) in class B will ignore A::foo contract at all. Same applies
to type difference, since
this is what "overloading" is.
PHP is weakly typed. There is no point follow D principle for "overridden"
methods because PHP type
is weak and PHP does not have "overloading".
I think this answers to your question.
Regards,
P.S. Are we really going to consider strict type safety for PHP??
--
Yasuo Ohgaki
yohgaki@ohgaki.net