2012-08-14 87 views
1
private bool SearchFilter(object sender) 
{ 
    CommDGDataSource item = sender as CommDGDataSource; 
    if (FilterPropertyList.IsErrorFilter) 
    { 
     if (!item.Error) 
      return false; 
    } 
    if (FilterPropertyList.IsDestinationFilter) 
    { 
     if (!(item.Destination == FilterPropertyList.Destination)) 
      return false; 
    } 
    if (FilterPropertyList.IsSourceFilter) 
    { 
     if (!(item.Source == FilterPropertyList.Source)) 
      return false; 
    } 

    return true; 
} 

上面的代碼運行良好,但我想知道是否有更多的優雅的方式來編寫上述代碼。更優雅的處理這種邏輯的方式

+1

我只會用'!'爲原子語句,在這種情況下'!='會救你的括號... – 2012-08-14 09:06:30

+0

你也可以使用一個開關語句外,如果結構 – Terry 2012-08-14 09:08:20

+0

的過濾器可以更比一次的事情?例如。它可以是'ErrorFilter'和'SourceFilter'嗎? – verdesmarald 2012-08-14 09:12:57

回答

4

您可以更具可讀性一點通過製作小改動如下

private bool SearchFilter(object sender) 
{ 
    CommDGDataSource item = sender as CommDGDataSource; 

    if (FilterPropertyList.IsErrorFilter && !item.Error) 
     return false; 

    if (FilterPropertyList.IsDestinationFilter && item.Destination != FilterPropertyList.Destination) 
     return false; 

    if (FilterPropertyList.IsSourceFilter && item.Source != FilterPropertyList.Source) 
     return false; 

    return true; 
} 
+3

這是否更具可讀性取決於顯示器的寬度,但我認爲它應該適合大多數人。 – RickL 2012-08-14 09:16:58

+1

這可能是我會寫的。我知道有些人更喜歡用'return'替換最後一個'if',而不是使用額外的'return',但我更喜歡這個,因爲它稍後使得修改過濾器變得更容易和更清晰。 – verdesmarald 2012-08-14 09:20:29

+0

唯一的缺點是你不能粘貼任何額外的邏輯,如果只有第一個條件爲真 – JleruOHeP 2012-08-14 09:29:55

3

我不認爲這是在與布爾表達式搞亂,除非是在我的comment提到的簡單的修改很多優點。如果你最終得到醜陋的代碼,你的設計就不那麼好了。

在這種情況下,你很可能通過重構responsibities:

  • 創建過濾器列表對象
  • 在這些對象

事情是這樣的僞代碼實現的邏輯:

foreach (var filter in filters) 
    if !filter.Filter(item) return false; 
return true; 
public interface IFilter 
{ 
    bool Filter(CommDGDataSource item); 
} 

public class ErrorFilter : IFilter 
{ 
    public bool Filter(CommDGDataSource item) 
    { 
     return item.Error; 
    } 
} 

public class DestinationFilter : IFilter 
{ 
    public string Destination { get; set; } 

    public bool Filter(CommDGDataSource item) 
    { 
     return item.Destination == Destination; 
    } 
} 

//etc.. 
相關問題