2012-04-09 2 views
1

비즈니스 규칙의 유효성을 검사하기 위해이 코드를 작성 했으므로 비즈니스 개체의 유효성을 검사하는 최상의 솔루션인지 알고 싶습니다. 그런 식으로 모든 프로젝트에 대해 이렇게 유효성 검사를하는 법을 배울 수 있습니다. 이 솔루션은 소프트웨어 설계 모범 사례와 관련하여 많은 심각한 문제가있을 수 있습니다.이 방법은 비즈니스 개체의 유효성을 검사하는 가장 좋은 방법입니다.

public interface IRule 
{ 
    bool Isvalid(); 
} 
public class CategoryRule : IRule 
{ 
    CategoryRepository _category; 
    string _id, _name, _parent; 

    public CategoryRule(string id, string name, string parent) 
    { 
     _id = id; 
     _name = name; 
     _parent = parent; 
    } 
    public object IsValid() 
    { 
     bool result = this.ValidateId(); 
     if (result) 
      result = this.ValidateName(); 
     else 
     { 
      this.Message = "the id value is not correct."; 
      return false; 
     } 
     if (result) 
      result = this.ValidateParent(); 
     else 
     { 
      this.Message = "the name value is not correct."; 
      return false; 
     } 
     if (result) 
      return _category; 
     else 
     { 
      this.Message = "the parent value is not correct."; 
      return false; 
     } 

    } 
    private bool ValidateId() 
    { 
     long id; 
     if (long.TryParse(_id, out id)) 
      return true; 
     _category.Id = id; 
     return false; 
    } 
    private bool ValidateName() 
    { 
     if (!string.IsNullOrWhiteSpace(_name)) 
      return true; 
     _category.Name = _name; 
     return false; 
    } 
    private bool ValidateParent() 
    { 
     long parent; 
     if (long.TryParse(_parent, out parent)) 
      return true; 
     _category.Parent = parent; 
     return false; 
    } 
    public string Message 
    { 
     get; 
     private set; 
    } 
} 
public class CategoryPresenter 
{ 
    View _view; 
    CategoryRepository _model; 

    public void AddCategory() 
    { 
     CategoryRule rule = new CategoryRule(_view.Id, _view.Name, _view.Parent); 
     object obj = rule.IsValid(); 
     if (obj.GetType() == typeof(bool)) 
      _view.ShowError(rule.Message); 
     _model.Add(obj as CategoryRepository); 
    } 
} 

이 코드의 작성 방법에 대한 조언을 주시면 감사하겠습니다.

답변

2

IValidatableObject 인터페이스를 살펴보십시오. 동일한 오류 메시지가 동시에 반환되는 것을 제외하고는 IRule 인터페이스와 동일합니다.

데이터 주석 패키지에는 유효성 검사 규칙이 내장되어 있습니다. 예를 들어, MVC 모델을 작성할 때 [Required] 속성이있는 필드를 표시하면 자동으로 null이 아니도록 요구됩니다. 유효성 검사를 수동으로 수행하려면 Validator 도우미 클래스를 사용하십시오.

+0

mvc를 사용하고 있지 않습니다. 나는 mvp로 질문을 태그했지만 정보를 주셔서 감사합니다. – jim

+0

IRule 인터페이스를 제외한 다른 모든 문제는 무엇입니까? – jim

관련 문제