A pragmatic view of private and public

I have always been interested in the topic of the properties public , protected and private . My memory can easily remember the time when I had to crack someone’s code, and the presence of class variables declared as private was always a violation.

In addition, there were (more) times I wrote the class myself and never recognized any potential benefit from privatizing property. I should note here that using public vars is not my habit: I adhere to the principles of OOP using getters and setters.

So what is all of these limitations?

+6
private public
source share
9 answers

Using private and public is called Encapsulation. This is a simple understanding that a software package (class or module) needs internal and external.

External (public) is your contract with the rest of the world. You should try to keep it simple, consistent, obvious, reliable and, very importantly, stable.

If you are interested in a good software design, this is just a rule: make all data confidential and make methods available only if necessary.

The principle of data hiding is that the sum of all the fields in the class determines the state of the objects. For a well-written class, each object must be responsible for maintaining the actual state. If part of the state is publicly available, the class will never be able to provide such guarantees.

A small example, suppose that:

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

You cannot prevent a class user from ignoring 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 the system will have valid dates.

+7
source share

The thing is to use private and protected to prevent the publication of the internal details of your class, so that other classes have access to the public "interfaces" provided by your class. This can be useful if done correctly.

I agree that private can be a real pain, especially if you are extending classes from a library. At the same time, I had to extend various classes from Piccolo.NET , and it was great that they declared everything I needed instead of protected from private , so I was able to extend everything I needed without copying their code and / or not changing the library. The important lesson from this is that you write code for a library or other “reusable” component that you really need to think twice before declaring something private .

+4
source share

The private keyword should not be used to privatize the property you want to open, but to protect the internal code of your class. I found them very useful because they help you identify parts of your code that should be hidden from those that might be accessible to everyone.

+2
source share

One example that comes to my mind is when you need to do some kind of adjustment or verification before setting / getting the value of a private member. Therefore, you should create a public setter / getter with some logic (check that something does not matter or any other calculations) instead of directly accessing the private variable and should always handle this logic in your code. This helps with code contracts and what is expected.

Another example is helper functions. You can break part of your larger logic into smaller functions, but this does not mean that you want everyone to see and use these auxiliary functions, you want them to have access to your main API functions.

In other words, you want to hide some of the internal elements of your code from the interface .

Check out some videos on the API, such as this Google talk .

0
source share

Recently, we had an exceptional luxury that allows us to design and implement an object system from scratch, I took the policy of forcing all variables (equivalent) protected . My goal was to encourage users to always consider variables as part of an implementation, not a specification. OTOH, I also left hooks to allow the code to break this restriction, because there are reasons not to follow it (for example, the object serialization mechanism cannot follow the rules).

Please note that my classes were not required to provide security; there were other mechanisms for this language.

0
source share

In my opinion, the most important reason for using private members hides the implementation, so that it can change in the future without changing the descendants.

0
source share

Some languages ​​- Smalltalk, for example, do not have visibility modifiers at all.

With Smalltalk, all instance variables are always private, and all methods are always public. The developer indicates that the "private" method is something that can change, or a helper method, which in itself does not make much sense, by putting the method in the "private" protocol.

Class users can then see that they should think twice about sending a message marked private to that class, but still have the freedom to use this method.

(Note: “properties” in Smalltalk are simply getter and setter methods.)

0
source share

I personally rarely use protected members. I usually prefer a composition , decorator template, or strategy template . There are very few cases where I trust a subclass (programmer) to correctly process protected variables. Sometimes I defended methods to explicitly propose an interface specifically for subclasses, but these cases are actually rare.

In most cases, I have an absract base class with only publicly available clean virtual machines (now speaking C ++), and the implementing classes implement them. Sometimes they add some special initialization methods or other specific functions, but the rest are private.

0
source share

First of all, “properties” can refer to different things in different languages. For example, in Java you must understand instance variables, while C # has a distinction between them.

I assume that you mean instance variables, since you specify getters / setters.

The reason others have talked about is encapsulation. And what does encapsulation buy us?

Flexibility

When things need to change (and they usually do), we are much less likely to disrupt the assembly by properly encapsulating the properties.

For example, we can decide to change, for example:

 int getFoo() { return foo; } int getFoo() { return bar + baz; } 

If we did not encapsulate "foo" to begin with, then we would have much more code to change. (than this one line)

Another reason for encapsulating a property is to provide a way to bullet our code:

 void setFoo(int val) { if(foo < 0) throw MyException(); // or silently ignore foo = val; } 

This is also convenient, since we can set a breakpoint in the mutator so that we can break down whenever something tries to change our data.

If our property was publicly available, we could not do that!

0
source share

All Articles