我有一个棕色的应用程序,它有一个复杂的方法。 CC为14. if语句验证应用程序设置并生成相应的内联SQL。
E.G。此if语句检查设置。设置是自定义代码,包含多个bool
(不 bool?
)属性的DTO。
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);
}
我不知道如何简化这个bool逻辑。 Null coalesce?...我不知道它会让这更好。该模式在同一方法中出现多次。所以我希望多次重复使用这个答案来减少整体CC并提高可读性。你有什么建议?
已更新
在决定撕掉第一个验证后,添加了进一步的方法逻辑。
答案 0 :(得分:1)
我首先要缩小代码:
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);
可以收缩:
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);
但我同意这不是一个非常好的代码。