2015-10-05 90 views
1

我有一個'Validator'類需要做一些簡單的驗證。但是,有些情況下可能需要調用全部或只是一種方法。依賴於參數的可選驗證

用於驗證的接口被定義爲:

internal interface IBrandValidator 
    { 
    BrandInfo ValidateBrands(); 
    } 

類定義爲對象返回:

internal class BrandInfo 
    { 
    public Organisation Brand { get; set; } 
    public Client Client { get; set; } 
    public Location Location { get; set; } 
    public Language Language { get; set; } 
    } 

實現該接口的類:

internal class ClientValidator : IBrandValidator 
    { 
    private readonly int? clientId; 
    private readonly int? locationId; 
    private readonly int? languageId; 

    public ClientValidator(int clientId, int? locationId, int? languageId) 
    { 
     this.clientId = clientId; 
     this.locationId = locationId; 
     this.languageId = languageId; 
    } 

    public BrandInfo ValidateBrandDimensions() 
    { 
     var brandInfo= new BrandInfo(); 

     //Optional validation 
     if(client != null) 
     brandDimensions.Client = ValidateClient(clientId); 
     if(locationId != null) 
      brandDimensions.Location = ValidateLocation(locationId); 
     if(languageId != null) 
      brandDimensions.Language = ValidateLanguage(languageId); 

     return brandInfo; 
    } 
    } 

我的問題是。評論'可選驗證'下的3種驗證方法。可能或可能不需要被調用。但是,可能還有一些事情需要在將來驗證,並且使用if語句的可空int可能是一條糟糕的路線。

有沒有我可以實現的設計模式來實現類似的東西?

+0

可能會單獨執行你的界面嗎? –

回答

1

你的代碼是難以預料通過閱讀例如:

brandDimensions.Client = ValidateClient(clientId); 

ValidateClient應該返回truthy或falsy對象。但分配給名稱爲「客戶端」的對象。 您的驗證器返回BrandInfo對象。但不包括任何指示其是否有效的財產或方法?!?

ClientValidator不必驗證客戶端 - 因爲它可以爲空?

它認爲你應該考慮重新組織你的部分代碼。

如果一個類從一個標識符創建了很多對象,你可以使用工廠模式。

如果您想在ComplexObjectValidator之後驗證複雜的對象名稱。 複雜對象的每個部分都得到驗證。

如果有效的是,例如Id是可以爲空的,則將該檢查放入Validator Implementation中。

很難說更多的細節,因爲它不清楚你的代碼做什麼或打算做什麼。

編輯: 作爲一個經驗法則:

Truthy或falsy方法:用前綴「是」,「必須」,「應該」,「有」,「可以」等 如果一個方法應返回一個對象:「 「GetValidatedClient」「ValidateAndReturnClient」「CreateClient」

因此,有人在未來(6個月,3年,10年)閱讀您的代碼,可以從您的函數名稱推斷出行爲。

ValidateClient會暗示它只是驗證。更具體地說,它只是返回void。因爲它只是驗證。如果它返回真值或僞值,則使用上面列出的前綴之一。如果它返回一個Validator對象,例如使用「GetValidationResultFor(xyz)」。

+0

感謝您的迴應。每種驗證方法都會返回一個對象。如果驗證失敗,則拋出異常。我將使用你提到的命名約定。 – JBond