Coding-standard: Suggestion: forbid protected members in final classes

Created on 11 Oct 2019  路  6Comments  路  Source: slevomat/coding-standard

Protected members (constants, properties, methods) make no sense in final classes, as it amounts to them being private. Thus, a sniff should mark protected members in final classes as errors and auto-fix them to being private.

This also helps only expose selected API if the final keyword is removed from the class at a later stage to open it for extension.

All 6 comments

This one is helpful too:
DB46E9DE-76A6-4DA3-A2D6-A6686F1C4A62

This can't be reliably implemented for classes with ancestors.
If the ancestor declares a protected method (could be abstract or not) and the final class overrides (implements) it PHPCS can't reliably detect this.

Imagine:

abstract class Foo
{
    abstract protected function getName() : string;
}

final class Bar extends Foo
{
    protected function getName() : string
    {
        return 'John Doe';
    }
}

Same applies to properties. Such sniff could work for consts though.

Right, so this would definitely have to be implemented in a static analyser. Closing here since this would generate false positives.

Btw just realized while browsing issues in phpstan-strict-rules repo this was a dupe of #754 & has FR in phpstan-strict-rules (where this is possible): https://github.com/phpstan/phpstan-strict-rules/issues/57. 馃槃

LOL. I鈥檒l probably suggest it again next year. The signs of getting older...

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings