15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Defining the Scope of a Variable 155<br />

Program<br />

File 1 File 2<br />

Global X : integer<br />

Book II<br />

Chapter 2<br />

Figure 2-5:<br />

Every part of<br />

a program<br />

can access<br />

and change<br />

a global<br />

variable.<br />

File 3 File 4<br />

Variables,<br />

Data Types,<br />

and Constants<br />

Use global variables sparingly. If you create a global variable and some part<br />

of your program keeps modifying that variable’s data by mistake, you have<br />

to search through your entire program to find which command is messing up<br />

that variable. If you have a million-line program, guess what? You have to<br />

examine a million lines of code to find the one line that’s changing that variable<br />

by mistake. If that’s your idea of fun, go ahead and use global variables.<br />

In the old days, all <strong>programming</strong> languages let you create global variables,<br />

and it was up to the programmer to make sure no commands accidentally<br />

modified that variable in unintended ways. When writing small programs,<br />

programmers can do this easily, but when working on massive programs created<br />

by teams of programmers, the odds of abusing global variables<br />

increases dramatically.<br />

Think of a shelf where you can store your books, wallet, and laptop computer.<br />

If you’re the only person who has access to that shelf, you can be sure<br />

anything you put on that shelf is there when you look <strong>for</strong> it again.<br />

Now imagine putting your shelf of personal belongings (books, wallet, and<br />

laptop computer) on a shelf located in Grand Central Station where thousands<br />

of people can grab anything they want off that shelf or put something

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!