views:

367

answers:

1

I currently have to validate custom Field Objects for my application. Simply put, each Field object consists of information about the validation for the field, as well as the value of the field. I am validating fields in bulk, so currently, I have a validation class, that has a method for each validation. For required fields, it looks something like this:

      private void RequiredFields()
      {
            foreach (Field field in allFields)
            {
                if ((field.Required == true) && (field.Value == string.Empty))
                {
                    field.isValid = false;
                }
            }
      }

Now my problem is that I feel like I should a layer of abstraction to the validation, so instead of saying:

if ((field.Required == true) && (field.Value == string.Empty))

... I would add a validation class, to accept the values and turn it into this:

if (!validater.RequiredFields(field.Required, field.Value))

If I were to do this, it would allow me to reuse the validation class without use of the field objects, and it would also allow better unit testing... However, it seems like and unnecessary layer of abstraction and also somewhat repetitive... Keep in mind, this is the most simple of all the validation.

Suggestions?

+1  A: 

Why not have make Field objects responsible for their own validation?

class Field
{
    public bool Required { get; }
    public string Value { get; set; }

    // assuming that this method is virtual here
    // if different Fields have different validation logic
    // they should probably be separate classes anyhow and
    // simply implement a common interface of inherit from a common base class.
    public override bool IsValid
    {
        get { return Required && Value != String.Empty; }
    }
}
Ed Swangren
I second this but I would be hesitant to make a Field that isn't required alway invalid.
Austin Salonen
Well, I did consider this. However, I am validating roughly 100 fields, all with different validation, only some of which is Field Object specific. I'd like to keep the validation together.
Jeff
If you are validating 100 field, all of which require different validation logic, and only some of them are your own custom classes, then I would say you have a deeper design flaw.
Ed Swangren
I would suggest that every Field should be a "Field" type but perhaps extend the Field class when you need to. Now every field object exposes the same interface and you simply ask each one "are you valid?"
Ed Swangren
The fact that your validation logic is so disparate should nudge you toward using polymorphism to your advantage.
Ed Swangren
To clarify what I meant in my previous comment, each field is a Field Object and has to undergo required field validation. Some fields, on top of the normal field validation, require special validation... this is sounding more and more like a case for polymorphism. Thanks Ed.
Jeff