Refactor this method to reduce its Cognitive Complexity

In our C# project, we use sonar qube to find out cognitive complexity in the code. And I have several methods which contains switch cases and If conditions. Suppose that, I have a method in which following conditions.

Public void FindUI(string id)
{
  string uiName="";
  case "1":
       ui = new uiWin1();
       SetPosition(ui);
       uiName = SetName(id);
       if (uiName != "")
          ShowToolTip();
  case "2":
       ui = new uiWin2();
       SetPosition(ui);
       uiName = SetName(id);
       if (uiName != "")
          ShowToolTip();
   case "3" :
      same as above but ui = new uiWin3();
      same as above...

And it goes up to 15 case level.

}

How can I reduce the complexity here ? I have see a solution by using Dictionary in the stack overflow. But I think that cannot be used in my scenario.

If you any idea, please help me.

Hi,

Welcome to the community!

As the interface should be showing you, the nesting is coming from the nested if statements. The classic answer is to offload complexity into a helper method. So in this case, something like

Public void conditionallyShowToolTip(String uiName) {
     if (uiName != "")
          ShowToolTip();
}

Public void FindUI(string id)
{
  string uiName="";
  case "1":
       ui = new uiWin1();
       SetPosition(ui);
       uiName = SetName(id);
       conditionallyShowToolTip(uiName);
  case "2":
       ui = new uiWin2();
       SetPosition(ui);
       uiName = SetName(id);
       conditionallyShowToolTip(uiName);
   case "3" :
      // &etc...

 
HTH,
Ann

1 Like