Dot Net For All

Use the C# Switch statement the correct way

Hello friends, In this article I will help you to understand how having a switch statement at a wrong place in your program lead to future headache and nuances. If you want to know how to use the switch statement at the right place, continue on this article.

Generally using the C# Switch statement

Lets start by looking at a small piece of code and do the analysis.

Below is the code which calculates the employee salary based on his employment status.

class Program
    {
        static void Main(string[] args)
        {
           
        }

        public int calculateSalary(Employee employee){
            switch (employee.Type)
            {
                case EmployeeType.PERMANENT:
                    return calculateSalaryForPeromanentEmployee();
                case EmployeeType.HOURLY:
                    return calculateSalaryForHourlyEmployee();
                case EmployeeType.DAILY:
                    return calculateSalaryForDailyEmployee();
                default:
                    break;
            }

            return 0;
        }

        private int calculateSalaryForDailyEmployee()
        {
            throw new NotImplementedException();
        }

        private int calculateSalaryForHourlyEmployee()
        {
            throw new NotImplementedException();
        }

        private int calculateSalaryForPeromanentEmployee()
        {
            throw new NotImplementedException();
        }
    }

    public class Employee{
        public EmployeeType Type { get; set; }
    }

    public enum EmployeeType{
        PERMANENT,
        HOURLY,
        DAILY

    }    

There are several problems with the above code. First is that it is already a big piece of code and if new EmployeeType are added it will grow even bigger.

Another important thing is it doesn’t do a single thing, thus violating Single Reponsibility Principle(SRP). The reason for same is that there are many reasons for change of calculateSalary method. The method also violates the Open Closed Principle(OCP) because it must change whenever new types or new employees are added.

But the worst problem is that there would be many functions which will have the same structure as calculateSalary. For example, AssignCompanyBenefits or IsPayDay or AssignAccessToResources. All these methods will again have one more set of switch statement contained within themselves.

Clearly if there is a new EmployeeType is added, you have to change all these methods as well.

Solution to Above Problem

The solution to the problem to bury the switch statement deep down in the Factory class as shown in the code below.

public interface IEmployee{
        int CalculateSalary();
        bool IsPayDay();
        void AssignCompanyBenefits();
        void AssignAccessToREsources();
    }

    public class PermanentEmployee : IEmployee
    {
        public void AssignAccessToREsources()
        {
            throw new NotImplementedException();
        }

        public void AssignCompanyBenefits()
        {
            throw new NotImplementedException();
        }

        public int CalculateSalary()
        {
            throw new NotImplementedException();
        }

        public bool IsPayDay()
        {
            throw new NotImplementedException();
        }
    }

    public interface IEmployeeFactory{
        public IEmployee MakeEmployee(EmployeeType employeeType);
    }

    public class EmployeeFactory : IEmployeeFactory
    {
        public IEmployee MakeEmployee(EmployeeType employeeType)
        {
            switch (employeeType)
            {
                case EmployeeType.PERMANENT:
                    return new PermanentEmployee();
                
                default:
                    return null;

            }
        }
    }

The benefits of the above code is that whenever a new employee type is added you have to change the only EmployeeFactory class and all the rest will be taken care polymorphically.

Lets look at out main code which will handle this creation and polymorphism.

        static void Main(string[] args)
        {
           IEmployeeFactory employeeFactory = new EmployeeFactory();
           IEmployee employee = employeeFactory.MakeEmployee(EmployeeType.PERMANENT);
           employee.CalculateSalary();
        }

The general rule for switch statements is that they can be tolerated if they appear only once, are used to create polymorphic objects, and are hidden behind an inheritance so that the rest of the system can’t see them.

Whenever you are using a C# Switch statement in your code, it should be red sign for you to watch out for.

Conclusions:

In this article I have shown you how a switch statement used at wrong place can increase the code complexity and maintainability. And with the use of simple object oriented concepts, we can drastically reduce the complexity.

Image Credit: https://www.abelectricians.com.au/sydney-electrician/

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview