Re: Design by Contract

From: Date: Thu, 05 Feb 2015 12:13:45 +0000
Subject: Re: Design by Contract
References: 1  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
On Thursday 05 February 2015 15:14:04 Dmitry Stogov wrote:
>
> function foo()
>     requre(<input-assert-expression>)
>     ensure(<output-assert-expression>)
> {
>   ...
> }
> 
> It would require only one new reserved word "ensure".

Regarding syntax.... This could be another place where the irrationally-
dreaded declare would make sense:

function foo() {
    declare(pre) {
      if (whatever...) return false;
      // arbitrary PHP code
    }
    declare(post=$resultvar) {
      if ($resultvar == XXX) return true;
      return false;
    }
}

This way, no new reserved words are needed at all, and the programmer can give 
a name to the "variable that holds the result" locally to avoid clashes with 
anything else in the function.

I'm a bit undecided whether returning true/false there to give the verdict, 
would be the best way. Maybe better would be another use for declare, without 
a block, to declare that the pre/postcondition failed - giving a nice place to 
put a suitable message, too. And again without introducing any extra keywords:

function foo() {
    declare(post=$resultvar) {
        if ($resultvar == XXX) declare(fail="My $resultvar looks fishy");
    }
}
    
best regards
  Patrick


Thread (220 messages)

« previous php.internals (#81906) next »