I have following C# code. It works fine; but the GetDestination()
method is cluttered with multiple if
conditions by using is operator.
In
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();
}
}