Re: Proposal For Return-If / Early Return / Guard Clause Syntax
| From: | John Bafford | Date: | Sun, 10 May 2020 20:00:16 +0000 |
| Subject: | Re: Proposal For Return-If / Early Return / Guard Clause Syntax | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-110117@lists.php.net to get a copy of this message | ||
Benas,
> On May 10, 2020, at 15:19, Benas IML <benas.molis.iml@gmail.com> wrote:
>
> Hello,
>
> I think that we SHOULD not introduce a new keyword (e. g. guard) since that
> would be a "major major" backwards incompatibility. "Guard" is a really
> generic
> word and a great example of that is Laravel and their authentication guards.
>
> In general, I don't think that early returns require a seperate syntax and/or
> block statement since a simple
if (...) { return; } is already
> sufficient
> enough.
>
> Best regards,
> Benas Seliuginas
I think there's three main reasons for guard, as opposed to if:
1) It further and clearly establishes intent: if you see guard, you have more information about the
programmer's intent and what the code will actually do.
2) It prevents having to negate the condition: guard (is valid) else, instead of if (not valid)
then; negations impose additional cognitive load when attempting to understand code, especially if
your condition already has a negation.
3) The language provides a guarantee that if the guard condition is not met, execution can not
proceed past the else clause. This helps prevent accidental fall-through, such as if you wrote:
if(!$valid) { terminate(); } expecting it to end execution (e.g. via a throw or exit), but for some
reason it failed to do so.
To take an idea from Ralph's original proposal, perhaps some syntax like "if guard
(condition) else ...". In this context, guard could not possibly be confused with a function
from the parser's point of view, instead serving as an intent modifier to if.
-John