Yesterday, Felix Geisendörfer recommended in an article not to use private/protected properties and methods and called them “one of the most stupid concepts of OOP”.
I disagree with him, because visibility is one of the essential concepts of OOP. Let me explain why with a short story.
Max and Moritz both own a coke machine. And both want to make a lot of money with their machines ;-)
Max has a traditional coke machine: its basic functionality is to give you a bottle of coke after you paid for it. And from time to time Max has to replenish the machine with new bottles.
Moritz’ coke machine is slightly different: it doesn’t contain a front cover (it saves him 100 dollar). You just take a bottle of coke and then you can pay for it. And of course it has to be replenished from time to time by Moritz.
After the first day Max is happy about what he earned with his machine. And what about Moritz? He is depressed. His machine is empty. And the cash box too…
If we analyze both machines, we see that Max’ machine is successful because it only gives you access to a bottle when you paid for it.
Or to say it more generally: it is often necessary to restrict the access to something.
It is a concept you find everywhere in the real world. You don’t want that everyone drives with your car, or that everyone can get money from your bank account, and so on.
And so it makes sense to use the same concept in the software engineering world. If I want to model Max’ machine in software, I need a way to show that not everyone can access the bottles. And the same applies at the implementation level. And for this purpose it is essential to be able to distinguish between public and private (plus protected, but it doesn’t fit in the machine metaphor).
At last I want to recommend the opposite to Felix’ recommendation: Make as much as possible private or protected. Not everything has to be public!