Home > other >  How would you refactor code with many bool fields?
How would you refactor code with many bool fields?

Time:12-31

For example, I have several possible logical combinations and I need to determine which ones are true and perform actions based on the results.

public bool VerificationConnection(Transport objectFirst, Transport objectSecond) 
{
   bool isCarFirst = objectFirst is Car;
   bool isMotorcycleFirst = objectFirst is Motorcycle;
   
   bool isCarSecond = objectSecond is Car;
   bool isMotocycleSecond = objectSecond is Motorcycle;

   if(isCarFirst && isCarSecond) 
   {
      //do something
   }
   if(isCarFirst && isMotocycleSecond) 
   {
     //do something
   }
   if(isMotocycleFirst && isCarSecond) 
   {
     //do something
   }

   return true;
}

CodePudding user response:

You can use the handy pattern matching (C# 7.0 - C# 10.0) in a switch statement. This combines two type patterns in a tuple pattern:

switch ((objectFirst, objectSecond)) {
    case (Car, Car):
        DoSomething();
        break;
    case (Car, Motorcycle):
        DoSomething();
        break;
    case (Motorcycle, Car):
        DoSomething();
        break;
    case (Motorcycle, Motorcycle):
        DoSomething();
        break;
}

If you need the values as strongly typed, you can use the declaration pattern; however, then this might also be a hint, that your code does not use object oriented principles optimally.

switch ((objectFirst, objectSecond)) {
    case (Car c1, Car c2):
        DoSomething(c1, c2);
        break;
    case (Car c, Motorcycle m):
        DoSomething(c, m);
        break;
    case (Motorcycle m, Car c):
        DoSomething(m, c);
        break;
    case (Motorcycle m1, Motorcycle m2):
        DoSomething(m1, m2);
        break;
}

If the switch statement returns a value, then use a switch expression instead.

var value = (objectFirst, objectSecond) switch {
    (Car c1, Car c2) => GetValue(c1, c2),
    (Car c, Motorcycle m) => GetValue(c, m),
    (Motorcycle m, Car c) => GetValue(m, c),
    (Motorcycle m1, Motorcycle m2) => GetValue(m1, m2),
    _ => null
};

CodePudding user response:

You could use a dispatch table. For your use case with two boolean fields a dictionary of delegates or something similar might be enough.

Dictionary<(bool, bool), Delegate> dispatch = new Dictionary<(bool, bool), Delegate>();

dispatch[(true, true)] = new Action(() => Console.WriteLine("Hello"));
dispatch[(true, false)] = new Action<string>(s => Console.WriteLine(s));

dispatch[(true, true)].DynamicInvoke();
dispatch[(true, false)].DynamicInvoke("World");
  • Related