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.
Why is it good programming practice to limit scope?
scope
Because the more things you have to deal with in any task the harder it becomes. For example, try patting your head. Then try patting your head and counting backwards from 1000. Then try patting your head counting backwards from 1000 and hopping on one leg. Then try patting your head counting backwards from 1000 and hopping on one leg and singing the national anthem. Gets a lot harder doesn't it? Each of those tasks were simple and would be easy on their own. If you keep your code small and granular and limit the amount of variables in scope you're dealing with less things at a time. This means you're less likely to fall over while standing on one leg because you were distracted by singing the national anthem and counting backwards from 1000.