.Net Tips – Use Request and Response objects

We’ve all been there before, write a simple service with a simple method:

[ServiceContract]
public interface IService
{
    [OperationContract]
    int SimpleMethod(object param1);
}

As time goes by, the simple method gets more complicated, and the list of parameters grows and eventually simple method is overloaded to provide more variety and simple method is simple no more!

A simple solution to this is the Request-Response pattern, by encapsulating all the input and output values into request and response objects you will be able to:

  • solve the problem with growing parameters
  • have an easy way of providing multiple results
  • add input/output values incrementally

And you’ll be able to do all this without even changing the service contract!

[ServiceContract]
public interface IService
{
    [OperationContract]
    SimpleMethodResponse SimpleMethod(SimpleMethodRequest request);
}

[DataContract]
public void SimpleMethodRequest
{
    [DataMember]
    public object Param1 { get; set; }

    [DataMember]
    public string Param2 { get; set; }

    [DataMember]
    public int Param3 { get; set; }

    …
}

[DataContract]
public void SimpleMethodResponse
{
    [DataMember]
    public bool Success { get; set; }

    [DataMember]
    public int? ErrorCode { get; set; }

    [DataMember]
    public string ErrorMessage { get; set; }

    …
}

In addition, you can also create a hierarchy of request/response objects and consolidate your validation logic in validator classes or custom validation attractions (you can use PostSharp to write attributes that take care of the validation ‘aspect’ of your application).

References:

API Design Patterns – Request/Response

Leave a Comment

Your email address will not be published. Required fields are marked *