Global data is accessible anywhere in a program. Using global data is riskier than using local data.
Here are some common problems with using Global Data:
Problems with Global Data
- Unexpected changes to global data. Since global data can be accessed anywhere, it can also be changed anywhere without the intent of doing so.
- Cannot concentrate on only one routine. You have to concentrate on one routine and every other routine that uses the same global data.
- It’s difficult to modularize your application.
Usage of Global Data
There are some situations when using global data is ok. For example, configuration data is often used for an application using variables that you may want to change without recompiling and redeploying your code. You can store application or user settings in a config file, database or windows registry.
General Guidelines
Create global variables only when you need to. Always start with creating local variables first and expand scope as necessary. If you start with global variables, it’s very difficult to limit scope later on.
Have access routines work with the data within the class. Avoid letting outside code work directly with the data and require it to use the access routines. This centralizes control over your data.
Organize access routines and data into classes. Don’t just put all your data into the same class. Think about which class each variable belongs in and then package the data and its access routines in that class.
Accessors in C#
Property accessors in C# allow more control over your variables. The code block for the get accessor is executed when the property is read. The code block for the set accessor is executed when the property is assigned a new value.
- A property without a set accessor is considered read-only
- A property without a get accessor is considered write-only
- A property that has both accessors is read-write
Examples:
public class Person { public string FirstName { get; set; } public string LastName { get; set; } public string FullName { get { return string.Format("{0}, {1}", LastName, FirstName); } // Read only property } }
In this example, you can easily change where the data is coming from without changing it anywhere else in the program.
public static class ApplicationSettings { public static string DbConnectionString { get { return ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString; } } public static string ServiceUrl { get { return ConfigurationManager.AppSettings["ServiceUrl"]; } } }
It is also possible to limit the scope of one of the accessors. For example, you can create a variable with a public get accessor and a private set accessor. This limits the variable to only be changed inside the class.
In conclusion, avoid global variables as much as possible. Always start with the most restrictive scope and expand as necessary.
For further information see Global variables in Code Complete, Global variables are bad and Refactoring Legacy Code
Speak Your Mind