.Net Tips — Use Request and Response objects

We’ve all been there before, write a sim­ple ser­vice with a sim­ple method:

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

As time goes by, the sim­ple method gets more com­pli­cat­ed, and the list of para­me­ters grows and even­tu­al­ly sim­ple method is over­loaded to pro­vide more vari­ety and sim­ple method is sim­ple no more!

A sim­ple solu­tion to this is the Request-Response pat­tern, by encap­su­lat­ing all the input and out­put val­ues into request and response objects you will be able to:

  • solve the prob­lem with grow­ing para­me­ters
  • have an easy way of pro­vid­ing mul­ti­ple results
  • add input/output val­ues incre­men­tal­ly

And you’ll be able to do all this with­out even chang­ing the ser­vice con­tract!

[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 addi­tion, you can also cre­ate a hier­ar­chy of request/response objects and con­sol­i­date your val­i­da­tion log­ic in val­ida­tor class­es or cus­tom val­i­da­tion attrac­tions (you can use Post­Sharp to write attrib­ut­es that take care of the val­i­da­tion ‘aspect’ of your appli­ca­tion).

References:

API Design Pat­terns – Request/Response