Re: [RFC] Reclassifying engine warnings
| From: | Rowan Tommins | Date: | Thu, 12 Sep 2019 20:45:43 +0000 |
| Subject: | Re: [RFC] Reclassifying engine warnings | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-107018@lists.php.net to get a copy of this message | ||
On 12/09/2019 15:43, Robert Korulczyk wrote:
One additional line will make your code much more obvious and easier to read and understand: $i ??= 0; $i++;I don't find this code at all obvious: foreach ( $something as $foo ) {
$i ??= 0; $i++;} I mean, huh? What's that zero doing there, is it resetting the variable every loop? Now, in that simple case, you can and probably should initialise the counter before the loop: $i=0; foreach ( $something as $foo ) {
$i++;} But that's not the example I gave earlier! The example I gave earlier was a multi-dimensional array: $foo = []; foreach ( $something as $key1 ) {
foreach ( $somethingElse as $key2 ) {
$foo[$key1][$key2]++;
}
}
Even using ??= the initialise-everything-before-use version looks like this:
$foo = [];
foreach ( $something as $key1 ) {
foreach ( $somethingElse as $key2 ) {
$foo[$key1] ??= [];
$foo[$key1][$key2] ??= 0;
$foo[$key1][$key2]++;
}
}
Again, the values are confusing: the end result will never contain an empty array at the first level, and will never contain a 0 at the second level.
Those two lines aren't aiding the readability of that algorithm in any way; I have to read past them to find the actual business of the loop, which is counting something, using the ++ operator.
What's more, they're not preventing any bugs either! If I accidentally reuse $foo from a previous loop, the extra lines won't reinitialise anything for me; if I initialise it to empty, the two loops are functionally identical.
So that's where I came up with two suggestions to actually add to the language, rather than just taking away:
- a more granular way to express that this code is not actually error-prone, combining the 3 lines back into one
- or, a way to express the intent of the code more clearly, such as declaring the shape of an array
Regards,
--
Rowan Tommins (né Collins)
[IMSoP]