Home  /  Questions  /  Question



D K
50   50
Apr 07, 2014


Pattern for performing validation on fields in a data object

I have a data object called "APIRequest". This object contains all the data necessary to make a request on an API I have. The object has several data fields (ex: Address, Address2, City, State, Zip). Once the request object is populated with data, I want to run several post-processing validation steps on the fields before sending them to the API.

Currently, I'm looking at a single long method (~50 lines) called "ValidateInputs()" that is inside APIRequest. I don't like that this kind of business logic is in what's supposed to be a simple data payload object -- the request really should only be concerned with its data. There's also tons of duplicated code inside the ValidateInputs() method that needs to be composed into smaller methods, and I also want to be able to change this validation behavior on the fly. All of this suggests I really need the validation steps to be in their own class.

I was considering moving the ValidateInputs() method into a Decorator object that decorates around APIRequest so the request doesn't need to know anything about the validation being performed on it (as opposed to Strategy pattern in which case the request does need to know about the validation step).

But, I'm a bit hesitant to use Decorator because it's a bit heavy, and I'm not sure it really fits the Decorator paradigm of the decoration being transparent to the object underneath it (implementing all its public methods).

Any thoughts? Code sample attached.
public class APIRequest
{
   public string Address;
   public string Address2;
   public string City;
   public string State;
   public string Zip;

   public APIRequest(string Address, string Address2, string City, string State, string Zip)
   {
       //... populate fields
   }

   //Move this functionality into "class ValidateAPIRequest" which is a decorator of APIRequest?
   public void ValidateInputs()
   {
      Address = Address.Trim();
      Address2 = Address2.Trim();
      City = City.Trim();

      Address = Address.Replace(" - ", "");
      Address2 = Address2.Replace(" - ", "");
      
      Address = Address.Replace("#", " # ");
      Address2 = Address2.Replace("#", " # ");

      //...50 more lines of validation...
   }
}