我编写了这段代码来验证我的业务规则,我想知道这是否是验证业务对象的最佳解决方案。这样我就可以学会对我的所有项目进行这样的验证。这个解决方案可能有很多关于软件设计最佳实践的严重问题。
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);
}
}
我将不胜感激有关如何编写此代码的任何建议。