On 16/05/2020 10:13, Pavel Patapau wrote:
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
Hi Pavel,
This certainly seems to be a "problem space" which several people want
to explore, but I'm not quite convinced by any of the proposals so far.
I read through the links in your RFC, and a few articles about Swift's
"guard" syntax, and have a few observations:
* An important defining feature of a guard clause is that it occurs
*before* any of the logic of the function. Some languages have syntax to
codify that, putting guards or pre-conditions as part of the function's
header, rather than in its body.
* Another defining feature is that guard clauses should be simple,
getting easy cases out of the way early. Having "guard ... else" take a
whole block of statements, including other flow control, makes it feel
less like a guard clause, and more like normal flow control.
* Swift's "guard" clause is used for assertions which affect the static
analysis of the code. Most notably, "guard let x else { return; }" can
be used to check an Optional value, and the compiler will allow that
value to be used in the rest of the function without further
"unwrapping". That explains the requirement that the guard clause aborts
the flow of the function (including calling a function with a "Never"
return type, as John Bafford points out). There's not really any
equivalent of that in PHP, so including similar limitations feels rather
arbitrary.
* As with Ralph Schindler's e-mail, Perl and Ruby are being slightly
misrepresented here: they don't have explicit syntax for guard clauses
per se, they just have more ways of spelling "if", which is useful for
making guard clauses read nicely; that includes "unless", which just
means "if not".
Regarding the specific syntax, I agree with others that "guard something
else return" doesn't read particularly naturally, although opinions may
differ here - I found one blog post about Swift saying:
> It’s easiest to read the above code as: /“Guard that/ number /is
greater than or equal to zero, or else, return nil.”/ See how that reads
quite naturally?
[Reinder de Vries -
https://learnappmaking.com/swift-guard-let-statement-how-to/]
One thing I'd like to see on proposals like this is more explicit
examples comparing to current language features. For instance, why would
(or shouldn't) someone use:
* "guard( condition ) else { throw new Exception; }" instead of "assert(
condition );"?
* "guard ( condition ) else { return; }" instead of "if ( ! condition )
return;"?
* "guard ( condition ) { complex logic }" instead of "if ( ! condition )
{ complex logic }"?
Regards,
--
Rowan Tommins (né Collins)
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php