I'm relatively new to programming (July 2015), and I've always wondered why it's good programming practice to hide variables as much as possible.
I've run into this question mainly recently when I looked into events and delegates in C#. I searched around as to why I should use events rather than just a delegate, since they do the same thing it seems. I read that it's better programming practice to hide the delegate fields and use an event.
I decided it was time to learn why it was good programming practice, but I couldn't really find anything other than "Because it's good programming practice".
If you could provide some basic examples and maybe some pseudo-code that would be helpful.
As a basic metaphor let's imagine I ask you for a favour: go to my flat and throw all the cows milk. When you enter my flat only one door is open and it leads you directly to the fridge with milk. You quickly throw the milk and leave without being able to touch the milk stashed in the living room bar.
Scoping variables means limiting access to reduce the chances of unintended changes.
– Johan Oct 09 '17 at 21:03