16

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.

moooeeeep
  • 133
  • 4
overki11
  • 187

2 Answers2

43

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.

Dan
  • 664
Tom Squires
  • 17,835
5

The simpler your application is, the less likely it will be to break.

Adding complexity means adding places where errors can occur. Usually those errors will be in your code, but occasionally you can hit errors from either the compiler or operating system.

An Example

You build a calculator object. It can do all sorts of calculator things (i.e., add numbers, multiply numbers, even determine square roots). You wouldn't need or want to add a method that draws lines on an image. You also wouldn't need or want a method that asks StackExchange for the person with the most reputation on all of its sites.

Adam Zuckerman
  • 3,725
  • 1
  • 21
  • 27