如何提高代码中的认知复杂性?
我有一个方法,它有 while 循环,在很多 IF ELSE 块中,我尝试使用 SWITCH 语句删除 IF ELSE,但根据 SONAR 立方体分析,认知复杂性没有改善。
这是我现有的代码:
while (this.moveNextDelegate(fileLineEnumerator))
{
var line = fileLineEnumerator.Current;
var recordType = GetRecordType(line); // This Method returns the type of record
if (recordType == "1")
{
headerId++;
fileHeader = line; // Here fileHeader is being used in downsteam code flow - line 19
// some custom logic - deleted
}
else if (recordType == "5")
{
batchHeader = line; // Here batchHeader is being used in downsteam code flow - line 19
isRepeativeRecord = false;
}
else if (recordType == "6")
{
batchHeaderId = // some custom logic - deleted
// Here batchHeaderId is being used in downsteam code flow - line 35
detailId++;
isFlag = false;
isRepeativeRecord = true;
// some custom logic - deleted
}
else if (recordType == "7" && !isFlag)
{
addendaId++;
detailRecordsExist = true;
// some custom logic - deleted
}
currentIndex++;
}
我使用 Switch 语句的新代码 - 但复杂性仍然没有改善
while (this.moveNextDelegate(fileLineEnumerator))
{
var line = fileLineEnumerator.Current;
var recordType = GetRecordType(line);
switch (recordType)
{
case "1":
{
headerId++;
fileHeader = line;
// some custom logic - deleted
break;
}
case "2":
{
batchHeader = line;
isRepeativeRecord = false;
break;
}
case "6":
{
// some custom logic - deleted
break;
}
case "7":
{
if (!isFlag)
{
// some custom logic - deleted
}
break;
}
case "8":
{
if (!isFlag)
{
// some custom logic - deleted
}
break;
}
}
currentIndex++;
}