.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

Enjoy what you’re reading? Subscribe to my newsletter and get more content on AWS and serverless technologies delivered straight to your inbox.


Yan Cui

I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I have run production workload at scale in AWS for nearly 10 years and I have been an architect or principal engineer with a variety of industries ranging from banking, e-commerce, sports streaming to mobile gaming. I currently work as an independent consultant focused on AWS and serverless.

You can contact me via Email, Twitter and LinkedIn.

Hire me.


Check out my new course, Complete Guide to AWS Step Functions.

In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, design patterns and best practices.

Get Your Copy