jim
jim

Reputation: 495

is this method the best way to validate business objects

I’ve written this code to validate my business rules and I want to know if this is the best possible solution to validate business objects. That way I can learn to do my validation like this for all my projects. This solution might have a lot of serious issues regarding the best practices of software design.

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);
    }
}

I would appreciate any kind of advice on how this code should have been written.

Upvotes: 1

Views: 723

Answers (1)

Anders Abel
Anders Abel

Reputation: 69270

Take a look at the IValidatableObject interface. It's doing the same as your IRule interface, except that it allows several error messages to be returned on the same time.

There are also built in validation rules in the data annotations package. For example, when writing an MVC model it is enough to mark a field with a [Required] attribute to have it automatically required to be non-null. The perform the validation manually, use the Validator helper class.

Upvotes: 2

Related Questions