Frodosghost

Following the Footsteps of Heros, Never Lead to the Straight and Grey Roads.

​A developer. PHP and javascript. I like Symfony2 and MooTools.

​Husband. 5 sons. 1 daughter. Like the though of travel, even though it doesn't happen much.

Public vs Private Variables

When I began coding I was using public variables in all my classes. It was super easy to extend and I knew that I had access to all variables from any of the sub-classes I was extending with.

I changed to use private variables, could see the benefits that my code inherited and have not looked back. Like a white-list of allowed IP's on a server it should be the same with variables and methods in a class.

Default Public Variables

If all variables are accessible from sub-classes then code can be extended in any direction a future developer wants to take it. While it is easier for everyone to have access, it could lead to code with too many dependencies, code that is difficult to test and code that is difficult to refactor.

Are all variables or methods required to be public?

Default Private Variables

By closing all variable access to sub-classes and allowing access by public methods it encourages those who come after you to extend the code cleaner. It shows them your intent with the class and describes how it can be used.

Private variables encourages decoupling - the process of separating blocks of logic - which makes the code cleaner. A sub-class cannot use any variable to change the functionality of the original intent, it enforces better adaption.

A few more class files may seem a burden but the logic and naming structure will be easier to test and easier to understand. It will be easier to use with Dependency Injection and encourages reuse in a cleaner style.

Given access via getter/setter methods it also explains variables that have external access and produces a nice API for your code.

Lastbit

I am not saying that Private defeats Public because the decision is made by the developer and the intent of the code. I am saying that choosing Private first builds better code and builds better decisions around the code when it is created.

Frodosghost