Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A pragmatic view on private vs public

Tags:

private

public

I've always wondered on the topic of public, protected and private properties. My memory can easily recall times when I had to hack somebody's code, and having the hacked-upon class variables declared as private was always upsetting.

Also, there were (more) times I've written a class myself, and had never recognized any potential gain of privatizing the property. I should note here that using public vars is not in my habit: I adhere to the principles of OOP by utilizing getters and setters.

So, what's the whole point in these restrictions?

like image 963
Denis Gorbachev Avatar asked Mar 28 '10 18:03

Denis Gorbachev


2 Answers

The use of private and public is called Encapsulation. It is the simple insight that a software package (class or module) needs an inside and an outside.

The outside (public) is your contract with the rest of the world. You should try to keep it simple, coherent, obvious, foolproof and, very important, stable.

If you are interested in good software design the rule simply is: make all data private, and make methods only public when they need to be.

The principle for hiding the data is that the sum of all fields in a class define the objects state. For a well written class, each object should be responsible for keeping a valid state. If part of the state is public, the class can never give such guarantees.

A small example, suppose we have:

class MyDate
{ 
    public int y, m, d;
    public void AdvanceDays(int n) { ... } // complicated month/year overflow
    // other utility methods
};

You cannot prevent a user of the class to ignore AdvanceDays() and simply do:

date.d = date.d + 1; // next day

But if you make y, m, d private and test all your MyDate methods, you can guarantee that there will only be valid dates in the system.

like image 155
Henk Holterman Avatar answered Jan 04 '23 17:01

Henk Holterman


The whole point is to use private and protected to prevent exposing internal details of your class, so that other classes only have access to the public "interfaces" provided by your class. This can be worthwhile if done properly.

I agree that private can be a real pain, especially if you are extending classes from a library. Awhile back I had to extend various classes from the Piccolo.NET framework and it was refreshing that they had declared everything I needed as protected instead of private, so I was able to extend everything I needed without having to copy their code and/or modify the library. An important take-away lesson from that is if you are writing code for a library or other "re-usable" component, that you really should think twice before declaring anything private.

like image 20
Justin Ethier Avatar answered Jan 04 '23 15:01

Justin Ethier