Simple Communications

Here’s a set of patterns that I’ve seen in other projects and used a number of times myself, with success. I’d like to share them with you. They revolve around communication over a network.

The first is more of a convenience than anything else, but I’ve enjoyed it so much, for such a long time now, that I think you might as well. It’s a fluent builder for constructing REST requests. As you probably deciphered, it’s a combination of the fluent interface pattern and a builder pattern, and it looks like this:

public class RequestBuilder
{
    private IRestRequest request;

    private static RequestBuilder Init(string resourceUri, Method method)
    {
        var resource = resourceUri.StartsWith("/", StringComparison.CurrentCultureIgnoreCase) 
            ? resourceUri.Substring(1) 
            : resourceUri;
        var builder = new RequestBuilder { request = new RestRequest($"api/{resource}", method) };
        builder.request.AddHeader(C.Headers.Accept, C.Headers.Json);

        return builder;
    }

    #region Static Constructors

    public static RequestBuilder POST(string resourceUri)
    {
        return Init(resourceUri, Method.POST);
    }

    #endregion
}
  1. The point here is that the entry point to this class is no-longer the constructor. It’s one of the static constructors, each representing an http verb (I’ve omitted the other http verbs for brevity, but you can check the gist for a fuller version).
  2. I’m using RestSharp here to build the rest request, but I’ve used multiple different libraries in other projects just the same for making requests (RestSharpPortable, and plain HttpClient being two others).

This isn’t very interesting yet, but it becomes so when you start adding the fluent builder methods that build up the request. Those look like this:

public RequestBuilder WithHeader(string key, string value)
{
    if (!string.IsNullOrEmpty(value))
    {
        this.request.AddHeader(key, value);
    }

    return this;
}

public RequestBuilder WithParameter(string key, string value)
{
    this.request.AddParameter(key, value);

    return this;
}

public RequestBuilder WithQueryStringParameter(string key, string value)
{
    this.request.AddQueryParameter(key, value);

    return this;
}

… which are all very simple, in and of themselves, but they lead to being able to write code that looks like this:

var request = RequestBuilder.GET($"v1/emeployee/{id}")
    .WithHeader(C.Headers.ContentType, C.Headers.Json)
    .WithHeader(C.Headers.Authorization, $"Bearer {auth.AccessToken}")
    .WithQueryStringParameter("key", "value")
    .Build();

Which, to my eyes, is very readable and really nice to work with (and code completion tools work really well with this as well).

I’m sure you are seeing the Build function and have a good idea what that might be… it’s here:

public IRestRequest Build()
{
    return this.request;
}

Simple and effective. I hope you use it and enjoy writing code with it.

Next post, I will show the next pattern, which often results on rock solid communication over a network.

Hope it helps!

What are your thoughts?

This site uses Akismet to reduce spam. Learn how your comment data is processed.