2015-01-14 24 views
0

好的,所以這是我在我的應用程序的某些地方的代碼片段。我需要提高這個功能的maintainbility指數和圈複雜度:在switch case使用的字符串的有什麼方法可以提高此代碼片段的可維護性指數和圈複雜度?

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; 

基本上,我有不同的參數不同的方法和返回類型,以及不同的組,但什麼是常見的是while loop and the if else conditions 。我需要找到一種方法來使代碼「不那麼複雜」,特別是在條件和循環的使用方面。 我的想法是將開關盒移到一個方法然後調用它,但那仍然是正常的。 那麼,有沒有什麼辦法可以改善這段代碼呢?

編輯:我一直特別要求不要使用對象的XML序列化,或xmlDoc中,對於這個問題,遺憾的是

+0

您可以申請多態性。對於switch case中的每個案例字符串,使用單個方法分隔派生類型。和一個工廠來創建派生類型的實例。 –

+4

此問題似乎是無關緊要的,因爲它屬於http://codereview.stackexchange.com/ –

+0

將源xml序列化爲對象並使用它們創建HotelBookLogEntry。 – Reniuz

回答

1

你可能可以做什麼,即使我真的不知道,如果這個執行得更好或產量更好的複雜性結果,是使用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(); 
    } 
} 
相關問題