有没有办法提高此代码片段的可维护性指数和圈复杂度
本文关键字:指数 可维护性 复杂度 片段 高此 代码 有没有 | 更新日期: 2023-09-27 18:37:25
好的,这是我在应用程序的某些地方的代码片段。我需要提高此函数的可维护性指数和圈复杂度:
private HotelBookLogEntry ParseService(XmlReader xmlReader, HotelBookLogEntry hotelBookLogEntry)
{
while (!xmlReader.EOF)
{
if (xmlReader.IsStartElement())
{
switch (xmlReader.Name.ToLower())
{
case "datefrom":
hotelBookLogEntry.HotelBookCriteria.CheckInDate = DateTime.ParseExact(xmlReader.GetAttribute("date"), "yyyymmdd", CultureInfo.InvariantCulture);
xmlReader.Read();
break;
case "dateto":
hotelBookLogEntry.HotelBookCriteria.CheckOutDate = DateTime.ParseExact(xmlReader.GetAttribute("date"), "yyyymmdd", CultureInfo.InvariantCulture);
xmlReader.Read();
break;
case "currency":
hotelBookLogEntry.HotelBookCriteria.RequestedCurrency = xmlReader.GetAttribute("code");
xmlReader.Read();
break;
case "hotelinfo":
xmlReader.ReadToDescendant("Code");
hotelBookLogEntry.HotelBookCriteria.SupplierHotelId = xmlReader.ReadElementContentAsString();
break;
case "availableroom":
hotelBookLogEntry = ParseAvailableRoom(xmlReader.ReadSubtree(), hotelBookLogEntry);
break;
case "errorlist":
hotelBookLogEntry = GetErrors(xmlReader, hotelBookLogEntry);
break;
default:
xmlReader.Read();
break;
}
}
else
{
xmlReader.Read();
}
}
return hotelBookLogEntry;
基本上,我有不同的方法,具有不同的参数和返回类型,以及switch case
中使用的不同字符串集,但常见的是while loop and the if else conditions
。我需要找到一种方法来使这段代码"不那么复杂",尤其是在使用的条件和循环数量方面。我的想法是将开关大小写移动到一个方法,然后调用它,但这仍然可以。那么,有什么方法可以改进这段代码吗?
编辑:不幸的是,我被特别要求不要使用Object-XML序列化或XMLDoc
即使我真的不知道这是否表现更好或产生更好的复杂性结果,您也可以做的是使用Dictionary
并为您的情况定义几个Action
。
我个人喜欢像您这样的场景的这个解决方案,因为它看起来很漂亮,并且如果您必须添加更多情况,它不会弄乱您的代码。
刚刚创建了一个快速示例来说明我的意思:
class Program
{
static void Main(string[] args)
{
var delegates = new Dictionary<char, Action<char>>
{
{'e', c => { Console.WriteLine("Found an 'e'"); }},
{'o', c => { Console.WriteLine("Found an 'o'"); }}
};
var s = "Hello World";
var it = s.GetEnumerator();
while (it.MoveNext())
{
if (delegates.ContainsKey(it.Current))
delegates[it.Current](it.Current);
}
Console.ReadKey();
}
}