简体   繁体   中英

How to refactor this method to reduce its cognitive complexity

I need help, I'm trying to refactor this method to reduce its cognitive complexity sonarqube display this issue

private void PopulateBook(Book b)
{
    if (b.page.num001 == null) b.page.num001 = string.Empty;
    if (b.page.num002 == null) b.page.num002 = string.Empty;
    if (b.page.num003 == null) b.page.num003 = string.Empty;
    if (b.page.num004 == null) b.page.num004 = string.Empty;
    if (b.page.num005 == null) b.page.num005 = string.Empty;
    if (b.page.num006 == null) b.page.num006 = string.Empty;
    if (b.page.num007 == null) b.page.num007 = string.Empty;
    if (b.page.num008 == null) b.page.num008 = string.Empty;
    if (b.page.num009 == null) b.page.num009 = string.Empty;
    if (b.page.num010 == null) b.page.num010 = string.Empty;
    if (b.page.num011 == null) b.page.num011 = string.Empty;
    if (b.page.num012 == null) b.page.num012 = string.Empty;
    if (b.page.num013 == null) b.page.num013 = string.Empty;
    if (b.page.num014 == null) b.page.num014 = string.Empty;
    if (b.page.num015 == null) b.page.num015 = string.Empty;
    if (b.page.num016 == null) b.page.num016 = string.Empty;
    if (b.page.num017 == null) b.page.num017 = string.Empty;
    if (b.page.num018 == null) b.page.num018 = string.Empty;
    if (b.page.num019 == null) b.page.num019 = string.Empty;
    if (b.page.num020 == null) b.page.num020 = string.Empty;
}

You could redesign the Page class.

I do not know what num001 etc, refer to as a number on a page. Is it word indexes? number of characters, specific characters? Or something else entirely?

But whatever it is:

public class Page {

   public List<Num> numList

   public Page()
   {
      NumList = InitializeNumList();
   }

   private List<Num> InitializeNumList()
   {
      NumList = new List<Num>{};
      for(int i = 0; i < 20; i++)
      {
          NumList.add(new Num(i))
      }
   }

} 

public class Num
{
   public int Id {get;set;};
   public string SomeString {get;set;}

   public Num(int id)
   {
       Id = id;
       SomeString = "";
   }
}

If you want to reduce number of lines of code and assuming your "Page" is a class with these properties only - Then you can use some sort of reflection to set properties using a loop.

  private static void PopulateBook(Book b)
        {
            var page = b.page;
            PropertyInfo[] properties = typeof(page).GetProperties();
            foreach(var prop in properties)
            {
                if(prop.GetValue(page) == null)
                prop.SetValue(page, String.Empty);
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM