.Net 4.0 Optimized code for refactoring existing “if” conditions and “is” operator

后端 未结 7 773
遥遥无期
遥遥无期 2021-01-06 18:02

I have following C# code. It works fine; but the GetDestination() method is cluttered with multiple if conditions by using is operator.

In

7条回答
  •  心在旅途
    2021-01-06 18:38

    Approach 1 (Selected): Using dynamic keyword to implement multimethods / double dispatch

    Approach 2: Use a dictionary to avoid if blocks as mentioned in Jon Skeet’s answer below.

    Approach 3: Use a HashList with delegates if there is condition other than equality (For example, if input < 25). Refer how to refactor a set of <= , >= if...else statements into a dictionary or something like that

    Apporach 4: Virtual Functions as mentioned in MarcinJuraszek’s answer below.

    MultiMethods / Double Dispatch approach using dynamic keyword

    Rationale: Here the algorithm changes based on the type. That is, if the input is Accountant, the function to be executed is different than for Manager.

        public static class DestinationHelper
        {
            public static string GetDestinationSepcificImplm(Manager x)
            {
                return @"\ManagerHome";
            }
    
            public static string GetDestinationSepcificImplm(Accountant x)
            {
                return @"\AccountantHome";
            }
    
            public static string GetDestinationSepcificImplm(Cleaner x)
            {
                return @"\CleanerHome";
            }
        }
    
       class Program
        {
            static string GetDestination(Role x)
            {
    
                #region Other Common Works
                //Do logging
                //Other Business Activities
                #endregion
    
                string destination = String.Empty;
                dynamic inputRole = x;
                destination = DestinationHelper.GetDestinationSepcificImplm(inputRole);
                return destination;
            }
    
            static void Main(string[] args)
            {
                string destination = GetDestination(new Security());
                Console.WriteLine(destination);
                Console.WriteLine("....");
                Console.ReadLine();
            }
    
        }
    

提交回复
热议问题