Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would you refactor code with many bool fields?

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading