Proposal: Disallow assignments in conditions and remove the Yoda condition requirement for PHP

After discussion with several coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. committers and WordPress leads, the title and the contents of the text were changed to clarify that this is a proposal and not a decision set in stone.

This proposal is the continuation of the long discussion on the WordPress Coding Standards (WPCS) repo.

Yoda conditions (or Yoda notation) is the programming style where the parts of an expression in the condition are reversed from the ‘typical’ order.

In a large part of the world, the natural reading order is left to right (LTR). This is what most programming languages adhere to. That means the variable assignments or echo/print statements are written with the variable first:

$post_type = 'post';

echo $post_type;

With the same idea in mind, conditions can also be written left to right, like:

if ( $post_type == 'post' ) {
    $category = get_the_category();
}

With Yoda conditions applied, the above condition would be written as:

if ( 'post' == $post_type ) {
    $category = get_the_category();
}

The idea behind it is that writing the value on the left side of the condition will prevent accidentally assigning the value to the variable since assignments can’t be made to values.

if ( $post_type = 'post' ) {
    $category = get_the_category();
}

While seemingly helpful at first glance, the obvious problem with them is the decreased readability of code, especially for people with reading disabilities such as dyslexia.

How we got here

When the handbook rule about Yoda conditions was introduced there was barely any static analysis tooling available in the PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher world. The only ‘foolproof’ way to prevent accidental assignment in conditions was to invert the order of the value being checked and the variable.

Automated checking for assignments in conditions via PHP_CodeSniffer (PHPCSPHP Code Sniffer PHP Code Sniffer, a popular tool for analyzing code quality. The WordPress Coding Standards rely on PHPCS.), the underlying tooling for WPCSWPCS The collection of PHP_CodeSniffer rules (sniffs) used to format and validate PHP code developed for WordPress according to the WordPress Coding Standards. May also be an acronym referring to the Accessibility, PHP, JavaScript, CSS, HTML, etc. coding standards as published in the WordPress Coding Standards Handbook., became available in 2017. Moreover, the current sniffsniff A module for PHP Code Sniffer that analyzes code for a specific problem. Multiple stiffs are combined to create a PHPCS standard. The term is named because it detects code smells, similar to how a dog would "sniff" out food. enforcing Yoda condition in the WPCS doesn’t protect against accidental assignments in conditions.

Today there is tooling in place that can help with identifying assignments in conditions, making the Yoda rules obsolete.

Keep in mind that strict comparisons (===) are already strongly encouraged and a part of the WordPress-Core ruleset (warning), making accidental assignments even less likely.

A thorough analysis was made by Lucas Bustamante in the WPCS ticketticket Created for both bug reports and feature development on the bug tracker. on the impact this could have on the plugins in the WordPress directory. The analysis showed that Yoda conditions are used in 18.02% of the plugins, so the majority of pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party developers are using non-Yoda conditions.

What to do next?

The discussion in the WPCS ticket is long and opinionated, but comes down to these points:

Disallow Yoda condition

  • Drop the handbook rule that requires Yoda conditions and instead explicitly disallow using them.

Remove Yoda condition as a requirement

  • Discourage, but don’t disallow Yoda conditions. Just don’t report if the code is or is not using Yoda conditions. The rule would also be dropped from the handbook.

In both cases, assignments in conditions will still be checked for and forbidden.

Impact on the Core code

Disallowing Yoda conditions for WordPress Core would mean that all existing patches on open tickets for Core would need to be revisited and fixed accordingly, which could burden the contributors.

Running the same analysis as Lucas did for plugins, over the WordPress Core, there were 5427 Yoda conditions, and 312 non-Yoda conditions.

Luckily, these are violations that can be automatically fixed using phpcbf tool, but care should be taken to check if all the violations were correctly fixed.

If Yoda conditions are discouraged (option 2), and the existing Yoda conditions in the Core code remain, that would mean less work for the Core contributorsCore Contributors Core contributors are those who have worked on a release of WordPress, by creating the functions or finding and patching bugs. These contributions are done through Trac. https://core.trac.wordpress.org., but also would add lots of inconsistencies in the Core code (mixed Yoda and non-Yoda conditions).

Next steps

The chosen way forward is to remove the Yoda condition as a requirement (remove it from the handbook) but not disallow it for the time being.

For WPCS, that would mean the removal of the Yoda conditions requirement (and sniff) in WPCS 3.0, with a notice that non-Yoda conditions will start to be required in WPCS 4.0 version.

Work is currently actively ongoing to prepare for the WPCS 3.0.0 release. There will be a minimum of six months between the 3.0.0 and the 4.0.0 release to allow time for Core and other projects to adjust.

Once WPCS 4.0.0 version is released, a one-time-only auto-fix of all the remaining Yoda conditions in Core will be made, and any patches to the Core which go in after that will have to use non-Yoda.

How to enforce the non-Yoda conditions in your code

If you are a WordPress plugin or theme developer, and you’d like to enforce non-Yoda conditions in your code, you can use the Generic.ControlStructures.DisallowYodaConditions sniff. In your phpcs.xml.dist file you should add the following sniff:

<?xml version="1.0"?>
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Example Project" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/squizlabs/PHP_CodeSniffer/master/phpcs.xsd">

    <!-- Your custom rules. -->

    <!-- Disallow Yoda conditions in your codebase. -->
    <rule ref="Generic.ControlStructures.DisallowYodaConditions"/>

</ruleset>

If you want to change the Yoda conditions to non-Yoda conditions, use the phpcbf tool (part of PHPCS) with the Slevomat coding standards. Specifically, the SlevomatCodingStandard.ControlStructures.DisallowYodaComparison sniff that has the fixer for the Yoda conditions.

Props to Juliette Reinders Folmer and Gary Jones for the proofreading and adding valuable feedback on the text. Also, a big props to Lucas Bustamante for the impact analysis on WordPress plugins.

#codingstandards, #php, #wpcs