Skip to content

Use private instead of protected visibility #1019

@joshdifabio

Description

@joshdifabio

In Magento 1, class properties and methods are all defined with public or protected visibility. In PHP, changing the API of a protected property or method usually constitutes a backwards compatibility break. Have Magento considered using private instead of protected visibility as the default alternative to public in Magento 2?

Consider the following examples:

namespace Magento;

// version 1.0
class Product
{
    protected function somethingInternal() {}
}
namespace SomeThirdParty;

class MyProduct extends \Magento\Product
{
    public function somethingPublic()
    {
        // ...
        parent::somethingInternal();
        // ...
    }
}
namespace SomeOtherThirdParty;

class MyProduct extends \Magento\Product
{
    public function someCoolNewMethod() {}
}
namespace Magento;

// version 1.1
class Product
{
    // this breaks SomeThirdParty\MyProduct
    protected function somethingInternal($newParam) {}

    // this breaks SomeOtherThirdParty\MyProduct
    protected function someCoolNewMethod($requiredParam) {}
}

The above examples demonstrate how adding or modifying protected methods can break downstream packages. If those methods had been declared private, re-factoring would have been fine without any BC issues.

Why use protected by default? Presumably it's 'just in case' someone downstream wants to replace or re-use a piece of functionality. The thing to understand is that protected comes with a cost; it essentially means you can't do any re-factoring. If a piece of functionality is really worth exposing then why isn't it public?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue: Format is not validGate 1 Failed. Automatic verification of issue format is failed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions