Reduce the cyclic complexity of checking settings

I have an application that has a complicated method. CC is 14. If statements check application parameters and generate the corresponding embedded SQL.

eg. This if statement checks the settings. settings - this is custom code, DTO with several properties bool( not bool? ).

        string conditions = " AND (";

        List<string> conditionStrings = new List<string>();

        if (settings.AlwaysIncludeCommonResults && settings.SelectedCommonLabs.Count > 0)
        {
            string common = " (Table.Name in (";
            for (int i = 0; i < settings.SelectedCommonLabs.Count; i++)
            {
                common += string.Format("'{0}'", settings.SelectedCommonLabs[i]);
                if (i < settings.SelectedCommonLabs.Count - 1)
                    common += ", ";
            }
            common += ")) ";
            conditionStrings.Add(common);
        }

        if (settings.AlwaysSelectLast24HoursResults)
        {
            string last24 = " (DateDiff(hh, Table.PerformedDtm, GetDate()) < 24) ";
            conditionStrings.Add(last24);
        }

I do not know what to do to simplify this bool logic. Does the zero merge? ... I do not know what will make it better. This pattern appears several times in the same method. Therefore, I hope to reuse the answer several times in order to reduce the overall CC and increase readability. What are you offering?

UPDATED
After making a decision to break the first check, additional method logic has been added.

+3
source share
1 answer

I would shorten the code a bit:

   string common = " (Table.Name in (";
            for (int i = 0; i < settings.SelectedCommonLabs.Count; i++)
            {
                common += string.Format("'{0}'", settings.SelectedCommonLabs[i]);
                if (i < settings.SelectedCommonLabs.Count - 1)
                    common += ", ";
            }
            common += ")) ";
            conditionStrings.Add(common);

can be reduced:

string common = " (Table.Name in (";
//if SelectedCommonLabs is a collection of strings, LINQ your way through it
common += string.Join(", ", settings.SelectedCommonLabs.ToList().Select(lab => string.Format("'{0}'",lab)));
common += ")) ";
conditionStrings.Add(common);

But I agree that this is not very good code to start with.

+1
source

All Articles