Menu
Create Custom Side Menus
Frodo's Ghost | Public vs Private Variables
19
post-template-default,single,single-post,postid-19,single-format-standard,eltd-core-1.0.1,ajax_fade,page_not_loaded,,borderland - frodosghost-child-ver-1.0.0,borderland-ver-1.2, vertical_menu_with_scroll,smooth_scroll,side_menu_slide_with_content,width_470,paspartu_enabled,paspartu_on_bottom_fixed,wpb-js-composer js-comp-ver-4.4.4,vc_responsive

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.

james
No Comments

Post a Comment