Do you use global variables?

Permabanned
Joined
15 Nov 2006
Posts
164
Location
Visit Athens
What's your opinion guys? :rolleyes:
Especially the professional programmers (I am not one).
Personally I do this cos it helps me to passing parameters to all necessary functions easily.
But it is dangerous sometimes (wrong results).
 
nope - the app I work on uses them, but I don't really like them. I've never really had the need to use them so I just don't
 
I must inform more all of you.
Basically I worked during the first years at university with FORTRAN so I have some "bad" habbits e.g. goto etc.....
Now working under Windows enviroment (Visual Studio) I assume that textboxes (for example) are external (global) variables also.
And status bar cos you can modify its properties in every function.
Before using an external variable I seek always above especially when I modify its value.
 
Last edited:
Of course. Why wouldn't you?

If you had a variable that contained a boolean result of whether the current user was allowed to, say, delete a record then why would you need to either:

a) Check the user credentials all the time by accessing either a server or environment
b) Create a new variable each section of your program to check

If you say it's dangerous, i.e., wrong results, then that's nothing to do with the reasoning behind global variables, it's just that you're looking at the problem wrong.
 
If possible I generally avoid global variables unless I can't think of another way round the problem.

Although I am still in the early stages of my development career I have some wonderful guys who help me out whenever I get stuck with a problem or shed light on better/ more code efficent ways of completing tasks.

I probably have a lot of bad habits when it comes to coding as I am entirely self taught in c# so I am amazed at the progress I have made in such a short time and am still trying to learn even more.
 
No! Use properties if you need to pass data to and from forms or classes. Global variables can get out of hand are difficult to keep track of.

TrUz
 
I tend to use object oriented software engineering with private variables for non-performance dependant software, objects with public methods for performance dependant (such as graphics) and global variables for application level data only. I also use environmental variables (at the operating system) which can be shared between programs, such as $PATH etc.
 
it's bad form, generally, but if a language (by which i mean compiler) allows it, then it is legal.

it's entirely possible to write bug free code with globals, and buggy code that is elegant.

there are reasons to shy away from them, in the main, try to avoid them until you become much more experienced. by then you'll know when to break the rules.

it's a bit like goto. everyone bangs on about "don't use got". almost every set of company coding standards i've ever seen forbid them. and fair enough, you never need to use goto. there's always another way. but then, every time you do switch, break, continue, if, else, for, while... you're really just doing a goto. they all compile to some sort of JMP instruction. you can screw up with any of them.

there's rarely a need to use globals, but sometimes, it's just easy to do so, and why not.

i'm guessing here that your still learning the language. well, what they rarely tell you at uni is that writing code takes up a tiny proportion of the development time of the average project. like literally maybe even as little as 5%. in the real world, you tend to spend far more hours, testing your code, and debugging/fixing it, than you do writing it in the first place.
the truth is, with any reasonably complex code you write, there will be mistakes in there. don't think you can learn all the rules and then just write perfect code. it doesn't work like that. so you'll make some mistakes, and then you'll find them, or someone else will. and then you'll fix them. and each time you do, hopefully you'll learn yet another mistake, not to make in future.

and after a while, you might find that globals cause you much trouble, or you might not.

:)
 
Thanks programmers.
Well look this source code:

Code:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace Chipset_FSB_estimator
{
	public class frmChipset_FSB_estimator : System.Windows.Forms.Form
	{
		#region Messages
		private string message1;
		private string message2;
		private string message3;
		private string message4;
		private string message5;
		private string message6;
		private string message7;
		private string message8;
		private string message9;
		private string message10;
		private string message11;
		private string message12;
		private string message13;
		private string message14;
		#endregion

        #region External variables
        private bool translation=false;
        double[] Vdd=new double[6];
        double[] FSB=new double[6];
        int number;
        #endregion		

		#region Form's routines
		private void frmChipset_FSB_estimator_Load(object sender, System.EventArgs e)
		{
            Translation();
           	double Vdd=1.2;
			while (Vdd <= 2.0)
			{
				comboBox1.Items.Add(Vdd.ToString(System.Globalization.CultureInfo.InvariantCulture));
				comboBox2.Items.Add(Vdd.ToString(System.Globalization.CultureInfo.InvariantCulture));
				comboBox3.Items.Add(Vdd.ToString(System.Globalization.CultureInfo.InvariantCulture));
				comboBox4.Items.Add(Vdd.ToString(System.Globalization.CultureInfo.InvariantCulture));
				comboBox5.Items.Add(Vdd.ToString(System.Globalization.CultureInfo.InvariantCulture));
				Vdd+=0.001;
				Vdd=Math.Round(Vdd,3);
			}     
		}
		private void statusBar1_TextChanged(object sender, System.EventArgs e)
		{
			for (int i=1; i<=5; i++)
			{
				statusBar1.Visible=false;
				System.Threading.Thread.Sleep(1);
				statusBar1.Visible=true;
			}
		}
		#endregion
		
		#region Translation routine
		private void Translation()
		{
			FileInfo theSourceFile=new FileInfo(@"Language.txt");  // Το αρχείο εισόδου
			TextReader reader=theSourceFile.OpenText();
			string text="";
			bool crash=false;

			while (text != "[Chipset FSB estimator]")
			{
				text=reader.ReadLine();
				if (text == null)  // Βρήκε EOF άρα έχει γίνει @@ρια με το αρχείο μετάφρασης
				{
					this.TopMost=false;
					MessageBox.Show("A critical error found in language file\n"+
						"and program must be terminated.\n"+
						"You must check and replace the header.",
						"ERROR in language file!",MessageBoxButtons.OK,MessageBoxIcon.Error); 
					crash=true;
					break;
				}
			}
			if (crash)
                Application.Exit();
            translation=true;
			text=reader.ReadLine();
			statusBar1.Text=text;
			text=reader.ReadLine();
			group_Data.Text=text;
			text=reader.ReadLine();
			group_Button_panel.Text=text;
			text=reader.ReadLine();
			lbl_Measurements.Text=text;
			text=reader.ReadLine();
			group_Estimation_card.Text=text;
			text=reader.ReadLine();
			lbl_Desired_Vdd.Text=text;
			text=reader.ReadLine();
			group_Results.Text=text;
			text=reader.ReadLine();
			lbl_Estimated_area.Text=text;
			message1=reader.ReadLine();    
			message2=reader.ReadLine();
			message3=reader.ReadLine();
			message4=reader.ReadLine();
			message5=reader.ReadLine();
			message6=reader.ReadLine();
			message7=reader.ReadLine();
			message8=reader.ReadLine();
			message9=reader.ReadLine();
			message10=reader.ReadLine();
			message11=reader.ReadLine();
			message12=reader.ReadLine();
			message13=reader.ReadLine();
			message14=reader.ReadLine();
			reader.Close();
		}	
		#endregion					         
		
		#region Βutton Compute
		private void btn_Compute_Click(object sender, System.EventArgs e)
		{
			double maxvoltage=0, value=0.0;
            bool flag=true;  

            for (int i=0; i<=5; i++)
                Vdd[i]=FSB[i]=0.0;
			try
			{
				number=int.Parse(combo_Measurements.Text,System.Globalization.NumberFormatInfo.InvariantInfo);
			}
			catch
			{
				if (!translation)
				{
					MessageBox.Show("You must choose measurements number!\n"+"Retry and be careful!",
						"Empty combobox!",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
					statusBar1.Text="You are not careful!";
				}
				else
				{
					MessageBox.Show(message1 + "\n" + message2,message3,MessageBoxButtons.OK,MessageBoxIcon.Error);
					statusBar1.Text=message4;
				}
				combo_Measurements.Text="??";
				combo_Measurements.Focus();
				flag=false;
			}
			try
			{
				Vdd[1]=double.Parse(comboBox1.Text,System.Globalization.NumberFormatInfo.InvariantInfo);
				FSB[1]=double.Parse(textBox1.Text,System.Globalization.NumberFormatInfo.InvariantInfo);
				Vdd[2]=double.Parse(comboBox2.Text,System.Globalization.NumberFormatInfo.InvariantInfo);
				FSB[2]=double.Parse(textBox2.Text,System.Globalization.NumberFormatInfo.InvariantInfo);
				if (number >= 3)
				{
					Vdd[3]=double.Parse(comboBox3.Text,System.Globalization.NumberFormatInfo.InvariantInfo);
					FSB[3]=double.Parse(textBox3.Text,System.Globalization.NumberFormatInfo.InvariantInfo);
				}
				if (number >= 4)
				{
					Vdd[4]=double.Parse(comboBox4.Text,System.Globalization.NumberFormatInfo.InvariantInfo);
					FSB[4]=double.Parse(textBox4.Text,System.Globalization.NumberFormatInfo.InvariantInfo);
				}
				if (number >= 5)   
				{
					Vdd[5]=double.Parse(comboBox5.Text,System.Globalization.NumberFormatInfo.InvariantInfo);
					FSB[5]=double.Parse(textBox5.Text,System.Globalization.NumberFormatInfo.InvariantInfo);
				}			    	    										  	   					
			}   // <--- END ΟF TRY
			catch
			{
				if (!translation)
				{
					MessageBox.Show("Enter proper values in all boxes!\n"+"Retry and be careful!",
						"Empty boxes or bad arguments!",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
					statusBar1.Text="You are not careful!";
				}
				else
				{
					MessageBox.Show(message5 + "\n" + message3,message6,MessageBoxButtons.OK,MessageBoxIcon.Error);
					statusBar1.Text=message4;
				}
				flag=false;
			}	
			if (flag)
			{
				maxvoltage=Vdd[1];
				for (int i=1; i<=number; i++)
					if (Vdd[number] > maxvoltage)
						maxvoltage=Vdd[number];
				value=1.000;
				if (1.07*maxvoltage > 2.0)
				{
					while (value <= 2.0)
					{
						combo_Desired_Vdd.Items.Add(value.ToString(System.Globalization.CultureInfo.InvariantCulture));
						value+=0.001;
						value=Math.Round(value,3);
					}   
				}
				else
				{
					while (value <= 1.07*maxvoltage)
					{
						combo_Desired_Vdd.Items.Add(value.ToString(System.Globalization.CultureInfo.InvariantCulture));
						value+=0.001;
						value=Math.Round(value,3);
					}
				}
				if (!translation)
					statusBar1.Text="Choose the desired Vdd now:";
				else
					statusBar1.Text=message7;
				group_Estimation_card.Visible=true;
			}
		}
		private void btn_Compute_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			btn_Compute.Top--;
			btn_Compute.Left--;
		}
		private void btn_Compute_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			btn_Compute.Top++;
			btn_Compute.Left++;
		}
		#endregion

		#region Buttons help and clear
		private void btn_Help_Click(object sender, System.EventArgs e)
		{
			System.Threading.Thread.Sleep(100);
			try
			{
				ProcessStartInfo psi=new ProcessStartInfo("Manuals\\Chipset FSB estimator\\Chipset FSB estimator.htm");
				psi.UseShellExecute=true;
				Process.Start(psi);
			}
			catch
			{
				if (!translation)
					MessageBox.Show("Help file is missing!","No help!",MessageBoxButtons.OK,MessageBoxIcon.Error);
				else
					MessageBox.Show(message8,message9,MessageBoxButtons.OK,MessageBoxIcon.Error);
			}
		}
		private void btn_Help_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			btn_Help.Top++;
			btn_Help.Left++;
		}
		private void btn_Help_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			btn_Help.Top--;
			btn_Help.Left--;
		}
		private void btn_Clear_Click(object sender, System.EventArgs e)
		{
			System.Threading.Thread.Sleep(100);
			for (int i=1; i<=50; i++)
			{
				this.Top+=10;
				this.Left+=10;
				this.Top-=10;
				this.Left-=10;
			}   
			textBox1.Text=textBox2.Text=textBox3.Text=textBox4.Text=textBox5.Text=""; 
			group_Estimation_card.Visible=group_Results.Visible=false;
            combo_Desired_Vdd.Text=combo_Measurements.Text=comboBox1.Text=comboBox2.Text=comboBox3.Text=comboBox4.Text=comboBox5.Text="";
            combo_Desired_Vdd.Items.Clear();  
            if (!translation)                     
				statusBar1.Text="All boxes cleared! Repeat or close the form!";
			else
				statusBar1.Text=message10;
		}
		private void btn_Clear_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			btn_Clear.Top++;
			btn_Clear.Left++;
		}
		private void btn_Clear_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			btn_Clear.Top--;
			btn_Clear.Left--;
		}
		#endregion
		
		#region Βutton Estimate
		private void btn_Estimate_Click(object sender, System.EventArgs e)
		{
			double edge1,edge2,voltage,value;
			double a1,b1,a2,b2,a3,b3,cor1,cor2,cor3;
			string text;

            try
            {
                voltage=double.Parse(combo_Desired_Vdd.Text,System.Globalization.NumberFormatInfo.InvariantInfo);
            }
            catch
            {
                if (!translation)
                {
                    MessageBox.Show("Critical error!\n"+"Retry and be careful!","Cannot continue!",
                        MessageBoxButtons.OK,MessageBoxIcon.Error);
                    statusBar1.Text="What's up?";
                    combo_Desired_Vdd.Focus();
                }
                else
                {
                    MessageBox.Show(message11+"\n"+message2,message12,MessageBoxButtons.OK,MessageBoxIcon.Error);
                    statusBar1.Text=message13;
                }
                goto Telos;
            }
            cor1=0.99; cor2=0.98; cor3=1.0;       // The part of complex calculations removed anyway assume that 
            a1=1; a2=2; a3=3; b1=4; b2=5; b3=6;   // after these calculations a1,a2.. have these values
            btn_Clear.Visible=group_Results.Visible=true;
            if (!translation)
                statusBar1.Text="All calculations performed! Repeat/clear or close the form!";
            else
                statusBar1.Text=message14;
            if (100.0*cor1 < 100.0)
            {
                cor1=Math.Round(100*cor1,6);
                text=cor1.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
                text+="%";
                textBox7.Text=text;
            }
            else
                textBox7.Text="100.0%";
            if (100.0*cor2 < 100.0)
            {
                cor2=Math.Round(100*cor2,6);
                text=cor2.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
                text+="%";
                textBox9.Text=text;
            }
            else
                textBox9.Text="100.0%";
            if (100.0*cor3 < 100.0)
            {
                cor3=Math.Round(100*cor3,6);
                text=cor3.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
                text+="%";
                textBox11.Text=text;
            }
            else
                textBox11.Text="100.0%";
            value=a1+b1*voltage;
            text="";
            edge1=Math.Round(value-2.0,0);
            text+=edge1.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
            text+=" - ";
            edge2=Math.Round(value,0);
            text+=edge2.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
            text+=" MHz.";
            textBox6.Text=text;
            value=a2+b2*Math.Log(voltage);
            text="";
            edge1=Math.Round(value-2.0,0);
            text+=edge1.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
            text+=" - ";
            edge2=Math.Round(value,0);
            text+=edge2.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
            text+=" MHz.";
            textBox8.Text=text;
            value=a3*Math.Pow(b3,voltage);
            text="";
            edge1=Math.Round(value-2.0,0);
            text+=edge1.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
            text+=" - ";
            edge2=Math.Round(value,0);
            text+=edge2.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
            text+=" MHz.";
            textBox10.Text=text;
            Telos:
            int dummy=69;
            dummy++;
		}
		private void btn_Estimate_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			btn_Estimate.Top++;
			btn_Estimate.Left++;
		}
		private void btn_Estimate_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			btn_Estimate.Top--;
			btn_Estimate.Left--;
		}
		#endregion
	}
}

It is a C# code.
Is it possible to stop using external (global) variables????
In this case it is trouble IMHO.
Read it carefully and we can go on. :)
 
I'm used to object-oriented programming so the concept of globals is a little different, it's genrally bad practice to declare a variable as public unless you have a good reason, this is because OO programming is designed to encourage high cohesion and low coupling. Having public variables can be tempting to solve some problems but can easily lead to bad cohesion and coupling. As Shoseki said, you normally use a public method to access a private variable, which enforces the use of the objects interface rather than direct access.
 
Code:
            string[] message = new string[13];
            message[0] = "test";
            message[1] = "test";
TrUz
 
Semantically/Pedantically, it's impossible to not use global variables. You'd never be able to instantiate an object from a class or use any other keyword if that was the case :p

However, yes I do not use global variables. I also avoid singletons unless it is an absolute necessity. Registry objects are winners in place of messy arrays/collections, too.
 
It is a C# code.
Is it possible to stop using external (global) variables????
In this case it is trouble IMHO.
Read it carefully and we can go on. :)

In the example given, the variables highlighted as external aren't really *global* variables in the traditional sense (I'm probably just being pedantic here though). Typically global variables are those defined outside the scope of any type, accessible to all types. Generally since the days of C, the use of such things has been shunned in derivative languages (C++, Java, C#, etc) as they can quickly become hard to manage.

The variables marked as external in the example are also not visible outside of the class in which they are defined, as without an explicit member access modifier (public, private, protected, etc.) these members will be private and only visible from within the type in which they are defined. If public access is required then such member variables should be exposed as a property.

I think the original question might then relate to the general use of member variables from within an instance of the type in which they are defined. There should be no problem with this, as implemented correctly such member variables define the "state" of the object upon which it's methods should operate.
 
I also avoid singletons
I wrote one singleton (actually I copied a sample) :D so I also avoid them.
The variables marked as external in the example are also not visible outside of the class in which they are defined.
Exactly. They are visible (and accessible) inside the class.

TrUz thanks for the sample I was too messed! :)
 
Last edited:
Global Variables are evil; ok so that's a university indoctrinated opinion but I've been programming for several years and I've yet to encounter a problem that requires it, or in fact that would have been that much easier to solve had I used them. (And I've found many where it would have been a great deal easier without them.... sigh...)

Now I don't consider private fields inside an object to be global variables (as in the your code snippet) as they have a clearly defined scope (ie the class). Besides object orientated languages seem to naturally discourage global variables unlike FORTRAN et al.

So I wouldn't worry too much about it but start getting into a habit of not using them, if anyone else ever reads your code they will thank you for it.

akakjs
 
Exactly. They are visible (and accessible) inside the class.
The point I was making was that the "external" comment against those variables is misleading and suggests the intention is for those variables to be accessible outside your class. This may have prompted a couple of the replies where use of properties to wrap such variables was suggested.
 
Last edited:
Properties are not globals, Java/C#(afaik) allow for shortcutting of property accessors so that:
Code:
public void function doSomething () {
  someVar = 'foo';
  this.someVar = 'foo'; // this is identical to the above, providing there is no 'someVar' in the local scope.
}

Anything external to the local scope should be considered global, and just as "dangerous" as global.
 
Back
Top Bottom