Re: [RFC] Guard statement
| From: | Mike Schinkel | Date: | Sat, 16 May 2020 22:40:45 +0000 |
| Subject: | Re: [RFC] Guard statement | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-110195@lists.php.net to get a copy of this message | ||
> On May 16, 2020, at 5:13 AM, Pavel Patapau <algerd.blr@gmail.com> wrote:
>
> Hello everyone,
>
> I want to propose new syntax addition - guard statement, that executes code only if expression
> equals false and must contain control-flow changing code, and written a respective RFC:
>
> https://wiki.php.net/rfc/guard_statement
> <https://wiki.php.net/rfc/unbundle_xmlprc>
>
> Implementation in progress.
>
> I started work before this proposal
> https://externals.io/message/110107 and respected some moments in
> the RFC.
>
>
> Thanks for consideration,
> Pavel
Many others have already made comments that I agree with so won't echo as they have already
been said.
Two points:
1. That adding a
guard would make it a reserved word is of significant concern to me,
and looking at your examples I would ask why not simply ask that the if statement be able to omit
the "true" block which could accomplish the same w/o needing to add another reserved word?
e.g.
if (condition) else {
//this code executed only if condition equals false
return|throw|goto;
//or
continue | break(in loop context only);
}
// in loop context - valid code
while (condition){
if (condition) else {
break; //valid
}
}
Alternately, why not simply use what we already have, and what I do often, invert the condition?
if ( ! condition) {
//this code executed only if condition equals false
return|throw|goto;
//or
continue | break(in loop context only);
}
// in loop context - valid code
while (condition){
if ( ! condition ) {
break; //valid
}
}
Secondly, you reference this essay[1] which mentions why multiple returns are a bad idea, yet your
proposal seems to want to encourage people to write more early returns, not fewer.
Regarding the multiple returns, consider the following, using an if(condition)else{} syntax AND
assuming that we could add support for try{} without being required to use a catch():
function example() {
try {
$value = null;
if (condition1) else {
break;
}
if (condition2) else {
break;
}
if (condition3) else {
break;
}
$value = do_work();
}
return $value;
}
-Mike
[1] https://medium.com/@scadge/if-statements-design-guard-clauses-might-be-all-you-need-67219a1a981a