15 Most Recent [RSS]
More...
|
Globals, instance variables, and Visual Studio
Just got around to reading Charles Petzold's article on Visual Studio's code-writing aids and found this interesting snippet: In the pre-object oriented days of C programming, we had local variables and global variables, variables inside of functions, and variables outside of functions. One objective of good programming in C was in keeping the number of global variables to a minimum. Because any global variable could be modified by any function, it was easier to get the sense of a program if there simply weren’t very many of them — if functions communicated among themselves strictly through arguments and return values.
Sometimes, however, C programmers got a little, let’s say, sleepy, and made a lot of variables global that didn’t really need to be, because it was just easier that way. Rather than add an extra argument to a function, why not just store it as a global?
Global variables are basically gone in object-oriented programming, except that fields are now the new global variables, and they can be abused just as badly. I think that's a good point to keep in mind. And I'm not talking about the stupid don't use globals mantra some people follow. Globals are good, as long as you use them correctly and sparingly. Modern OO-systems encourage you to use accessors not just for instance variables, but also for globals.The similarities don't end there: While instance variables are good in general, they're "global" to their class, and can be abused just as well, and can make your class's code just as unreadable. In procedural C programming, you have static variables, which are the same as a global, but can only be accessed from inside the function they were declared in. It'd be nice if there was a similar construct for instance variables, i.e. a per-instance static or so... Or is there a pattern you folks can recommend that beautifully avoids this without a new language construct?
To offer a concrete example, let's take asynchronous mouse-tracking inside a view, where you typically use ivars to keep track of what item is currently highlighted etc. Any alternatives to ivars? Is this actually a Good Thing(tm) ?
| |