Skip to content

EarlyExitNotUsed sniff promotes inconsistent code organization #371

@morozov

Description

@morozov

Consider an example:

<?php

function main($a, $b)
{
    if ($a !== null) {
        echo $a;
    }

    if ($b !== null) {
        echo $b;
    }
}
$ phpcs test.php 
FILE: test.php
------------------------------------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
------------------------------------------------------------------------------------------------
 9 | ERROR | [x] Use early exit to reduce code nesting.
   |       |     (SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed)
------------------------------------------------------------------------------------------------

The two if-statements are identical and have the same semantics. Using an early exit in the latter will make them look different and therefore will increas the cognitive load on the reader.

Besides that, even with one if-statement in the block, the sniff sometimes produces a sub-optimal suggestion:

<?php

function main($a, $b)
{
    if ($a !== null) {
        echo $a;
    }
}
$ phpcs test.php 
FILE: test.php
------------------------------------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
------------------------------------------------------------------------------------------------
 5 | ERROR | [x] Use early exit to reduce code nesting.
   |       |     (SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed)
------------------------------------------------------------------------------------------------

In this case, fixing this violation will not reduce code nesting and will add one more line of code.

I like the sniff itself to not disable it entirely, but it'd be nice if it was optimized for handling cases like the above.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions