Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Last active February 21, 2020 07:33
Show Gist options
  • Save atifaziz/98637da96690c6862391828d1e1bc541 to your computer and use it in GitHub Desktop.
Save atifaziz/98637da96690c6862391828d1e1bc541 to your computer and use it in GitHub Desktop.
A less ceremonial approach to “explicit endomorphism” presented by Mark Seemann in “Builder as a monoid”
// This script is related the following blog entry by Mark Seeman titled,
// "Builder as a monoid":
//
// https://blog.ploeh.dk/2020/02/17/builder-as-a-monoid/
//
// It demonstrates a simpler approach to avoid the ceremony of "explicit
// endomorphism" by using merely delegates. It does so by replacing
// "IEndomorphism<T>" with "Func<T, T>" and then using "+" in lieu of
// "AppendEndomorphism<T>" to achieve the same effect.
//
// Run using dotnet-script (https://github.com/filipw/dotnet-script).
// First, ensure you have it installed:
//
// dotnet tool install -g dotnet-script
//
// then execute this script using the following command-line:
//
// dotnet script BuilderAsMonoid.csx
#r "nuget: Newtonsoft.Json, 12.0.3"
#nullable enable
using System;
using System.Linq;
using System.Net.Http;
using Newtonsoft.Json;
using static System.Console;
using HttpRequestMessageBuilderEndomorphism = System.Func<HttpRequestMessageBuilder, HttpRequestMessageBuilder>;
var setup
= HttpRequestMessageSetup.Method(HttpMethod.Post)
+ HttpRequestMessageSetup.Json(new
{
id = Guid.NewGuid(),
date = "2020-03-22 19:30:00",
name = "Ælfgifu",
email = "ælfgifu@example.net",
quantity = 1
});
var msg = setup(new HttpRequestMessageBuilder("http://example.com/")).Build();
WriteLine($"{msg.Method} {msg.RequestUri} HTTP/{msg.Version.ToString(2)}");
foreach (var (name, values) in msg.Headers.Concat(msg.Content.Headers))
WriteLine($"{name}: {string.Join(", ", values)}");
WriteLine();
WriteLine(await msg.Content.ReadAsStringAsync());
static class HttpRequestMessageSetup
{
public static HttpRequestMessageBuilderEndomorphism Method(HttpMethod method) => b => b.WithMethod(method);
public static HttpRequestMessageBuilderEndomorphism Json(object body) => b => b.AddJsonBody(body);
}
// Source: https://blog.ploeh.dk/2020/02/10/builder-isomorphisms/#ed99bc3715f541be8b6b9239848395e3
// Copyright Mark Seemann 2020
sealed class HttpRequestMessageBuilder
{
private readonly Uri url;
private object? jsonBody;
public HttpRequestMessageBuilder(string url) : this(new Uri(url)) { }
public HttpRequestMessageBuilder(Uri url)
{
this.url = url;
Method = HttpMethod.Get;
}
public HttpMethod Method { get; private set; }
public HttpRequestMessageBuilder WithMethod(HttpMethod newMethod)
{
Method = newMethod;
return this;
}
public HttpRequestMessageBuilder AddJsonBody(object jsonBody)
{
this.jsonBody = jsonBody;
return this;
}
public HttpRequestMessage Build()
{
var message = new HttpRequestMessage(Method, url);
BuildBody(message);
return message;
}
private void BuildBody(HttpRequestMessage message)
{
if (jsonBody is null)
return;
string json = JsonConvert.SerializeObject(jsonBody);
message.Content = new StringContent(json);
message.Content.Headers.ContentType.MediaType = "application/json";
}
}
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment