Skip to main content

Using of global variables in C# - Drawbacks & Solutions

How using global variables can have implications on the design, maintainability, and test-ability of C# code:

Harder to understand and reason about the code:

     class Program

    {

        public static int globalCounter = 0;

        static void Main()

        {

            globalCounter++;

            Console.WriteLine(globalCounter);

        }

    }

  In this example, the global variable globalCounter is accessible from anywhere in the program, including the Main method. It's not clear where the value of the globalCounter is updated, it could be updated in other methods or classes, making it harder to trace the flow of data and understand the source of bugs.
 

More prone to errors:

 

    class Program

    {

        public static string globalString;

        static void Main()

        {

            globalString = "Hello";

            Method1();

            Method2();

        }

        static void Method1()

        {

            globalString = "Method1";

        }

        static void Method2()

        {

            globalString = "Method2";

        }

    }

 In this example, the global variable globalString is accessible from anywhere in the program, including the Main, Method1 and Method2 methods. It's not clear which method will update the value of the globalString, it could lead to unexpected behavior and bugs.
 

Harder to test:


    class Program

    {

        public static int globalCounter = 0;

        static void Main()

        {

            globalCounter++;

            Console.WriteLine(globalCounter);

        }

        public static int GetCounter()

        {

            return globalCounter;

        }

    }

 In this example, the global variable globalCounter is accessible from anywhere in the program, including the Main method and the GetCounter method. To test the GetCounter method, it would be necessary to control the state of the globalCounter, which can be difficult and make the test less effective.
 

Less flexible:

  class Program

    {

        public static string globalString;

        static void Main()

        {

            globalString = "Hello";

            Method1();

            Method2();

        }

        static void Method1()

        {

            globalString = "Method1";

        }

        static void Method2()

        {

            globalString = "Method2";

        }

        static void Method3()

        {

            if (globalString.Equals("Hello"))

            {

                // do something

            }

        }

    }

 In this example, the global variable globalString is used by multiple methods in the program, if the value of the globalString is changed, it will affect multiple methods, including Method1, Method2, and Method3. This makes it harder to make modifications or refactor the code.
 

Less modular:

Using global variables in C# can make the code less modular because they create tight coupling between different parts of the code. When global variables are used, different parts of the code are dependent on the state of the global variables, making it more difficult to reuse or replace individual parts.

For example, let's say you have a global variable globalCount that is used in multiple parts of the code, such as in the Main method and in a method called DoSomething:

     class Program

    {

        public static int globalCount = 0;

 

        static void Main(string[] args)

        {

            // Use globalCount here

            globalCount++;

            //...

            globalCount--;

        }

 

        public static void DoSomething()

        {

            // Use globalCount here

            globalCount++;

        }

    }

In this example, the globalCount variable is used in multiple parts of the code, making it difficult to reuse or replace the Main method or the DoSomething method without also affecting the other part of the code that depends on the globalCount.

Also, if you want to reuse DoSomething method in another class, you have to keep track of the global variable and make sure that it's updated correctly before and after the method call which creates additional complexity and tight coupling between the classes and methods.

By using dependency injection, inversion of control and local variables, you can make your code more modular and less dependent on global variables. This makes it easier to reuse and replace individual parts of the code without affecting other parts of the code.

Comments

Popular posts from this blog

Task Parallel Library (TPL) and Akka.NET: Differences

Task Parallel Library (TPL) and Akka.NET are both powerful tools in the .NET ecosystem for handling parallelism and concurrency, but they serve different purposes and use different models of computation. Here are some key differences:s 1.    Actor Model vs Task-Based Model: Akka.NET is built around the actor model, where actors are the fundamental units of computation and they communicate by exchanging messages. TPL, on the other hand, is task-based. It's designed to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. TPL uses tasks (which are independently executing work units) and provides various ways to control and coordinate them. 2.    Fault Tolerance: One of the key features of Akka.NET is its built-in fault tolerance. It has a "let-it-crash" philosophy, where the system is designed to self-heal from errors. If an actor fails, its parent actor can decide on the supervision strategy: either to resta

Extension Methods - Advanced

Here we will see how can we use the Extension Methods in advanced manner in other types Imagine you often need to retrieve items from a List based on a custom criterion that the built-in LINQ methods don't cover. Extension Methods for Lists: Filtering based on Custom Criteria And the output would be   Extending Enums: Displaying Descriptive Strings Output: Extending DateTime: Calculating Age     Output: The code samples can be found at https://github.com/oneananda/C_Sharp_Examples/tree/main/ExtensionMethods