Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to reduce cyclomatic complexity in a Factory method without using reflection

In my factory method I use Switch statement to create concrete objects. This results in very high cyclomatic complexity. Here is a sample code:

private static UnitDescriptor createUnitDescriptor(string code)
{
     switch (code)
     {
         case UnitCode.DEG_C:
             return new UnitDescriptorDegC();

         case UnitCode.DEG_F:
             return new UnitDescriptorDegF();

         :
         :
         default:
             throw new SystemException(string.format("unknown code: {o}", code);
      }
  }

How can I refactor this to reduce cyclomatic complexity? If I use reflection to create objects or something else to build objects is it better than above method?

like image 875
r.net Avatar asked Aug 23 '13 08:08

r.net


1 Answers

It's possible for you to use a Dictionary to remove the switch statement entirely:

class MyClass
{
    private static Dictionary<string, Func<UnitDescriptor>> dict = new Dictionary<string, Func<UnitDescriptor>>();

    static MyClass()
    {
        dict.Add(UnitCode.DEG_C, () => new UnitDescriptorDegC());
        dict.Add(UnitCode.DEG_F, () => new UnitDescriptorDegF());
        // Other mappings...
    }

    private static UnitDescriptor createUnitDescriptor(string code)
    {
        Func<UnitDescriptor> value;
        if (dict.TryGetValue(code, out value))
        {
            return value();
        }

        throw new SystemException(string.Format("unknown code: {0}", code));
    }
}
like image 94
Adi Lester Avatar answered Nov 10 '22 19:11

Adi Lester