Digital Web Magazine

The web professional's online magazine of choice.

Variable Scope for New Programmers : Comments

By Jonathan Snook

October 17, 2005

Comments

Aaron Pepper

October 18, 2005 8:45 AM

Great article, this cleared up a lot of things for me. I especially like the

Douglas Clifton

October 23, 2005 8:32 PM

Global variables have their place. For instance, if I store a list of key/value pairs in a DB table, and I want to refer to them often, I will write a function to extract the values and then store them in memory in a global array. Now I no longer need to access the database every time I want to look something up in the list. Sure, you could certainly pass the list around to various functions that need it as a parameter, and even make this more efficient by passing it by reference, but to me it makes more sense to just declare the array globally. One caveat for either of these approaches is you need to watch out for modifying list and side effects. I generally treat such data structures as read only.

Jonathan Snook

October 25, 2005 6:32 AM

To clarify, I don’t believe that global variables should never be used. Certainly one of the common ways I use them is to store application settings like filepaths and database connection information. And if your application is custom built from top to bottom, it’s easier to control variable access.

However, when you start integrating other libraries or want to offer what you’ve built into the global market, those global variables can create conflicts. Then, like other frameworks out there, it’s better to rely on YAML or XML as a storage mechanism for application settings.

The article is also meant to be generic. In JavaScript, for example, it’s easier to fall into the global variable trap and it’s also more likely to cause conflicts. There are situations where it makes sense to use global variables but it should be the last option and not the first.

Jennifer Grucza

October 26, 2005 1:19 PM

Good intro to scope, though I feel that declaring all your variables at the beginning of a function is unnecessary. I think it’s more important to choose your variable names wisely (“self-documenting”) and avoid global variables (like you said). I’m not going to declare every silly little loop index variable at the top of my function.

By the way, various IDE’s are able to do syntax highlighting based on the variable’s scope, or will let you easily jump to a variable’s declaration by clicking on it (at least for Java).

If you wanted to get even more in-depth in talking about scope, you could talk about pass-by-value vs. pass-by-reference and the difference between mutable and immutable objects.

Sorry, comments are closed.

Media Temple

via Ad Packs