WordPress-Coding-Standards icon indicating copy to clipboard operation
WordPress-Coding-Standards copied to clipboard

Core: Ban Yoda conditions, loose comparisons and assignments in conditions

Open jrfnl opened this issue 7 years ago β€’ 66 comments

Is your feature request related to a problem?

Yoda conditions are the practice to reverse how comparisons in conditions are written, having the value being compared to on the left hand of the condition and the variable on the right hand, to prevent accidentally assigning something to a variable in a condition.

// This condition:
if ( $variable === 'value' ) {}

// ...would be written like this in Yoda style:
if ( 'value' === $variable ) {}

// ... to prevent this:
if ( $variable = 'value' ) {}

The problem with this is that code readability is decreased significantly to prevent a beginner's mistake which shouldn't be made in the first place and the chances of which are small when using strict comparisons anyhow.

Now, the WordPress coding standards contains a few sniffs related to this:

  • Core: WordPress.PHP.YodaConditions (error) - demands the use of Yoda conditions as per the handbook. However, this sniff only looks at comparison operators, i.e. ==, ===, != and !==, not at assignment operators, like =, so in effect, it doesn't actually prevent assignments in conditions in the first place.
  • Extra: WordPress.CodeAnalysis.AssignmentInCondition (warning) - warns against assignments found in conditions of control structures as well as, in as far possible, assignments in the condition part of ternaries.
  • Extra: WordPress.PHP.StrictComparisons (warning) - warns against using loose comparisons.
  • Extra: WordPress.PHP.StrictInArray (warning) - warns against using loose comparisons in array comparison functions.

Note: none of these sniffs currently contain (auto-)fixers.

Describe the solution you'd like

At this moment, I'd like to propose the following:

  • Drop the handbook rule to demand Yoda conditions.
  • Remove the WordPress.PHP.YodaConditions sniff - both from the Core ruleset and from the repo (initially deprecated and emptied out, to be removed in the next major release).
  • Move the WordPress.CodeAnalysis.AssignmentInCondition sniff to the Core ruleset and change it from a warning to an error.
  • Move the WordPress.PHP.StrictComparisons and WordPress.PHP.StrictInArray sniffs to the Core ruleset, but leave these as a warning.

Impact

  • At this point, WPCS would have no opinion on whether or not to use Yoda conditions.
  • I expect that the WordPress.CodeAnalysis.AssignmentInCondition sniff would introduce a limited set of newly detected issues for the WP Core code.
  • I expect that the introduction of the WordPress.PHP.StrictComparisons and WordPress.PHP.StrictInArray sniffs would introduce a large number of new warnings for the WP Core code base.

Once these changes have been made to WPCS and Core has upgraded, contributors can be encouraged to start looking at the newly detected issues and to fix up the existing (non-strict) comparisons. This should be done carefully as changing the type of comparison is a behavioural change. It is recommended to make sure that all changes are covered by unit tests before making this type of change.

Next phase

As a next step, I'd like to propose the handbook to be adjusted to forbid Yoda conditions.

A new sniff will need to be written to detect the use of Yoda Conditions, throw an error and where possible, auto-fix this.

Alternatively it could be considered to add the Slevomat Coding Standard as a dependency to WPCS and use the existing sniff in that standard. The downsides of that would be:

  • A new external dependency making installation of WPCS with anything but Composer more fiddly.
  • No control over the sniff, making getting bugfixes and such accepted slightly more fiddly.

Additional context (optional)

Some discussion about this has been had in other channels. I'm quoting some relevant parts of that discussion here.

@jrfnl Regarding Yoda conditions - we've talked about this before. IMO this rule should be dropped in favour of the "No assignment in condition" rule and the associated sniff WordPress/Generic.CodeAnalysis.AssignmentInCondition which is currently in Extra should be moved to Core.

At the time you asked me to investigate whether there is a sniff available out there which could revert existing Yoda conditions. The answer to that is "Yes". The external Slevomat Coding Standard contains a sniff which can auto-fix Yoda to non-Yoda. Tests could (should) be run to see how well it works, but this sniff could be used in a one-time action to move away from Yoda. Note: if the sniff would not be good enough/would turn out to be buggy, I'm happy to contribute fixes to the Slevomat standard just to make moving away from Yoda possible.

Having said that, as the tooling is available which would allow us to move away from Yoda and still prevent assignments in conditions, I would strongly suggest now is a good time to take a decision on this.

Source: https://core.trac.wordpress.org/ticket/45934#comment:14

@pento Yah, I agree that WordPress/Generic.CodeAnalysis.AssignmentInCondition should be moved into Core, violations should be fixed, and then Yoda conditions should be removed. There's some discussion on #42885 about Yoda conditions, too.

Notably, the JS team are planning on removing guidance on Yoda conditions, I'm inclined to disallow Yoda conditions, rather than simply allow either style, though.

Source: https://core.trac.wordpress.org/ticket/45934#comment:15

Opinions ?

jrfnl avatar Jan 13 '19 12:01 jrfnl

I'm in favour of this change.

There are 559 violations of WordPress.CodeAnalysis.AssignmentInCondition in WordPress Core.

This seems like something that could be auto-fixed, though. Move the assignment to before the offending block, and replace the assignment in the condition to just the variable name.

For example:

if ( $foo = bar() ) {
	// ...
} elseif ( $baz = bat() ) {
	// ...
}

Would become:

$foo = bar();
$baz = bat();
if ( $foo ) {
	// ...
} elseif ( $baz ) {
	// ...
}

This could be a problem if bat() should only over be run if bar() returned something false-y, due to side-effects or whatever. Arguably such code is fundamentally broken, anyway. πŸ™‚

It would also break on this code:

if ( $foo = bar() ) {
	// ...
} elseif ( $foo = bat() ) {
	// ...
}

pento avatar Jan 14 '19 02:01 pento

@pento IMO assignments in condition should not be auto-fixed. A tool can not determine whether this is an assignment which should be moved out of the condition or an accidental assignment while a comparison was intended.

While I hope and presume that that last type doesn't exist in Core, we won't know for sure until we look at them.

Also, the complexity would be too high for an auto-fixer. Think:

if ( isset($foo) && ! ($bar = function_call($foo)) && $bar > 3) {}

Or:

while ( ($foo = function_call($bar)) !== false) {
    // Do something
}

Note: for assignments in while conditions, the sniff has a separate error code to allow selectively whitelisting those, as at times, that is a valid way of writing the code, though changing the code to a do {} while() or other type of control structure should probably be preferred.

jrfnl avatar Jan 14 '19 05:01 jrfnl

I'm in favour of these changes as well.

Just stating something that may already be obvious - dropping the Yoda check will result in a drop in reported violations, but later adding in a check to highlight anti-Yoda statements will likely significantly bump it up again until they are fixed.

GaryJones avatar Jan 14 '19 08:01 GaryJones

I agree that removing the Yoda Condition check could be removed from the Core ruleset, but it should not be removed from the "PHP Coding Standards" in the handbook and should still be checked in the WordPress and/or WordPress-Extra ruleset.

2ndkauboy avatar Jan 23 '19 15:01 2ndkauboy

@2ndkauboy That is not how it works. The Core ruleset represents the automatic checks for what's in the PHP Coding Standards handbook.

jrfnl avatar Jan 23 '19 18:01 jrfnl

A new sniff will need to be written to detect the use of Yoda Conditions, throw an error and where possible, auto-fix this.

Alternatively it could be considered to add the Slevomat Coding Standard as a dependency to WPCS and use the existing sniff in that standard.

Would it be an option to add detection sniff in WPCS, and use a composer suggest with message that SlevomatCodingStandard.ControlStructures.DisallowYodaComparison can be used as a fixer.

Looking at the Slevomat Coding standard it appears the fixer is far more complex than the sniff part of the implementation.

I think most projects would likely only be using it once during onboarding/initial scan. After that it's enough to be warned about the instance, an it would be natural to not type yoda conditions in the first place.

NielsdeBlaauw avatar Feb 17 '19 14:02 NielsdeBlaauw

Anecdotally, I believe Yoda conditions improve code quality & readability.

They are a decades old practice with a proven track record at avoiding accidental assignment errors.

Removing them is removing the steel toes from our workboots because they aren’t comfortable.

Evidently my feelings here aren’t the currently popular ones, but I’m a big -1 on switching away from them.

JJJ avatar Mar 04 '19 18:03 JJJ

Removing them is removing the steel toes from our workboots because they aren’t comfortable.

The presence of the assignment in condition check, means we've already removed the chance of anything heavy landing on our feet, so the steel toe caps would be redundant πŸ˜„

GaryJones avatar Mar 04 '19 20:03 GaryJones

I'm with @JJJ on this. I don't see any need or improvement to switching away from Yoda conditions.

The problem with this is that code readability is decreased significantly

How is readability decreased, especially "significantly"? Are there references somewhere that aren't included here that can be linked to?

Even if the preference against Yoda conditions continues, I think there's no reason to completely reverse stance and start saying that Yoda conditions are bad practice.

JPry avatar Mar 05 '19 16:03 JPry

Having thought about this some more, as well as discussing it with a range of different people, I'm not sure that banning Yoda conditions entirely is the most reasonable next step.

@JJJ was kind enough to go into the detail of how he finds Yoda conditions easier than non-Yoda to understand. @nacin mentioned the special case of checking false === strpos( ... ), and the like.

So, I'd like to explore this further before making a change. @davidakennedy recently published an interesting post about designing for accessibility, which I think also applies to this conversation. Let's work out what our constraints are, then make a change that works as well as possible for everyone.

I'm writing a post for make/core about WordPress coding standards changes with relation to the PHP version bump, so I'll include a call for feedback on the topic of Yoda conditions there.

pento avatar Mar 08 '19 03:03 pento

@pento What about the initial step ?

  • Removing the yoda conditions rule, without replacing it with a ban (i.e. no opinion, both yoda and non-yoda allowed);
  • Banning assignments in conditions;
  • Recommending strict comparisons.

Should any or all of these be actioned yet ?

Note: each of these three points can be actioned independently of the others.

jrfnl avatar Mar 08 '19 06:03 jrfnl

  • Removing the yoda conditions rule, without replacing it with a ban (i.e. no opinion, both yoda and non-yoda allowed);

To state what might be obvious - the decision to follow Yoda conditions in Core could be set in Core's ruleset or WordPress-Core, even if WordPress-Extra removes this requirement.

GaryJones avatar Mar 08 '19 06:03 GaryJones

@jrfnl: Still working on the post about these. πŸ™‚ Let's not action any of them yet, I suspect that 2 and 3 can happen quickly, but 1 will need some more information on the best way forward.

pento avatar Mar 25 '19 04:03 pento

@pento OK, thanks for the heads-up. I will remove this from the WPCS 2.1.0 milestone for now.

jrfnl avatar Mar 25 '19 04:03 jrfnl

@pento

I'm writing a post for make/core about WordPress coding standards changes with relation to the PHP version bump, so I'll include a call for feedback on the topic of Yoda conditions there.

Can you provide link to the post you mentioned? Just trying to trace the progress of this issue. Thanks!

curtisbelt avatar Jan 02 '20 12:01 curtisbelt

@CurtisBelt: The post I was referring to was published here, with a followup posted a little later.

You'll note that Yoda conditions weren't mentioned in either post. On further reflection while writing the posts, that topic had the potential to be too much of a distraction from the more immediate changes that could happen. Unfortunately, I never got back to writing a post just for the Yoda conditions discussion.

I'm currently taking a break from working on WordPress Core, so I don't expect to have time to look at this in the near future. Given that the next step is to explore the topic further in a wider discussion, this is something that anyone interested could drive, it certainly doesn't require my input to move it along. I would suggest bringing it up at the next core dev chat as a way to gauge interest in a wider discussion.

pento avatar Jan 06 '20 05:01 pento

I really just think the Yoda conditions need to be removed. I am all for keeping loose comparisons and assignments in conditions warnings. I agree with @GaryJones that by having loose comparisons and assignments in conditions is enough to also prevent accidental typos with "=" and "==".

ggedde avatar Aug 21 '20 00:08 ggedde

Sidenote: Yoda conditions can be automatically converted to regular conditions with PHP CS Fixer as well:

'yoda_style' => [
    'equal' => false,
    'identical' => false,
    'less_and_greater' => false,
],

Luc45 avatar Nov 21 '20 20:11 Luc45

Have we considered the fact to only enforce it when using 2 equal operators and ignore it when using a strict comparison with 3 equal operators instead?

// Enforce it if
if ( $value == false ) {
}

// Ignore if
if ( $value === false ) {
}

Primarily because based on:

In the above example, if you omit an equals sign (admit it, it happens even to the most seasoned of us), you’ll get a parse error, because you can’t assign to a constant like true. If the statement were the other way around ( $the_force = true ), the assignment would be perfectly valid, returning 1, causing the if statement to evaluate to true, and you could be chasing that bug for a while.

Source

When using strict operator the premise from the docs is no longer valid as you are ensuring that won't happen :)

mitogh avatar Feb 14 '22 22:02 mitogh

Have we considered the fact to only enforce it when using 2 equal operators and ignore it when using a strict comparison with 3 equal operators instead?

That's a reasonable idea, but in that case why not enforce it only if using one equals operator (which really is the bug this rule is trying to prevent)?

// Enforce it if
if ( $value = false ) {
}

// Ignore it if
if ( $value == false ) {
}

// Ignore if
if ( $value === false ) {
}

The standard is there to make sure that a typo isn't made on a comparison, but automated linting can do that instead, and generally better than humans.

sirbrillig avatar Feb 15 '22 00:02 sirbrillig

That's a reasonable idea, but in that case, why not enforce it only if using one equals operator (which really is the bug this rule is trying to prevent)?

Mostly for backward compatibility and to make sure when updating to a new rule system existing rules are no longer valid or considered instead. But I do agree if this can be automated I don't see a practical reason why not to replicate it in 2 comparison operators as well.

The standard is there to make sure that a typo isn't made on a comparison, but automated linting can do that instead, and generally better than humans.

:100: on board with this idea.

mitogh avatar Feb 15 '22 01:02 mitogh

May I suggest reading the original proposal ? As that's kind of what was originally suggested.

jrfnl avatar Feb 15 '22 01:02 jrfnl

There must be some axiom that says that if a discussion thread gets long enough it will loop back over itself. 😁

sirbrillig avatar Feb 15 '22 01:02 sirbrillig

May I suggest reading the original proposal ? As that's kind of what was originally suggested.

Well partially, from the main proposal is actually requesting a ban which was updated here: https://github.com/WordPress/WordPress-Coding-Standards/issues/1624#issuecomment-470821000

Maybe should the main ticket description should be updated for a more simple approach instead as you described here: https://github.com/WordPress/WordPress-Coding-Standards/issues/1624#issuecomment-470821000

mitogh avatar Feb 15 '22 04:02 mitogh

Please do not standardize against Yoda conditions.

JJJ avatar Feb 15 '22 16:02 JJJ

+1 to non-yoda conditions. I find yoda counter-intuitive and hard to read, as imagine you could.

Perhaps we could open a poll to settle this?

Luc45 avatar Feb 15 '22 16:02 Luc45

WordPress standardized on Yoda conditions 15 years ago.

Every plugin & theme has inherited that standard, resulting in verifiably millions of lines of PHP code that are written this way.

A timeline of future events after this change happens:

  • WordPress changes everything internally
  • Several plugins & themes immediately adopt
  • Some plugins & themes slowly adopt
  • Most plugins & themes never adopt

If this changes, the larger WordPress landscape is left littered with the simplest code imaginable (variable comparisons) looking different everywhere, in every project, all over the web. A few people will be happy and feel accomplished, and everyone will suffer.

Changing this results in code-slurry across the web that is marginally easier for a vocal minority to ingest, but will be highly disorienting for everyone else – I.E. people like my brilliant wife who is, as I write this, learning PHP for her very first time and is constantly tripping over (and frustrated by) uselessly differing code structure.

It will be a mistake to the entire ecosystem to intentionally invert such a prolific WordPress'ism.

(Edit: ADHD over-explanation incoming – I personally know & believe everyone here is saying & doing what they feel is best & right. I also know that, perhaps, I am wrong. What I'm asking for here is some acknowledgement of the possibility that this standard was set for important reasons then, that those reasons are still important today, and that flipping it 180 degrees around has a non-zero chance of making everything worse.)

JJJ avatar Feb 15 '22 17:02 JJJ

If this changes, the larger WordPress landscape is left littered with the simplest code imaginable (variable comparisons) looking different everywhere, in every project, all over the web.

On the other hand, the larger PHP ecosystem seems to generally be non-Yoda. From this perspective WordPress seems like the outlier.

Then again, the larger PHP ecosystem has also standardized on PSR-4 for naming files containing classes, camelCase for method and variable names, and short array syntax. I've not seen any other project that requires aligning the => in arrays or = in assignments. And few projects seem to have clung to PHP 5.6 for so long.

anomiex avatar Feb 15 '22 22:02 anomiex

@JJJ just because something was added 15 years ago, doesn't mean it should stay this way forever.

I don't think that the argument that various plugins/themes/projects out there having different coding standards (the reality is that the majority doesn't have any) should prevent changes in the WordPress core coding standards.

If anything it would be better if we are doing what the rest of the PHP community is doing and see if we can somehow align with their standard.

That way WordPress wouldn't be the odd one out IMO.

Plus, the point of using automated tools such as PHPCS is to prevent issues that Yoda conditions solved back when we didn't have such tools (or didn't use them).

dingo-d avatar Feb 16 '22 09:02 dingo-d

A few people will be happy and feel accomplished, and everyone will suffer.

easier for a vocal minority to ingest, but will be highly disorienting for everyone else

I have downloaded almost all the 93 965 plugins in the WordPress Plugin Repository (Due to network gaps, I was able to download 82 450 plugins directly from wordpress.org servers (93GB)) and ran PHPCS to find the usage of Yoda vs Non Yoda conditions. This provides us with data that brings a pragmatic insight that can be beneficial to the discussion.

I will try to be as transparent, pragmatic, and scientific as possible, to describe every inch of my methodology so that it can be peer-reviewed to make sure it does not contain any bias.

This is the phpcs.xml that I have used:

<?xml version="1.0"?>
<ruleset name="Yoda Analyzer">
    <config name="installed_paths" value="/home/lucas/local/data/www/plugin-directory/WordPress-Plugin-Directory-Slurper/phpcs/vendor/slevomat/coding-standard"/>

    <file>/home/lucas/local/data/www/plugin-directory/WordPress-Plugin-Directory-Slurper/plugins/0-delay-late-caching-for-feeds</file>
    <file>/home/lucas/local/data/www/plugin-directory/WordPress-Plugin-Directory-Slurper/plugins/0-errors</file>
    <file>/home/lucas/local/data/www/plugin-directory/WordPress-Plugin-Directory-Slurper/plugins/001-prime-strategy-translate-accelerator</file>
    <file>/home/lucas/local/data/www/plugin-directory/WordPress-Plugin-Directory-Slurper/plugins/002-ps-custom-post-type</file>
    <file>/home/lucas/local/data/www/plugin-directory/WordPress-Plugin-Directory-Slurper/plugins/011-ps-custom-taxonomy</file>
    <file>/home/lucas/local/data/www/plugin-directory/WordPress-Plugin-Directory-Slurper/plugins/012-ps-multi-languages</file>
    <file>/home/lucas/local/data/www/plugin-directory/WordPress-Plugin-Directory-Slurper/plugins/028-ps-combine-taxonomy-children</file>
    <file>/home/lucas/local/data/www/plugin-directory/WordPress-Plugin-Directory-Slurper/plugins/030-ps-display-upload-path-for-wp35</file>
    <file>/home/lucas/local/data/www/plugin-directory/WordPress-Plugin-Directory-Slurper/plugins/03talk-community-conference</file>
    <file>/home/lucas/local/data/www/plugin-directory/WordPress-Plugin-Directory-Slurper/plugins/0gravatar</file>
    <!-- ... etc, until all plugins are scanned (in batches) -->

    <exclude-pattern>*/vendor/*</exclude-pattern>
    <exclude-pattern>*/node_modules/*</exclude-pattern>
    <exclude-pattern>*/freemius/*</exclude-pattern>
    <exclude-pattern>*/vendor_prefixed/*</exclude-pattern>
    <exclude-pattern>*/composer/*</exclude-pattern>

    <arg name="extensions" value="php"/>

    <arg name="parallel" value="12"/>

    <rule ref="SlevomatCodingStandard.ControlStructures.DisallowYodaComparison"/>
    <rule ref="SlevomatCodingStandard.ControlStructures.RequireYodaComparison"/>
</ruleset>

I have tried to do my best to exclude any vendor code, such as packages that might be installed using composer, and focus only on the WordPress PHP code of the plugin.

  • This is what the sniff SlevomatCodingStandard.ControlStructures.DisallowYodaComparison considers Yoda code.
  • This is what the sniff SlevomatCodingStandard.ControlStructures.RequireYodaComparison considers non-Yoda code.

I've used PHPCS's --report=source option, which gives me a result such as this (this example is for the first 10k scans):

PHP CODE SNIFFER VIOLATION SOURCE SUMMARY
--------------------------------------------------------------------------------------------
    STANDARD  CATEGORY            SNIFF                                                COUNT
--------------------------------------------------------------------------------------------
[x] Slevomat  Control structures  Require yoda comparison required yoda comparison     426417
[x] Slevomat  Control structures  Disallow yoda comparison disallowed yoda comparison  100539
[ ] Internal                      No code found                                        1851
[ ] Internal                      Line endings                                         1475
[ ] Internal                      Exception                                            6
--------------------------------------------------------------------------------------------
A TOTAL OF 530288 SNIFF VIOLATIONS WERE FOUND IN 5 SOURCES
--------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SOURCES AUTOMATICALLY (526479 VIOLATIONS IN TOTAL)
--------------------------------------------------------------------------------------------

Time: 7 mins, 3.01 secs; Memory: 56.24MB

I had to split the PHPCS run into batches, as it was too much for my PC to process in one go. To do that, I wrote a small script that generates a phpcs.xml with plugins within a range.

Results per batch

Plugins 0 to 10k:

➜  phpcs git:(master) βœ— cat 0_10000.txt 

PHP CODE SNIFFER VIOLATION SOURCE SUMMARY
--------------------------------------------------------------------------------------------
    STANDARD  CATEGORY            SNIFF                                                COUNT
--------------------------------------------------------------------------------------------
[x] Slevomat  Control structures  Require yoda comparison required yoda comparison     426417
[x] Slevomat  Control structures  Disallow yoda comparison disallowed yoda comparison  100539
[ ] Internal                      No code found                                        1851
[ ] Internal                      Line endings                                         1475
[ ] Internal                      Exception                                            6
--------------------------------------------------------------------------------------------
A TOTAL OF 530288 SNIFF VIOLATIONS WERE FOUND IN 5 SOURCES
--------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SOURCES AUTOMATICALLY (526479 VIOLATIONS IN TOTAL)
--------------------------------------------------------------------------------------------

Time: 7 mins, 3.01 secs; Memory: 56.24MB

Plugins 10k to 20k:

➜  phpcs git:(master) βœ— cat 10000_20000.txt 

PHP CODE SNIFFER VIOLATION SOURCE SUMMARY
--------------------------------------------------------------------------------------------
    STANDARD  CATEGORY            SNIFF                                                COUNT
--------------------------------------------------------------------------------------------
[x] Slevomat  Control structures  Require yoda comparison required yoda comparison     418345
[x] Slevomat  Control structures  Disallow yoda comparison disallowed yoda comparison  91076
[ ] Internal                      No code found                                        2743
[ ] Internal                      Line endings                                         1233
--------------------------------------------------------------------------------------------
A TOTAL OF 513397 SNIFF VIOLATIONS WERE FOUND IN 4 SOURCES
--------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SOURCES AUTOMATICALLY (509083 VIOLATIONS IN TOTAL)
--------------------------------------------------------------------------------------------

Time: 7 mins, 0.65 secs; Memory: 54.12MB

Plugins 20k to 30k:

➜  phpcs git:(master) βœ— cat 20000_30000.txt 

PHP CODE SNIFFER VIOLATION SOURCE SUMMARY
--------------------------------------------------------------------------------------------
    STANDARD  CATEGORY            SNIFF                                                COUNT
--------------------------------------------------------------------------------------------
[x] Slevomat  Control structures  Require yoda comparison required yoda comparison     445222
[x] Slevomat  Control structures  Disallow yoda comparison disallowed yoda comparison  92608
[ ] Internal                      Line endings                                         2012
[ ] Internal                      No code found                                        1590
[ ] Internal                      Exception                                            2
--------------------------------------------------------------------------------------------
A TOTAL OF 541434 SNIFF VIOLATIONS WERE FOUND IN 5 SOURCES
--------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SOURCES AUTOMATICALLY (537569 VIOLATIONS IN TOTAL)
--------------------------------------------------------------------------------------------

Time: 7 mins, 37.34 secs; Memory: 54.27MB

Plugins 30k to 40k:

➜  phpcs git:(master) βœ— cat 30000_40000.txt 

PHP CODE SNIFFER VIOLATION SOURCE SUMMARY
--------------------------------------------------------------------------------------------
    STANDARD  CATEGORY            SNIFF                                                COUNT
--------------------------------------------------------------------------------------------
[x] Slevomat  Control structures  Require yoda comparison required yoda comparison     458963
[x] Slevomat  Control structures  Disallow yoda comparison disallowed yoda comparison  101565
[ ] Internal                      Line endings                                         3784
[ ] Internal                      No code found                                        2689
[ ] Internal                      Exception                                            7
--------------------------------------------------------------------------------------------
A TOTAL OF 567008 SNIFF VIOLATIONS WERE FOUND IN 5 SOURCES
--------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SOURCES AUTOMATICALLY (560188 VIOLATIONS IN TOTAL)
--------------------------------------------------------------------------------------------

Time: 6 mins, 50.86 secs; Memory: 58.91MB

Plugins 40k to 50k:

➜  phpcs git:(master) βœ— cat 40000_50000.txt 

PHP CODE SNIFFER VIOLATION SOURCE SUMMARY
--------------------------------------------------------------------------------------------
    STANDARD  CATEGORY            SNIFF                                                COUNT
--------------------------------------------------------------------------------------------
[x] Slevomat  Control structures  Require yoda comparison required yoda comparison     479307
[x] Slevomat  Control structures  Disallow yoda comparison disallowed yoda comparison  96621
[ ] Internal                      Line endings                                         3196
[ ] Internal                      No code found                                        1631
[ ] Internal                      Exception                                            1
--------------------------------------------------------------------------------------------
A TOTAL OF 580756 SNIFF VIOLATIONS WERE FOUND IN 5 SOURCES
--------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SOURCES AUTOMATICALLY (575509 VIOLATIONS IN TOTAL)
--------------------------------------------------------------------------------------------

Time: 7 mins, 33.55 secs; Memory: 62.96MB

Plugins 50k to 60k:

➜  phpcs git:(master) βœ— cat 50000_60000.txt 

PHP CODE SNIFFER VIOLATION SOURCE SUMMARY
--------------------------------------------------------------------------------------------
    STANDARD  CATEGORY            SNIFF                                                COUNT
--------------------------------------------------------------------------------------------
[x] Slevomat  Control structures  Require yoda comparison required yoda comparison     364109
[x] Slevomat  Control structures  Disallow yoda comparison disallowed yoda comparison  82842
[ ] Internal                      No code found                                        1617
[ ] Internal                      Line endings                                         1123
--------------------------------------------------------------------------------------------
A TOTAL OF 449691 SNIFF VIOLATIONS WERE FOUND IN 4 SOURCES
--------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SOURCES AUTOMATICALLY (446646 VIOLATIONS IN TOTAL)
--------------------------------------------------------------------------------------------

Time: 6 mins, 25.88 secs; Memory: 47.55MB

Plugins 60k to 70k:

➜  phpcs git:(master) βœ— cat 60000_70000.txt

PHP CODE SNIFFER VIOLATION SOURCE SUMMARY
--------------------------------------------------------------------------------------------
    STANDARD  CATEGORY            SNIFF                                                COUNT
--------------------------------------------------------------------------------------------
[x] Slevomat  Control structures  Require yoda comparison required yoda comparison     472825
[x] Slevomat  Control structures  Disallow yoda comparison disallowed yoda comparison  106476
[ ] Internal                      Line endings                                         1831
[ ] Internal                      No code found                                        1762
[ ] Internal                      Exception                                            4
[ ] Internal                      Tokenizer                                            1
--------------------------------------------------------------------------------------------
A TOTAL OF 582899 SNIFF VIOLATIONS WERE FOUND IN 6 SOURCES
--------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SOURCES AUTOMATICALLY (578880 VIOLATIONS IN TOTAL)
--------------------------------------------------------------------------------------------

Time: 8 mins, 5.99 secs; Memory: 58.7MB

Plugins 70k to 80k:

➜  phpcs git:(master) βœ— cat 70000_80000.txt

PHP CODE SNIFFER VIOLATION SOURCE SUMMARY
-----------------------------------------------------------------------------
    STANDARD  CATEGORY            SNIFF                                 COUNT
-----------------------------------------------------------------------------
[x] Slevomat  Control structures  Require yoda comparison required yod  549068
[x] Slevomat  Control structures  Disallow yoda comparison disallowed   120069
[ ] Internal                      No code found                         1731
[ ] Internal                      Line endings                          1428
[ ] Internal                      Exception                             6
-----------------------------------------------------------------------------
A TOTAL OF 672302 SNIFF VIOLATIONS WERE FOUND IN 5 SOURCES
-----------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SOURCES AUTOMATICALLY (668881 VIOLATIONS IN TOTAL)
-----------------------------------------------------------------------------

Time: 9 mins, 26.69 secs; Memory: 63.78MB

Plugins 80k to 82450:

➜  phpcs git:(master) βœ— cat 80000_82450.txt 

PHP CODE SNIFFER VIOLATION SOURCE SUMMARY
--------------------------------------------------------------------------------------------
    STANDARD  CATEGORY            SNIFF                                                COUNT
--------------------------------------------------------------------------------------------
[x] Slevomat  Control structures  Require yoda comparison required yoda comparison     166025
[x] Slevomat  Control structures  Disallow yoda comparison disallowed yoda comparison  38594
[ ] Internal                      No code found                                        536
[ ] Internal                      Line endings                                         251
[ ] Internal                      Exception                                            1
--------------------------------------------------------------------------------------------
A TOTAL OF 205407 SNIFF VIOLATIONS WERE FOUND IN 5 SOURCES
--------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SOURCES AUTOMATICALLY (204464 VIOLATIONS IN TOTAL)
--------------------------------------------------------------------------------------------

Time: 3 mins, 38.64 secs; Memory: 24.75MB

This is the final result:

  • Total Conditions: 4 610 671 (100%)
  • Regular Conditions: 3 780 281 (81.98%)
  • Yoda Conditions: 830 390 (18.02%)

My thoughts:

Looking at the data, I don't see a cascading effect on the entire world wide web that could bring doom and calamity to the internet if we stop using Yoda in Core. The Codex itself has a funny statement on the "Yoda" section: A little bizarre, it is, to read. Get used to it, you will., which seems to go against what it says just a couple lines below, on the "Clever Code" section: In general, readability is more important than cleverness or brevity..

To be quite frank, I think I'm dumber than most people. I really do. I don't have a very high cognitive capacity. That's why for me it's very important that the code is easy to read, follow, and understand. My personal opinion is that it compromises readability, and this is pretty much the consensus of Yoda conditions on the internet for the majority. People will not agree on everything, but we can pretty much confidently say that the majority prefers regular conditions, so I think this is a pretty pertinent discussion to have.

Luc45 avatar Feb 17 '22 00:02 Luc45