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 Alternatives

Task Parallel Library (TPL) and Akka.NET are among the most commonly used libraries for parallel and concurrent programming in the .NET ecosystem. However, there are also several other options available, depending on your specific needs: Parallel Language Integrated Query (PLINQ) is a parallel programming feature of .NET that provides an easy and efficient way to perform operations on collections in parallel. LINQ (Language Integrated Query) is a powerful feature in .NET that allows developers to work with data in a more declarative and language-integrated manner. While LINQ queries are inherently sequential, PLINQ extends LINQ by providing parallel versions of the query operators, allowing some queries to execute faster by utilizing multiple processors or cores on a machine. PLINQ is great when you are working with large collections where operations might be CPU-intensive or I/O-bound and could potentially be sped up by parallel execution. Here is a simple example of a PLI

SOLID Principles with Real World examples in C#

  SOLID Principles with Real World examples in C#   SOLID principles are formed by using S Single Responsibility Principles (SRP) O Open Closed Principle (OCP) L Liskov’s Substitution Principle (LCP) I Interface Segregation Principle (ISP) D Dependency Inversion Principle (DIP)   S Single Responsibility Principles (SRP) There should never be more than one reason for a class to change, to be precise one class should have only one responsibility Single Responsibility Principles (SRP) Real world example, A perfect match for SRP is Microservices , a Microservice will not contain functionalities other than the one it is designated to do,  Example ·                   Order Processing Service, ·                   Shipment Management Service, ·                   User Authentication Service, ·                   Catalogue List Service       class OrderProcessor     {         public void Process(Order order)         {             // Check inven