2012-04-09 126 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]属性标记字段足以使其自动被要求为非空值。手动执行验证,使用Validator辅助类。

+0

我没有使用mvc。我用mvp标记了这个问题,但是感谢这些信息。 – jim 2012-04-09 20:02:29

+0

除IRule接口外的其他任何问题? – jim 2012-04-13 08:22:36