From: Eivind Eklund Date: 2006-01-10T06:14:29+09:00 Subject: Re: global variables are bad?? On 1/9/06, Lyndon Samson wrote: > On 1/9/06, John Maclean wrote: > > I'm not sure were I have read this but I recall a page or two saying that > > global variables are bad for some reason. I've overcome my main hurdle, of > > understanding some of the basics of OO. > > Interestingly it's allmost universally accepted that Global Variables are > bad ( in the same camp along with GOTO ), yet instance variables are just a > more restrictive variation on the same theme, yet they are best practice :-) What's important here is how easy the code is to work with. Global variables will usually lead to it being hard to see how different parts of the program communicate, and make the program behaviour vary due to a large amount of state stored in a plethora of different variables. They also often make it hard to change the program, for instance to have two of something there used to be only one of. So the critique isn't against "global variables" per se - it's against global variables used in a way that makes it hard to understand and change a program. That's the same critique as we have against goto. Global variables do not always lead to this, and instance variables can lead to the same problems. And sometimes global variables is the right solution, leading to a clearer program that's easier to modify. Just as goto sometimes makes it possible to create programs that's easier to read. Especially direct implementations of state machines tend to be easier to read when written using goto than when written with a separate variable keeping track of the state. I've missed goto in Ruby a couple of times for this (and before somebody jump in: I know I can sort of implement it using callcc.) Eivind.