ploeh blog https://blog.ploeh.dk danish software design en-us Mark Seemann Tue, 27 Sep 2022 06:13:58 UTC Tue, 27 Sep 2022 06:13:58 UTC Refactoring the TCP State pattern example to pure functions https://blog.ploeh.dk/2022/09/26/refactoring-the-tcp-state-pattern-example-to-pure-functions/ Mon, 26 Sep 2022 05:50:00 UTC <div id="post"> <p> <em>A C# example.</em> </p> <p> This article is one of the examples that I promised in the earlier article <a href="/2022/09/05/the-state-pattern-and-the-state-monad">The State pattern and the State monad</a>. That article examines the relationship between the <a href="https://en.wikipedia.org/wiki/State_pattern">State design pattern</a> and the <a href="/2022/06/20/the-state-monad">State monad</a>. That article is deliberately abstract, so one or more examples are in order. </p> <p> In this article, I show you how to start with the example from <a href="/ref/dp">Design Patterns</a> and refactor it to an immutable solution using <a href="https://en.wikipedia.org/wiki/Pure_function">pure functions</a>. </p> <p> The code shown here is <a href="https://github.com/ploeh/TCPStateCSharp">available on GitHub</a>. </p> <h3 id="f70ca28a361241e5a352399f8cf912d7"> TCP connection <a href="#f70ca28a361241e5a352399f8cf912d7" title="permalink">#</a> </h3> <p> The example is a class that handles <a href="https://en.wikipedia.org/wiki/Transmission_Control_Protocol">TCP</a> connections. The book's example is in C++, while I'll show my C# interpretation. </p> <p> A TCP connection can be in one of several states, so the <code>TcpConnection</code> class keeps an instance of the polymorphic <code>TcpState</code>, which implements the state and transitions between them. </p> <p> <code>TcpConnection</code> plays the role of the State pattern's <code>Context</code>, and <code>TcpState</code> of the <code>State</code>. </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">TcpConnection</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;TcpState&nbsp;State&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">internal</span>&nbsp;<span style="color:blue;">set</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">TcpConnection</span>() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;State&nbsp;=&nbsp;TcpClosed.Instance; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;ActiveOpen() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;State.ActiveOpen(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;PassiveOpen() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;State.PassiveOpen(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;More&nbsp;members&nbsp;that&nbsp;delegate&nbsp;to&nbsp;State&nbsp;follows...</span></pre> </p> <p> The <code>TcpConnection</code> class' methods delegate to a corresponding method on <code>TcpState</code>, passing itself an argument. This gives the <code>TcpState</code> implementation an opportunity to change the <code>TcpConnection</code>'s <code>State</code> property, which has an <code>internal</code> setter. </p> <h3 id="ffea200499f94145a0686e2481aebf2c"> State <a href="#ffea200499f94145a0686e2481aebf2c" title="permalink">#</a> </h3> <p> This is the <code>TcpState</code> class: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">TcpState</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">virtual</span>&nbsp;<span style="color:blue;">void</span>&nbsp;Transmit(TcpConnection&nbsp;connection,&nbsp;TcpOctetStream&nbsp;stream) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">virtual</span>&nbsp;<span style="color:blue;">void</span>&nbsp;ActiveOpen(TcpConnection&nbsp;connection) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">virtual</span>&nbsp;<span style="color:blue;">void</span>&nbsp;PassiveOpen(TcpConnection&nbsp;connection) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">virtual</span>&nbsp;<span style="color:blue;">void</span>&nbsp;Close(TcpConnection&nbsp;connection) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">virtual</span>&nbsp;<span style="color:blue;">void</span>&nbsp;Synchronize(TcpConnection&nbsp;connection) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">virtual</span>&nbsp;<span style="color:blue;">void</span>&nbsp;Acknowledge(TcpConnection&nbsp;connection) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">virtual</span>&nbsp;<span style="color:blue;">void</span>&nbsp;Send(TcpConnection&nbsp;connection) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> I don't consider this entirely <a href="/2015/08/03/idiomatic-or-idiosyncratic">idiomatic</a> C# code, but it seems closer to the book's C++ example. (It's been a couple of decades since I wrote C++, so I could be mistaken.) It doesn't matter in practice, but instead of a concrete class with <a href="https://en.wikipedia.org/wiki/NOP_(code)">no-op</a> <code>virtual</code> methods, I would usually define an interface. I'll do that in the next example article. </p> <p> The methods have the same names as the methods on <code>TcpConnection</code>, but the signatures are different. All the <code>TcpState</code> methods take a <code>TcpConnection</code> parameter, whereas the <code>TcpConnection</code> methods take no arguments. </p> <p> While the <code>TcpState</code> methods don't do anything, various classes can inherit from the class and override some or all of them. </p> <h3 id="d68a32e30a314c9ea7f45004482a7d98"> Connection closed <a href="#d68a32e30a314c9ea7f45004482a7d98" title="permalink">#</a> </h3> <p> The book shows implementations of three classes that inherit from <code>TcpState</code>, starting with <code>TcpClosed</code>. Here's my translation to C#: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">TcpClosed</span>&nbsp;:&nbsp;TcpState { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;TcpState&nbsp;Instance&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;TcpClosed(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:#2b91af;">TcpClosed</span>() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">void</span>&nbsp;ActiveOpen(TcpConnection&nbsp;connection) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Send&nbsp;SYN,&nbsp;receive&nbsp;SYN,&nbsp;Ack,&nbsp;etc.</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;connection.State&nbsp;=&nbsp;TcpEstablished.Instance; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">void</span>&nbsp;PassiveOpen(TcpConnection&nbsp;connection) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;connection.State&nbsp;=&nbsp;TcpListen.Instance; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> This implementation overrides <code>ActiveOpen</code> and <code>PassiveOpen</code>. In both cases, after performing some work, they change <code>connection.State</code>. </p> <blockquote> <p> "<code>TCPState</code> subclasses maintain no local state, so they can be shared, and only one instance of each is required. The unique instance of <code>TCPState</code> subclass is obtained by the static <code>Instance</code> operation. [...] </p> <p> "This make each <code>TCPState</code> subclass a Singleton [...]." </p> <footer><cite><a href="/ref/dp">Design Patterns</a></cite></footer> </blockquote> <p> I've maintained that property of each subclass in my C# code, even though it has no impact on the structure of the State pattern. </p> <h3 id="8e21a702cffe4ef09455a29c2981ab39"> The other subclasses <a href="#8e21a702cffe4ef09455a29c2981ab39" title="permalink">#</a> </h3> <p> The next subclass, <code>TcpEstablished</code>, is cast in the same mould: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">TcpEstablished</span>&nbsp;:&nbsp;TcpState { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;TcpState&nbsp;Instance&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;TcpEstablished(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:#2b91af;">TcpEstablished</span>() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">void</span>&nbsp;Close(TcpConnection&nbsp;connection) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;send&nbsp;FIN,&nbsp;receive&nbsp;ACK&nbsp;of&nbsp;FIN</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;connection.State&nbsp;=&nbsp;TcpListen.Instance; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">void</span>&nbsp;Transmit( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TcpConnection&nbsp;connection, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TcpOctetStream&nbsp;stream) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;connection.ProcessOctet(stream); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> As is <code>TcpListen</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">TcpListen</span>&nbsp;:&nbsp;TcpState { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;TcpState&nbsp;Instance&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;TcpListen(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:#2b91af;">TcpListen</span>() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">void</span>&nbsp;Send(TcpConnection&nbsp;connection) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Send&nbsp;SYN,&nbsp;receive&nbsp;SYN,&nbsp;ACK,&nbsp;etc.</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;connection.State&nbsp;=&nbsp;TcpEstablished.Instance; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> I admit that I find these examples a bit anaemic, since there's really no logic going on. None of the overrides change state <em>conditionally</em>, which would be possible and make the examples a little more interesting. If you're interested in an example where this happens, see my article <a href="/2021/05/24/tennis-kata-using-the-state-pattern">Tennis kata using the State pattern</a>. </p> <h3 id="68a957ca3dcd40e9986b078223f0763e"> Refactor to pure functions <a href="#68a957ca3dcd40e9986b078223f0763e" title="permalink">#</a> </h3> <p> There's only one obvious source of impurity in the example: The literal <code>State</code> mutation of <code>TcpConnection</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;TcpState&nbsp;State&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">internal</span>&nbsp;<span style="color:blue;">set</span>;&nbsp;}</pre> </p> <p> While client code can't <code>set</code> the <code>State</code> property, subclasses can, and they do. After all, it's how the State pattern works. </p> <p> It's quite a stretch to claim that if we can only get rid of that property setter then all else will be pure. After all, who knows what all those comments actually imply: </p> <p> <pre><span style="color:green;">//&nbsp;Send&nbsp;SYN,&nbsp;receive&nbsp;SYN,&nbsp;ACK,&nbsp;etc.</span></pre> </p> <p> To be honest, we must imagine that <a href="https://en.wikipedia.org/wiki/Input/output">I/O</a> takes place here. This means that even though it's possible to refactor away from mutating the <code>State</code> property, these implementations are not really going to be pure functions. </p> <p> I could try to imagine what that <code>SYN</code> and <code>ACK</code> would look like, but it would be unfounded and hypothetical. I'm not going to do that here. Instead, that's the reason I'm going to publish a second article with a more realistic and complex example. When it comes to the present example, I'm going to proceed with the unreasonable assumption that the comments hide no nondeterministic behaviour or side effects. </p> <p> As outlined in the <a href="/2022/09/05/the-state-pattern-and-the-state-monad">article that compares the State pattern and the State monad</a>, you can refactor state mutation to a pure function by instead returning the new state. Usually, you'd have to return a tuple, because you'd also need to return the 'original' return value. Here, however, the 'return type' of all methods is <code>void</code>, so this isn't necessary. </p> <p> <code>void</code> is <a href="/2018/01/15/unit-isomorphisms">isomorphic to unit</a>, so strictly speaking you could refactor to a return type like <code>Tuple&lt;Unit, TcpConnection&gt;</code>, but that is isomorphic to <code>TcpConnection</code>. (If you need to understand why that is, try writing two functions: One that converts a <code>Tuple&lt;Unit, TcpConnection&gt;</code> to a <code>TcpConnection</code>, and another that converts a <code>TcpConnection</code> to a <code>Tuple&lt;Unit, TcpConnection&gt;</code>.) </p> <p> There's no reason to make things more complicated than they have to be, so I'm going to use the simplest representation: <code>TcpConnection</code>. Thus, you can get rid of the <code>State</code> mutation by instead returning a new <code>TcpConnection</code> from all methods: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">TcpConnection</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;TcpState&nbsp;State&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">TcpConnection</span>() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;State&nbsp;=&nbsp;TcpClosed.Instance; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:#2b91af;">TcpConnection</span>(TcpState&nbsp;state) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;State&nbsp;=&nbsp;state; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;TcpConnection&nbsp;ActiveOpen() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;TcpConnection(State.ActiveOpen(<span style="color:blue;">this</span>)); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;TcpConnection&nbsp;PassiveOpen() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;TcpConnection(State.PassiveOpen(<span style="color:blue;">this</span>)); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;More&nbsp;members&nbsp;that&nbsp;delegate&nbsp;to&nbsp;State&nbsp;follows...</span></pre> </p> <p> The <code>State</code> property no longer has a setter; there's only a public getter. In order to 'change' the state, code must return a new <code>TcpConnection</code> object with the new state. To facilitate that, you'll need to add a constructor overload that takes the new state as an input. Here I made it <code>private</code>, but making it more accessible is not prohibited. </p> <p> This implies, however, that the <code>TcpState</code> methods <em>also</em> return values instead of mutating state. The base class now looks like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">TcpState</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">virtual</span>&nbsp;TcpState&nbsp;Transmit(TcpConnection&nbsp;connection,&nbsp;TcpOctetStream&nbsp;stream) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">virtual</span>&nbsp;TcpState&nbsp;ActiveOpen(TcpConnection&nbsp;connection) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">virtual</span>&nbsp;TcpState&nbsp;PassiveOpen(TcpConnection&nbsp;connection) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;And&nbsp;so&nbsp;on...</span></pre> </p> <p> Again, all the methods previously 'returned' <code>void</code>, so while, according to the State monad, you should strictly speaking return <code>Tuple&lt;Unit, TcpState&gt;</code>, this simplifies to <code>TcpState</code>. </p> <p> Individual subclasses now do their work and return other <code>TcpState</code> implementations. I'm not going to tire you with all the example subclasses, so here's just <code>TcpEstablished</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">TcpEstablished</span>&nbsp;:&nbsp;TcpState { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;TcpState&nbsp;Instance&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;TcpEstablished(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:#2b91af;">TcpEstablished</span>() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;TcpState&nbsp;Close(TcpConnection&nbsp;connection) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;send&nbsp;FIN,&nbsp;receive&nbsp;ACK&nbsp;of&nbsp;FIN</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;TcpListen.Instance; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;TcpState&nbsp;Transmit( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TcpConnection&nbsp;connection, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TcpOctetStream&nbsp;stream) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TcpConnection&nbsp;newConnection&nbsp;=&nbsp;connection.ProcessOctet(stream); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;newConnection.State; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> The trickiest implementation is <code>Transmit</code>, since <code>ProcessOctet</code> returns a <code>TcpConnection</code> while the <code>Transmit</code> method has to return a <code>TcpState</code>. Fortunately, the <code>Transmit</code> method can achieve that goal by returning <code>newConnection.State</code>. It feels a bit roundabout, but highlights a point I made in the <a href="/2022/09/05/the-state-pattern-and-the-state-monad">previous article</a>: The <code>TcpConnection</code> and <code>TcpState</code> classes are isomorphic - or, they would be if we made the <code>TcpConnection</code> constructor overload public. Thus, the <code>TcpConnection</code> class is redundant and might be deleted. </p> <h3 id="a94a0e101f6b49d3b4caea30060ae1e1"> Conclusion <a href="#a94a0e101f6b49d3b4caea30060ae1e1" title="permalink">#</a> </h3> <p> This article shows how to refactor the <em>TCP connection</em> sample code from <a href="/ref/dp">Design Patterns</a> to pure functions. </p> <p> If it feels as though something's missing there's a good reason for that. The example, as given, is degenerate because all methods 'return' <code>void</code>, and we don't really know what the actual implementation code (all that <em>Send SYN, receive SYN, ACK, etc.</em>) looks like. This means that we actually don't have to make use of the State monad, because we can get away with <a href="https://en.wikipedia.org/wiki/Endomorphism">endomorphisms</a>. All methods on <code>TcpConnection</code> are really functions that take <code>TcpConnection</code> as input (the instance itself) and return <code>TcpConnection</code>. If you want to see a more realistic example showcasing that perspective, see my article <a href="/2021/05/31/from-state-tennis-to-endomorphism">From State tennis to endomorphism</a>. </p> <p> Even though the example is degenerate, I wanted to show it because otherwise you might wonder how the book's example code fares when exposed to the State monad. To be clear, because of the nature of the example, the State monad never becomes necessary. Thus, we need a second example. </p> <p> <strong>Next:</strong> Refactoring a saga from the State pattern to the State monad. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2022/09/26/refactoring-the-tcp-state-pattern-example-to-pure-functions When to refactor https://blog.ploeh.dk/2022/09/19/when-to-refactor/ Mon, 19 Sep 2022 06:36:00 UTC <div id="post"> <p> <em>FAQ: How do I convince my manager to let me refactor?</em> </p> <p> This question frequently comes up. Developers want to refactor, but are under the impression that managers or other stakeholders will not let them. </p> <p> Sometimes people ask me how to convince their managers to get permission to refactor. I can't answer that. <a href="/2021/03/22/the-dispassionate-developer">I don't know how to convince other people</a>. That's not my métier. </p> <p> I also believe that professional programmers <a href="/2019/03/18/the-programmer-as-decision-maker">should make their own decisions</a>. You don't ask permission to add three lines to a file, or create a new class. Why do you feel that you have to ask permission to refactor? </p> <h3 id="4af4356cd706457ebf8968e92850b140"> Does refactoring take time? <a href="#4af4356cd706457ebf8968e92850b140" title="permalink">#</a> </h3> <p> In <a href="/code-that-fits-in-your-head">Code That Fits in Your Head</a> I tell the following story: </p> <blockquote> <p> "I once led an effort to <a href="/ref/ddd">refactor towards deeper insight</a>. My colleague and I had identified that the key to implementing a new feature would require changing a fundamental class in our code base. </p> <p> "While such an insight rarely arrives at an opportune time, we wanted to make the change, and our manager allowed it. </p> <p> "A week later, our code still didn’t compile. </p> <p> "I’d hoped that I could make the change to the class in question and then <a href="/ref/welc">lean on the compiler</a> to identify the call sites that needed modification. The problem was that there was an abundance of compilation errors, and fixing them wasn’t a simple question of search-and-replace. </p> <p> "My manager finally took me aside to let me know that he wasn’t satisfied with the situation. I could only concur. </p> <p> "After a mild dressing down, he allowed me to continue the work, and a few more days of heroic effort saw the work completed. </p> <p> "That’s a failure I don’t intend to repeat." </p> <footer><cite><a href="/code-that-fits-in-your-head">Code That Fits in Your Head</a></cite></footer> </blockquote> <p> There's a couple of points to this story. Yes, I <em>did</em> ask for permission before refactoring. I expected the process to take time, and I felt that making such a choice of prioritisation should involve my manager. While this manager trusted me, I felt a moral obligation to be transparent about the work I was doing. I didn't consider it professional to take a week out of the calendar and work on one thing while the rest of the organisation was expecting me to be working on something else. </p> <p> So I can understand why developers feel that they have to ask permission to refactor. After all, refactoring takes time... Doesn't it? </p> <h3 id="ddb8e36130fe475da5ea914ccf06ae45"> Small steps <a href="#ddb8e36130fe475da5ea914ccf06ae45" title="permalink">#</a> </h3> <p> This may unearth the underlying assumption that prevents developers from refactoring: The notion that refactoring takes time. </p> <p> As I wrote in <a href="/code-that-fits-in-your-head">Code That Fits in Your Head</a>, that was a failure I didn't intend to repeat. I've never again asked permission to refactor, because I've never since allowed myself to be in a situation where refactoring would take significant time. </p> <p> The reason I tell the story in the book is that I use it to motivate using the <a href="https://martinfowler.com/bliki/StranglerFigApplication.html">Strangler pattern</a> at the code level. The book proceeds to show an example of that. </p> <p> Migrating code to a new API by allowing the old and the new to coexist for a while is only one of many techniques for taking smaller steps. Another is the use of <a href="https://en.wikipedia.org/wiki/Feature_toggle">feature flags</a>, a technique that I also show in the book. <a href="https://martinfowler.com/">Martin Fowler</a>'s <a href="/ref/refactoring">Refactoring</a> is literally an entire book about how to improve code bases in small, controlled steps. </p> <p> Follow the <a href="/2019/10/21/a-red-green-refactor-checklist">red-green-refactor checklist</a> and commit after each <em>green</em> and <em>refactor</em> step. Move in small steps and <a href="https://stackoverflow.blog/2022/04/06/use-git-tactically/">use Git tactically</a>. </p> <p> I'm beginning to realise, though, that <em>moving in small steps</em> is a skill that must be explicitly learned. This may seem obvious once posited, but it may also be helpful to explicitly state it. </p> <p> Whenever I've had a chance to talk to other software professionals and <a href="https://twitter.com/hillelogram/status/1445435617047990273">thought leaders</a>, they agree. As far as I can tell, universities and coding boot camps don't teach this skill, and if (like me) you're autodidact, you probably haven't learned it either. After all, few people insist that this is an important skill. It may, however, be one of the most important programming skills you can learn. </p> <h3 id="11afa6718a3c4a6f8e50aa5066474ac8"> Make it work, then make it right <a href="#11afa6718a3c4a6f8e50aa5066474ac8" title="permalink">#</a> </h3> <p> When should you refactor? As <a href="https://wiki.c2.com/?BoyScoutRule">the boy scout rule</a> suggests: All the time. </p> <p> You can, specifically, do it after implementing a new feature. As <a href="https://wiki.c2.com/?MakeItWorkMakeItRightMakeItFast">Kent Beck perhaps said or wrote</a>: <em>Make it work, then make it right</em>. </p> <p> How long does it take to make it right? </p> <p> Perhaps you think that it takes as much time as it does to make it work. </p> <p> <img src="/content/binary/make-it-work-then-right-50-50.png" alt="A timeline with two sections: 'make it work' and 'make it right'. Each section has the same size."> </p> <p> Perhaps you think that making it right takes even more time. </p> <p> <img src="/content/binary/make-it-work-then-right-20-80.png" alt="A timeline with two sections: 'make it work' and 'make it right'. The 'make it right' section is substantially larger than the 'make it work' section."> </p> <p> If this is how much time making the code right takes, I can understand why you feel that you need to ask your manager. That's what I did, those many years ago. But what if the proportions are more like this? </p> <p> <img src="/content/binary/make-it-work-then-right-80-20.png" alt="A timeline with two sections: 'make it work' and 'make it right'. The 'make it right' section is substantially smaller than the 'make it work' section."> </p> <p> Do you still feel that you need to ask for permission to refactor? </p> <p> Writing code so that the team can keep a sustainable pace is your job. It's not something you should have to ask for permission to do. </p> <blockquote> <p> "Any fool can write code that a computer can understand. Good programmers write code that humans can understand." </p> <footer><cite>Martin Fowler, <a href="/ref/refactoring">Refactoring</a></cite></footer> </blockquote> <p> Making the code right is not always a huge endeavour. It can be, if you've already made a mess of it, but if it's in good condition, keeping it that way doesn't have to take much extra effort. It's part of the ongoing design process that programming is. </p> <p> How do you know what <em>right</em> is? Doesn't this make-it-work-make-it-right mentality lead to <a href="https://wiki.c2.com/?SpeculativeGenerality">speculative generality</a>? </p> <p> No-one expects you to be able to predict the future, so don't try. Making it right means making the code good in the current context. Use good names, remove duplication, get rid of code smells, keep methods small and complexity low. <a href="/2020/04/13/curb-code-rot-with-thresholds">Refactor if you exceed a threshold</a>. </p> <h3 id="1a2eb1f23d70440c84e518babf7dc373"> Make code easy to change <a href="#1a2eb1f23d70440c84e518babf7dc373" title="permalink">#</a> </h3> <p> The purpose of keeping code in a good condition is to make future changes as easy as possible. If you can't predict the future, however, then how do you know how to factor the code? </p> <p> Another <a href="https://en.wikipedia.org/wiki/Kent_Beck">Kent Beck</a> aphorism suggests a tactic: </p> <blockquote> <p> "for each desired change, make the change easy (warning: this may be hard), then make the easy change" </p> <footer><cite><a href="https://twitter.com/KentBeck/status/250733358307500032">Kent Beck</a></cite></footer> </blockquote> <p> In other words, when you know what you need to accomplish, first refactor the code so that it becomes easier to achieve the goal, and only then write the code to do that. </p> <p> <img src="/content/binary/refactor-implement-40-60.png" alt="A timeline with two sections: Refactor and Implement. The Implement section is visibly larger than the Refactor section."> </p> <p> Should you ask permission to refactor in such a case? Only if you sincerely believe that you can complete the entire task significantly faster without first improving the code. How likely is that? If the code base is already a mess, how easy is it to make changes? Not easy, and granted: That will also be true for refactoring. The difference between first refactoring and <em>not</em> refactoring, however, is that if you refactor, you leave the code in a better state. If you don't, you leave it in a worse state. </p> <p> These decisions compound. </p> <p> But what if, as Kent Beck implies, refactoring is hard? Then the situation might look like this: </p> <p> <img src="/content/binary/refactor-implement-80-20.png" alt="A timeline with two sections: Refactor and Implement. The Refactor section is significantly larger than the Implement section."> </p> <p> Should you ask for permission to refactor? I don't think so. While refactoring in this diagram is most of the work, it makes the change easy. Thus, once you're done refactoring, you make the easy change. The total amount of time this takes may turn out to be quicker than if you hadn't refactored (compare this figure to the previous figure: they're to scale). You also leave the code base in a better state so that future changes may be easier. </p> <h3 id="ff4ce77459af4e64a9e3df797fc01d8d"> Conclusion <a href="#ff4ce77459af4e64a9e3df797fc01d8d" title="permalink">#</a> </h3> <p> There are lots of opportunities for refactoring. Every time you see something that could be improved, why not improve it? The fact that you're already looking at a piece of code suggests that it's somehow relevant to your current task. If it takes ten, fifteen minutes to improve it, why not do it? What if it takes an hour? </p> <p> Most people think nothing of spending hours in meetings without asking their managers. If this is true, you can also decide to use a couple of hours improving code. They're likely as well spent as the meeting hours. </p> <p> The key, however, is to be able to perform opportunistic refactoring. You can't do that if you can only move in day-long iterations; if hours, or days, go by when you can't compile, or when most tests fail. </p> <p> On the other hand, if you're able to incrementally improve the code base in one-minute, or fifteen-minute, steps, then you can improve the code base every time an occasion arrives. </p> <p> This is a skill that you need to learn. You're not born with the ability to improve in small steps. You'll have to practice - for example by <a href="/2020/01/13/on-doing-katas">doing katas</a>. One customer of mine told me that they found Kent Beck's <a href="https://medium.com/@kentbeck_7670/test-commit-revert-870bbd756864">TCR</a> a great way to teach that skill. </p> <p> You can refactor in small steps. It's part of software engineering. Usually, you don't need to ask for permission. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="4dc52487bcee4459857d6fb6741dbcad"> <div class="comment-author"><a href="https://danielt1263.medium.com">Daniel Tartaglia</a></div> <div class="comment-content"> <p> I've always had a problem with the notion of "red, green, refactor" and "first get it working, then make it right." I think the order is completely wrong. </p> <p> As an explanation, I refer you to the first chapter of the first edition of Martin Fowler's Refactoring book. In that chapter is an example of a working system and we are presented with a change request. </p> <p> In the example, the first thing that Fowler points out and does is the refactoring. And one of the highlighted ideas in the chapter says: <blockquote>When you find you have to add a feature to a program, and the program's code is not structured in a convenient way to add the feature, first refactor the program to make it easy to add the feature, then add the feature.</blockquote> </p> <p> In other words, the refactoring <i>comes first</i>. You refactor as part of adding the feature, not as a separate thing that is done after you have working code. It may not trip off the tongue as nicely, but the saying should be "refactor, red, green." </p> <p> Once you have working code, you are done, and when you are estimating the time it will take to add the feature, <i>you include the refactoring time</i>. Lastly, you never refactor "just because," you refactor in order to make a new feature easy to add. </p> <p> This mode of working makes much more sense to me. I feel that refactoring with no clear goal in mind ("improve the design" is not a clear goal) just leads to an over-designed/unnecessarily complex system. What do you think of this idea? </p> </div> <div class="comment-date">2022-09-24 02:28 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2022/09/19/when-to-refactor Coalescing DTOs https://blog.ploeh.dk/2022/09/12/coalescing-dtos/ Mon, 12 Sep 2022 07:35:00 UTC <div id="post"> <p> <em>Refactoring to a universal abstraction.</em> </p> <p> Despite my best efforts, no code base I write is perfect. This is also true for the code base that accompanies <a href="/code-that-fits-in-your-head">Code That Fits in Your Head</a>. </p> <p> One (among several) warts that has annoyed me for long is this: </p> <p> <pre>[HttpPost(<span style="color:#a31515;">&quot;restaurants/{restaurantId}/reservations&quot;</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">async</span>&nbsp;Task&lt;ActionResult&gt;&nbsp;Post( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;restaurantId, &nbsp;&nbsp;&nbsp;&nbsp;ReservationDto&nbsp;dto) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(dto&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;ArgumentNullException(nameof(dto)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;id&nbsp;=&nbsp;dto.ParseId()&nbsp;??&nbsp;Guid.NewGuid(); &nbsp;&nbsp;&nbsp;&nbsp;Reservation?&nbsp;reservation&nbsp;=&nbsp;dto.Validate(id); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(reservation&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;BadRequestResult(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;More&nbsp;code&nbsp;follows...</span></pre> </p> <p> Passing <code>id</code> to <code>Validate</code> annoys me. Why does <code>Validate</code> need an <code>id</code>? </p> <p> When you see it in context, it <em>may</em> makes some sort of sense, but in isolation, it seems arbitrary: </p> <p> <pre><span style="color:blue;">internal</span>&nbsp;Reservation?&nbsp;Validate(Guid&nbsp;id)</pre> </p> <p> Why does the method need an <code>id</code>? Doesn't <code>ReservationDto</code> have an <code>Id</code>? </p> <h3 id="90765fa49a8149d0bf54d8d9de19ffee"> Abstraction, broken <a href="#90765fa49a8149d0bf54d8d9de19ffee" title="permalink">#</a> </h3> <p> Yes, indeed, <code>ReservationDto</code> <em>has</em> an <code>Id</code> property: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">string</span>?&nbsp;Id&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;}</pre> </p> <p> Then why do callers have to pass an <code>id</code> argument? Doesn't <code>Validate</code> use the <code>Id</code> property? It's almost as though the <code>Validate</code> method <em>begs</em> you to read the implementing code: </p> <p> <pre><span style="color:blue;">internal</span>&nbsp;Reservation?&nbsp;Validate(Guid&nbsp;id) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!DateTime.TryParse(At,&nbsp;<span style="color:blue;">out</span>&nbsp;var&nbsp;d)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(Email&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(Quantity&nbsp;&lt;&nbsp;1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;Reservation( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;id, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;d, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;Email(Email), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;Name(Name&nbsp;??&nbsp;<span style="color:#a31515;">&quot;&quot;</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity); }</pre> </p> <p> Indeed, the method doesn't use the <code>Id</code> property. Reading the code may not be of much help, but at least we learn that <code>id</code> is passed to the <code>Reservation</code> constructor. It's still not clear why the method isn't trying to parse the <code>Id</code> property, like it's doing with <code>At</code>. </p> <p> I'll return to the motivation in a moment, but first I'd like to dwell on the problems of this design. </p> <p> It's a typical example of ad-hoc design. I had a set of behaviours I needed to implement, and in order to avoid code duplication, I came up with a method that seemed to solve the problem. </p> <p> And indeed, the <code>Validate</code> method does solve the problem of code duplication. It also passes all tests. It could be worse. </p> <p> It could also be better. </p> <p> The problem with an ad-hoc design like this is that the motivation is unclear. As a reader, you feel that you're missing the full picture. Perhaps you feel compelled to read the implementation code to gain a better understanding. Perhaps you look for other call sites. Perhaps you search the Git history to find a helpful comment. Perhaps you ask a colleague. </p> <p> It slows you down. Worst of all, it may leave you apprehensive of refactoring. If you feel that there's something you don't fully understand, you may decide to leave the API alone, instead of improving it. </p> <p> It's one of the many ways that code slowly rots. </p> <p> What's missing here is a proper abstraction. </p> <h3 id="c6b50930baf541eb9243611e2090b1e6"> Motivation <a href="#c6b50930baf541eb9243611e2090b1e6" title="permalink">#</a> </h3> <p> I recently hit upon a design that I like better. Before I describe it, however, you need to understand the problem I was trying to solve. </p> <p> The code base for the book is a restaurant reservation REST API, and I was evolving the code as I wrote it. I wanted the code base (and its Git history) to be as realistic as possible. In a real-world situation, you don't always know all requirements up front, or even if you do, they may change. </p> <p> At one point I decided that a REST client could supply a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">GUID</a> when making a new reservation. On the other hand, I had lots of existing tests (and a deployed system) that accepted reservations <em>without</em> IDs. In order to not break compatibility, I decided to use the ID if it was supplied with the <a href="https://en.wikipedia.org/wiki/Data_transfer_object">DTO</a>, and otherwise create one. (I later explored <a href="/2021/09/20/keep-ids-internal-with-rest">an API without explicit IDs</a>, but that's a different story.) </p> <p> The <code>id</code> is a JSON property, however, so there's no guarantee that it's properly formatted. Thus, the need to first parse it: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;id&nbsp;=&nbsp;dto.ParseId()&nbsp;??&nbsp;Guid.NewGuid();</pre> </p> <p> To make matters even more complicated, when you <code>PUT</code> a reservation, the ID is actually part of the resource address, which means that even if it's present in the JSON document, that value should be ignored: </p> <p> <pre>[HttpPut(<span style="color:#a31515;">&quot;restaurants/{restaurantId}/reservations/{id}&quot;</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">async</span>&nbsp;Task&lt;ActionResult&gt;&nbsp;Put( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;restaurantId, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">string</span>&nbsp;id, &nbsp;&nbsp;&nbsp;&nbsp;ReservationDto&nbsp;dto) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(dto&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;ArgumentNullException(nameof(dto)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!Guid.TryParse(id,&nbsp;<span style="color:blue;">out</span>&nbsp;var&nbsp;rid)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;NotFoundResult(); &nbsp;&nbsp;&nbsp;&nbsp;Reservation?&nbsp;reservation&nbsp;=&nbsp;dto.Validate(rid); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(reservation&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;BadRequestResult(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;More&nbsp;code&nbsp;follows...</span></pre> </p> <p> Notice that this <code>Put</code> implementation exclusively considers the resource address <code>id</code> parameter. Recall that the <code>Validate</code> method ignores the <code>dto</code>'s <code>Id</code> property. </p> <p> This is knowledge about implementation details that leaks through to the calling code. As a client developer, you need to know and keep this knowledge in your head while you write your own code. That's not really code that fits in your head. </p> <p> As I usually put it: If you have to read the code, it implies that encapsulation is broken. </p> <p> At the time, however, I couldn't think of a better alternative, and since the problem is still fairly small and localised, I decided to move on. After all, <a href="https://en.wikipedia.org/wiki/Perfect_is_the_enemy_of_good">perfect is the enemy of good</a>. </p> <h3 id="7e10ecc024e94a20817f0054bde56c29"> Why don't you just..? <a href="#7e10ecc024e94a20817f0054bde56c29" title="permalink">#</a> </h3> <p> Is there a better way? Perhaps you think that you've spotted an obvious improvement. Why don't I just try to parse <code>dto.Id</code> and then create a <code>Guid.NewGuid()</code> if parsing fails? Like this: </p> <p> <pre><span style="color:blue;">internal</span>&nbsp;Reservation?&nbsp;<span style="color:#74531f;">Validate</span>() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(!Guid.TryParse(Id,&nbsp;<span style="color:blue;">out</span>&nbsp;var&nbsp;<span style="color:#1f377f;">id</span>)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;id&nbsp;=&nbsp;Guid.NewGuid(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(!DateTime.TryParse(At,&nbsp;<span style="color:blue;">out</span>&nbsp;var&nbsp;<span style="color:#1f377f;">d</span>)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(Email&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(Quantity&nbsp;&lt;&nbsp;1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;Reservation( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;id, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;d, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;Email(Email), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;Name(Name&nbsp;??&nbsp;<span style="color:#a31515;">&quot;&quot;</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity); }</pre> </p> <p> The short answer is: Because it doesn't work. </p> <p> It may work for <code>Get</code>, but then <code>Put</code> doesn't have a way to tell the <code>Validate</code> method which ID to use. </p> <p> Or rather: That's not entirely true, because this is possible: </p> <p> <pre>dto.Id&nbsp;=&nbsp;id; Reservation?&nbsp;<span style="color:#1f377f;">reservation</span>&nbsp;=&nbsp;dto.Validate();</pre> </p> <p> This does suggest an even better way. Before we go there, however, there's another reason I don't like this particular variation: It makes <code>Validate</code> impure. </p> <p> <em>Why care?</em> you may ask. </p> <p> I always end up regretting making an otherwise potentially <a href="https://en.wikipedia.org/wiki/Pure_function">pure function</a> non-deterministic. Sooner or later, it turns out to have been a bad decision, regardless of how alluring it initially looked. <a href="/2022/05/23/waiting-to-never-happen">I recently gave an example of that</a>. </p> <p> When weighing the advantages and disadvantages, I preferred passing <code>id</code> explicitly rather than relying on <code>Guid.NewGuid()</code> inside <code>Validate</code>. </p> <h3 id="cb79dc6987854f8b9a897285af649360"> First monoid <a href="#cb79dc6987854f8b9a897285af649360" title="permalink">#</a> </h3> <p> One of the reasons I find <a href="/2017/10/04/from-design-patterns-to-category-theory">universal abstractions</a> beneficial is that you only have to learn them once. As Felienne Hermans writes in <a href="/ref/programmers-brain">The Programmer's Brain</a> our working memory juggles a combination of ephemeral data and knowledge from our long-term memory. The better you can leverage existing knowledge, the easier it is to read code. </p> <p> Which universal abstraction enables you to choose from a prioritised list of candidates? The <a href="/2018/04/03/maybe-monoids">First monoid</a>! </p> <p> In C# with <a href="https://docs.microsoft.com/dotnet/csharp/nullable-references">nullable reference types</a> the <a href="https://docs.microsoft.com/dotnet/csharp/language-reference/operators/null-coalescing-operator">null-coalescing operator</a> <code>??</code> already implements the desired functionality. (If you're using another language or an older version of C#, you can instead use <a href="/2018/06/04/church-encoded-maybe">Maybe</a>.) </p> <p> Once I got that idea I was able to simplify the API. </p> <h3 id="ad2f0a4d20da4c9c8006e9587b011911"> Parsing and coalescing DTOs <a href="#ad2f0a4d20da4c9c8006e9587b011911" title="permalink">#</a> </h3> <p> Instead of that odd <code>Validate</code> method which isn't quite a validator and not quite a parser, this insight suggests to <a href="https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/">parse, don't validate</a>: </p> <p> <pre><span style="color:blue;">internal</span>&nbsp;Reservation?&nbsp;<span style="color:#74531f;">TryParse</span>() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(!Guid.TryParse(Id,&nbsp;<span style="color:blue;">out</span>&nbsp;var&nbsp;<span style="color:#1f377f;">id</span>)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(!DateTime.TryParse(At,&nbsp;<span style="color:blue;">out</span>&nbsp;var&nbsp;<span style="color:#1f377f;">d</span>)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(Email&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(Quantity&nbsp;&lt;&nbsp;1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;Reservation( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;id, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;d, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;Email(Email), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;Name(Name&nbsp;??&nbsp;<span style="color:#a31515;">&quot;&quot;</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity); }</pre> </p> <p> This function only returns a parsed <code>Reservation</code> object when the <code>Id</code> is present and well-formed. What about the cases where the <code>Id</code> is absent? </p> <p> The calling <code>ReservationsController</code> can deal with that: </p> <p> <pre>Reservation?&nbsp;<span style="color:#1f377f;">candidate1</span>&nbsp;=&nbsp;dto.TryParse(); dto.Id&nbsp;=&nbsp;Guid.NewGuid().ToString(<span style="color:#a31515;">&quot;N&quot;</span>); Reservation?&nbsp;<span style="color:#1f377f;">candidate2</span>&nbsp;=&nbsp;dto.TryParse(); Reservation?&nbsp;<span style="color:#1f377f;">reservation</span>&nbsp;=&nbsp;candidate1&nbsp;??&nbsp;candidate2; <span style="color:#8f08c4;">if</span>&nbsp;(reservation&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;BadRequestResult();</pre> </p> <p> First try to parse the <code>dto</code>, then explicitly overwrite its <code>Id</code> property with a new <code>Guid</code>, and then try to parse it again. Finally, pick the first of these that aren't null, using the null-coalescing <code>??</code> operator. </p> <p> This API also works consistently in the <code>Put</code> method: </p> <p> <pre>dto.Id&nbsp;=&nbsp;id; Reservation?&nbsp;<span style="color:#1f377f;">reservation</span>&nbsp;=&nbsp;dto.TryParse(); <span style="color:#8f08c4;">if</span>&nbsp;(reservation&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;BadRequestResult();</pre> </p> <p> Why is this better? I consider it better because the <code>TryParse</code> function should be a familiar abstraction. Once you've seen a couple of those, you know that a well-behaved parser either returns a valid object, or nothing. You don't have to go and read the implementation of <code>TryParse</code> to (correctly) guess that. Thus, encapsulation is maintained. </p> <h3 id="72d1eececc3f4166ba426d6a39cd6721"> Where does mutation go? <a href="#72d1eececc3f4166ba426d6a39cd6721" title="permalink">#</a> </h3> <p> The <code>ReservationsController</code> mutates the <code>dto</code> and relies on the impure <code>Guid.NewGuid()</code> method. Why is that okay when it wasn't okay to do this inside of <code>Validate</code>? </p> <p> This is because the code base follows the <a href="https://www.destroyallsoftware.com/screencasts/catalog/functional-core-imperative-shell">functional core, imperative shell</a> architecture. Specifically, Controllers make up the imperative shell, so I consider it appropriate to put impure actions there. After all, they have to go somewhere. </p> <p> This means that the <code>TryParse</code> function remains pure. </p> <h3 id="85ce3840fad04a0c8cb106f6d36459d5"> Conclusion <a href="#85ce3840fad04a0c8cb106f6d36459d5" title="permalink">#</a> </h3> <p> Sometimes a good API design can elude you for a long time. When that happens, I move on with the best solution I can think of in the moment. As it often happens, though, ad-hoc abstractions leave me unsatisfied, so I'm always happy to improve such code later, if possible. </p> <p> In this article, you saw an example of an ad-hoc API design that represented the best I could produce at the time. Later, it dawned on me that an implementation based on a universal abstraction would be possible. In this case, the universal abstraction was null coalescing (which is a specialisation of the <em>monoid</em> abstraction). </p> <p> I like universal abstractions because, once you know them, you can trust that they work in well-understood ways. You don't have to waste time reading implementation code in order to learn whether it's safe to call a method in a particular way. </p> <p> This saves time when you have to work with the code, because, after all, we spend more time reading code than writing it. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="abb3e1c91878423a94835a798fc8b32d"> <div class="comment-author"><a href="https://about.me/tysonwilliams">Tyson Williams</a></div> <div class="comment-content"> <p> After the refactor in this article, is the entirety of your Post method (including the part you didn't show in this article) an <a href="https://blog.ploeh.dk/2020/03/02/impureim-sandwich/">impureim sandwich</a>? </p> </div> <div class="comment-date">2022-09-17 18:37 UTC</div> </div> <div class="comment" id="2352255931b1499184b5ba3782436d61"> <div class="comment-author"><a href="/">Mark Seemann</a></div> <div class="comment-content"> <p> Not yet. There's a lot of (preliminary) interleaving of impure actions and pure functions remaining in the controller, even after this refactoring. </p> <p> A future article will tackle that question. One of the reasons I even started writing about monads, functor relationships, etcetera was to establish the foundations for what this requires. If it can be done without monads and traversals I don't know how. </p> <p> Even though the <code>Post</code> method isn't an impureim sandwich, I still consider the architecture <a href="https://www.destroyallsoftware.com/screencasts/catalog/functional-core-imperative-shell">functional core, imperative shell</a>, since I've kept all impure actions in the controllers. </p> <p> The reason I didn't go all the way to impureim sandwiches with the book's code is didactic. For complex logic, you'll need traversals, monads, sum types, and so on, and none of those things were in scope for the book. </p> </div> <div class="comment-date">2022-09-18 19:28 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2022/09/12/coalescing-dtos The State pattern and the State monad https://blog.ploeh.dk/2022/09/05/the-state-pattern-and-the-state-monad/ Mon, 05 Sep 2022 12:48:00 UTC <div id="post"> <p> <em>The names are the same. Is there a connection? An article for object-oriented programmers.</em> </p> <p> This article is part of <a href="/2018/03/05/some-design-patterns-as-universal-abstractions">a series of articles about specific design patterns and their category theory counterparts</a>. In this article I compare the <a href="https://en.wikipedia.org/wiki/State_pattern">State design pattern</a> to the <a href="/2022/06/20/the-state-monad">State monad</a>. </p> <p> Since the design pattern and the monad share the name <em>State</em> you'd think that they might be <a href="/2018/01/08/software-design-isomorphisms">isomorphic</a>, but it's not quite that easy. I find it more likely that the name is an example of <a href="https://en.wikipedia.org/wiki/Parallel_evolution">parallel evolution</a>. Monads were discovered by <a href="https://en.wikipedia.org/wiki/Eugenio_Moggi">Eugenio Moggi</a> in the early nineties, and <a href="/ref/dp">Design Patterns</a> is from 1994. That's close enough in time that I find it more likely that whoever came up with the names found them independently. <em>State</em>, after all, is hardly an exotic word. </p> <p> Thus, it's possible that the choice of the same name is coincidental. If this is true (which is only my conjecture), does the State pattern have anything in common with the State monad? I find that the answer is a tentative <em>yes</em>. The State design pattern describes an open polymorphic stateful computation. That kind of computation can also be described with the State monad. </p> <p> This article contains a significant amount of code, and it's all quite abstract. It examines the abstract shape of the pattern, so there's little prior intuition on which to build an understanding. While later articles will show more concrete examples, if you want to follow along, you can use the <a href="https://github.com/ploeh/StatePatternAndMonad">GitHub repository</a>. </p> <h3 id="320763be103b49018debc64b45069e3c"> Shape <a href="#320763be103b49018debc64b45069e3c" title="permalink">#</a> </h3> <p> <a href="/ref/dp">Design Patterns</a> is a little vague when it comes to representing the essential form of the pattern. What one can deduce from the diagram in the <em>Structure</em> section describing the pattern, you have an abstract <code>State</code> class with a <code>Handle</code> method like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">virtual</span>&nbsp;<span style="color:blue;">void</span>&nbsp;<span style="color:#74531f;">Handle</span>(Context&nbsp;<span style="color:#1f377f;">context</span>) { }</pre> </p> <p> This, however, doesn't capture all scenarios. What if you need to pass more arguments to the method? What if the method returns a result? What if there's more than one method? </p> <p> Taking into account all those concerns, you might arrive at a more generalised description of the State pattern where an abstract <code>State</code> class might define methods like these: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">abstract</span>&nbsp;Out1&nbsp;<span style="color:#74531f;">Handle1</span>(Context&nbsp;<span style="color:#1f377f;">context</span>,&nbsp;In1&nbsp;<span style="color:#1f377f;">in1</span>); <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">abstract</span>&nbsp;Out2&nbsp;<span style="color:#74531f;">Handle2</span>(Context&nbsp;<span style="color:#1f377f;">context</span>,&nbsp;In2&nbsp;<span style="color:#1f377f;">in2</span>);</pre> </p> <p> There might be an arbitrary number of <code>Handle</code> methods, from <code>Handle1</code> to <code>HandleN</code>, each with their own input and return types. </p> <p> The idea behind the State pattern is that clients don't interact directly with <code>State</code> objects. Instead, they interact with a <code>Context</code> object that delegates operations to a <code>State</code> object, passing itself as an argument: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;Out1&nbsp;<span style="color:#74531f;">Request1</span>(In1&nbsp;<span style="color:#1f377f;">in1</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;State.Handle1(<span style="color:blue;">this</span>,&nbsp;in1); } <span style="color:blue;">public</span>&nbsp;Out2&nbsp;<span style="color:#74531f;">Request2</span>(In2&nbsp;<span style="color:#1f377f;">in2</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;State.Handle2(<span style="color:blue;">this</span>,&nbsp;in2); }</pre> </p> <p> Classes that derive from the abstract <code>State</code> may then mutate <code>context.State</code>. </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;Out2&nbsp;<span style="color:#74531f;">Handle2</span>(Context&nbsp;<span style="color:#1f377f;">context</span>,&nbsp;In2&nbsp;<span style="color:#1f377f;">in2</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(in2&nbsp;==&nbsp;In2.Epsilon) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;context.State&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;ConcreteStateB(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;Out2.Eta; }</pre> </p> <p> Clients interact with the <code>Context</code> object and aren't aware of this internal machinery: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;<span style="color:#1f377f;">actual</span>&nbsp;=&nbsp;ctx.Request2(in2);</pre> </p> <p> With such state mutation going on, is it possible to refactor to a design that uses immutable data and <a href="https://en.wikipedia.org/wiki/Pure_function">pure functions</a>? </p> <h3 id="463f29ae1f8240ec8de7ed18cd429b9f"> State pair <a href="#463f29ae1f8240ec8de7ed18cd429b9f" title="permalink">#</a> </h3> <p> When you have a <code>void</code> method that mutates state, you can refactor it to a pure function by leaving the existing state unchanged and instead returning the new state. What do you do, however, when the method in question already returns a value? </p> <p> This is the case with the generalised <code>HandleN</code> methods, above. </p> <p> One way to resolve this problem is to introduce a more complex type to return. To avoid too much duplication or boilerplate code, you could make it a generic type: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">StatePair</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">StatePair</span>(T&nbsp;<span style="color:#1f377f;">value</span>,&nbsp;State&nbsp;<span style="color:#1f377f;">state</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Value&nbsp;=&nbsp;value; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;State&nbsp;=&nbsp;state; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;T&nbsp;Value&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;State&nbsp;State&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;<span style="color:#74531f;">Equals</span>(<span style="color:blue;">object</span>&nbsp;<span style="color:#1f377f;">obj</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;obj&nbsp;<span style="color:blue;">is</span>&nbsp;StatePair&lt;T&gt;&nbsp;<span style="color:#1f377f;">result</span>&nbsp;&amp;&amp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;EqualityComparer&lt;T&gt;.Default.Equals(Value,&nbsp;result.Value)&nbsp;&amp;&amp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;EqualityComparer&lt;State&gt;.Default.Equals(State,&nbsp;result.State); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">int</span>&nbsp;<span style="color:#74531f;">GetHashCode</span>() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;HashCode.Combine(Value,&nbsp;State); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> This enables you to change the signatures of the <code>Handle</code> methods: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">abstract</span>&nbsp;StatePair&lt;Out1&gt;&nbsp;<span style="color:#74531f;">Handle1</span>(Context&nbsp;<span style="color:#1f377f;">context</span>,&nbsp;In1&nbsp;<span style="color:#1f377f;">in1</span>); <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">abstract</span>&nbsp;StatePair&lt;Out2&gt;&nbsp;<span style="color:#74531f;">Handle2</span>(Context&nbsp;<span style="color:#1f377f;">context</span>,&nbsp;In2&nbsp;<span style="color:#1f377f;">in2</span>);</pre> </p> <p> This refactoring is always possible. Even if the original return type of a method was <code>void</code>, you can <a href="/2018/01/15/unit-isomorphisms">use a <em>unit</em> type as a replacement for <em>void</em></a>. While redundant but consistent, a method could return <code>StatePair&lt;Unit&gt;</code>. </p> <h3 id="e2ca8d320e684cf89407880d06256b64"> Generic pair <a href="#e2ca8d320e684cf89407880d06256b64" title="permalink">#</a> </h3> <p> The above <code>StatePair</code> type is so coupled to a particular <code>State</code> class that it's not reusable. If you had more than one implementation of the State pattern in your code base, you'd have to duplicate that effort. That seems wasteful, so why not make the type generic in the state dimension as well? </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">StatePair</span>&lt;<span style="color:#2b91af;">TState</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">StatePair</span>(T&nbsp;<span style="color:#1f377f;">value</span>,&nbsp;TState&nbsp;<span style="color:#1f377f;">state</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Value&nbsp;=&nbsp;value; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;State&nbsp;=&nbsp;state; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;T&nbsp;Value&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;TState&nbsp;State&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;<span style="color:#74531f;">Equals</span>(<span style="color:blue;">object</span>&nbsp;<span style="color:#1f377f;">obj</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;obj&nbsp;<span style="color:blue;">is</span>&nbsp;StatePair&lt;TState,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">pair</span>&nbsp;&amp;&amp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;EqualityComparer&lt;T&gt;.Default.Equals(Value,&nbsp;pair.Value)&nbsp;&amp;&amp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;EqualityComparer&lt;TState&gt;.Default.Equals(State,&nbsp;pair.State); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">int</span>&nbsp;<span style="color:#74531f;">GetHashCode</span>() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;HashCode.Combine(Value,&nbsp;State); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> When you do that then clearly you'd also need to modify the <code>Handle</code> methods accordingly: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">abstract</span>&nbsp;StatePair&lt;State,&nbsp;Out1&gt;&nbsp;<span style="color:#74531f;">Handle1</span>(Context&nbsp;<span style="color:#1f377f;">context</span>,&nbsp;In1&nbsp;<span style="color:#1f377f;">in1</span>); <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">abstract</span>&nbsp;StatePair&lt;State,&nbsp;Out2&gt;&nbsp;<span style="color:#74531f;">Handle2</span>(Context&nbsp;<span style="color:#1f377f;">context</span>,&nbsp;In2&nbsp;<span style="color:#1f377f;">in2</span>);</pre> </p> <p> Notice that, as is the case with <a href="/2021/07/19/the-state-functor">the State functor</a>, the <em>type</em> declares the type with <code>TState</code> before <code>T</code>, while the <em>constructor</em> takes <code>T</code> before <code>TState</code>. While odd and potentially confusing, I've done this to stay consistent with my previous articles, which again do this to stay consistent with prior art (mainly <a href="https://www.haskell.org/">Haskell</a>). </p> <p> With <code>StatePair</code> you can make the methods pure. </p> <h3 id="cacad33b630d4529b4f703337b9b0a61"> Pure functions <a href="#cacad33b630d4529b4f703337b9b0a61" title="permalink">#</a> </h3> <p> Since <code>Handle</code> methods can now return a new state instead of mutating objects, they can be pure functions. Here's an example: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;StatePair&lt;State,&nbsp;Out2&gt;&nbsp;<span style="color:#74531f;">Handle2</span>(Context&nbsp;<span style="color:#1f377f;">context</span>,&nbsp;In2&nbsp;<span style="color:#1f377f;">in2</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(in2&nbsp;==&nbsp;In2.Epsilon) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;StatePair&lt;State,&nbsp;Out2&gt;(Out2.Eta,&nbsp;<span style="color:blue;">new</span>&nbsp;ConcreteStateB()); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;StatePair&lt;State,&nbsp;Out2&gt;(Out2.Eta,&nbsp;<span style="color:blue;">this</span>); }</pre> </p> <p> The same is true for <code>Context</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;StatePair&lt;Context,&nbsp;Out1&gt;&nbsp;<span style="color:#74531f;">Request1</span>(In1&nbsp;<span style="color:#1f377f;">in1</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;<span style="color:#1f377f;">pair</span>&nbsp;=&nbsp;State.Handle1(<span style="color:blue;">this</span>,&nbsp;in1); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;StatePair&lt;Context,&nbsp;Out1&gt;(pair.Value,&nbsp;<span style="color:blue;">new</span>&nbsp;Context(pair.State)); } <span style="color:blue;">public</span>&nbsp;StatePair&lt;Context,&nbsp;Out2&gt;&nbsp;<span style="color:#74531f;">Request2</span>(In2&nbsp;<span style="color:#1f377f;">in2</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;<span style="color:#1f377f;">pair</span>&nbsp;=&nbsp;State.Handle2(<span style="color:blue;">this</span>,&nbsp;in2); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;StatePair&lt;Context,&nbsp;Out2&gt;(pair.Value,&nbsp;<span style="color:blue;">new</span>&nbsp;Context(pair.State)); }</pre> </p> <p> Does this begin to look familiar? </p> <h3 id="bf25630a0d324f628f400c73ddaa78fa"> Monad <a href="#bf25630a0d324f628f400c73ddaa78fa" title="permalink">#</a> </h3> <p> The <code>StatePair</code> class is nothing but a glorified tuple. Armed with that knowledge, you can introduce a variation of <a href="/2021/07/19/the-state-functor">the IState interface I used to introduce the State functor</a>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IState</span>&lt;<span style="color:#2b91af;">TState</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;StatePair&lt;TState,&nbsp;T&gt;&nbsp;<span style="color:#74531f;">Run</span>(TState&nbsp;<span style="color:#1f377f;">state</span>); }</pre> </p> <p> This variation uses the explicit <code>StatePair</code> class as the return type of <code>Run</code>, rather than a more anonymous tuple. These representations are isomorphic. (That might be a good exercise: Write functions that convert from one to the other, and vice versa.) </p> <p> You can write the usual <code>Select</code> and <code>SelectMany</code> implementations to make <code>IState</code> a functor and monad. Since I have already shown these in previous articles, I'm also going to skip those. (Again, it might be a good exercise to implement them if you're in doubt of how they work.) </p> <p> You can now, for example, use C# query syntax to run the same computation multiple times: </p> <p> <pre>IState&lt;Context,&nbsp;(Out1&nbsp;a,&nbsp;Out1&nbsp;b)&gt;&nbsp;<span style="color:#1f377f;">s</span>&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;a&nbsp;<span style="color:blue;">in</span>&nbsp;in1.Request1() &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;b&nbsp;<span style="color:blue;">in</span>&nbsp;in1.Request1() &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;(a,&nbsp;b); StatePair&lt;Context,&nbsp;(Out1&nbsp;a,&nbsp;Out1&nbsp;b)&gt;&nbsp;<span style="color:#1f377f;">t</span>&nbsp;=&nbsp;s.Run(ctx);</pre> </p> <p> This example calls <code>Request1</code> twice, and collects both return values in a tuple. Running the computation with a <code>Context</code> will produce both a result (the two outputs <code>a</code> and <code>b</code>) as well as the 'current' <code>Context</code> (state). </p> <p> <code>Request1</code> is a State-valued extension method on <code>In1</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;IState&lt;Context,&nbsp;Out1&gt;&nbsp;<span style="color:#74531f;">Request1</span>(<span style="color:blue;">this</span>&nbsp;In1&nbsp;<span style="color:#1f377f;">in1</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;ctx&nbsp;<span style="color:blue;">in</span>&nbsp;Get&lt;Context&gt;() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;p&nbsp;=&nbsp;ctx.Request1(in1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;_&nbsp;<span style="color:blue;">in</span>&nbsp;Put(p.State) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;p.Value; }</pre> </p> <p> Notice the abstraction level in play. This extension method doesn't return a <code>StatePair</code>, but rather an <code>IState</code> computation, defined by using <a href="/2022/07/04/get-and-put-state">the State monad's Get and Put functions</a>. Since the computation is running with a <code>Context</code> state, the computation can <code>Get</code> a <code>ctx</code> object and call its <code>Request1</code> method. This method returns a pair <code>p</code>. The computation can then <code>Put</code> the pair's <code>State</code> (here, a <code>Context</code> object) and return the pair's <code>Value</code>. </p> <p> This stateful computation is composed from the building blocks of the State monad, including query syntax supported by <code>SelectMany</code>, <code>Get</code>, and <code>Put</code>. </p> <p> This does, however, still feel unsatisfactory. After all, you have to know enough of the details of the State monad to know that <code>ctx.Request1</code> returns a pair of which you must remember to <code>Put</code> the <code>State</code>. Would it be possible to also express the underlying <code>Handle</code> methods as stateful computations? </p> <h3 id="f8c4147c58924cd19f1d0bdae8fc05a5"> StatePair bifunctor <a href="#f8c4147c58924cd19f1d0bdae8fc05a5" title="permalink">#</a> </h3> <p> The <code>StatePair</code> class is isomorphic to a <em>pair</em> (a <em>two-tuple</em>), and we know that <a href="/2018/12/31/tuple-bifunctor">a pair gives rise to a bifunctor</a>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;StatePair&lt;TState1,&nbsp;T1&gt;&nbsp;<span style="color:#74531f;">SelectBoth</span>&lt;<span style="color:#2b91af;">TState1</span>,&nbsp;<span style="color:#2b91af;">T1</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;T,&nbsp;T1&gt;&nbsp;<span style="color:#1f377f;">selectValue</span>, &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;TState,&nbsp;TState1&gt;&nbsp;<span style="color:#1f377f;">selectState</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;StatePair&lt;TState1,&nbsp;T1&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;selectValue(Value), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;selectState(State)); }</pre> </p> <p> You can use <code>SelectBoth</code> to implement both <code>Select</code> and <code>SelectState</code>. In the following we're only going to need <code>SelectState</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;StatePair&lt;TState1,&nbsp;T&gt;&nbsp;<span style="color:#74531f;">SelectState</span>&lt;<span style="color:#2b91af;">TState1</span>&gt;(Func&lt;TState,&nbsp;TState1&gt;&nbsp;<span style="color:#1f377f;">selectState</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;SelectBoth(<span style="color:#1f377f;">x</span>&nbsp;=&gt;&nbsp;x,&nbsp;selectState); }</pre> </p> <p> This enables us to slightly simplify the <code>Context</code> methods: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;StatePair&lt;Context,&nbsp;Out1&gt;&nbsp;<span style="color:#74531f;">Request1</span>(In1&nbsp;<span style="color:#1f377f;">in1</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;State.Handle1(<span style="color:blue;">this</span>,&nbsp;in1).SelectState(<span style="color:#1f377f;">s</span>&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;Context(s)); } <span style="color:blue;">public</span>&nbsp;StatePair&lt;Context,&nbsp;Out2&gt;&nbsp;<span style="color:#74531f;">Request2</span>(In2&nbsp;<span style="color:#1f377f;">in2</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;State.Handle2(<span style="color:blue;">this</span>,&nbsp;in2).SelectState(<span style="color:#1f377f;">s</span>&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;Context(s)); }</pre> </p> <p> Keep in mind that <code>Handle1</code> returns a <code>StatePair&lt;State,&nbsp;Out1&gt;</code>, <code>Handle2</code> returns <code>StatePair&lt;State,&nbsp;Out2&gt;</code>, and so on. While <code>Request1</code> calls <code>Handle1</code>, it must return a <code>StatePair&lt;Context,&nbsp;Out1&gt;</code> rather than a <code>StatePair&lt;State,&nbsp;Out1&gt;</code>. Since <code>StatePair</code> is a bifunctor, the <code>Request1</code> method can use <code>SelectState</code> to map the <code>State</code> to a <code>Context</code>. </p> <p> Unfortunately, this doesn't seem to move us much closer to being able to express the underlying functions as stateful computations. It does, however, set up the code so that the next change is a little easier to follow. </p> <h3 id="21f08903569d4c1a898914092f2bf3f9"> State computations <a href="#21f08903569d4c1a898914092f2bf3f9" title="permalink">#</a> </h3> <p> Is it possible to express the <code>Handle</code> methods on <code>State</code> as <code>IState</code> computations? One option is to write another extension method: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;IState&lt;State,&nbsp;Out1&gt;&nbsp;<span style="color:#74531f;">Request1S</span>(<span style="color:blue;">this</span>&nbsp;In1&nbsp;<span style="color:#1f377f;">in1</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;s&nbsp;<span style="color:blue;">in</span>&nbsp;Get&lt;State&gt;() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;ctx&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;Context(s) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;p&nbsp;=&nbsp;s.Handle1(ctx,&nbsp;in1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;_&nbsp;<span style="color:blue;">in</span>&nbsp;Put(p.State) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;p.Value; }</pre> </p> <p> I had to add an <code>S</code> suffix to the name, since it only differs from the above <code>Request1</code> extension method on its return type, and C# doesn't allow method overloading on return types. </p> <p> You can add a similar <code>Request2S</code> extension method. It feels like boilerplate code, but enables us to express the <code>Context</code> methods in terms of running stateful computations: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;StatePair&lt;Context,&nbsp;Out1&gt;&nbsp;<span style="color:#74531f;">Request1</span>(In1&nbsp;<span style="color:#1f377f;">in1</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;in1.Request1S().Run(State).SelectState(<span style="color:#1f377f;">s</span>&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;Context(s)); } <span style="color:blue;">public</span>&nbsp;StatePair&lt;Context,&nbsp;Out2&gt;&nbsp;<span style="color:#74531f;">Request2</span>(In2&nbsp;<span style="color:#1f377f;">in2</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;in2.Request2S().Run(State).SelectState(<span style="color:#1f377f;">s</span>&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;Context(s)); }</pre> </p> <p> This still isn't entirely satisfactory, since the return types of these <code>Request</code> methods are state pairs, and not <code>IState</code> values. The above <code>Request1S</code> function, however, contains a clue about how to proceed. Notice how it can create a <code>Context</code> object from the underlying <code>State</code>, and convert that <code>Context</code> object back to a <code>State</code> object. That's a generalizable idea. </p> <h3 id="6ec1667fe3354e8bb9b5f7b3540b74f9"> Invariant functor <a href="#6ec1667fe3354e8bb9b5f7b3540b74f9" title="permalink">#</a> </h3> <p> While it's possible to map the <code>TState</code> dimension of the state pair, it seems harder to do it on <code><span style="color:#2b91af;">IState</span>&lt;<span style="color:#2b91af;">TState</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;</code>. A tuple, after all, is covariant in both dimensions. The State monad, on the other hand, is neither co- nor contravariant in the state dimension. You can deduce this with positional variance analysis (which I've learned from <a href="https://thinkingwithtypes.com/">Thinking with Types</a>). In short, this is because <code>TState</code> appears as both input and output in <code>StatePair&lt;TState,&nbsp;T&gt;&nbsp;<span style="color:#74531f;">Run</span>(TState&nbsp;<span style="color:#1f377f;">state</span>)</code> - it's neither co- nor contravariant, but rather <em>invariant</em>. </p> <p> What little option is left us, then, is to make <code>IState</code> an <a href="/2022/08/01/invariant-functors">invariant functor</a> in the state dimension: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;IState&lt;TState1,&nbsp;T&gt;&nbsp;<span style="color:#74531f;">SelectState</span>&lt;<span style="color:#2b91af;">TState</span>,&nbsp;<span style="color:#2b91af;">TState1</span>,&nbsp;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;IState&lt;TState,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">state</span>, &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;TState,&nbsp;TState1&gt;&nbsp;<span style="color:#1f377f;">forward</span>, &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;TState1,&nbsp;TState&gt;&nbsp;<span style="color:#1f377f;">back</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;s1&nbsp;<span style="color:blue;">in</span>&nbsp;Get&lt;TState1&gt;() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;s&nbsp;=&nbsp;back(s1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;p&nbsp;=&nbsp;state.Run(s) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;_&nbsp;<span style="color:blue;">in</span>&nbsp;Put(forward(p.State)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;p.Value; }</pre> </p> <p> Given an <code>IState&lt;TState,&nbsp;T&gt;</code> the <code>SelectState</code> function enables us to turn it into a <code>IState&lt;TState1,&nbsp;T&gt;</code>. This is, however, only possible if you can translate both <code>forward</code> and <code>back</code> between two representations. When we have two such translations, we can produce a new computation that runs in <code>TState1</code> by first using <code>Get</code> to retrieve a <code>TState1</code> value from the new environment, translate it <code>back</code> to <code>TState</code>, which enables the expression to <code>Run</code> the <code>state</code>. Then translate the resulting <code>p.State</code> <code>forward</code> and <code>Put</code> it. Finally, return the <code>Value</code>. </p> <p> As <a href="https://reasonablypolymorphic.com/">Sandy Maguire</a> explains: </p> <blockquote> <p> "... an invariant type <code>T</code> allows you to map from <code>a</code> to <code>b</code> if and only if <code>a</code> and <code>b</code> are isomorphic. [...] an isomorphism between <code>a</code> and <code>b</code> means they're already the same thing to begin with." </p> <footer><cite>Sandy Maguire, <a href="https://thinkingwithtypes.com/">Thinking with Types</a></cite></footer> </blockquote> <p> This may seem limiting, but is enough in this case. The <code>Context</code> class is only a wrapper of a <code>State</code> object: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Context</span>(State&nbsp;<span style="color:#1f377f;">state</span>) { &nbsp;&nbsp;&nbsp;&nbsp;State&nbsp;=&nbsp;state; } <span style="color:blue;">public</span>&nbsp;State&nbsp;State&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;}</pre> </p> <p> If you have a <code>State</code> object, you can create a <code>Context</code> object via the <code>Context</code> constructor. On the other hand, if you have a <code>Context</code> object, you can get the wrapped <code>State</code> object by reading the <code>State</code> property. </p> <p> The first improvement this offers is simplification of the <code>Request1</code> extension method: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;IState&lt;Context,&nbsp;Out1&gt;&nbsp;<span style="color:#74531f;">Request1</span>(<span style="color:blue;">this</span>&nbsp;In1&nbsp;<span style="color:#1f377f;">in1</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;in1.Request1S().SelectState(<span style="color:#1f377f;">s</span>&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;Context(s),&nbsp;<span style="color:#1f377f;">ctx</span>&nbsp;=&gt;&nbsp;ctx.State); }</pre> </p> <p> Recall that <code>Request1S</code> returns a <code>IState&lt;State,&nbsp;Out1&gt;</code>. Since a two-way translation between <code>State</code> and <code>Context</code> exists, <code>SelectState</code> can translate <code>IState&lt;State,&nbsp;Out1&gt;</code> to <code>IState&lt;Context,&nbsp;Out1&gt;</code>. </p> <p> The same applies to the equivalent <code>Request2</code> extension method. </p> <p> This, again, enables us to rewrite the <code>Context</code> methods: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;StatePair&lt;Context,&nbsp;Out1&gt;&nbsp;<span style="color:#74531f;">Request1</span>(In1&nbsp;<span style="color:#1f377f;">in1</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;in1.Request1().Run(<span style="color:blue;">this</span>); } <span style="color:blue;">public</span>&nbsp;StatePair&lt;Context,&nbsp;Out2&gt;&nbsp;<span style="color:#74531f;">Request2</span>(In2&nbsp;<span style="color:#1f377f;">in2</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;in2.Request2().Run(<span style="color:blue;">this</span>); }</pre> </p> <p> While this may seem like an insignificant change, one result has been gained: This last refactoring pushed the <code>Run</code> call to the right. It's now clear that each expression is a stateful computation, and that the only role that the <code>Request</code> methods play is to <code>Run</code> the computations. </p> <p> This illustrates that the <code>Request</code> methods can be decomposed into two decoupled steps: <ol> <li>A stateful computation expression</li> <li>Running the expression</li> </ol> The question now becomes: How useful is the <code>Context</code> wrapper class now? </p> <h3 id="4fc39c9d7bd647cb9773344082468051"> Eliminating the Context <a href="#4fc39c9d7bd647cb9773344082468051" title="permalink">#</a> </h3> <p> A reasonable next refactoring might be to remove the <code>context</code> parameter from each of the <code>Handle</code> methods. After all, this parameter is a remnant of the State design pattern. Its original purpose was to enable <code>State</code> implementers to mutate the <code>context</code> by changing its <code>State</code>. </p> <p> After refactoring to immutable functions, the <code>context</code> parameter no longer needs to be there - for that reason. Do we need it for other reasons? Does it carry other information that a <code>State</code> implementer might need? </p> <p> In the form that the code now has, it doesn't. Even if it did, we could consider moving that data to the other input parameter: <code>In1</code>, <code>In2</code>, etcetera. </p> <p> Therefore, it seems sensible to remove the <code>context</code> parameter from the <code>State</code> methods: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">abstract</span>&nbsp;StatePair&lt;State,&nbsp;Out1&gt;&nbsp;<span style="color:#74531f;">Handle1</span>(In1&nbsp;<span style="color:#1f377f;">in1</span>); <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">abstract</span>&nbsp;StatePair&lt;State,&nbsp;Out2&gt;&nbsp;<span style="color:#74531f;">Handle2</span>(In2&nbsp;<span style="color:#1f377f;">in2</span>);</pre> </p> <p> This also means that a function like <code>Request1S</code> becomes simpler: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;IState&lt;State,&nbsp;Out1&gt;&nbsp;<span style="color:#74531f;">Request1S</span>(<span style="color:blue;">this</span>&nbsp;In1&nbsp;<span style="color:#1f377f;">in1</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;s&nbsp;<span style="color:blue;">in</span>&nbsp;Get&lt;State&gt;() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;p&nbsp;=&nbsp;s.Handle1(in1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;_&nbsp;<span style="color:blue;">in</span>&nbsp;Put(p.State) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;p.Value; }</pre> </p> <p> Since <code>Context</code> and <code>State</code> are isomorphic, you can rewrite all callers of <code>Context</code> to instead use <code>State</code>, like the above example: </p> <p> <pre>IState&lt;State,&nbsp;(Out1&nbsp;a,&nbsp;Out1&nbsp;b)&gt;&nbsp;<span style="color:#1f377f;">s</span>&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;a&nbsp;<span style="color:blue;">in</span>&nbsp;in1.Request1() &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">from</span>&nbsp;b&nbsp;<span style="color:blue;">in</span>&nbsp;in1.Request1() &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">select</span>&nbsp;(a,&nbsp;b); <span style="color:blue;">var</span>&nbsp;<span style="color:#1f377f;">t</span>&nbsp;=&nbsp;s.Run(csa);</pre> </p> <p> Do this consistently, and you can eventually delete the <code>Context</code> class. </p> <h3 id="c92292ad071c4b468fa223d764d89ab8"> Further possible refactorings <a href="#c92292ad071c4b468fa223d764d89ab8" title="permalink">#</a> </h3> <p> With the <code>Context</code> class gone, you're left with the abstract <code>State</code> class and its implementers: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">abstract</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">State</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">abstract</span>&nbsp;StatePair&lt;State,&nbsp;Out1&gt;&nbsp;<span style="color:#74531f;">Handle1</span>(In1&nbsp;<span style="color:#1f377f;">in1</span>); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">abstract</span>&nbsp;StatePair&lt;State,&nbsp;Out2&gt;&nbsp;<span style="color:#74531f;">Handle2</span>(In2&nbsp;<span style="color:#1f377f;">in2</span>); }</pre> </p> <p> One further change worth considering might be to change the abstract base class to an interface. </p> <p> In this article, I've considered the general case where the <code>State</code> class supports an arbitrary number of independent state transitions, symbolised by the methods <code>Handle1</code> and <code>Handle2</code>. With an arbitrary number of such state transitions, you would have additional methods up to <code>HandleN</code> for <em>N</em> independent state transitions. </p> <p> At the other extreme, you may have just a single polymorphic state transition function. My intuition tells me that that's more likely to be the case than one would think at first. </p> <h3 id="c53b386a92b04575b675272d2dc85365"> Relationship between pattern and monad <a href="#c53b386a92b04575b675272d2dc85365" title="permalink">#</a> </h3> <p> You can view the State design pattern as a combination of two common practices in object-oriented programming: Mutation and polymorphism. </p> <p> <img src="/content/binary/state-pattern-venn.png" alt="Venn diagram with the two sets mutation and polymorphism. The intersection is labelled state."> </p> <p> The patterns in <em>Design Patterns</em> rely heavily on mutation of object state. Most other 'good' object-oriented code tends to do likewise. </p> <p> Proper object-oriented code also makes good use of polymorphism. Again, refer to <em>Design Patterns</em> or a book like <a href="https://blog.ploeh.dk/ref/refactoring">Refactoring</a> for copious examples. </p> <p> I view the State pattern as the intersection of these two common practices. The problem to solve is this: </p> <blockquote> <p> "Allow an object to alter its behavior when its internal state changes." </p> <footer><cite><a href="/ref/dp">Design Patterns</a></cite></footer> </blockquote> <p> The State pattern achieves that goal by having an inner polymorphic object (<code>State</code>) wrapped by an container object (<code>Context</code>). The <code>State</code> objects can mutate the <code>Context</code>, which enables them to replace themselves with other states. </p> <p> While functional programming also has notions of polymorphism, a pure function can't mutate state. Instead, a pure function must return a new state, leaving the old state unmodified. If there's nothing else to return, you can model such state-changing behaviour as an <a href="https://en.wikipedia.org/wiki/Endomorphism">endomorphism</a>. The article <a href="/2021/05/31/from-state-tennis-to-endomorphism">From State tennis to endomorphism</a> gives a quite literal example of that. </p> <p> Sometimes, however, an object-oriented method does more than one thing: It both mutates state and returns a value. (This, by the way, violates <a href="https://en.wikipedia.org/wiki/Command%E2%80%93query_separation">the Command Query Separation principle</a>.) The State monad is the functional way of doing that: Return both the result and the new state. </p> <p> Essentially, you replace mutation with the State monad. </p> <p> <img src="/content/binary/state-monad-venn.png" alt="Venn diagram with the two sets state monad and polymorphism. The intersection is labelled state."> </p> <p> From a functional perspective, then, we can view the State pattern as the intersection of polymorphism and the State monad. </p> <h3 id="d31601e4146d4f48ae30228f697de0a0"> Examples <a href="#d31601e4146d4f48ae30228f697de0a0" title="permalink">#</a> </h3> <p> This article is both long and abstract. Some examples might be helpful, so I'll give a few in separate articles: <ul> <li><a href="/2022/09/26/refactoring-the-tcp-state-pattern-example-to-pure-functions">Refactoring the TCP State pattern example to pure functions</a></li> <li>Refactoring a saga from the State pattern to the State monad</li> </ul> The first one uses the example from <em>Design Patterns</em>. That example is, unfortunately not that illuminating, since none of the book's methods return data. Thus, the endomorphism-based refactoring is enough, and you don't need the State monad. Therefore, another example is warranted. </p> <h3 id="1b5dead7f5c84f3896d639837314f17d"> Conclusion <a href="#1b5dead7f5c84f3896d639837314f17d" title="permalink">#</a> </h3> <p> You can view the State design pattern as the intersection of polymorphism and mutation. Both are object-oriented staples. The pattern uses polymorphism to model state, and mutation to change from one polymorphic state to another. </p> <p> In functional programming pure functions can't mutate state. You can often design around that problem, but if all else fails, the State monad offers a general-purpose alternative to both return a value and change object state. Thus, you can view the functional equivalent of the State pattern as the intersection of polymorphism and the State monad. </p> <p> <strong>Next:</strong> <a href="/2022/09/26/refactoring-the-tcp-state-pattern-example-to-pure-functions">Refactoring the TCP State pattern example to pure functions</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2022/09/05/the-state-pattern-and-the-state-monad Natural transformations as invariant functors https://blog.ploeh.dk/2022/08/29/natural-transformations-as-invariant-functors/ Mon, 29 Aug 2022 06:12:00 UTC <div id="post"> <p> <em>An article (also) for object-oriented programmers.</em> </p> <ins datetime="2022-09-04T06:40Z"> <p> <strong>Update 2022-09-04:</strong> <em>This article is most likely partially incorrect. What it describes works, but may not be a natural transformation. See <a href="#9336107b26fd48a8971e617d8ebd5159">the below comment</a> for more details.</em> </p> </ins> <p> This article is part of <a href="/2022/08/01/invariant-functors">a series of articles about invariant functors</a>. An invariant functor is a <a href="/2018/03/22/functors">functor</a> that is neither covariant nor contravariant. See the series introduction for more details. The <a href="/2022/08/08/endomorphism-as-an-invariant-functor">previous article</a> described how you can view an <a href="https://en.wikipedia.org/wiki/Endomorphism">endomorphism</a> as an invariant functor. This article generalises that result. </p> <h3 id="f3a2cab08b004fe2bfa8e4b307317d88"> Endomorphism as a natural transformation <a href="#f3a2cab08b004fe2bfa8e4b307317d88" title="permalink">#</a> </h3> <p> An endomorphism is a function whose <a href="https://en.wikipedia.org/wiki/Domain_of_a_function">domain</a> and <a href="https://en.wikipedia.org/wiki/Codomain">codomain</a> is the same. In C# you'd denote the type as <code>Func&lt;T, T&gt;</code>, in <a href="https://fsharp.org/">F#</a> as <code>'a -&gt; 'a</code>, and in <a href="https://www.haskell.org/">Haskell</a> as <code>a -&gt; a</code>. <code>T</code>, <code>'a</code>, and <code>a</code> all symbolise generic types - the notation is just different, depending on the language. </p> <p> A 'naked' value is isomorphic to <a href="/2018/09/03/the-identity-functor">the Identity functor</a>. You can wrap a value of the type <code>a</code> in <code>Identity a</code>, and if you have an <code>Identity a</code>, you can extract the <code>a</code> value. </p> <p> An endomorphism is thus isomorphic to a function from Identity to Identity. In C#, you might denote that as <code>Func&lt;Identity&lt;T&gt;, Identity&lt;T&gt;&gt;</code>, and in Haskell as <code>Identity a -&gt; Identity a</code>. </p> <p> In fact, you can lift any function to an Identity-valued function: </p> <p> <pre>Prelude Data.Functor.Identity&gt; :t \f -&gt; Identity . f . runIdentity \f -&gt; Identity . f . runIdentity :: (b -&gt; a) -&gt; Identity b -&gt; Identity a</pre> </p> <p> While this is a general result that allows <code>a</code> and <code>b</code> to differ, when <code>a ~ b</code> this describes an endomorphism. </p> <p> Since Identity is a functor, a function <code>Identity a -&gt; Identity a</code> is a <a href="/2022/07/18/natural-transformations">natural transformation</a>. </p> <p> The identity function (<code>id</code> in F# and Haskell; <code>x =&gt; x</code> in C#) is the only one possible entirely general endomorphism. You can use the <a href="https://hackage.haskell.org/package/natural-transformation">natural-transformation</a> package to make it explicit that this is a natural transformation: </p> <p> <pre><span style="color:#2b91af;">idNT</span>&nbsp;::&nbsp;<span style="color:blue;">Identity</span>&nbsp;:~&gt;&nbsp;<span style="color:blue;">Identity</span> idNT&nbsp;=&nbsp;NT&nbsp;$&nbsp;Identity&nbsp;.&nbsp;<span style="color:blue;">id</span>&nbsp;.&nbsp;runIdentity</pre> </p> <p> The point, so far, is that you can view an endomorphism as a natural transformation. </p> <p> Since an endomorphism forms an invariant functor, this suggests a promising line of inquiry. </p> <h3 id="88842564359c40978adb687e27cc460d"> Natural transformations as invariant functors <a href="#88842564359c40978adb687e27cc460d" title="permalink">#</a> </h3> <p> Are <em>all</em> natural transformations invariant functors? </p> <p> Yes, they are. In Haskell, you can implement it like this: </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;(<span style="color:blue;">Functor</span>&nbsp;f,&nbsp;<span style="color:blue;">Functor</span>&nbsp;g)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;<span style="color:blue;">Invariant</span>&nbsp;(<span style="color:blue;">NT</span>&nbsp;f&nbsp;g)&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;invmap&nbsp;f&nbsp;g&nbsp;(NT&nbsp;h)&nbsp;=&nbsp;NT&nbsp;$&nbsp;<span style="color:blue;">fmap</span>&nbsp;f&nbsp;.&nbsp;h&nbsp;.&nbsp;<span style="color:blue;">fmap</span>&nbsp;g</pre> </p> <p> Here, I chose to define <code>NT</code> from scratch, rather than relying on the <em>natural-transformation</em> package. </p> <p> <pre><span style="color:blue;">newtype</span>&nbsp;NT&nbsp;f&nbsp;g&nbsp;a&nbsp;=&nbsp;NT&nbsp;{&nbsp;unNT&nbsp;::&nbsp;f&nbsp;a&nbsp;-&gt;&nbsp;g&nbsp;a&nbsp;}</pre> </p> <p> Notice how the implementation (<code><span style="color:blue;">fmap</span>&nbsp;f&nbsp;.&nbsp;h&nbsp;.&nbsp;<span style="color:blue;">fmap</span>&nbsp;g</code>) looks like a generalisation of the endomorphism implementation of <code>invmap</code> (<code>f . h . g</code>). Instead of pre-composing with <code>g</code>, the generalisation pre-composes with <code>fmap g</code>, and instead of post-composing with <code>f</code>, it post-composes with <code>fmap f</code>. </p> <p> Using the same kind of diagram as in the previous article, this composition now looks like this: </p> <p> <img src="/content/binary/invariant-natural-transformation-map-diagram.png" alt="Arrow diagram showing the mapping from a natural transformation in a to a natural transformation in b."> </p> <p> I've used thicker arrows to indicate that each one potentially involves 'more work'. Each is a mapping from a functor to a functor. For the <a href="/2022/04/19/the-list-monad">List functor</a>, for example, the arrow implies zero to many values being mapped. Thus, 'more data' moves 'through' each arrow, and for that reason I thought it made sense to depict them as being thicker. This 'more data' view is not always correct. For example, for <a href="/2018/03/26/the-maybe-functor">the Maybe functor</a>, the amount of data transported though each arrow is zero or one, which rather suggests a thinner arrow. For something like <a href="/2021/07/19/the-state-functor">the State functor</a> or <a href="/2021/08/30/the-reader-functor">the Reader functor</a>, there's really no <em>data</em> in the strictest sense moving through the arrows, but rather functions (which are also, however, a kind of data). Thus, don't take this metaphor of the thicker arrows literally. I did, however, wish to highlight that there's something 'more' going on. </p> <p> The diagram shows a natural transformation <code>h</code> from some functor <code>F</code> to another functor <code>G</code>. It transports objects of the type <code>a</code>. If <code>a</code> and <code>b</code> are isomorphic, you can map that natural transformation to one that transports objects of the type <code>b</code>. </p> <p> Compared to endomorphisms, where you need to, say, map <code>b</code> to <code>a</code>, you now need to map <code>F b</code> to <code>F a</code>. If <code>g</code> maps <code>b</code> to <code>a</code>, then <code>fmap g</code> maps <code>F b</code> to <code>F a</code>. The same line of argument applies to <code>fmap f</code>. </p> <p> In C# you can implement the same behaviour as follows. Assume that you have a natural transformation <code>H</code> from the functor <code>F</code> to the functor <code>G</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;Func&lt;F&lt;A&gt;,&nbsp;G&lt;A&gt;&gt;&nbsp;H&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;}</pre> </p> <p> You can now implement a non-standard <code>Select</code> overload (as described in the introductory article) that maps a natural transformation <code>FToG&lt;A&gt;</code> to a natural transformation <code>FToG&lt;B&gt;</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;FToG&lt;B&gt;&nbsp;<span style="color:#74531f;">Select</span>&lt;<span style="color:#2b91af;">B</span>&gt;(Func&lt;A,&nbsp;B&gt;&nbsp;<span style="color:#1f377f;">aToB</span>,&nbsp;Func&lt;B,&nbsp;A&gt;&nbsp;<span style="color:#1f377f;">bToA</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;FToG&lt;B&gt;(<span style="color:#1f377f;">fb</span>&nbsp;=&gt;&nbsp;H(fb.Select(bToA)).Select(aToB)); }</pre> </p> <p> The implementation looks more imperative than in Haskell, but the idea is the same. First it uses <code>Select</code> on <code>F</code> in order to translate <code>fb</code> (of the type <code>F&lt;B&gt;</code>) to an <code>F&lt;A&gt;</code>. It then uses <code>H</code> to transform the <code>F&lt;A&gt;</code> to an <code>G&lt;A&gt;</code>. Finally, now that it has a <code>G&lt;A&gt;</code>, it can use <code>Select</code> on <em>that</em> functor to map to a <code>G&lt;B&gt;</code>. </p> <p> Note that there's two different functors (<code>F</code> and <code>G</code>) in play, so the two <code>Select</code> methods are different. This is also true in the Haskell code. <code>fmap g</code> need not be the same as <code>fmap f</code>. </p> <h3 id="70c39c1999864a82a73a4ce22f252110"> Identity law <a href="#70c39c1999864a82a73a4ce22f252110" title="permalink">#</a> </h3> <p> As in the previous article, I'll set out to <em>prove</em> the two laws for invariant functors, starting with the identity law. Again, I'll use equational reasoning with <a href="https://bartoszmilewski.com/2015/01/20/functors/">the notation that Bartosz Milewski uses</a>. Here's the proof that the <code>invmap</code> instance obeys the identity law: </p> <p> <pre>&nbsp;&nbsp;invmap&nbsp;id&nbsp;id&nbsp;(NT&nbsp;h) =&nbsp;{&nbsp;definition&nbsp;of&nbsp;invmap&nbsp;} &nbsp;&nbsp;NT&nbsp;$&nbsp;fmap&nbsp;id&nbsp;.&nbsp;h&nbsp;.&nbsp;fmap&nbsp;id =&nbsp;{&nbsp;first&nbsp;functor&nbsp;law&nbsp;} &nbsp;&nbsp;NT&nbsp;$&nbsp;id&nbsp;.&nbsp;h&nbsp;.&nbsp;id =&nbsp;{&nbsp;eta&nbsp;expansion&nbsp;} &nbsp;&nbsp;NT&nbsp;$&nbsp;(\x&nbsp;-&gt;&nbsp;(id&nbsp;.&nbsp;h&nbsp;.&nbsp;id)&nbsp;x) =&nbsp;{&nbsp;definition&nbsp;of&nbsp;(.)&nbsp;} &nbsp;&nbsp;NT&nbsp;$&nbsp;(\x&nbsp;-&gt;&nbsp;id(h(id(x)))) =&nbsp;{&nbsp;defintion&nbsp;of&nbsp;id&nbsp;} &nbsp;&nbsp;NT&nbsp;$&nbsp;(\x&nbsp;-&gt;&nbsp;h(x)) =&nbsp;{&nbsp;eta&nbsp;reduction&nbsp;} &nbsp;&nbsp;NT&nbsp;h =&nbsp;{&nbsp;definition&nbsp;of&nbsp;id&nbsp;} &nbsp;&nbsp;id&nbsp;(NT&nbsp;h)</pre> </p> <p> I'll leave it here without further comment. The Haskell type system is so expressive and abstract that it makes little sense to try to translate these findings to C# or F# in the abstract. Instead, you'll see some more concrete examples later. </p> <h3 id="d54ff79951db44559583a200d20cf6d9"> Composition law <a href="#d54ff79951db44559583a200d20cf6d9" title="permalink">#</a> </h3> <p> As with the identity law, I'll offer a proof for the composition law for the Haskell instance: </p> <p> <pre>&nbsp;&nbsp;invmap&nbsp;f2&nbsp;f2&#39;&nbsp;$&nbsp;invmap&nbsp;f1&nbsp;f1&#39;&nbsp;(NT&nbsp;h) =&nbsp;{&nbsp;definition&nbsp;of&nbsp;invmap&nbsp;} &nbsp;&nbsp;invmap&nbsp;f2&nbsp;f2&#39;&nbsp;$&nbsp;NT&nbsp;$&nbsp;fmap&nbsp;f1&nbsp;.&nbsp;h&nbsp;.&nbsp;fmap&nbsp;f1&#39; =&nbsp;{&nbsp;defintion&nbsp;of&nbsp;($)&nbsp;} &nbsp;&nbsp;invmap&nbsp;f2&nbsp;f2&#39;&nbsp;(NT&nbsp;(fmap&nbsp;f1&nbsp;.&nbsp;h&nbsp;.&nbsp;fmap&nbsp;f1&#39;)) =&nbsp;{&nbsp;definition&nbsp;of&nbsp;invmap&nbsp;} &nbsp;&nbsp;NT&nbsp;$&nbsp;fmap&nbsp;f2&nbsp;.&nbsp;(fmap&nbsp;f1&nbsp;.&nbsp;h&nbsp;.&nbsp;fmap&nbsp;f1&#39;)&nbsp;.&nbsp;fmap&nbsp;f2&#39; =&nbsp;{&nbsp;associativity&nbsp;of&nbsp;composition&nbsp;(.)&nbsp;} &nbsp;&nbsp;NT&nbsp;$&nbsp;(fmap&nbsp;f2&nbsp;.&nbsp;fmap&nbsp;f1)&nbsp;.&nbsp;h&nbsp;.&nbsp;(fmap&nbsp;f1&#39;&nbsp;.&nbsp;fmap&nbsp;f2&#39;) =&nbsp;{&nbsp;second&nbsp;functor&nbsp;law&nbsp;} &nbsp;&nbsp;NT&nbsp;$&nbsp;fmap&nbsp;(f2&nbsp;.&nbsp;f1)&nbsp;.&nbsp;h&nbsp;.&nbsp;fmap&nbsp;(f1&#39;&nbsp;.&nbsp;f2&#39;) =&nbsp;{&nbsp;definition&nbsp;of&nbsp;invmap&nbsp;} &nbsp;&nbsp;invmap&nbsp;(f2&nbsp;.&nbsp;f1)&nbsp;(f1&#39;&nbsp;.&nbsp;f2&#39;)&nbsp;(NT&nbsp;h)</pre> </p> <p> Unless I've made a mistake, these two proofs should demonstrate that all natural transformations can be turned into an invariant functor - in Haskell, at least, but I'll conjecture that that result carries over to other languages like F# and C# as long as one stays within the confines of <a href="https://en.wikipedia.org/wiki/Pure_function">pure functions</a>. </p> <h3 id="2afc7c35819c4d499f531a7229102404"> The State functor as a natural transformation <a href="#2afc7c35819c4d499f531a7229102404" title="permalink">#</a> </h3> <p> I'll be honest and admit that my motivation for embarking on this exegesis was because I'd come to the realisation that you can think about <a href="/2021/07/19/the-state-functor">the State functor</a> as a natural transformation. Recall that <code>State</code> is usually defined like this: </p> <p> <pre><span style="color:blue;">newtype</span>&nbsp;State&nbsp;s&nbsp;a&nbsp;=&nbsp;State&nbsp;{&nbsp;runState&nbsp;::&nbsp;s&nbsp;-&gt;&nbsp;(a,&nbsp;s)&nbsp;}</pre> </p> <p> You can easily establish that this definition of <code>State</code> is isomorphic with a natural transformation from <a href="/2018/09/03/the-identity-functor">the Identity functor</a> to <a href="/2018/12/31/tuple-bifunctor">the tuple functor</a>: </p> <p> <pre><span style="color:#2b91af;">stateToNT</span>&nbsp;::&nbsp;<span style="color:blue;">State</span>&nbsp;s&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">NT</span>&nbsp;<span style="color:blue;">Identity</span>&nbsp;((,)&nbsp;a)&nbsp;s stateToNT&nbsp;(State&nbsp;h)&nbsp;=&nbsp;NT&nbsp;$&nbsp;h&nbsp;.&nbsp;runIdentity <span style="color:#2b91af;">ntToState</span>&nbsp;::&nbsp;<span style="color:blue;">NT</span>&nbsp;<span style="color:blue;">Identity</span>&nbsp;((,)&nbsp;a)&nbsp;s&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">State</span>&nbsp;s&nbsp;a ntToState&nbsp;(NT&nbsp;h)&nbsp;=&nbsp;State&nbsp;$&nbsp;h&nbsp;.&nbsp;Identity</pre> </p> <p> Notice that this is a natural transformation in <code>s</code> - not in <code>a</code>. </p> <p> Since I've already established that natural transformations form invariant functors, this also applies to the State monad. </p> <h3 id="6c0025936a9949eca6191989f4d1b8c6"> State mapping <a href="#6c0025936a9949eca6191989f4d1b8c6" title="permalink">#</a> </h3> <p> My point with all of this isn't really to insist that anyone makes actual use of all this machinery, but rather that this line of reasoning helps to <em>identify a capability</em>. We now know that it's possible to translate a <code>State s a</code> value to a <code>State t a</code> value if <code>s</code> is isomorphic to <code>t</code>. </p> <p> As an example, imagine that you have some State-valued function that attempts to find the maximum value based on various criteria. Such a <code>pickMax</code> function may have the type <code><span style="color:blue;">State</span>&nbsp;(<span style="color:blue;">Max</span>&nbsp;<span style="color:#2b91af;">Integer</span>)&nbsp;<span style="color:#2b91af;">String</span></code> where the state type (<code><span style="color:blue;">Max</span>&nbsp;<span style="color:#2b91af;">Integer</span></code>) is used to keep track of the maximum value found while examining candidates. </p> <p> You could conceivably turn such a function around to instead look for the minimum by mapping the state to a <code>Min</code> value instead: </p> <p> <pre><span style="color:#2b91af;">pickMin</span>&nbsp;::&nbsp;<span style="color:blue;">State</span>&nbsp;(<span style="color:blue;">Min</span>&nbsp;<span style="color:#2b91af;">Integer</span>)&nbsp;<span style="color:#2b91af;">String</span> pickMin&nbsp;=&nbsp;ntToState&nbsp;$&nbsp;invmap&nbsp;(Min&nbsp;.&nbsp;getMax)&nbsp;(Max&nbsp;.&nbsp;getMin)&nbsp;$&nbsp;stateToNT&nbsp;pickMax</pre> </p> <p> You can use <code>getMax</code> to extract the underlying <code>Integer</code> from the <code><span style="color:blue;">Max</span>&nbsp;<span style="color:#2b91af;">Integer</span></code> and then <code>Min</code> to turn it into a <code><span style="color:blue;">Min</span>&nbsp;<span style="color:#2b91af;">Integer</span></code> value, and vice versa. <code><span style="color:blue;">Max</span>&nbsp;<span style="color:#2b91af;">Integer</span></code> and <code><span style="color:blue;">Min</span>&nbsp;<span style="color:#2b91af;">Integer</span></code> are isomorphic. </p> <p> In C#, you can implement a similar method. The code shown here extends the code shown in <a href="/2021/07/19/the-state-functor">The State functor</a>. I chose to call the method <code>SelectState</code> so as to not make things too confusing. The State functor already comes with a <code>Select</code> method that maps <code>T</code> to <code>T1</code> - that's the 'normal', covariant functor implementation. The new method is the invariant functor implementation that maps the state <code>S</code> to <code>S1</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;IState&lt;S1,&nbsp;T&gt;&nbsp;<span style="color:#74531f;">SelectState</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">S</span>,&nbsp;<span style="color:#2b91af;">S1</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;IState&lt;S,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">state</span>, &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;S,&nbsp;S1&gt;&nbsp;<span style="color:#1f377f;">sToS1</span>, &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;S1,&nbsp;S&gt;&nbsp;<span style="color:#1f377f;">s1ToS</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;InvariantStateMapper&lt;T,&nbsp;S,&nbsp;S1&gt;(state,&nbsp;sToS1,&nbsp;s1ToS); } <span style="color:blue;">private</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">InvariantStateMapper</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">S</span>,&nbsp;<span style="color:#2b91af;">S1</span>&gt;&nbsp;:&nbsp;IState&lt;S1,&nbsp;T&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;IState&lt;S,&nbsp;T&gt;&nbsp;state; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;Func&lt;S,&nbsp;S1&gt;&nbsp;sToS1; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;Func&lt;S1,&nbsp;S&gt;&nbsp;s1ToS; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">InvariantStateMapper</span>( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IState&lt;S,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">state</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;S,&nbsp;S1&gt;&nbsp;<span style="color:#1f377f;">sToS1</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;S1,&nbsp;S&gt;&nbsp;<span style="color:#1f377f;">s1ToS</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.state&nbsp;=&nbsp;state; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.sToS1&nbsp;=&nbsp;sToS1; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.s1ToS&nbsp;=&nbsp;s1ToS; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Tuple&lt;T,&nbsp;S1&gt;&nbsp;<span style="color:#74531f;">Run</span>(S1&nbsp;<span style="color:#1f377f;">s1</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;state.Run(s1ToS(s1)).Select(sToS1); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> As usual when working in C# with interfaces instead of higher-order functions, <a href="/2019/12/16/zone-of-ceremony">there's some ceremony to be expected</a>. The only interesting line of code is the <code>Run</code> implementation. </p> <p> It starts by calling <code>s1ToS</code> in order to translate the <code>s1</code> parameter into an <code>S</code> value. This enables it to call <code>Run</code> on <code>state</code>. The result is a tuple with the type <code>Tuple&lt;T,&nbsp;S&gt;</code>. It's necessary to translate the <code>S</code> to <code>S1</code> with <code>sToS1</code>. You could do that by extracting the value from the tuple, mapping it, and returning a new tuple. Since a tuple gives rise to a functor (<a href="/2018/12/31/tuple-bifunctor">two, actually</a>) I instead used the <code>Select</code> method I'd already defined on it. </p> <p> Notice how similar the implementation is to the implementation of <a href="/2022/08/08/endomorphism-as-an-invariant-functor">the endomorphism invariant functor</a>. The only difference is that when translating back from <code>S</code> to <code>S1</code>, this happens inside a <code>Select</code> mapping. This is as predicted by the general implementation of invariant functors for natural transformations. </p> <p> In a future article, you'll see an example of <code>SelectState</code> in action. </p> <h3 id="5a148244488b4391be257181108072b3"> Other natural transformations <a href="#5a148244488b4391be257181108072b3" title="permalink">#</a> </h3> <p> As the <a href="/2022/07/18/natural-transformations">natural transformations</a> article outlines, there are infinitely many natural transformations. Each one gives rise to an invariant functor. </p> <p> It might be a good exercise to try to implement a few of them as invariant functors. If you want to do it in C#, you could, for example, start with the <em>safe head</em> natural transformation. </p> <p> If you want to stick to interfaces, you could define one like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">ISafeHead</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;Maybe&lt;T&gt;&nbsp;<span style="color:#74531f;">TryFirst</span>(IEnumerable&lt;T&gt;&nbsp;<span style="color:#1f377f;">ts</span>); }</pre> </p> <p> The exercise is now to define and implement a method like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;ISafeHead&lt;T1&gt;&nbsp;<span style="color:#74531f;">Select</span>&lt;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">T1</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;ISafeHead&lt;T&gt;&nbsp;<span style="color:#1f377f;">source</span>, &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;T,&nbsp;T1&gt;&nbsp;<span style="color:#1f377f;">tToT1</span>, &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;T1,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">t1ToT</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Implementation&nbsp;goes&nbsp;here...</span> }</pre> </p> <p> The implementation, once you get the handle of it, is entirely automatable. After all, in Haskell it's possible to do it once and for all, as shown above. </p> <h3 id="2c86c2f77e0a404da80858d855898843"> Conclusion <a href="#2c86c2f77e0a404da80858d855898843" title="permalink">#</a> </h3> <p> A natural transformation forms an invariant functor. This may not be the most exciting result ever, because invariant functors are limited in use. They only work when translating between types that are already isomorphic. Still, I did <a href="/2022/09/05/the-state-pattern-and-the-state-monad">find a use for this result</a> when I was working with the relationship between the State design pattern and the <a href="/2022/06/20/the-state-monad">State monad</a>. </p> <p> <strong>Next:</strong> Functors as invariant functors. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="9336107b26fd48a8971e617d8ebd5159"> <div class="comment-author"><a href="/">Mark Seemann</a></div> <div class="comment-content"> <p> Due to feedback that I've received, I have to face evidence that this article may be partially incorrect. While I've added that proviso at the top of the article, I've decided to use a comment to expand on the issue. </p> <p> On Twitter, the user <a href="https://twitter.com/Savlambda">@Savlambda</a> (<em>borar</em>) argued that my <code>newtype</code> isn't a natural transformation: </p> <blockquote> <p> "The newtype 'NT' in the article is not a natural transformation though. Quantification over 'a' is at the "wrong place": it is not allowed for a client module to instantiate the container element type of a natural transformation." </p> <footer><cite><a href="https://twitter.com/Savlambda/status/1564175654845030400">@Savlambda</a></cite></footer> </blockquote> <p> While I engaged with the tweet, I have to admit that it took me a while to understand the core of the criticism. Of course I'm not happy about being wrong, but initially I genuinely didn't understand what was the problem. On the other hand, it's not the first time @Savlambda has provided valuable insights, so I knew it'd behove me to pay attention. </p> <p> After a few tweets back and forth, @Savlambda finally supplied a counter-argument that I understood. </p> <blockquote> <p> "This is not being overly pedantic. Here is one practical implication:" </p> <footer><cite><a href="https://twitter.com/Savlambda/status/1564970422981890048">@Savlambda</a></cite></footer> </blockquote> <p> The practical implication shown in the tweet is a screen shot (in order to get around Twitter's character limitation), but I'll reproduce it as code here in order to <a href="https://meta.stackoverflow.com/q/285551/126014">not show images of code</a>. </p> <p> <pre><span style="color:blue;">type</span>&nbsp;<span style="color:#2b91af;">(~&gt;)</span>&nbsp;f&nbsp;g&nbsp;=&nbsp;forall&nbsp;a.&nbsp;f&nbsp;a&nbsp;-&gt;&nbsp;g&nbsp;a <span style="color:green;">--&nbsp;Use&nbsp;the&nbsp;natural&nbsp;transformation&nbsp;twice,&nbsp;for&nbsp;different&nbsp;types </span><span style="color:#2b91af;">convertLists</span>&nbsp;::&nbsp;([]&nbsp;~&gt;&nbsp;g)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;(g&nbsp;<span style="color:#2b91af;">Int</span>,&nbsp;g&nbsp;<span style="color:#2b91af;">Bool</span>) convertLists&nbsp;nt&nbsp;=&nbsp;(nt&nbsp;[1,2],&nbsp;nt&nbsp;[True]) <span style="color:blue;">newtype</span>&nbsp;NT&nbsp;f&nbsp;g&nbsp;a&nbsp;=&nbsp;NT&nbsp;(f&nbsp;a&nbsp;-&gt;&nbsp;g&nbsp;a) <span style="color:green;">--&nbsp;Does&nbsp;not&nbsp;type&nbsp;check,&nbsp;does&nbsp;not&nbsp;work;&nbsp;not&nbsp;a&nbsp;natural&nbsp;transformation </span><span style="color:#2b91af;">convertLists2</span>&nbsp;::&nbsp;<span style="color:blue;">NT</span>&nbsp;[]&nbsp;g&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;(g&nbsp;<span style="color:#2b91af;">Int</span>,&nbsp;g&nbsp;<span style="color:#2b91af;">Bool</span>) convertLists2&nbsp;(NT&nbsp;f)&nbsp;=&nbsp;(f&nbsp;[1,2],&nbsp;f&nbsp;[True])</pre> </p> <p> I've moved the code comments to prevent horizontal scrolling, but otherwise tried to stay faithful to @Savlambda's screen shot. </p> <p> This was the example that finally hit the nail on the head for me. A natural transformation is a mapping from one functor (<code>f</code>) to another functor (<code>g</code>). I knew that already, but hadn't realised the implications. In Haskell (and other languages with <a href="https://en.wikipedia.org/wiki/Parametric_polymorphism">parametric polymorphism</a>) a <code>Functor</code> is defined for all <code>a</code>. </p> <p> A natural transformation is a higher level of abstraction, mapping one functor to another. That mapping must be defined for all <code>a</code>, and it must be <em>reusable</em>. The second example provided by @Savlambda demonstrates that the function wrapped by <code>NT</code> isn't reusable for different contained types. </p> <p> If you try to compile that example, GHC emits this compiler error: </p> <p> <pre>* Couldn't match type `a' with `Int' `a' is a rigid type variable bound by the type signature for: convertLists2 :: forall (g :: * -&gt; *) a. NT [] g a -&gt; (g Int, g Bool) Expected type: g Int Actual type: g a * In the expression: f [1, 2] In the expression: (f [1, 2], f [True]) In an equation for `convertLists2': convertLists2 (NT f) = (f [1, 2], f [True])</pre> </p> <p> Even though it's never fun to be proven wrong, I want to thank @Savlambda for educating me. One reason I write blog posts like this one is that writing is a way to learn. By writing about topics like these, I educate myself. Occasionally, it turns out that I make a mistake, and <a href="/2018/12/03/set-is-not-a-functor">this isn't the first time that's happened</a>. I also wish to apologise if this article has now left any readers more confused. </p> <p> A remaining question is what practical implications this has? Only rarely do you need a programming construct like <code>convertLists2</code>. On the other hand, had I wanted a function with the type <code>NT [] g Int -&gt; (g Int, g Int)</code>, it would have type-checked just fine. </p> <p> I'm not claiming that this is generally useful either, but I actually wrote this article because I <em>did</em> have use for the result that <code>NT</code> (whatever it is) is an invariant functor. As far as I can tell, that result still holds. </p> <p> I could be wrong about that, too. If you think so, please leave a comment. </p> </div> <div class="comment-date">2022-09-04 7:53 UTC</div> </div> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2022/08/29/natural-transformations-as-invariant-functors Can types replace validation? https://blog.ploeh.dk/2022/08/22/can-types-replace-validation/ Mon, 22 Aug 2022 05:57:00 UTC <div id="post"> <p> <em>With some examples in C#.</em> </p> <p> In a comment to my article on <a href="/2022/08/15/aspnet-validation-revisited">ASP.NET validation revisited</a> Maurice Johnson asks: </p> <blockquote> <p> "I was just wondering, is it possible to use the type system to do the validation instead ? </p> <p> "What I mean is, for example, to make all the ReservationDto's field a type with validation in the constructor (like a class name, a class email, and so on). Normally, when the framework will build ReservationDto, it will try to construct the fields using the type constructor, and if there is an explicit error thrown during the construction, the framework will send us back the error with the provided message. </p> <p> "Plus, I think types like "email", "name" and "at" are reusable. And I feel like we have more possibilities for validation with that way of doing than with the validation attributes. </p> <p> "What do you think ?" </p> <footer><cite><a href="/2022/08/15/aspnet-validation-revisited#f6deac18851d47c3b066f82a8be3847d">Maurice Johnson</a></cite></footer> </blockquote> <p> I started writing a response below the question, but it grew and grew so I decided to turn it into a separate article. I think the question is of general interest. </p> <h3 id="2492a444e49b49a09a4f7c03f38b29d5"> The halting problem <a href="#2492a444e49b49a09a4f7c03f38b29d5" title="permalink">#</a> </h3> <p> I'm all in favour of using the type system for encapsulation, but there are limits to what it can do. We know this because it follows from the <a href="https://en.wikipedia.org/wiki/Halting_problem">halting problem</a>. </p> <p> I'm basing my understanding of the halting problem on <a href="https://www.goodreads.com/review/show/1731926050">my reading</a> of <a href="/ref/annotated-turing">The Annotated Turing</a>. In short, given an arbitrary computer program in a Turing-complete language, there's no general algorithm that will determine whether or not the program will finish running. </p> <p> A compiler that performs type-checking is a program, but typical type systems aren't Turing-complete. It's possible to write type checkers that always finish, because the 'programming language' they are running on - the type system - isn't Turing-complete. </p> <p> Normal type systems (like C#'s) aren't Turing-complete. You expect the C# compiler to always arrive at a result (either compiled code or error) in finite time. As a counter-example, consider <a href="https://www.haskell.org/">Haskell</a>'s type system. By default it, too, isn't Turing-complete, but with sufficient language extensions, you <em>can</em> make it Turing-complete. Here's a fun example: <a href="https://aphyr.com/posts/342-typing-the-technical-interview">Typing the technical interview</a> by Kyle Kingsbury (Aphyr). When you make the type system Turing-complete, however, termination is no longer guaranteed. A program may now compile forever or, practically, until it times out or runs out of memory. That's what happened to me when I tried to compile Kyle Kingsbury's code example. </p> <p> How is this relevant? </p> <p> This matters because understanding that a normal type system is <em>not</em> Turing-complete means that there are truths it <em>can't</em> express. Thus, we shouldn't be surprised if we run into rules or policies that we can't express with the type system we're given. What exactly is inexpressible depends on the type system. There are policies you can express in Haskell that are impossible to express in C#, and so on. Let's stick with C#, though. Here are some examples of rules that are practically inexpressible: </p> <ul> <li>An integer must be positive.</li> <li>A string must be at most 100 characters long.</li> <li>A maximum value must be greater than a minimum value.</li> <li>A value must be a valid email address.</li> </ul> <p> <a href="https://www.hillelwayne.com/">Hillel Wayne</a> provides more compelling examples in the article <a href="https://buttondown.email/hillelwayne/archive/making-illegal-states-unrepresentable/">Making Illegal States Unrepresentable</a>. </p> <h3 id="34f9d2e5570842adbb79a20972f458a0"> Encapsulation <a href="#34f9d2e5570842adbb79a20972f458a0" title="permalink">#</a> </h3> <p> Depending on how many times you've been around the block, you may find the above list naive. You may, for example, say that it's possible to express that an integer is positive like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">struct</span>&nbsp;<span style="color:#2b91af;">NaturalNumber</span>&nbsp;:&nbsp;IEquatable&lt;NaturalNumber&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:blue;">int</span>&nbsp;i; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">NaturalNumber</span>(<span style="color:blue;">int</span>&nbsp;candidate) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(candidate&nbsp;&lt;&nbsp;1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;ArgumentOutOfRangeException( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nameof(candidate), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#a31515;">$&quot;The&nbsp;value&nbsp;must&nbsp;be&nbsp;a&nbsp;positive&nbsp;(non-zero)&nbsp;number,&nbsp;but&nbsp;was:&nbsp;</span>{candidate}<span style="color:#a31515;">.&quot;</span>); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.i&nbsp;=&nbsp;candidate; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Various&nbsp;other&nbsp;members&nbsp;follow...</span></pre> </p> <p> I like introducing wrapper types like this. To the inexperienced developer this may seem redundant, but using a wrapper like this has several advantages. For one, it makes preconditions explicit. Consider a constructor like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Reservation</span>( &nbsp;&nbsp;&nbsp;&nbsp;Guid&nbsp;id, &nbsp;&nbsp;&nbsp;&nbsp;DateTime&nbsp;at, &nbsp;&nbsp;&nbsp;&nbsp;Email&nbsp;email, &nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;name, &nbsp;&nbsp;&nbsp;&nbsp;NaturalNumber&nbsp;quantity)</pre> </p> <p> What are the preconditions that you, as a client developer, has to fulfil before you can create a valid <code>Reservation</code> object? First, you must supply five arguments: <code>id</code>, <code>at</code>, <code>email</code>, <code>name</code>, and <code>quantity</code>. There is, however, more information than that. </p> <p> Consider, as an alternative, a constructor like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Reservation</span>( &nbsp;&nbsp;&nbsp;&nbsp;Guid&nbsp;id, &nbsp;&nbsp;&nbsp;&nbsp;DateTime&nbsp;at, &nbsp;&nbsp;&nbsp;&nbsp;Email&nbsp;email, &nbsp;&nbsp;&nbsp;&nbsp;Name&nbsp;name, &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">int</span>&nbsp;quantity)</pre> </p> <p> This constructor requires you to supply the same five arguments. There is, however, less explicit information available. If that was the only available constructor, you might be wondering: <em>Can I pass zero as <code>quantity</code>? Can I pass <code>-1</code>?</em> </p> <p> When the only constructor available is the first of these two alternatives, you already have the answer: No, the <code>quantity</code> must be a natural number. </p> <p> Another advantage of creating wrapper types like <code>NaturalNumber</code> is that you centralise run-time checks in one place. Instead of sprinkling defensive code all over the code base, you have it in one place. Any code that receives a <code>NaturalNumber</code> object knows that the check has already been performed. </p> <p> There's a word for this: <a href="/encapsulation-and-solid">Encapsulation</a>. </p> <p> You gather a coherent set of invariants and collect it in a single type, making sure that the type always guarantees its invariants. Note that this is an important design technique in functional programming too. While you may not have to worry about state mutation preserving invariants, it's still important to guarantee that all values of a type are <em>valid</em>. </p> <h3 id="8c48a55a5db74686ab7a0c8fc40dd650"> Predicative and constructive data <a href="#8c48a55a5db74686ab7a0c8fc40dd650" title="permalink">#</a> </h3> <p> It's debatable whether the above <code>NaturalNumber</code> class <em>really</em> uses the type system to model what constitutes valid data. Since it relies on a run-time predicate, it falls in the category of types Hillel Wayne <a href="https://www.hillelwayne.com/post/constructive/">calls <em>predicative</em></a>. Such types are easy to create and compose well, but on the other hand fail to take full advantage of the type system. </p> <p> It's often worthwhile considering if a <em>constructive</em> design is possible and practical. In other words, is it possible to <a href="https://blog.janestreet.com/effective-ml-video/">make illegal states unrepresentable</a> (MISU)? </p> <p> What's wrong with <code>NaturalNumber</code>? Doesn't it do that? No, it doesn't, because this compiles: </p> <p> <pre><span style="color:blue;">new</span>&nbsp;NaturalNumber(-1)</pre> </p> <p> Surely it <em>will</em> fail at run time, but it compiles. Thus, it's <em>representable</em>. </p> <p> <a href="/2011/04/29/Feedbackmechanismsandtradeoffs">The compiler gives you feedback faster than tests</a>. Considering MISU is worthwhile. </p> <p> Can we model natural numbers in a constructive way? Yes, with <a href="https://en.wikipedia.org/wiki/Peano_axioms">Peano numbers</a>. This is even <a href="/2018/05/28/church-encoded-natural-numbers">possible in C#</a>, but I wouldn't consider it practical. On the other hand, while it's possible to represent any natural number, there is <em>no way</em> to express -1 as a Peano number. </p> <p> As Hillel Wayne describes, constructive data types are much harder and requires a considerable measure of creativity. Often, a constructive model can seem impossible until you get a good idea. </p> <blockquote> <p> "a list can only be of even length. Most languages will not be able to express such a thing in a reasonable way in the data type." </p> <footer><cite><a href="https://note89.github.io/state-of-emergency/">Nils Eriksson</a></cite></footer> </blockquote> <p> Such a requirement may look difficult until inspiration hits. Then one day you may realise that it'd be as simple as a list of pairs (two-tuples). In Haskell, it could be as simple as this: </p> <p> <pre>newtype EvenList a = EvenList [(a,a)] deriving (Eq, Show)</pre> </p> <p> With such a constructive data model, lists of uneven length are unrepresentable. This is a simple example of the kind of creative thinking you may need to engage in with constructive data modelling. </p> <p> If you feel the need to object that Haskell isn't 'most languages', then here's the same idea expressed in C#: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">EvenCollection</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;:&nbsp;IEnumerable&lt;T&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;IEnumerable&lt;Tuple&lt;T,&nbsp;T&gt;&gt;&nbsp;values; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">EvenCollection</span>(IEnumerable&lt;Tuple&lt;T,&nbsp;T&gt;&gt;&nbsp;<span style="color:#1f377f;">values</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.values&nbsp;=&nbsp;values; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;IEnumerator&lt;T&gt;&nbsp;<span style="color:#74531f;">GetEnumerator</span>() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">foreach</span>&nbsp;(var&nbsp;<span style="color:#1f377f;">x</span>&nbsp;<span style="color:#8f08c4;">in</span>&nbsp;values) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">yield</span>&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;x.Item1; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">yield</span>&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;x.Item2; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;IEnumerator&nbsp;IEnumerable.<span style="color:#74531f;">GetEnumerator</span>() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;GetEnumerator(); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> You can create such a list like this: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;<span style="color:#1f377f;">list</span>&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;EvenCollection&lt;<span style="color:blue;">string</span>&gt;(<span style="color:blue;">new</span>[] { &nbsp;&nbsp;&nbsp;&nbsp;Tuple.Create(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;bar&quot;</span>), &nbsp;&nbsp;&nbsp;&nbsp;Tuple.Create(<span style="color:#a31515;">&quot;baz&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;qux&quot;</span>) });</pre> </p> <p> On the other hand, this doesn't compile: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;<span style="color:#1f377f;">list</span>&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;EvenCollection&lt;<span style="color:blue;">string</span>&gt;(<span style="color:blue;">new</span>[] { &nbsp;&nbsp;&nbsp;&nbsp;Tuple.Create(<span style="color:#a31515;">&quot;foo&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;bar&quot;</span>), &nbsp;&nbsp;&nbsp;&nbsp;Tuple.Create(<span style="color:#a31515;">&quot;baz&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;qux&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;quux&quot;</span>) });</pre> </p> <p> Despite this digression, the point remains: Constructive data modelling may be impossible, unimagined, or impractical. </p> <p> Often, in languages like C# we resort to predicative data modelling. That's also what I did in the article <a href="/2022/08/15/aspnet-validation-revisited">ASP.NET validation revisited</a>. </p> <h3 id="830f3f7a663b459994cc585ef9604d11"> Validation as functions <a href="#830f3f7a663b459994cc585ef9604d11" title="permalink">#</a> </h3> <p> That was a long rambling detour inspired by a simple question: Is it possible to use types instead of validation? </p> <p> In order to address that question, it's only proper to explicitly state assumptions and definitions. What's the definition of <em>validation?</em> </p> <p> I'm not aware of a ubiquitous definition. While I could draw from <a href="https://en.wikipedia.org/wiki/Data_validation">the Wikipedia article on the topic</a>, at the time of writing it doesn't cite any sources when it sets out to define what it is. So I may as well paraphrase. It seems fair, though, to consider the stem of the word: <em>Valid</em>. </p> <p> Validation is the process of examining input to determine whether or not it's valid. I consider this a (mostly) self-contained operation: Given the data, is it well-formed and according to specification? If you have to query a database before making a decision, you're not validating the input. In that case, you're applying a business rule. As a rule of thumb I expect validations to be <a href="https://en.wikipedia.org/wiki/Pure_function">pure functions</a>. </p> <p> Validation, then, seems to imply a process. Before you execute the process, you don't know if data is valid. After executing the process, you do know. </p> <p> Data types, whether predicative like <code>NaturalNumber</code> or constructive like <code>EvenCollection&lt;T&gt;</code>, aren't processes or functions. They are results. </p> <p> <img src="/content/binary/validation-as-a-function-from-data-to-type.png" alt="An arrow labelled 'validation' pointing from a document to the left labelled 'Data' to a box to the right labelled 'Type'."> </p> <p> Sometimes an algorithm can use a type to <em>infer</em> the validation function. This is common in statically typed languages, from C# over <a href="https://fsharp.org/">F#</a> to Haskell (which are the languages with which I'm most familiar). </p> <h3 id="4cc324c1919e45958542bb82c2ca73d4"> Data Transfer Object as a validation DSL <a href="#4cc324c1919e45958542bb82c2ca73d4" title="permalink">#</a> </h3> <p> In a way you can think of the type system as a <a href="https://en.wikipedia.org/wiki/Domain-specific_language">domain-specific language</a> (DSL) for defining validation functions. It's not perfectly suited for that task, but often good enough that many developers reach for it. </p> <p> Consider the <code>ReservationDto</code> class from the <a href="/2022/08/15/aspnet-validation-revisited">ASP.NET validation revisited</a> article where I eventually gave up on it: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">ReservationDto</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;LinkDto[]?&nbsp;Links&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Guid?&nbsp;Id&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;[Required,&nbsp;NotNull] &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;DateTime?&nbsp;At&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;[Required,&nbsp;NotNull] &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">string</span>?&nbsp;Email&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">string</span>?&nbsp;Name&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;[NaturalNumber] &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">int</span>&nbsp;Quantity&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;} }</pre> </p> <p> It actually tries to do what Maurice Johnson suggests. Particularly, it defines <code>At</code> as a <code>DateTime?</code> value. </p> <p> <pre>&gt; <span style="color:blue;">var</span>&nbsp;<span style="color:#1f377f;">json</span>&nbsp;=&nbsp;<span style="color:#a31515;">&quot;{&nbsp;\&quot;At\&quot;:&nbsp;\&quot;2022-10-11T19:30\&quot;,&nbsp;\&quot;Email\&quot;:&nbsp;\&quot;z@example.com\&quot;,&nbsp;\&quot;Quantity\&quot;:&nbsp;1}&quot;</span>; &gt; JsonSerializer.Deserialize&lt;ReservationDto&gt;(json) ReservationDto { At=[11.10.2022 19:30:00], Email="z@example.com", Id=null, Name=null, Quantity=1 }</pre> </p> <p> A JSON deserializer like this one uses run-time reflection to examine the type in question and then maps the incoming data onto an instance. Many XML deserializers work the same way. </p> <p> What happens if you supply malformed input? </p> <p> <pre>&gt; <span style="color:blue;">var</span>&nbsp;<span style="color:#1f377f;">json</span>&nbsp;=&nbsp;<span style="color:#a31515;">&quot;{&nbsp;\&quot;At\&quot;:&nbsp;\&quot;foo\&quot;,&nbsp;\&quot;Email\&quot;:&nbsp;\&quot;z@example.com\&quot;,&nbsp;\&quot;Quantity\&quot;:&nbsp;1}&quot;</span>; &gt; JsonSerializer.Deserialize&lt;ReservationDto&gt;(json) <span style="color:red">System.Text.Json.JsonException:↩ The JSON value could not be converted to System.Nullable`1[System.DateTime].↩ Path: $.At | LineNumber: 0 | BytePositionInLine: 26.↩ [...]</span></pre> </p> <p> (I've wrapped the result over multiple lines for readability. The <code>↩</code> symbol indicates where I've wrapped the text. I've also omitted a stack trace, indicated by <code>[...]</code>. I'll do that repeatedly throughout this article.) </p> <p> What happens if we try to define <code>ReservationDto.Quantity</code> with <code>NaturalNumber</code>? </p> <p> <pre>&gt; var json = "{ \"At\": \"2022-10-11T19:30\", \"Email\": \"z@example.com\", \"Quantity\": 1}"; &gt; JsonSerializer.Deserialize&lt;ReservationDto&gt;(json) <span style="color:red">System.Text.Json.JsonException:↩ The JSON value could not be converted to NaturalNumber.↩ Path: $.Quantity | LineNumber: 0 | BytePositionInLine: 67.↩ [...]</span></pre> </p> <p> While <a href="https://docs.microsoft.com/dotnet/api/system.text.json.jsonserializer">JsonSerializer</a> is a sophisticated piece of software, it's not so sophisticated that it can automatically map <code>1</code> to a <code>NaturalNumber</code> value. </p> <p> I'm sure that you can configure the behaviour with one or more <a href="https://docs.microsoft.com/dotnet/api/system.text.json.serialization.jsonconverter">JsonConverter</a> objects, but this is exactly the kind of framework <a href="https://en.wikipedia.org/wiki/Whac-A-Mole">Whack-a-mole</a> that I consider costly. It also suggests a wider problem. </p> <h3 id="bdad63c97ad44f1199f4f06e2b2e3fff"> Error handling <a href="#bdad63c97ad44f1199f4f06e2b2e3fff" title="permalink">#</a> </h3> <p> What happens if input to a validation function is malformed? You may want to report the errors to the caller, and you may want to report all errors in one go. Consider the user experience if you don't: A user types in a big form and submits it. The system informs him or her that there's an error in the third field. Okay, correct the error and submit again. Now there's an error in the fifth field, and so on. </p> <p> It's often better to return all errors as one collection. </p> <p> The problem is that type-based validation doesn't <em>compose</em> well. What do I mean by that? </p> <p> It's fairly clear that if you take a <em>simple</em> (i.e. non-complex) type like <code>NaturalNumber</code>, if you fail to initialize a value it's because the input is at fault: </p> <p> <pre>&gt; <span style="color:blue;">new</span>&nbsp;NaturalNumber(-1) <span style="color:red">System.ArgumentOutOfRangeException: The value must be a positive (non-zero) number, but was: -1.↩ (Parameter 'candidate') + NaturalNumber..ctor(int)</span></pre> </p> <p> The problem is that for complex types (i.e. types made from other types), exceptions short-circuit. As soon as one exception is thrown, further data validation stops. The <a href="/2022/08/15/aspnet-validation-revisited">ASP.NET validation revisited</a> article shows examples of that particular problem. </p> <p> This happens when validation functions have no composable way to communicate errors. When throwing exceptions, you can return an exception message, but exceptions short-circuit rather than compose. The same is true for the <a href="/2022/05/09/an-either-monad">Either monad</a>: It short-circuits. Once you're on <a href="https://fsharpforfunandprofit.com/posts/recipe-part2/">the failure track</a> you stay there and no further processing takes place. Errors don't compose. </p> <h3 id="7a85a7339fc24eda8e922ba12fdb3d89"> Monoidal versus applicative validation <a href="#7a85a7339fc24eda8e922ba12fdb3d89" title="permalink">#</a> </h3> <p> The naive take on validation is to answer the question: <em>Is that data valid or invalid?</em> Notice the binary nature of the question. It's either-or. </p> <p> This is true for both predicative data and constructive data. </p> <p> For constructive data, the question is: Is a candidate value representable? For example, can you represent <em>-1</em> as a Peano number? The answer is either yes or no; true or false. </p> <p> This is even clearer for predicative data, which is defined by a <em>predicate</em>. (Here's another <a href="/2021/09/09/the-specification-contravariant-functor">example of a natural number specification</a>.) A predicate is a function that returns a Boolean value: True or false. </p> <p> It's possible to compose Boolean values. The composition that we need in this case is Boolean <em>and</em>, which is also known as the <em>all</em> <a href="/2017/10/06/monoids">monoid</a>: If all values are <em>true</em>, the composed value is <em>true</em>; if just one value is <em>false</em>, the composed value is <em>false</em>. </p> <p> The problem is that during composition, we lose information. While a single <em>false</em> value causes the entire aggregated value to be <em>false</em>, we don't know why. And we don't know if there was only a single <em>false</em> value, or if there were more than one. Boolean <em>all</em> short-circuits on the first <em>false</em> value it encounters, and stops processing subsequent predicates. </p> <p> In logic, that's all you need, but in data validation you often want to know <em>what's wrong with the data</em>. </p> <p> Fortunately, this is <a href="/2020/12/14/validation-a-solved-problem">a solved problem</a>. Use <a href="/2018/11/05/applicative-validation">applicative validation</a>, an example of which I supplied in the article <a href="/2022/07/25/an-applicative-reservation-validation-example-in-c">An applicative reservation validation example in C#</a>. </p> <p> This changes focus on validation. No longer is validation a <em>true/false</em> question. Validation is a function from less-structured data to more-structured data. <a href="https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/">Parse, don't validate</a>. </p> <h3 id="96d5b6c4df424f79b9eec8b186a2b3de"> Conclusion <a href="#96d5b6c4df424f79b9eec8b186a2b3de" title="permalink">#</a> </h3> <p> Can types replace validation? </p> <p> In some cases they can, but I think that the general answer is <em>no</em>. Granted, this answer is partially based on capabilities of current deserialisers. <a href="https://docs.microsoft.com/dotnet/api/system.text.json.jsonserializer.deserialize">JsonSerializer.Deserialize</a> short-circuits on the first error it encounters, and the same does <a href="https://hackage.haskell.org/package/aeson/docs/Data-Aeson.html">aeson</a>'s <a href="https://hackage.haskell.org/package/aeson/docs/Data-Aeson.html#v:eitherDecode">eitherDecode</a>. </p> <p> While that's the current state of affairs, it may not have to stay like that forever. One might be able to derive an applicative parser from a desired destination type, but I haven't seen that done yet. </p> <p> It sounds like a worthwhile research project. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="4e4498fcf878443e96fad490569a8e4f"> <div class="comment-author"><a href="https://www.lloydatkinson.net">Lloyd Atkinson</a></div> <div class="comment-content"> <p> This slightly reminds me of <a href="https://github.com/colinhacks/zod">Zod</a> which is described as "TypeScript-first schema validation with static type inference". </p> <p> The library automatically infers a type that matches the validation - in a way it blurs this line between types and validation by making them become one. </p> <p> Of course, once you have that infered type there is nothing stopping you using it without the library, but that's something code reviews could catch. It's quite interesting though. </p> <pre> <code> import { z } from 'zod'; const User = z.object({ username: z.string(), age: z.number().positive({ message: 'Your age must be positive!', }), }); User.parse({ username: 'Ludwig', age: -1 }); // extract the inferred type type User = z.infer<typeof User>; // { username: string, age: number } </code> </pre> </div> <div class="comment-date">2022-08-28 00:53 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2022/08/22/can-types-replace-validation ASP.NET validation revisited https://blog.ploeh.dk/2022/08/15/aspnet-validation-revisited/ Mon, 15 Aug 2022 05:48:00 UTC <div id="post"> <p> <em>Is the built-in validation framework better than applicative validation?</em> </p> <p> I recently published an article called <a href="/2022/07/25/an-applicative-reservation-validation-example-in-c">An applicative reservation validation example in C#</a> in which I describe how to use the universal abstractions of <a href="/2018/10/01/applicative-functors">applicative functors</a> and <a href="/2017/11/27/semigroups">semigroups</a> to implement reusable, composable validation. </p> <p> One reader reaction made me stop and think: </p> <blockquote> <p> "An exercise on how to reject 90% of the framework's existing services (*Validation) only to re implement them more poorly, by renouncing standardization, interoperability and globalization all for the glory of FP." </p> <footer><cite><a href="https://twitter.com/PopCatalin/status/1551478523981881349">PopCatalin</a></cite></footer> </blockquote> <p> (At the time of posting, the <a href="https://twitter.com/PopCatalin">PopCatalin Twitter account</a>'s display name was <em>Prime minister of truth™ カタリンポップ🇺🇦</em>, which I find unhelpful. The linked <a href="https://github.com/popcatalin81">GitHub account</a> locates the user in <a href="https://en.wikipedia.org/wiki/Cluj-Napoca">Cluj-Napoca</a>, a city I've <a href="/schedule">repeatedly visited for conferences</a> - the last time as recent as June 2022. I wouldn't be surprised if we've interacted, but if so, I'm sorry to say that I can't connect these accounts with one of the many wonderful people I've met there. In general, I'm getting a strong sarcastic vibe from that account, and I'm not sure whether or not to take <em>Pronouns kucf/fof</em> seriously. As the possibly clueless 51-year white male that I am, I will proceed with good intentions and to the best of my abilities.) </p> <p> That reply is an important reminder that I should once in a while check my assumptions. I'm aware that the ASP.NET framework comes with validation features, but I many years ago dismissed them because I found them inadequate. Perhaps, in the meantime, these built-in services have improved to the point that they are to be preferred over <a href="/2018/11/05/applicative-validation">applicative validation</a>. </p> <p> I decided to attempt to refactor the code to take advantage of the built-in ASP.NET validation to be able to compare the two approaches. This article is an experience report. </p> <h3 id="d4b2e6bdae494d0397866f683ddd64e9"> Requirements <a href="#d4b2e6bdae494d0397866f683ddd64e9" title="permalink">#</a> </h3> <p> In order to compare the two approaches, the ASP.NET-based validation should support the same validation features as the applicative validation example: </p> <ul> <li>The <code>At</code> property is required and should be a valid date and time. If it isn't, the validation message should report the problem and the offending input.</li> <li>The <code>Email</code> property should be required. If it's missing, the validation message should state so.</li> <li>The <code>Quantity</code> property is required and should be a natural number. If it isn't, the validation message should report the problem and the offending input.</li> </ul> <p> The <a href="/2022/07/25/an-applicative-reservation-validation-example-in-c">previous article</a> includes an interaction example that I'll repeat here for convenience: </p> <p> <pre>POST /restaurants/1/reservations?sig=1WiLlS5705bfsffPzaFYLwntrS4FCjE5CLdaeYTHxxg%3D HTTP/1.1 Content-Type: application/json {&nbsp;<span style="color:#2e75b6;">&quot;at&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;large&quot;</span>,&nbsp;<span style="color:#2e75b6;">&quot;name&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;Kerry&nbsp;Onn&quot;</span>,&nbsp;<span style="color:#2e75b6;">&quot;quantity&quot;</span>:&nbsp;-1&nbsp;} HTTP/1.1 400 Bad Request Invalid date or time: large. Email address is missing. Quantity must be a positive integer, but was: -1.</pre> </p> <p> ASP.NET validation formats the errors differently, as you'll see later in this article. That's not much of a concern, though: <a href="/2014/12/23/exception-messages-are-for-programmers">Error <em>messages</em> are for other developers</a>. They don't really have to be machine-readable or have a strict shape (as opposed to error <em>types</em>, which should be machine-readable). </p> <p> Reporting the offending values, as in <em>"Quantity must be a positive integer, but was: -1."</em> is part of the requirements. A REST API can make no assumptions about its clients. Perhaps one client is an unattended batch job that only logs errors. Logging offending values may be helpful to maintenance developers of such a batch job. </p> <h3 id="74d95aed3a5a40eb8f32ace05b0410a0"> Framework API <a href="#74d95aed3a5a40eb8f32ace05b0410a0" title="permalink">#</a> </h3> <p> The first observation to make about the ASP.NET validation API is that it's specific to ASP.NET. It's not a general-purpose API that you can use for other purposes. </p> <p> If, instead, you need to validate input to a console application, a background message handler, a batch job, or a desktop or phone app, you can't use that API. </p> <p> Perhaps each of these styles of software come with their own validation APIs, but even if so, that's a different API you'll have to learn. And in cases where there's no built-in validation API, then what do you do? </p> <p> The beauty and practicality of applicative validation is that it's <em>universal</em>. Since it's based on mathematical foundations, it's not tied to a particular framework, platform, or language. These concepts exist independently of technology. Once you understand the concepts, they're always there for you. </p> <p> The code example from the previous article, as well as here, build upon the code base that accompanies <a href="/code-that-fits-in-your-head">Code That Fits in Your Head</a>. An example code base has to be written in <em>some</em> language, and I chose C# because I'm more familiar with it than I am with <a href="https://www.java.com/">Java</a>, <a href="https://isocpp.org/">C++</a>, or <a href="https://www.typescriptlang.org/">TypeScript</a>. While I wanted the code base to be realistic, I tried hard to include only coding techniques and patterns that you could use in more than one language. </p> <p> As I wrote the book, I ran into many interesting problems and solutions that were specific to C# and ASP.NET. While I found them too specific to include in the book, I wrote <a href="/2021/06/14/new-book-code-that-fits-in-your-head">a series of blog posts</a> about them. This article is now becoming one of those. </p> <p> The point about the previous article on <a href="/2022/07/25/an-applicative-reservation-validation-example-in-c">applicative reservation validation in C#</a> was to demonstrate how the general technique works. Not specifically in ASP.NET, or even C#, but in general. </p> <p> It just so happens that this example is situated in a context where an alternative solution presents itself. This is not always the case. Sometimes you have to solve this problem yourself, and when this happens, it's useful to know that <a href="/2020/12/14/validation-a-solved-problem">validation is a solved problem</a>. Even so, while a universal solution exists, it doesn't follow that the universal solution is the best. Perhaps there are specialised solutions that are better, each within their constrained contexts. </p> <p> Perhaps ASP.NET validation is an example of that. </p> <h3 id="0b80f4aa36954378be9278761b2f27ba"> Email validation <a href="#0b80f4aa36954378be9278761b2f27ba" title="permalink">#</a> </h3> <p> The following is a report on my experience refactoring validation to use the built-in ASP.NET validation API. </p> <p> I decided to start with the <code>Email</code> property, since the only requirement is that this value should be present. That seemed like an easy way to get started. </p> <p> I added the <a href="https://docs.microsoft.com/dotnet/api/system.componentmodel.dataannotations.requiredattribute">[Required]</a> attribute to the <code>ReservationDto</code> class' <code>Email</code> property. Since this code base also uses <a href="https://docs.microsoft.com/dotnet/csharp/nullable-references">nullable reference types</a>, it was necessary to also annotate the property with the <a href="https://docs.microsoft.com/dotnet/api/system.diagnostics.codeanalysis.notnullattribute">[NotNull]</a> attribute: </p> <p> <pre>[Required,&nbsp;NotNull] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">string</span>?&nbsp;Email&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;}</pre> </p> <p> That's not too difficult, and seems to be working satisfactorily: </p> <p> <pre>POST /restaurants/1/reservations?sig=1WiLlS5705bfsffPzaFYLwntrS4FCjE5CLdaeYTHxxg%3D HTTP/1.1 > content-type: application/json { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;at&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;2022-11-21&nbsp;19:00&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;name&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;Kerry&nbsp;Onn&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;quantity&quot;</span>:&nbsp;1 } HTTP/1.1 400 Bad Request Content-Type: application/problem+json; charset=utf-8 { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;type&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;https://tools.ietf.org/html/rfc7231#section-6.5.1&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;title&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;One&nbsp;or&nbsp;more&nbsp;validation&nbsp;errors&nbsp;occurred.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;status&quot;</span>:&nbsp;400, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;traceId&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;|552ab5ff-494e1d1a9d4c6355.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;errors&quot;</span>:&nbsp;{&nbsp;<span style="color:#2e75b6;">&quot;Email&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;The&nbsp;Email&nbsp;field&nbsp;is&nbsp;required.&quot;</span>&nbsp;]&nbsp;} }</pre> </p> <p> As discussed above, the response body is formatted differently than in the applicative validation example, but I consider that inconsequential for the reasons I gave. </p> <p> So far, so good. </p> <h3 id="a10d6da09d064a96bc0022e9657b62e5"> Quantity validation <a href="#a10d6da09d064a96bc0022e9657b62e5" title="permalink">#</a> </h3> <p> The next property I decided to migrate was <code>Quantity</code>. This must be a natural number; that is, an integer greater than zero. </p> <p> Disappointingly, no such built-in validation attribute seems to exist. One <a href="https://stackoverflow.com/a/7419330/126014">highly voted Stack Overflow answer</a> suggested using the <a href="https://docs.microsoft.com/dotnet/api/system.componentmodel.dataannotations.rangeattribute">[Range]</a> attribute, so I tried that: </p> <p> <pre>[Range(1,&nbsp;<span style="color:blue;">int</span>.MaxValue,&nbsp;ErrorMessage&nbsp;=&nbsp;<span style="color:#a31515;">&quot;Quantity&nbsp;must&nbsp;be&nbsp;a&nbsp;natural&nbsp;number.&quot;</span>)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">int</span>&nbsp;Quantity&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;}</pre> </p> <p> As a <em>declarative</em> approach to validation goes, I don't think this is off to a good start. I like declarative programming, but I'd prefer to be able to declare that <code>Quantity</code> must be a <em>natural number</em>, rather than in the range of <code>1</code> and <code>int.MaxValue</code>. </p> <p> Does it work, though? </p> <p> <pre>POST /restaurants/1/reservations?sig=1WiLlS5705bfsffPzaFYLwntrS4FCjE5CLdaeYTHxxg%3D HTTP/1.1 content-type: application/json { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;at&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;2022-11-21&nbsp;19:00&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;name&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;Kerry&nbsp;Onn&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;quantity&quot;</span>:&nbsp;0 } HTTP/1.1 400 Bad Request Content-Type: application/problem+json; charset=utf-8 { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;type&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;https://tools.ietf.org/html/rfc7231#section-6.5.1&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;title&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;One&nbsp;or&nbsp;more&nbsp;validation&nbsp;errors&nbsp;occurred.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;status&quot;</span>:&nbsp;400, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;traceId&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;|d9a6be38-4be82ede7c525913.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;errors&quot;</span>:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;Email&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;The&nbsp;Email&nbsp;field&nbsp;is&nbsp;required.&quot;</span>&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;Quantity&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;Quantity&nbsp;must&nbsp;be&nbsp;a&nbsp;natural&nbsp;number.&quot;</span>&nbsp;] &nbsp;&nbsp;} }</pre> </p> <p> While it does capture the intent that <code>Quantity</code> must be one or greater, it fails to echo back the offending value. </p> <p> In order to address that concern, I tried reading the documentation to find a way forward. Instead I found this: </p> <blockquote> <p> "Internally, the attributes call <a href="https://docs.microsoft.com/en-us/dotnet/api/system.string.format">String.Format</a> with a placeholder for the field name and sometimes additional placeholders. [...]" </p> <p> "To find out which parameters are passed to <code>String.Format</code> for a particular attribute's error message, see the <a href="https://github.com/dotnet/runtime/tree/main/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations">DataAnnotations source code</a>." </p> <footer><cite><a href="https://docs.microsoft.com/aspnet/core/mvc/models/validation">ASP.NET validation documentation</a></cite></footer> </blockquote> <p> Really?! </p> <p> If you have to read implementation code, <a href="/encapsulation-and-solid">encapsulation</a> is broken. </p> <p> Hardly impressed, I nonetheless found <a href="https://github.com/dotnet/runtime/blob/main/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RangeAttribute.cs">the RangeAttribute source code</a>. Alas, it only passes the property <code>name</code>, <code>Minimum</code>, and <code>Maximum</code> to <code>string.Format</code>, but not the offending value: </p> <p> <pre>return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, Minimum, Maximum);</pre> </p> <p> This looked like a dead end, but at least it's possible to extend the ASP.NET validation API: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">NaturalNumberAttribute</span>&nbsp;:&nbsp;ValidationAttribute { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">protected</span>&nbsp;<span style="color:blue;">override</span>&nbsp;ValidationResult&nbsp;IsValid( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">object</span>&nbsp;value, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ValidationContext&nbsp;validationContext) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(validationContext&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;ArgumentNullException(nameof(validationContext)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;i&nbsp;=&nbsp;value&nbsp;<span style="color:blue;">as</span>&nbsp;<span style="color:blue;">int</span>?; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(i.HasValue&nbsp;&amp;&amp;&nbsp;0&nbsp;&lt;&nbsp;i) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;ValidationResult.Success; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;ValidationResult( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#a31515;">$&quot;</span>{validationContext.MemberName}<span style="color:#a31515;">&nbsp;must&nbsp;be&nbsp;a&nbsp;positive&nbsp;integer,&nbsp;but&nbsp;was:&nbsp;</span>{value}<span style="color:#a31515;">.&quot;</span>); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Adding this <code>NaturalNumberAttribute</code> class enabled me to change the annotation of the <code>Quantity</code> property: </p> <p> <pre>[NaturalNumber] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">int</span>&nbsp;Quantity&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;}</pre> </p> <p> This seems to get the job done: </p> <p> <pre>POST /restaurants/1/reservations?sig=1WiLlS5705bfsffPzaFYLwntrS4FCjE5CLdaeYTHxxg%3D HTTP/1.1 content-type: application/json { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;at&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;2022-11-21&nbsp;19:00&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;name&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;Kerry&nbsp;Onn&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;quantity&quot;</span>:&nbsp;0 } HTTP/1.1 400 Bad Request Content-Type: application/problem+json; charset=utf-8 { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;type&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;https://tools.ietf.org/html/rfc7231#section-6.5.1&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;title&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;One&nbsp;or&nbsp;more&nbsp;validation&nbsp;errors&nbsp;occurred.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;status&quot;</span>:&nbsp;400, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;traceId&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;|bb45b60d-4bd255194871157d.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;errors&quot;</span>:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;Email&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;The&nbsp;Email&nbsp;field&nbsp;is&nbsp;required.&quot;</span>&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;Quantity&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;Quantity&nbsp;must&nbsp;be&nbsp;a&nbsp;positive&nbsp;integer,&nbsp;but&nbsp;was:&nbsp;0.&quot;</span>&nbsp;] &nbsp;&nbsp;} }</pre> </p> <p> The <code>[NaturalNumber]</code> attribute now correctly reports the offending value together with a useful error message. </p> <p> Compare, however, the above <code>NaturalNumberAttribute</code> class to the <code>TryParseQuantity</code> function, repeated here for convenience: </p> <p> <pre><span style="color:blue;">private</span>&nbsp;Validated&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;<span style="color:#74531f;">TryParseQuantity</span>() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(Quantity&nbsp;&lt;&nbsp;1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;Validated.Fail&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#a31515;">$&quot;Quantity&nbsp;must&nbsp;be&nbsp;a&nbsp;positive&nbsp;integer,&nbsp;but&nbsp;was:&nbsp;</span>{Quantity}<span style="color:#a31515;">.&quot;</span>); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;Validated.Succeed&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;(Quantity); }</pre> </p> <p> <code>TryParseQuantity</code> is shorter and has half the <a href="https://en.wikipedia.org/wiki/Cyclomatic_complexity">cyclomatic complexity</a> of <code>NaturalNumberAttribute</code>. In isolation, at least, I'd prefer the shorter, simpler alternative. </p> <h3 id="3c90c9ded0af42fd9017593c9a387e97"> Date and time validation <a href="#3c90c9ded0af42fd9017593c9a387e97" title="permalink">#</a> </h3> <p> Remaining is validation of the <code>At</code> property. As a first step, I converted the property to a <code>DateTime</code> value and added attributes: </p> <p> <pre>[Required,&nbsp;NotNull] <span style="color:blue;">public</span>&nbsp;DateTime?&nbsp;At&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;<span style="color:blue;">set</span>;&nbsp;}</pre> </p> <p> I'd been a little apprehensive doing that, fearing that it'd break a lot of code (particularly tests), but that turned out not to be the case. In fact, it actually simplified a few of the tests. </p> <p> On the other hand, this doesn't really work as required: </p> <p> <pre>POST /restaurants/1/reservations?sig=1WiLlS5705bfsffPzaFYLwntrS4FCjE5CLdaeYTHxxg%3D HTTP/1.1 content-type: application/json { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;at&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;2022-11-21&nbsp;19:00&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;name&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;Kerry&nbsp;Onn&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;quantity&quot;</span>:&nbsp;0 } HTTP/1.1 400 Bad Request Content-Type: application/problem+json; charset=utf-8 { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;type&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;https://tools.ietf.org/html/rfc7231#section-6.5.1&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;title&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;One&nbsp;or&nbsp;more&nbsp;validation&nbsp;errors&nbsp;occurred.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;status&quot;</span>:&nbsp;400, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;traceId&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;|1e1d600e-4098fb36635642f6.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;errors&quot;</span>:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;dto&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;The&nbsp;dto&nbsp;field&nbsp;is&nbsp;required.&quot;</span>&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;$.at&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;The&nbsp;JSON&nbsp;value&nbsp;could&nbsp;not&nbsp;be&nbsp;converted&nbsp;to&nbsp;System.Nullable`1[System.DateTime].↩ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path:&nbsp;$.at&nbsp;|&nbsp;LineNumber:&nbsp;0&nbsp;|&nbsp;BytePositionInLine:&nbsp;26.&quot;</span>&nbsp;] &nbsp;&nbsp;} }</pre> </p> <p> (I've wrapped the last error message over two lines for readability. The <code>↩</code> symbol indicates where I've wrapped the text.) </p> <p> There are several problems with this response. First, in addition to complaining about the missing <code>at</code> property, it should also have reported that there are problems with the <code>Quantity</code> and that the <code>Email</code> property is missing. Instead, the response implies that the <code>dto</code> field is missing. That's likely confusing to client developers, because <code>dto</code> is an implementation detail; it's the name of the C# parameter of the method that handles the request. Client developers can't and shouldn't know this. Instead, it looks as though the REST API somehow failed to receive the JSON document that the client posted. </p> <p> Second, the error message exposes other implementation details, here that the <code>at</code> field has the type <code>System.Nullable`1[System.DateTime]</code>. This is, at best, irrelevant. At worst, it could be a security issue, because it reveals to a would-be attacker that the system is implemented on .NET. </p> <p> Third, the framework rejects what looks like a perfectly good date and time: <code>2022-11-21 19:00</code>. This is a breaking change, since the API used to accept such values. </p> <p> What's wrong with <code>2022-11-21 19:00</code>? It's not a valid <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> string. According to the ISO 8601 standard, the date and time must be separated by <code>T</code>: </p> <p> <pre>POST /restaurants/1/reservations?sig=1WiLlS5705bfsffPzaFYLwntrS4FCjE5CLdaeYTHxxg%3D HTTP/1.1 content-type: application/json { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;at&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;2022-11-21T19:00&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;name&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;Kerry&nbsp;Onn&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;quantity&quot;</span>:&nbsp;0 } HTTP/1.1 400 Bad Request Content-Type: application/problem+json; charset=utf-8 { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;type&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;https://tools.ietf.org/html/rfc7231#section-6.5.1&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;title&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;One&nbsp;or&nbsp;more&nbsp;validation&nbsp;errors&nbsp;occurred.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;status&quot;</span>:&nbsp;400, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;traceId&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;|1e1d600f-4098fb36635642f6.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;errors&quot;</span>:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;Email&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;The&nbsp;Email&nbsp;field&nbsp;is&nbsp;required.&quot;</span>&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;Quantity&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;Quantity&nbsp;must&nbsp;be&nbsp;a&nbsp;positive&nbsp;integer,&nbsp;but&nbsp;was:&nbsp;0.&quot;</span>&nbsp;] &nbsp;&nbsp;} }</pre> </p> <p> Posting a valid ISO 8601 string does, indeed, enable the client to proceed - only to receive a new set of error messages. After I converted <code>At</code> to <code>DateTime?</code>, the ASP.NET validation framework fails to collect and report all errors. Instead it stops if it can't parse the <code>At</code> property. It doesn't report any other errors that might also be present. </p> <p> That is exactly the requirement that applicative validation so elegantly solves. </p> <h3 id="e9986e66f63c476ca529788afaa863e4"> Tolerant Reader <a href="#e9986e66f63c476ca529788afaa863e4" title="permalink">#</a> </h3> <p> While it's true that <code>2022-11-21 19:00</code> isn't valid ISO 8601, it's unambiguous. According to <a href="https://en.wikipedia.org/wiki/Robustness_principle">Postel's law</a> an API should be a <a href="https://martinfowler.com/bliki/TolerantReader.html">Tolerant Reader</a>. It's not. </p> <p> This problem, however, is solvable. First, add the Tolerant Reader: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">DateTimeConverter</span>&nbsp;:&nbsp;JsonConverter&lt;DateTime&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;DateTime&nbsp;Read( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">ref</span>&nbsp;Utf8JsonReader&nbsp;reader, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Type&nbsp;typeToConvert, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;JsonSerializerOptions&nbsp;options) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;DateTime.Parse( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;reader.GetString(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CultureInfo.InvariantCulture); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">void</span>&nbsp;Write( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Utf8JsonWriter&nbsp;writer, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;DateTime&nbsp;value, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;JsonSerializerOptions&nbsp;options) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(writer&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;ArgumentNullException(nameof(writer)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;writer.WriteStringValue(value.ToString(<span style="color:#a31515;">&quot;s&quot;</span>)); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Then add it to the JSON serialiser's <a href="https://docs.microsoft.com/dotnet/api/system.text.json.jsonserializeroptions.converters">Converters</a>: </p> <p> <pre>opts.JsonSerializerOptions.Converters.Add(<span style="color:blue;">new</span>&nbsp;DateTimeConverter());</pre> </p> <p> This, at least, addresses the Tolerant Reader concern: </p> <p> <pre>POST /restaurants/1/reservations?sig=1WiLlS5705bfsffPzaFYLwntrS4FCjE5CLdaeYTHxxg%3D HTTP/1.1 content-type: application/json { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;at&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;2022-11-21&nbsp;19:00&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;name&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;Kerry&nbsp;Onn&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;quantity&quot;</span>:&nbsp;0 } HTTP/1.1 400 Bad Request Content-Type: application/problem+json; charset=utf-8 { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;type&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;https://tools.ietf.org/html/rfc7231#section-6.5.1&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;title&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;One&nbsp;or&nbsp;more&nbsp;validation&nbsp;errors&nbsp;occurred.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;status&quot;</span>:&nbsp;400, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;traceId&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;|11576943-400dafd4b489c282.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;errors&quot;</span>:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;Email&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;The&nbsp;Email&nbsp;field&nbsp;is&nbsp;required.&quot;</span>&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;Quantity&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;Quantity&nbsp;must&nbsp;be&nbsp;a&nbsp;positive&nbsp;integer,&nbsp;but&nbsp;was:&nbsp;0.&quot;</span>&nbsp;] &nbsp;&nbsp;} }</pre> </p> <p> The API now accepts the slightly malformed <code>at</code> field. It also correctly handles if the field is entirely missing: </p> <p> <pre>POST /restaurants/1/reservations?sig=1WiLlS5705bfsffPzaFYLwntrS4FCjE5CLdaeYTHxxg%3D HTTP/1.1 content-type: application/json { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;name&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;Kerry&nbsp;Onn&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;quantity&quot;</span>:&nbsp;0 } HTTP/1.1 400 Bad Request Content-Type: application/problem+json; charset=utf-8 { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;type&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;https://tools.ietf.org/html/rfc7231#section-6.5.1&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;title&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;One&nbsp;or&nbsp;more&nbsp;validation&nbsp;errors&nbsp;occurred.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;status&quot;</span>:&nbsp;400, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;traceId&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;|11576944-400dafd4b489c282.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;errors&quot;</span>:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;At&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;The&nbsp;At&nbsp;field&nbsp;is&nbsp;required.&quot;</span>&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;Email&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;The&nbsp;Email&nbsp;field&nbsp;is&nbsp;required.&quot;</span>&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;Quantity&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;Quantity&nbsp;must&nbsp;be&nbsp;a&nbsp;positive&nbsp;integer,&nbsp;but&nbsp;was:&nbsp;0.&quot;</span>&nbsp;] &nbsp;&nbsp;} }</pre> </p> <p> On the other hand, it <em>still</em> doesn't gracefully handle the case when the <code>at</code> field is unrecoverably malformed: </p> <p> <pre>POST /restaurants/1/reservations?sig=1WiLlS5705bfsffPzaFYLwntrS4FCjE5CLdaeYTHxxg%3D HTTP/1.1 content-type: application/json { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;at&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;foo&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;name&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;Kerry&nbsp;Onn&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;quantity&quot;</span>:&nbsp;0 } HTTP/1.1 400 Bad Request Content-Type: application/problem+json; charset=utf-8 { &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;type&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;https://tools.ietf.org/html/rfc7231#section-6.5.1&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;title&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;One&nbsp;or&nbsp;more&nbsp;validation&nbsp;errors&nbsp;occurred.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;status&quot;</span>:&nbsp;400, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;traceId&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;|11576945-400dafd4b489c282.&quot;</span>, &nbsp;&nbsp;<span style="color:#2e75b6;">&quot;errors&quot;</span>:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;The&nbsp;supplied&nbsp;value&nbsp;is&nbsp;invalid.&quot;</span>&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2e75b6;">&quot;dto&quot;</span>:&nbsp;[&nbsp;<span style="color:#a31515;">&quot;The&nbsp;dto&nbsp;field&nbsp;is&nbsp;required.&quot;</span>&nbsp;] &nbsp;&nbsp;} }</pre> </p> <p> <code>The supplied value is invalid.</code> and <code>The dto field is required.</code>? That's not really helpful. And what happened to <code>The Email field is required.</code> and <code>Quantity must be a positive integer, but was: 0.</code>? </p> <p> If there's a way to address this problem, I don't know how. I've tried adding another custom attribute, similar to the above <code>NaturalNumberAttribute</code> class, but that doesn't solve it - probably because the model binder (that deserialises the JSON document to a <code>ReservationDto</code> instance) runs before the validation. </p> <p> Perhaps there's a way to address this problem with yet another class that derives from a base class, but I think that I've already played enough <a href="https://en.wikipedia.org/wiki/Whac-A-Mole">Whack-a-mole</a> to arrive at a conclusion. </p> <h3 id="fc3e2119ed1c4a7a8cff0c0992a8b071"> Conclusion <a href="#fc3e2119ed1c4a7a8cff0c0992a8b071" title="permalink">#</a> </h3> <p> Your context may differ from mine, so the conclusion that I arrive at may not apply in your situation. For example, I'm given to understand that one benefit that the ASP.NET validation framework provides is that when used with ASP.NET MVC (instead of as a Web API), (some of) the validation logic can also run in <a href="https://www.javascript.com/">JavaScript</a> in browsers. This, ostensibly, reduces code duplication. </p> <blockquote> <p> "Yet in the case of validation, a Declarative model is far superior to a FP one. The declarative model allows various environments to implement validation as they need it (IE: Client side validation) while the FP one is strictly limited to the environment executing the code." </p> <footer><cite><a href="https://twitter.com/PopCatalin/status/1551478926005911553">PopCatalin</a></cite></footer> </blockquote> <p> On the other hand, using the ASP.NET validation framework requires more code, and more complex code, than with applicative validation. It's a particular set of APIs that you have to learn, and that knowledge doesn't transfer to other frameworks, platforms, or languages. </p> <p> Apart from client-side validation, I fail to see how applicative validation <em>"re implement[s validation] more poorly, by renouncing standardization, interoperability and globalization"</em>. </p> <p> I'm not aware that there's any <em>standard</em> for validation as such, so I think that @PopCatalin has the 'standard' ASP.NET validation API in mind. If so, I consider applicative validation a much more standardised solution than a specialised API. </p> <p> If by <em>interoperability</em> @PopCatalin means the transfer of logic from server side to client side, then it's true that the applicative validation I showed in the previous article runs exclusively on the server. I wonder, however, how much of such custom validation as <code>NaturalNumberAttribute</code> automatically transfers to the client side. </p> <p> When it comes to globalisation, I fail to see how applicative validation is less globalisable than the ASP.NET validation framework. One could easily replace the hard-coded strings in my examples with resource strings. </p> <p> It would seem, again, that <a href="https://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule">any sufficiently complicated custom validation framework contains an ad-hoc, informally-specified, bug-ridden, slow implementation of half of applicative validation</a>. </p> <blockquote> <p> "I must admit I really liked the declarative OOP model using annotations when I first saw it in Java (EJB3.0, almost 20yrs ago) until I saw FP way of doing things. FP way is so much simpler and powerful, because it's just function composition, nothing more, no hidden "magic"." </p> <footer><cite><a href="https://twitter.com/witoldsz/status/1552429555503493120">Witold Szczerba</a></cite></footer> </blockquote> <p> I still find myself in the same camp as Witold Szczerba. It's easy to get started using validation annotations, but it doesn't follow that it's simpler or better in the long run. As <a href="https://en.wikipedia.org/wiki/Rich_Hickey">Rich Hickey</a> points out in <a href="https://www.infoq.com/presentations/Simple-Made-Easy/">Simple Made Easy</a>, <em>simple</em> and <em>easy</em> isn't the same. If I have to maintain code, I'll usually choose the simple solution over the easy solution. That means choosing applicative validation over a framework-specific validation API. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="f6deac18851d47c3b066f82a8be3847d"> <div class="comment-author">Maurice Johnson</div> <div class="comment-content"> <p> Hello Mark. I was just wondering, is it possible to use the type system to do the validation instead ? </p> <p> What I mean is, for example, to make all the ReservationDto's field a type with validation in the constructor (like a class name, a class email, and so on). Normally, when the framework will build ReservationDto, it will try to construct the fields using the type constructor, and if there is an explicit error thrown during the construction, the framework will send us back the error with the provided message. </p> <p> Plus, I think types like "email", "name" and "at" are reusable. And I feel like we have more possibilities for validation with that way of doing than with the validation attributes. </p> <p> What do you think ? </p> <p> Regards. </p> </div> <div class="comment-date">2022-08-16 08:30 UTC</div> </div> <div class="comment" id="89a9ef6d57f645d7a1e848aaf20b8b72"> <div class="comment-author"><a href="/">Mark Seemann</a></div> <div class="comment-content"> <p> Maurice, thank you for writing. I started writing a reply, but it grew, so I'm going to turn it into a blog post. I'll post an update here once I've published it, but expect it to take a few weeks. </p> </div> <div class="comment-date">2022-08-18 7:50 UTC</div> </div> <div class="comment" id="e932eb2fd0804a049314872d5fe6a358"> <div class="comment-author"><a href="/">Mark Seemann</a></div> <div class="comment-content"> <p> I've published the article: <a href="/2022/08/22/can-types-replace-validation">Can types replace validation?</a>. </p> </div> <div class="comment-date">2022-08-22 6:00 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2022/08/15/aspnet-validation-revisited Endomorphism as an invariant functor https://blog.ploeh.dk/2022/08/08/endomorphism-as-an-invariant-functor/ Mon, 08 Aug 2022 04:43:00 UTC <div id="post"> <p> <em>An article (also) for object-oriented programmers.</em> </p> <p> This article is part of <a href="/2022/08/01/invariant-functors">a series of articles about invariant functors</a>. An invariant functor is a <a href="/2018/03/22/functors">functor</a> that is neither covariant nor contravariant. See the series introduction for more details. </p> <p> An <a href="https://en.wikipedia.org/wiki/Endomorphism">endomorphism</a> is a function where the return type is the same as the input type. </p> <p> In <a href="https://www.haskell.org/">Haskell</a> we denote an endomorphism as <code>a -&gt; a</code>, in <a href="http://fsharp.org/">F#</a> we have to add an apostrophe: <code>'a -&gt; 'a</code>, while in C# such a function corresponds to the delegate <code>Func&lt;T, T&gt;</code> or, alternatively, to a method that has the same return type as input type. </p> <p> In Haskell you can treat an endomorphism like a <a href="/2017/10/06/monoids">monoid</a> by wrapping it in a <a href="https://bartoszmilewski.com/2014/01/14/functors-are-containers">container</a> called <a href="https://hackage.haskell.org/package/base/docs/Data-Monoid.html#t:Endo">Endo</a>: <code>Endo a</code>. In C#, we <a href="/2021/05/31/from-state-tennis-to-endomorphism">might model it as an interface</a> called <code><span style="color:#2b91af;">IEndomorphism</span>&lt;<span style="color:#2b91af;">T</span>&gt;</code>. </p> <p> That looks enough like a functor that you might wonder if it is one, but it turns out that it's neither co- nor contravariant. You can deduce this with positional variance analysis (which I've learned from <a href="https://thinkingwithtypes.com/">Thinking with Types</a>). In short, this is because <code>T</code> appears as both input and output - it's neither co- nor contravariant, but rather <em>invariant</em>. </p> <h3 id="39fa705060f143aba4c18dd2c8ff7f2d"> Explicit endomorphism interface in C# <a href="#39fa705060f143aba4c18dd2c8ff7f2d" title="permalink">#</a> </h3> <p> Consider an <code><span style="color:#2b91af;">IEndomorphism</span>&lt;<span style="color:#2b91af;">T</span>&gt;</code> interface in C#: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IEndomorphism</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;T&nbsp;<span style="color:#74531f;">Run</span>(T&nbsp;<span style="color:#1f377f;">x</span>); }</pre> </p> <p> I've borrowed this interface from the article <a href="/2021/05/31/from-state-tennis-to-endomorphism">From State tennis to endomorphism</a>. In that article I explain that I only introduce this interface for educational reasons. I don't expect you to use something like this in production code bases. On the other hand, everything that applies to <code><span style="color:#2b91af;">IEndomorphism</span>&lt;<span style="color:#2b91af;">T</span>&gt;</code> also applies to 'naked' functions, as you'll see later in the article. </p> <p> As outlined in the introduction, you can make a container an invariant functor by implementing a non-standard version of <code>Select</code>: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;IEndomorphism&lt;B&gt;&nbsp;<span style="color:#74531f;">Select</span>&lt;<span style="color:#2b91af;">A</span>,&nbsp;<span style="color:#2b91af;">B</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;IEndomorphism&lt;A&gt;&nbsp;<span style="color:#1f377f;">endomorphism</span>, &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;A,&nbsp;B&gt;&nbsp;<span style="color:#1f377f;">aToB</span>, &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;B,&nbsp;A&gt;&nbsp;<span style="color:#1f377f;">bToA</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;SelectEndomorphism&lt;A,&nbsp;B&gt;(endomorphism,&nbsp;aToB,&nbsp;bToA); } <span style="color:blue;">private</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">SelectEndomorphism</span>&lt;<span style="color:#2b91af;">A</span>,&nbsp;<span style="color:#2b91af;">B</span>&gt;&nbsp;:&nbsp;IEndomorphism&lt;B&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;IEndomorphism&lt;A&gt;&nbsp;endomorphism; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;Func&lt;A,&nbsp;B&gt;&nbsp;aToB; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;Func&lt;B,&nbsp;A&gt;&nbsp;bToA; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">SelectEndomorphism</span>( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IEndomorphism&lt;A&gt;&nbsp;<span style="color:#1f377f;">endomorphism</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;A,&nbsp;B&gt;&nbsp;<span style="color:#1f377f;">aToB</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;B,&nbsp;A&gt;&nbsp;<span style="color:#1f377f;">bToA</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.endomorphism&nbsp;=&nbsp;endomorphism; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.aToB&nbsp;=&nbsp;aToB; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.bToA&nbsp;=&nbsp;bToA; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;B&nbsp;<span style="color:#74531f;">Run</span>(B&nbsp;<span style="color:#1f377f;">x</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;aToB(endomorphism.Run(bToA(x))); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> Since the <code>Select</code> method has to return an <code>IEndomorphism&lt;B&gt;</code> implementation, one option is to use a private, nested class. Most of this is <a href="/2019/12/16/zone-of-ceremony">ceremony</a> required because it's working with interfaces. The interesting part is the nested class' <code>Run</code> implementation. </p> <p> In order to translate an <code>IEndomorphism&lt;A&gt;</code> to an <code>IEndomorphism&lt;B&gt;</code>, the <code>Run</code> method first uses <code>bToA</code> to translate <code>x</code> to an <code>A</code> value. Once it has the <code>A</code> value, it can <code>Run</code> the <code>endomorphism</code>, which returns another <code>A</code> value. Finally, the method can use <code>aToB</code> to convert the returned <code>A</code> value to a <code>B</code> value that it can return. </p> <p> Here's a simple example. Imagine that you have an endomorphism like this one: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Incrementer</span>&nbsp;:&nbsp;IEndomorphism&lt;BigInteger&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;BigInteger&nbsp;<span style="color:#74531f;">Run</span>(BigInteger&nbsp;<span style="color:#1f377f;">x</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;x&nbsp;+&nbsp;1; &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> This one simply increments a <a href="https://docs.microsoft.com/dotnet/api/system.numerics.biginteger">BigInteger</a> value. Since <code>BigInteger</code> is isomorphic to a byte array, it's possible to transform this <code>BigInteger</code> endomorphism to a byte array endomorphism: </p> <p> <pre>[Theory] [InlineData(<span style="color:blue;">new</span>&nbsp;<span style="color:blue;">byte</span>[0],&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:blue;">byte</span>[]&nbsp;{&nbsp;1&nbsp;})] [InlineData(<span style="color:blue;">new</span>&nbsp;<span style="color:blue;">byte</span>[]&nbsp;{&nbsp;1&nbsp;},&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:blue;">byte</span>[]&nbsp;{&nbsp;2&nbsp;})] [InlineData(<span style="color:blue;">new</span>&nbsp;<span style="color:blue;">byte</span>[]&nbsp;{&nbsp;255,&nbsp;0&nbsp;},&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:blue;">byte</span>[]&nbsp;{&nbsp;0,&nbsp;1&nbsp;})] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;<span style="color:#74531f;">InvariantSelection</span>(<span style="color:blue;">byte</span>[]&nbsp;<span style="color:#1f377f;">bs</span>,&nbsp;<span style="color:blue;">byte</span>[]&nbsp;<span style="color:#1f377f;">expected</span>) { &nbsp;&nbsp;&nbsp;&nbsp;IEndomorphism&lt;BigInteger&gt;&nbsp;<span style="color:#1f377f;">source</span>&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;Incrementer(); &nbsp;&nbsp;&nbsp;&nbsp;IEndomorphism&lt;<span style="color:blue;">byte</span>[]&gt;&nbsp;<span style="color:#1f377f;">destination</span>&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;source.Select(<span style="color:#1f377f;">bi</span>&nbsp;=&gt;&nbsp;bi.ToByteArray(),&nbsp;<span style="color:#1f377f;">arr</span>&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;BigInteger(arr)); &nbsp;&nbsp;&nbsp;&nbsp;Assert.Equal(expected,&nbsp;destination.Run(bs)); }</pre> </p> <p> You can convert a <code>BigInteger</code> to a byte array with the <code>ToByteArray</code> method, and convert such a byte array back to a <code>BigInteger</code> using one of its constructor overloads. Since this is possible, the example test can convert this <code>IEndomorphism&lt;BigInteger&gt;</code> to an <code>IEndomorphism&lt;<span style="color:blue;">byte</span>[]&gt;</code> and later <code>Run</code> it. </p> <h3 id="f9afa75c0b014df68d29ddf1244f329f"> Mapping functions in F# <a href="#f9afa75c0b014df68d29ddf1244f329f" title="permalink">#</a> </h3> <p> You don't need an interface in order to turn an endomorphism into an invariant functor. An endomorphism is just a function that has the same input and output type. In C# such a function has the type <code>Func&lt;T, T&gt;</code>, while in F# it's written <code>&#39;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;&#39;a</code>. </p> <p> You could write an F# module that defines an <code>invmap</code> function, which would be equivalent to the above <code>Select</code> method: </p> <p> <pre><span style="color:blue;">module</span>&nbsp;Endo&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;(&#39;a&nbsp;-&gt;&nbsp;&#39;b)&nbsp;-&gt;&nbsp;(&#39;b&nbsp;-&gt;&nbsp;&#39;a)&nbsp;-&gt;&nbsp;(&#39;a&nbsp;-&gt;&nbsp;&#39;a)&nbsp;-&gt;&nbsp;(&#39;b&nbsp;-&gt;&nbsp;&#39;b)</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;invmap&nbsp;(f&nbsp;:&nbsp;&#39;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;&#39;b)&nbsp;(g&nbsp;:&nbsp;&#39;b&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;&#39;a)&nbsp;(h&nbsp;:&nbsp;&#39;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;&#39;a)&nbsp;=&nbsp;g&nbsp;&gt;&gt;&nbsp;h&nbsp;&gt;&gt;&nbsp;f</pre> </p> <p> Since this function doesn't have to deal with the ceremony of interfaces, the implementation is simple function composition: For any input, first apply it to the <code>g</code> function, then apply the output to the <code>h</code> function, and again apply the output of that function to the <code>f</code> function. </p> <p> Here's the same example as above: </p> <p> <pre><span style="color:blue;">let</span>&nbsp;increment&nbsp;(bi&nbsp;:&nbsp;BigInteger)&nbsp;=&nbsp;bi&nbsp;+&nbsp;BigInteger.One <span style="color:green;">//&nbsp;byte&nbsp;[]&nbsp;-&gt;&nbsp;byte&nbsp;[]</span> <span style="color:blue;">let</span>&nbsp;bArrInc&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;Endo.invmap&nbsp;(<span style="color:blue;">fun</span>&nbsp;(bi&nbsp;:&nbsp;BigInteger)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;bi.ToByteArray&nbsp;())&nbsp;BigInteger&nbsp;increment</pre> </p> <p> Here's a simple sanity check of the <code>bArrInc</code> function executed in F# Interactive: </p> <p> <pre>&gt; let bArr = bArrInc [| 255uy; 255uy; 0uy |];; val bArr : byte [] = [|0uy; 0uy; 1uy|]</pre> </p> <p> If you are wondering about that particular output value, I'll refer you to <a href="https://docs.microsoft.com/dotnet/api/system.numerics.biginteger">the BigInteger documentation</a>. </p> <h3 id="76c32ad7688b41fc9e083a51584e4a6a"> Function composition <a href="#76c32ad7688b41fc9e083a51584e4a6a" title="permalink">#</a> </h3> <p> The F# implementation of <code>invmap</code> (<code>g&nbsp;&gt;&gt;&nbsp;h&nbsp;&gt;&gt;&nbsp;f</code>) makes it apparent that an endomorphism is an invariant functor via function composition. In F#, though, that fact almost disappears in all the type declaration ceremony. In the Haskell instance from the <a href="https://hackage.haskell.org/package/invariant">invariant</a> package it's even clearer: </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;<span style="color:blue;">Invariant</span>&nbsp;<span style="color:blue;">Endo</span>&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;invmap&nbsp;f&nbsp;g&nbsp;(Endo&nbsp;h)&nbsp;=&nbsp;Endo&nbsp;(f&nbsp;.&nbsp;h&nbsp;.&nbsp;g)</pre> </p> <p> Perhaps a diagram is helpful: </p> <p> <img src="/content/binary/invariant-map-diagram.png" alt="Arrow diagram showing the mapping from an endomorphism in a to an endomorphism in b."> </p> <p> If you have a function <code>h</code> from the type <code>a</code> to <code>a</code> and you need a function <code>b -&gt; b</code>, you can produce it by putting <code>g</code> in front of <code>h</code>, and <code>f</code> after. That's also what the above C# implementation does. In F#, you can express such a composition as <code>g&nbsp;&gt;&gt;&nbsp;h&nbsp;&gt;&gt;&nbsp;f</code>, which seems natural to most westerners, since it goes from left to right. In Haskell, most expressions are instead expressed from right to left, so it becomes: <code>f&nbsp;.&nbsp;h&nbsp;.&nbsp;g</code>. In any case, the result is the desired function that takes a <code>b</code> value as input and returns a <code>b</code> value as output. That composed function is indicated by a dashed arrow in the above diagram. </p> <h3 id="3934e941d51f47c698d8b803b7adb97c"> Identity law <a href="#3934e941d51f47c698d8b803b7adb97c" title="permalink">#</a> </h3> <p> Contrary to my usual habit, I'm going to <em>prove</em> that both invariant functor laws hold for this implementation. I'll use equational reasoning with <a href="https://bartoszmilewski.com/2015/01/20/functors/">the notation that Bartosz Milewski uses</a>. Here's the proof that the <code>invmap</code> instance obeys the identity law: </p> <p> <pre>&nbsp;&nbsp;invmap&nbsp;id&nbsp;id&nbsp;(Endo&nbsp;h) =&nbsp;{&nbsp;definition&nbsp;of&nbsp;invmap&nbsp;} &nbsp;&nbsp;Endo&nbsp;(id&nbsp;.&nbsp;h&nbsp;.&nbsp;id) =&nbsp;{&nbsp;eta&nbsp;expansion&nbsp;} &nbsp;&nbsp;Endo&nbsp;(\x&nbsp;-&gt;&nbsp;(id&nbsp;.&nbsp;h&nbsp;.&nbsp;id)&nbsp;x) =&nbsp;{&nbsp;defintion&nbsp;of&nbsp;composition&nbsp;(.)&nbsp;} &nbsp;&nbsp;Endo&nbsp;(\x&nbsp;-&gt;&nbsp;id&nbsp;(h&nbsp;(id&nbsp;x))) =&nbsp;{&nbsp;defintion&nbsp;of&nbsp;id&nbsp;} &nbsp;&nbsp;Endo&nbsp;(\x&nbsp;-&gt;&nbsp;h&nbsp;x) =&nbsp;{&nbsp;eta&nbsp;reduction&nbsp;} &nbsp;&nbsp;Endo&nbsp;h =&nbsp;{&nbsp;definition&nbsp;of&nbsp;id&nbsp;} &nbsp;&nbsp;id&nbsp;(Endo&nbsp;h)</pre> </p> <p> While I'm not going to comment further on that, I can show you what the identity law looks like in C#: </p> <p> <pre>[Theory] [InlineData(0)] [InlineData(1)] [InlineData(9)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;<span style="color:#74531f;">IdentityLaw</span>(<span style="color:blue;">long</span>&nbsp;<span style="color:#1f377f;">l</span>) { &nbsp;&nbsp;&nbsp;&nbsp;IEndomorphism&lt;BigInteger&gt;&nbsp;<span style="color:#1f377f;">e</span>&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;Incrementer(); &nbsp;&nbsp;&nbsp;&nbsp;IEndomorphism&lt;BigInteger&gt;&nbsp;<span style="color:#1f377f;">actual</span>&nbsp;=&nbsp;e.Select(<span style="color:#1f377f;">x</span>&nbsp;=&gt;&nbsp;x,&nbsp;<span style="color:#1f377f;">x</span>&nbsp;=&gt;&nbsp;x); &nbsp;&nbsp;&nbsp;&nbsp;Assert.Equal(e.Run(l),&nbsp;actual.Run(l)); }</pre> </p> <p> In C#, you typically write the identity function (<code>id</code> in F# and Haskell) as the lambda expression <code><span style="color:#1f377f;">x</span>&nbsp;=&gt;&nbsp;x</code>, since the identity function isn't 'built in' for C# like it is for F# and Haskell. (You can define it yourself, but it's not as <a href="/2015/08/03/idiomatic-or-idiosyncratic">idiomatic</a>.) </p> <h3 id="e47f375aafe441949e057787a5d35178"> Composition law <a href="#e47f375aafe441949e057787a5d35178" title="permalink">#</a> </h3> <p> As with the identity law, I'll start by suggesting a proof for the composition law for the Haskell instance: </p> <p> <pre>&nbsp;&nbsp;invmap&nbsp;f2&nbsp;f2&#39;&nbsp;$&nbsp;invmap&nbsp;f1&nbsp;f1&#39;&nbsp;(Endo&nbsp;h) =&nbsp;{&nbsp;definition&nbsp;of&nbsp;invmap&nbsp;} &nbsp;&nbsp;invmap&nbsp;f2&nbsp;f2&#39;&nbsp;$&nbsp;Endo&nbsp;(f1&nbsp;.&nbsp;h&nbsp;.&nbsp;f1&#39;) =&nbsp;{&nbsp;defintion&nbsp;of&nbsp;($)&nbsp;} &nbsp;&nbsp;invmap&nbsp;f2&nbsp;f2&#39;&nbsp;(Endo&nbsp;(f1&nbsp;.&nbsp;h&nbsp;.&nbsp;f1&#39;)) =&nbsp;{&nbsp;definition&nbsp;of&nbsp;invmap&nbsp;} &nbsp;&nbsp;Endo&nbsp;(f2&nbsp;.&nbsp;(f1&nbsp;.&nbsp;h&nbsp;.&nbsp;f1&#39;)&nbsp;.&nbsp;f2&#39;) =&nbsp;{&nbsp;associativity&nbsp;of&nbsp;composition&nbsp;(.)&nbsp;} &nbsp;&nbsp;Endo&nbsp;((f2&nbsp;.&nbsp;f1)&nbsp;.&nbsp;h&nbsp;.&nbsp;(f1&#39;&nbsp;.&nbsp;f2&#39;)) =&nbsp;{&nbsp;definition&nbsp;of&nbsp;invmap&nbsp;} &nbsp;&nbsp;invmap&nbsp;(f2&nbsp;.&nbsp;f1)&nbsp;(f1&#39;&nbsp;.&nbsp;f2&#39;)&nbsp;(Endo&nbsp;h)</pre> </p> <p> As above, a C# example may also help. First, assume that you have some endomorphism like this: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">SecondIncrementer</span>&nbsp;:&nbsp;IEndomorphism&lt;TimeSpan&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;TimeSpan&nbsp;<span style="color:#74531f;">Run</span>(TimeSpan&nbsp;<span style="color:#1f377f;">x</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;x&nbsp;+&nbsp;TimeSpan.FromSeconds(1); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> A test then demonstrates the composition law in action: </p> <p> <pre>[Theory] [InlineData(-3)] [InlineData(0)] [InlineData(11)] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;<span style="color:#74531f;">CompositionLaw</span>(<span style="color:blue;">long</span>&nbsp;<span style="color:#1f377f;">x</span>) { &nbsp;&nbsp;&nbsp;&nbsp;IEndomorphism&lt;TimeSpan&gt;&nbsp;<span style="color:#1f377f;">i</span>&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;SecondIncrementer(); &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;TimeSpan,&nbsp;<span style="color:blue;">long</span>&gt;&nbsp;<span style="color:#1f377f;">f1</span>&nbsp;=&nbsp;<span style="color:#1f377f;">ts</span>&nbsp;=&gt;&nbsp;ts.Ticks; &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;<span style="color:blue;">long</span>,&nbsp;TimeSpan&gt;&nbsp;<span style="color:#1f377f;">f1p</span>&nbsp;=&nbsp;<span style="color:#1f377f;">l</span>&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;TimeSpan(l); &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;<span style="color:blue;">long</span>,&nbsp;IntPtr&gt;&nbsp;<span style="color:#1f377f;">f2</span>&nbsp;=&nbsp;<span style="color:#1f377f;">l</span>&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;IntPtr(l); &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;IntPtr,&nbsp;<span style="color:blue;">long</span>&gt;&nbsp;<span style="color:#1f377f;">f2p</span>&nbsp;=&nbsp;<span style="color:#1f377f;">ip</span>&nbsp;=&gt;&nbsp;ip.ToInt64(); &nbsp;&nbsp;&nbsp;&nbsp;IEndomorphism&lt;IntPtr&gt;&nbsp;<span style="color:#1f377f;">left</span>&nbsp;=&nbsp;i.Select(f1,&nbsp;f1p).Select(f2,&nbsp;f2p); &nbsp;&nbsp;&nbsp;&nbsp;IEndomorphism&lt;IntPtr&gt;&nbsp;<span style="color:#1f377f;">right</span>&nbsp;=&nbsp;i.Select(<span style="color:#1f377f;">ts</span>&nbsp;=&gt;&nbsp;f2(f1(ts)),&nbsp;<span style="color:#1f377f;">ip</span>&nbsp;=&gt;&nbsp;f1p(f2p(ip))); &nbsp;&nbsp;&nbsp;&nbsp;Assert.Equal(left.Run(<span style="color:blue;">new</span>&nbsp;IntPtr(x)),&nbsp;right.Run(<span style="color:blue;">new</span>&nbsp;IntPtr(x))); }</pre> </p> <p> Don't try to make any sense of this. As outlined in the introductory article, in order to use an invariant functor, you're going to need an isomorphism. In order to demonstrate the composition law, you need <em>three</em> types that are isomorphic. Since you can convert back and forth between <code>TimeSpan</code> and <code>IntPtr</code> via <code>long</code>, this requirement is formally fulfilled. It doesn't make any sense to add a second to a value and then turn it into a function that changes a pointer. It sounds more like a security problem waiting to happen... Don't try this at home, kids. </p> <h3 id="ac1e8d3a75b54f9691c616755750ff77"> Conclusion <a href="#ac1e8d3a75b54f9691c616755750ff77" title="permalink">#</a> </h3> <p> Since an endomorphism can be modelled as a 'generic type', it may look like a candidate for a functor or <a href="/2021/09/02/contravariant-functors">contravariant functor</a>, but alas, neither is possible. The best we can get (apart from <a href="/2017/11/13/endomorphism-monoid">a monoid instance</a>) is an invariant functor. </p> <p> The invariant functor instance for an endomorphism turns out to be simple function composition. That's not how all invariant functors, work, though. </p> <p> <strong>Next:</strong> <a href="/2022/08/29/natural-transformations-as-invariant-functors">Natural transformations as invariant functors</a>. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2022/08/08/endomorphism-as-an-invariant-functor Invariant functors https://blog.ploeh.dk/2022/08/01/invariant-functors/ Mon, 01 Aug 2022 05:49:00 UTC <div id="post"> <p> <em>Containers that support mapping isomorphic values.</em> </p> <p> This article series is part of <a href="/2018/03/19/functors-applicatives-and-friends">a larger series of articles about functors, applicatives, and other mappable containers</a>. So far, you've seen examples of both co- and <a href="/2021/09/02/contravariant-functors">contravariant functors</a>, including <a href="/2021/11/01/profunctors">profunctors</a>. You've also seen a few examples of <a href="/2020/10/19/monomorphic-functors">monomorphic functors</a> - mappable containers where there's no variance at all. </p> <p> What happens, on the other hand, if you have a container of (generic) values, but it's neither co- nor contravariant? An <a href="https://en.wikipedia.org/wiki/Endomorphism">endomorphism</a> is an example - it's neither co- nor contravariant. You'll see a treatment of that in a later article. </p> <p> Even if neither co- nor contravariant mappings exists for a container, all may not be lost. It may still be an <em>invariant functor</em>. </p> <h3 id="40d4c4a6deed4af593b3cf002563f085"> Invariance <a href="#40d4c4a6deed4af593b3cf002563f085" title="permalink">#</a> </h3> <p> Consider a <a href="https://bartoszmilewski.com/2014/01/14/functors-are-containers">container</a> <code>f</code> (for <em>functor</em>). Depending on its variance, we call it <em>covariant</em>, <em>contravariant</em>, or <em>invariant</em>: </p> <ul> <li><em>Covariance</em> means that any function <code>a -&gt; b</code> can be lifted into a function <code>f a -&gt; f b</code>.</li> <li><em>Contravariance</em> means that any function <code>a -&gt; b</code> can be lifted into a function <code>f b -&gt; f a</code>.</li> <li><em>Invariance</em> means that in general, no function <code>a -&gt; b</code> can be lifted into a function over <code>f a</code>.</li> </ul> <p> <em>In general</em>, that is. A limited escape hatch exists: </p> <blockquote> <p> "an invariant type [...] allows you to map from <code>a</code> to <code>b</code> if and only if <code>a</code> and <code>b</code> are isomorphic. In a very real sense, this isn't an interesting property - an isomorphism between <code>a</code> and <code>b</code> means they're already the same thing to begin with." </p> <footer><cite>Sandy Maguire, <a href="https://thinkingwithtypes.com/">Thinking with Types</a></cite></footer> </blockquote> <p> In <a href="https://www.haskell.org/">Haskell</a> we may define an invariant functor (AKA <a href="http://comonad.com/reader/2008/rotten-bananas/">exponential functor</a>) as in the <a href="https://hackage.haskell.org/package/invariant">invariant</a> package: </p> <p> <pre><span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Invariant</span>&nbsp;f&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;<span style="color:#2b91af;">invmap</span>&nbsp;::&nbsp;(a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;b)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;(b&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;a)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;f&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;f&nbsp;b</pre> </p> <p> This means that an <em>invariant functor</em> <code>f</code> is a container of values where a translation from <code>f a</code> to <code>f b</code> exists if it's possible to translate contained values both ways: From <code>a</code> to <code>b</code>, and from <code>b</code> to <code>a</code>. Callers of the <code>invmap</code> function must supply translations that go both ways. </p> <h3 id="36e114d8871c46c9addb2e38936a2872"> Invariant functor in C# <a href="#36e114d8871c46c9addb2e38936a2872" title="permalink">#</a> </h3> <p> It's possible to translate the concept to a language like C#. Since C# doesn't have higher-kinded types, we have to examine the abstraction as a set of patterns or templates. For <a href="/2018/03/22/functors">functors</a> and <a href="/2022/03/28/monads">monads</a>, the C# compiler can perform 'compile-time duck typing' to recognise these motifs to enable query syntax. For more advanced or exotic universal abstractions, such as <a href="/2018/12/24/bifunctors">bifunctors</a>, <a href="/2021/11/01/profunctors">profunctors</a>, or invariant functors, we have to use a concrete container type as a stand-in for 'any' functor. In this article, I'll call it <code><span style="color:#2b91af;">Invariant</span>&lt;<span style="color:#2b91af;">A</span>&gt;</code>. </p> <p> Such a generic class must have a mapping function that corresponds to the above <code>invmap</code>. In C# it has this signature: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;Invariant&lt;B&gt;&nbsp;<span style="color:#74531f;">InvMap</span>&lt;<span style="color:#2b91af;">B</span>&gt;(Func&lt;A,&nbsp;B&gt;&nbsp;<span style="color:#1f377f;">aToB</span>,&nbsp;Func&lt;B,&nbsp;A&gt;&nbsp;<span style="color:#1f377f;">bToA</span>)</pre> </p> <p> In this example, <code>InvMap</code> is an instance method on <code><span style="color:#2b91af;">Invariant</span>&lt;<span style="color:#2b91af;">A</span>&gt;</code>. You may use it like this: </p> <p> <pre>Invariant&lt;<span style="color:blue;">long</span>&gt;&nbsp;<span style="color:#1f377f;">il</span>&nbsp;=&nbsp;createInvariant(); Invariant&lt;TimeSpan&gt;&nbsp;<span style="color:#1f377f;">its</span>&nbsp;=&nbsp;il.InvMap(<span style="color:#1f377f;">l</span>&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;TimeSpan(l),&nbsp;<span style="color:#1f377f;">ts</span>&nbsp;=&gt;&nbsp;ts.Ticks);</pre> </p> <p> It's not that easy to find good examples of truly isomorphic primitives, but <a href="https://docs.microsoft.com/dotnet/api/system.timespan">TimeSpan</a> is just a useful wrapper of <code>long</code>, so it's possible to translate back and forth without loss of information. To create a <code>TimeSpan</code> from a <code>long</code>, you can use the suitable constructor overload. To get a <code>long</code> from a <code>TimeSpan</code>, you can read the <a href="https://docs.microsoft.com/dotnet/api/system.timespan.ticks">Ticks</a> property. </p> <p> Perhaps you find a method name like <code>InvMap</code> non-idiomatic in C#. Perhaps a more <a href="/2015/08/03/idiomatic-or-idiosyncratic">idiomatic</a> name might be <code>Select</code>? That's not a problem: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;Invariant&lt;B&gt;&nbsp;<span style="color:#74531f;">Select</span>&lt;<span style="color:#2b91af;">B</span>&gt;(Func&lt;A,&nbsp;B&gt;&nbsp;<span style="color:#1f377f;">aToB</span>,&nbsp;Func&lt;B,&nbsp;A&gt;&nbsp;<span style="color:#1f377f;">bToA</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;InvMap(aToB,&nbsp;bToA); }</pre> </p> <p> In that case, usage would look like this: </p> <p> <pre>Invariant&lt;<span style="color:blue;">long</span>&gt;&nbsp;<span style="color:#1f377f;">il</span>&nbsp;=&nbsp;createInvariant(); Invariant&lt;TimeSpan&gt;&nbsp;<span style="color:#1f377f;">its</span>&nbsp;=&nbsp;il.Select(<span style="color:#1f377f;">l</span>&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;TimeSpan(l),&nbsp;<span style="color:#1f377f;">ts</span>&nbsp;=&gt;&nbsp;ts.Ticks);</pre> </p> <p> In this article, I'll use <code>Select</code> in order to be consistent with C# naming conventions. Using that name, however, will not make query syntax light up. While the name is fine, the signature is not one that the C# compiler will recognise as enabling special syntax. The name does, however, suggest a kinship with a normal functor, where the mapping in C# is called <code>Select</code>. </p> <h3 id="4a5c0a55258d4e398931d2880df059fb"> Laws <a href="#4a5c0a55258d4e398931d2880df059fb" title="permalink">#</a> </h3> <p> As is usual with these kinds of universal abstractions, an invariant functor must satisfy a few laws. </p> <p> The first one we might call the <em>identity law:</em> </p> <p> <pre>invmap id id = id</pre> </p> <p> This law corresponds to the first functor law. When performing the mapping operation, if the values in the invariant functor are mapped to themselves, the result will be an unmodified functor. </p> <p> In C# such a mapping might look like this: </p> <p> <pre><span style="color:blue;">var</span>&nbsp;<span style="color:#1f377f;">actual</span>&nbsp;=&nbsp;i.Select(<span style="color:#1f377f;">x</span>&nbsp;=&gt;&nbsp;x,&nbsp;<span style="color:#1f377f;">x</span>&nbsp;=&gt;&nbsp;x);</pre> </p> <p> The law then says that <code>actual</code> should be equal to <code>i</code>. </p> <p> The second law we might call the <em>composition law:</em> </p> <p> <pre>invmap f2 f2' . invmap f1 f1' = invmap (f2 . f1) (f1' . f2')</pre> </p> <p> Granted, this looks more complicated, but also directly corresponds to the second functor law. If two sequential mapping operations are performed one after the other, the result should be the same as a single mapping operation where the functions are composed. </p> <p> In C# the left-hand side might look like this: </p> <p> <pre>Invariant&lt;IntPtr&gt;&nbsp;<span style="color:#1f377f;">left</span>&nbsp;=&nbsp;i.Select(f1,&nbsp;f1p).Select(f2,&nbsp;f2p);</pre> </p> <p> In C# you can't name functions or variables with a quotation mark (like the Haskell code's <code>f1'</code> and <code>f2'</code>), so instead I named them <code>f1p</code> and <code>f2p</code> (with a <em>p</em> for <em>prime</em>). </p> <p> Likewise, the right-hand side might look like this: </p> <p> <pre>Invariant&lt;IntPtr&gt;&nbsp;<span style="color:#1f377f;">right</span>&nbsp;=&nbsp;i.Select(<span style="color:#1f377f;">ts</span>&nbsp;=&gt;&nbsp;f2(f1(ts)),&nbsp;<span style="color:#1f377f;">ip</span>&nbsp;=&gt;&nbsp;f1p(f2p(ip)));</pre> </p> <p> The composition law says that the <code>left</code> and <code>right</code> values must be equal. </p> <p> You'll see some more detailed examples in later articles. </p> <h3 id="14c58dc57f9744dfbc955015d03b871e"> Examples <a href="#14c58dc57f9744dfbc955015d03b871e" title="permalink">#</a> </h3> <p> This is all too abstract to seem useful in itself, so example are warranted. You'll be able to peruse examples of specific invariant functors in separate articles: </p> <ul> <li><a href="/2022/08/08/endomorphism-as-an-invariant-functor">Endomorphism as an invariant functor</a></li> <li><a href="/2022/08/29/natural-transformations-as-invariant-functors">Natural transformations as invariant functors</a></li> <li>Functors as invariant functors</li> <li>Contravariant functors as invariant functors</li> </ul> <p> As two of the titles suggest, all functors are also invariant functors, and the same goes for contravariant functors: </p> <p> <img src="/content/binary/invariant-functor-set-diagram.png" alt="Set diagram. The biggest set labelled invariant functos contains two other sets labelled functors and invariant functors."> </p> <p> To be honest, invariant functors are exotic, and you are unlikely to need them in all but the rarest cases. Still, I <em>did</em> run into a scenario where I needed an invariant functor instance to be able to perform <a href="/2022/09/05/the-state-pattern-and-the-state-monad">a particular sleight of hand</a>. The rabbit holes we sometimes fall into... </p> <h3 id="ffa0e597f09c40e7bcd1cabe808aa0d5"> Conclusion <a href="#ffa0e597f09c40e7bcd1cabe808aa0d5" title="permalink">#</a> </h3> <p> Invariant functors form a set that contains both co- and contravariant functors, as well as some data structures that are neither. This is an exotic abstraction that you may never need. It did, however, get me out of a bind at one time. </p> <strong>Next:</strong> <a href="/2022/08/08/endomorphism-as-an-invariant-functor">Endomorphism as an invariant functor</a>. </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="faae4a8cbe294be8ac7596488d675483"> <div class="comment-author"><a href="https://about.me/tysonwilliams">Tyson Williams</a></div> <div class="comment-content"> <blockquote> For <a href="/2018/03/22/functors">functors</a> and <a href="/2022/03/28/monads">monads</a>, the C# compiler can perform 'compile-time duck typing' to recognise these motifs to enable query syntax. </blockquote> <p> Instead of 'compile-time duck typing', I think a better phrase to describe this is <a href="https://en.wikipedia.org/wiki/Structural_type_system">structural typing</a>. </p> </div> <div class="comment-date">2022-09-17 16:20 UTC</div> </div> <div class="comment" id="98be00b677484b11a51d8e583c25baa5"> <div class="comment-author"><a href="/">Mark Seemann</a></div> <div class="comment-content"> <p> Tyson, thank you for writing. I wasn't aware of the term <em>structural typing</em>, so thank you for the link. I've now read that Wikipedia article, but all I know is what's there. Based on it, though, it looks as though <a href="https://fsharp.org">F#</a>'s <a href="https://learn.microsoft.com/dotnet/fsharp/language-reference/generics/statically-resolved-type-parameters">Statically Resolved Type Parameters</a> are another example of structural typing, in addition to the <a href="https://ocaml.org/">OCaml</a> example given in the article. </p> <p> IIRC, <a href="https://www.purescript.org/">PureScript</a>'s <em>row polymorphism</em> may be another example, but it's been many years since <a href="/2017/06/06/fractal-trees-with-purescript">I played with it</a>. In other words, I could be mistaken. </p> <p> Based on the Wikipedia article, it looks as though structural typing is more concerned with polymorphism, but granted, so is duck typing. Given how wrong 'compile-time duck typing' actually is in the above context, 'structural typing' seems more correct. </p> <p> I may still stick with 'compile-time duck typing' as a loose metaphor, though, because most people know what duck typing is, whereas I'm not sure as many people know of structural typing. The purpose of the metaphor is, after all, to be helpful. </p> </div> <div class="comment-date">2022-09-19 14:46 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2022/08/01/invariant-functors An applicative reservation validation example in C# https://blog.ploeh.dk/2022/07/25/an-applicative-reservation-validation-example-in-c/ Mon, 25 Jul 2022 06:56:00 UTC <div id="post"> <p> <em>How to return all relevant error messages in a composable way.</em> </p> <p> I've previously suggested that <a href="/2020/12/14/validation-a-solved-problem">I consider validation a solved problem</a>. I still do, until someone disproves me with a counterexample. Here's a fairly straightforward <a href="/2018/11/05/applicative-validation">applicative validation</a> example in C#. </p> <p> After corresponding and speaking with readers of <a href="/code-that-fits-in-your-head">Code That Fits in Your Head</a> I've learned that some readers have objections to the following lines of code: </p> <p> <pre>Reservation?&nbsp;<span style="color:#1f377f;">reservation</span>&nbsp;=&nbsp;dto.Validate(id); <span style="color:#8f08c4;">if</span>&nbsp;(reservation&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;BadRequestResult();</pre> </p> <p> This code snippet demonstrates how to <a href="https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/">parse, not validate</a>, an incoming Data Transfer Object (DTO). This code base uses C#'s <a href="https://docs.microsoft.com/dotnet/csharp/nullable-references">nullable reference types</a> feature to distinguish between null and non-null objects. Other languages (and earlier versions of C#) can instead use <a href="/2022/04/25/the-maybe-monad">the Maybe monad</a>. Nothing in this article or the book hinges on the <em>nullable reference types</em> feature. </p> <p> If the <code>Validate</code> method (which I really should have called <code>TryParse</code> instead) returns a null value, the Controller from which this code snippet is taken returns a <code>400 Bad Request</code> response. </p> <p> The <code>Validate</code> method is an instance method on the DTO class: </p> <p> <pre><span style="color:blue;">internal</span>&nbsp;Reservation?&nbsp;<span style="color:#74531f;">Validate</span>(Guid&nbsp;<span style="color:#1f377f;">id</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(!DateTime.TryParse(At,&nbsp;<span style="color:blue;">out</span>&nbsp;var&nbsp;<span style="color:#1f377f;">d</span>)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(Email&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(Quantity&nbsp;&lt;&nbsp;1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">null</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;Reservation( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;id, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;d, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;Email(Email), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;Name(Name&nbsp;??&nbsp;<span style="color:#a31515;">&quot;&quot;</span>), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity); }</pre> </p> <p> What irks some readers is the loss of information. While <code>Validate</code> 'knows' why it's rejecting a candidate, that information is lost and no error message is communicated to unfortunate HTTP clients. </p> <p> One email from a reader went on about this for quite some time and I got the impression that the sender considered this such a grave flaw that it invalidates the entire book. </p> <p> That's not the case. </p> <h3 id="26803ee560dd42be825ec266694d0211"> Rabbit hole, evaded <a href="#26803ee560dd42be825ec266694d0211" title="permalink">#</a> </h3> <p> When I wrote the code like above, I was fully aware of trade-offs and priorities. I understood that this particular design would mean that clients get no information about <em>why</em> a particular reservation JSON document is rejected - only that it is. </p> <p> This was a simplification that I explicitly decided to make for educational reasons. </p> <p> The above design is based on something as simple as a null check. I expect all my readers to be able to follow that code. As hinted above, you could also model a method like <code>Validate</code> with the Maybe monad, but while Maybe preserves success cases, it throws away all information about errors. In a production system, this is rarely acceptable, but I found it acceptable for the example code in the book, since this isn't the main topic. </p> <p> Instead of basing the design on nullable reference types or the Maybe monad, you can instead base parsing on applicative validation. In order to explain that, I'd first need to explain <a href="/2018/03/22/functors">functors</a>, <a href="/2018/10/01/applicative-functors">applicative functors</a>, and applicative validation. It might also prove helpful to the reader to explain <a href="/2018/05/22/church-encoding">Church encodings</a>, <a href="/2018/12/24/bifunctors">bifunctors</a>, and <a href="/2017/11/27/semigroups">semigroups</a>. That's quite a rabbit hole to fall into, and I felt that it would be such a big digression from the themes of the book that I decided not to go there. </p> <p> On this blog, however, I have all the space and time I'd like. I can digress as much as I'd like. Most of that digression has already happened. Those articles are already on the blog. I'm going to assume that you've read all of the articles I just linked, or that you understand these concepts. </p> <p> In this article, I'm going to rewrite the DTO parser to also return error messages. It's an entirely local change that breaks no existing tests. </p> <h3 id="5f6a7326fb484c1d8b4402b24e49d13b"> Validated <a href="#5f6a7326fb484c1d8b4402b24e49d13b" title="permalink">#</a> </h3> <p> Most functional programmers are already aware of the <a href="/2022/05/09/an-either-monad">Either monad</a>. They often reach for it when they need to expand the Maybe monad with <a href="https://fsharpforfunandprofit.com/posts/recipe-part2/">an error track</a>. </p> <p> The problem with the Either monad is, however, that it short-circuits error handling. It's like throwing exceptions. As soon as an Either composition hits the first error, it stops processing the rest of the data. As a caller, you only get one error message, even if there's more than one thing wrong with your input value. </p> <p> In a distributed system where a client posts a document to a service, you'd like to respond with a collection of errors. </p> <p> You can do this with a data type that's isomorphic with Either, but behaves differently as an applicative functor. Instead of short-circuiting on the first error, it collects them. This, however, turns out to be incompatible to the Either monad's short-circuiting behaviour, so this data structure is usually not given monadic features. </p> <p> This data type is usually called <code>Validation</code>, but when I translated that to C# various static code analysis rules lit up, claiming that there was already a referenced namespace called <code>Validation</code>. Instead, I decided to call the type <code><span style="color:#2b91af;">Validated</span>&lt;<span style="color:#2b91af;">F</span>,&nbsp;<span style="color:#2b91af;">S</span>&gt;</code>, which I like better anyway. </p> <p> The type arguments are <code>F</code> for <em>failure</em> and <code>S</code> for <em>success</em>. I've put <code>F</code> before <code>S</code> because by convention that's how Either works. </p> <p> I'm using an encapsulated variation of a Church encoding and a series of <code>Apply</code> overloads as described in the article <a href="/2018/10/15/an-applicative-password-list">An applicative password list</a>. There's quite a bit of boilerplate, so I'll just dump the entire contents of the file here instead of tiring you with a detailed walk-through: </p> <p> <pre><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Validated</span>&lt;<span style="color:#2b91af;">F</span>,&nbsp;<span style="color:#2b91af;">S</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">IValidation</span> &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;T&nbsp;<span style="color:#74531f;">Match</span>&lt;<span style="color:#2b91af;">T</span>&gt;(Func&lt;F,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">onFailure</span>,&nbsp;Func&lt;S,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">onSuccess</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;IValidation&nbsp;imp; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:#2b91af;">Validated</span>(IValidation&nbsp;<span style="color:#1f377f;">imp</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.imp&nbsp;=&nbsp;imp; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">internal</span>&nbsp;<span style="color:blue;">static</span>&nbsp;Validated&lt;F,&nbsp;S&gt;&nbsp;<span style="color:#74531f;">Succeed</span>(S&nbsp;<span style="color:#1f377f;">success</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;Validated&lt;F,&nbsp;S&gt;(<span style="color:blue;">new</span>&nbsp;Success(success)); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">internal</span>&nbsp;<span style="color:blue;">static</span>&nbsp;Validated&lt;F,&nbsp;S&gt;&nbsp;<span style="color:#74531f;">Fail</span>(F&nbsp;<span style="color:#1f377f;">failure</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;<span style="color:blue;">new</span>&nbsp;Validated&lt;F,&nbsp;S&gt;(<span style="color:blue;">new</span>&nbsp;Failure(failure)); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;T&nbsp;<span style="color:#74531f;">Match</span>&lt;<span style="color:#2b91af;">T</span>&gt;(Func&lt;F,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">onFailure</span>,&nbsp;Func&lt;S,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">onSuccess</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;imp.Match(onFailure,&nbsp;onSuccess); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Validated&lt;F1,&nbsp;S1&gt;&nbsp;<span style="color:#74531f;">SelectBoth</span>&lt;<span style="color:#2b91af;">F1</span>,&nbsp;<span style="color:#2b91af;">S1</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;F,&nbsp;F1&gt;&nbsp;<span style="color:#1f377f;">selectFailure</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;S,&nbsp;S1&gt;&nbsp;<span style="color:#1f377f;">selectSuccess</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">f</span>&nbsp;=&gt;&nbsp;Validated.Fail&lt;F1,&nbsp;S1&gt;(selectFailure(f)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">s</span>&nbsp;=&gt;&nbsp;Validated.Succeed&lt;F1,&nbsp;S1&gt;(selectSuccess(s))); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Validated&lt;F1,&nbsp;S&gt;&nbsp;<span style="color:#74531f;">SelectFailure</span>&lt;<span style="color:#2b91af;">F1</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;F,&nbsp;F1&gt;&nbsp;<span style="color:#1f377f;">selectFailure</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;SelectBoth(selectFailure,&nbsp;<span style="color:#1f377f;">s</span>&nbsp;=&gt;&nbsp;s); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Validated&lt;F,&nbsp;S1&gt;&nbsp;<span style="color:#74531f;">SelectSuccess</span>&lt;<span style="color:#2b91af;">S1</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;S,&nbsp;S1&gt;&nbsp;<span style="color:#1f377f;">selectSuccess</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;SelectBoth(<span style="color:#1f377f;">f</span>&nbsp;=&gt;&nbsp;f,&nbsp;selectSuccess); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;Validated&lt;F,&nbsp;S1&gt;&nbsp;<span style="color:#74531f;">Select</span>&lt;<span style="color:#2b91af;">S1</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;S,&nbsp;S1&gt;&nbsp;<span style="color:#1f377f;">selector</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;SelectSuccess(selector); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Success</span>&nbsp;:&nbsp;IValidation &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;S&nbsp;success; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Success</span>(S&nbsp;<span style="color:#1f377f;">success</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.success&nbsp;=&nbsp;success; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;T&nbsp;<span style="color:#74531f;">Match</span>&lt;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;F,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">onFailure</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;S,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">onSuccess</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;onSuccess(success); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Failure</span>&nbsp;:&nbsp;IValidation &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;F&nbsp;failure; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Failure</span>(F&nbsp;<span style="color:#1f377f;">failure</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.failure&nbsp;=&nbsp;failure; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;T&nbsp;<span style="color:#74531f;">Match</span>&lt;<span style="color:#2b91af;">T</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;F,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">onFailure</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;S,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">onSuccess</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;onFailure(failure); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} } <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">Validated</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;Validated&lt;F,&nbsp;S&gt;&nbsp;<span style="color:#74531f;">Succeed</span>&lt;<span style="color:#2b91af;">F</span>,&nbsp;<span style="color:#2b91af;">S</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;S&nbsp;<span style="color:#1f377f;">success</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;Validated&lt;F,&nbsp;S&gt;.Succeed(success); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;Validated&lt;F,&nbsp;S&gt;&nbsp;<span style="color:#74531f;">Fail</span>&lt;<span style="color:#2b91af;">F</span>,&nbsp;<span style="color:#2b91af;">S</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;F&nbsp;<span style="color:#1f377f;">failure</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;Validated&lt;F,&nbsp;S&gt;.Fail(failure); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;Validated&lt;F,&nbsp;S&gt;&nbsp;<span style="color:#74531f;">Apply</span>&lt;<span style="color:#2b91af;">F</span>,&nbsp;<span style="color:#2b91af;">T</span>,&nbsp;<span style="color:#2b91af;">S</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;Validated&lt;F,&nbsp;Func&lt;T,&nbsp;S&gt;&gt;&nbsp;<span style="color:#1f377f;">selector</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Validated&lt;F,&nbsp;T&gt;&nbsp;<span style="color:#1f377f;">source</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;F,&nbsp;F,&nbsp;F&gt;&nbsp;<span style="color:#1f377f;">combine</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(selector&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;ArgumentNullException(nameof(selector)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;selector.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">f1</span>&nbsp;=&gt;&nbsp;source.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">f2</span>&nbsp;=&gt;&nbsp;Fail&lt;F,&nbsp;S&gt;(combine(f1,&nbsp;f2)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">_</span>&nbsp;&nbsp;=&gt;&nbsp;Fail&lt;F,&nbsp;S&gt;(f1)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">map</span>&nbsp;=&gt;&nbsp;source.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">f2</span>&nbsp;=&gt;&nbsp;Fail&lt;F,&nbsp;S&gt;(f2), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">x</span>&nbsp;&nbsp;=&gt;&nbsp;Succeed&lt;F,&nbsp;S&gt;(map(x)))); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;Validated&lt;F,&nbsp;Func&lt;T2,&nbsp;S&gt;&gt;&nbsp;<span style="color:#74531f;">Apply</span>&lt;<span style="color:#2b91af;">F</span>,&nbsp;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">S</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;Validated&lt;F,&nbsp;Func&lt;T1,&nbsp;T2,&nbsp;S&gt;&gt;&nbsp;<span style="color:#1f377f;">selector</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Validated&lt;F,&nbsp;T1&gt;&nbsp;<span style="color:#1f377f;">source</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;F,&nbsp;F,&nbsp;F&gt;&nbsp;<span style="color:#1f377f;">combine</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(selector&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;ArgumentNullException(nameof(selector)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;selector.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">f1</span>&nbsp;=&gt;&nbsp;source.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">f2</span>&nbsp;=&gt;&nbsp;Fail&lt;F,&nbsp;Func&lt;T2,&nbsp;S&gt;&gt;(combine(f1,&nbsp;f2)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">_</span>&nbsp;&nbsp;=&gt;&nbsp;Fail&lt;F,&nbsp;Func&lt;T2,&nbsp;S&gt;&gt;(f1)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">map</span>&nbsp;=&gt;&nbsp;source.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">f2</span>&nbsp;=&gt;&nbsp;Fail&lt;F,&nbsp;Func&lt;T2,&nbsp;S&gt;&gt;(f2), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">x</span>&nbsp;&nbsp;=&gt;&nbsp;Succeed&lt;F,&nbsp;Func&lt;T2,&nbsp;S&gt;&gt;(<span style="color:#1f377f;">y</span>&nbsp;=&gt;&nbsp;map(x,&nbsp;y)))); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;Validated&lt;F,&nbsp;Func&lt;T2,&nbsp;T3,&nbsp;S&gt;&gt;&nbsp;<span style="color:#74531f;">Apply</span>&lt;<span style="color:#2b91af;">F</span>,&nbsp;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">T3</span>,&nbsp;<span style="color:#2b91af;">S</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;Validated&lt;F,&nbsp;Func&lt;T1,&nbsp;T2,&nbsp;T3,&nbsp;S&gt;&gt;&nbsp;<span style="color:#1f377f;">selector</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Validated&lt;F,&nbsp;T1&gt;&nbsp;<span style="color:#1f377f;">source</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;F,&nbsp;F,&nbsp;F&gt;&nbsp;<span style="color:#1f377f;">combine</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(selector&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;ArgumentNullException(nameof(selector)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;selector.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">f1</span>&nbsp;=&gt;&nbsp;source.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">f2</span>&nbsp;=&gt;&nbsp;Fail&lt;F,&nbsp;Func&lt;T2,&nbsp;T3,&nbsp;S&gt;&gt;(combine(f1,&nbsp;f2)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">_</span>&nbsp;&nbsp;=&gt;&nbsp;Fail&lt;F,&nbsp;Func&lt;T2,&nbsp;T3,&nbsp;S&gt;&gt;(f1)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">map</span>&nbsp;=&gt;&nbsp;source.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">f2</span>&nbsp;=&gt;&nbsp;Fail&lt;F,&nbsp;Func&lt;T2,&nbsp;T3,&nbsp;S&gt;&gt;(f2), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">x</span>&nbsp;&nbsp;=&gt;&nbsp;Succeed&lt;F,&nbsp;Func&lt;T2,&nbsp;T3,&nbsp;S&gt;&gt;((<span style="color:#1f377f;">y</span>,&nbsp;<span style="color:#1f377f;">z</span>)&nbsp;=&gt;&nbsp;map(x,&nbsp;y,&nbsp;z)))); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;Validated&lt;F,&nbsp;Func&lt;T2,&nbsp;T3,&nbsp;S&gt;&gt;&nbsp;<span style="color:#74531f;">Apply</span>&lt;<span style="color:#2b91af;">F</span>,&nbsp;<span style="color:#2b91af;">T1</span>,&nbsp;<span style="color:#2b91af;">T2</span>,&nbsp;<span style="color:#2b91af;">T3</span>,&nbsp;<span style="color:#2b91af;">S</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>&nbsp;Func&lt;T1,&nbsp;T2,&nbsp;T3,&nbsp;S&gt;&nbsp;<span style="color:#1f377f;">map</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Validated&lt;F,&nbsp;T1&gt;&nbsp;<span style="color:#1f377f;">source</span>, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Func&lt;F,&nbsp;F,&nbsp;F&gt;&nbsp;<span style="color:#1f377f;">combine</span>) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;Apply( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Succeed&lt;F,&nbsp;Func&lt;T1,&nbsp;T2,&nbsp;T3,&nbsp;S&gt;&gt;((<span style="color:#1f377f;">x</span>,&nbsp;<span style="color:#1f377f;">y</span>,&nbsp;<span style="color:#1f377f;">z</span>)&nbsp;=&gt;&nbsp;map(x,&nbsp;y,&nbsp;z)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;source, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;combine); &nbsp;&nbsp;&nbsp;&nbsp;} }</pre> </p> <p> I only added the <code>Apply</code> overloads that I needed for the following demo code. As stated above, I'm not going to launch into a detailed walk-through, since the code follows the concepts lined out in the various articles I've already mentioned. If there's something that you'd like me to explain then please <a href="https://github.com/ploeh/ploeh.github.com#comments">leave a comment</a>. </p> <p> Notice that <code><span style="color:#2b91af;">Validated</span>&lt;<span style="color:#2b91af;">F</span>,&nbsp;<span style="color:#2b91af;">S</span>&gt;</code> has no <code>SelectMany</code> method. It's deliberately not a <a href="/2022/03/28/monads">monad</a>, because monadic <em>bind</em> (<code>SelectMany</code>) would conflict with the applicative functor implementation. </p> <h3 id="533e728019834b22b323ffab10f4cae8"> Individual parsers <a href="#533e728019834b22b323ffab10f4cae8" title="permalink">#</a> </h3> <p> An essential quality of applicative validation is that it's composable. This means that you can compose a larger, more complex parser from smaller ones. Parsing a <code><span style="color:#2b91af;">ReservationDto</span></code> object, for example, involves parsing the date and time of the reservation, the email address, and the quantity. Here's how to parse the date and time: </p> <p> <pre><span style="color:blue;">private</span>&nbsp;Validated&lt;<span style="color:blue;">string</span>,&nbsp;DateTime&gt;&nbsp;<span style="color:#74531f;">TryParseAt</span>() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(!DateTime.TryParse(At,&nbsp;<span style="color:blue;">out</span>&nbsp;var&nbsp;<span style="color:#1f377f;">d</span>)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;Validated.Fail&lt;<span style="color:blue;">string</span>,&nbsp;DateTime&gt;(<span style="color:#a31515;">$&quot;Invalid&nbsp;date&nbsp;or&nbsp;time:&nbsp;</span>{At}<span style="color:#a31515;">.&quot;</span>); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;Validated.Succeed&lt;<span style="color:blue;">string</span>,&nbsp;DateTime&gt;(d); }</pre> </p> <p> In order to keep things simple I'm going to use strings for error messages. You could instead decide to encode error conditions as a <a href="https://en.wikipedia.org/wiki/Tagged_union">sum type</a> or other polymorphic type. This would be appropriate if you also need to be able to make programmatic decisions based on individual error conditions, or if you need to translate the error messages to more than one language. </p> <p> The <code><span style="color:#74531f;">TryParseAt</span></code> function only attempts to parse the <code>At</code> property to a <code>DateTime</code> value. If parsing fails, it returns a <code><span style="color:#2b91af;">Failure</span></code> value with a helpful error message; otherwise, it wraps the parsed date and time in a <code><span style="color:#2b91af;">Success</span></code> value. </p> <p> Parsing the email address is similar: </p> <p> <pre><span style="color:blue;">private</span>&nbsp;Validated&lt;<span style="color:blue;">string</span>,&nbsp;Email&gt;&nbsp;<span style="color:#74531f;">TryParseEmail</span>() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(Email&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;Validated.Fail&lt;<span style="color:blue;">string</span>,&nbsp;Email&gt;(<span style="color:#a31515;">$&quot;Email&nbsp;address&nbsp;is&nbsp;missing.&quot;</span>); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;Validated.Succeed&lt;<span style="color:blue;">string</span>,&nbsp;Email&gt;(<span style="color:blue;">new</span>&nbsp;Email(Email)); }</pre> </p> <p> As is parsing the quantity: </p> <p> <pre><span style="color:blue;">private</span>&nbsp;Validated&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;&nbsp;<span style="color:#74531f;">TryParseQuantity</span>() { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(Quantity&nbsp;&lt;&nbsp;1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;Validated.Fail&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#a31515;">$&quot;Quantity&nbsp;must&nbsp;be&nbsp;a&nbsp;positive&nbsp;integer,&nbsp;but&nbsp;was:&nbsp;</span>{Quantity}<span style="color:#a31515;">.&quot;</span>); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;Validated.Succeed&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">int</span>&gt;(Quantity); }</pre> </p> <p> There's no reason to create a parser for the reservation name, because if the name doesn't exist, instead use the empty string. That operation can't fail. </p> <h3 id="48f0650702f1490392838bf3c5c88cd1"> Composition <a href="#48f0650702f1490392838bf3c5c88cd1" title="permalink">#</a> </h3> <p> You can now use applicative composition to reuse those individual parsers in a more complex parser: </p> <p> <pre><span style="color:blue;">internal</span>&nbsp;Validated&lt;<span style="color:blue;">string</span>,&nbsp;Reservation&gt;&nbsp;<span style="color:#74531f;">TryParse</span>(Guid&nbsp;<span style="color:#1f377f;">id</span>) { &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;DateTime,&nbsp;Email,&nbsp;<span style="color:blue;">int</span>,&nbsp;Reservation&gt;&nbsp;<span style="color:#1f377f;">createReservation</span>&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(<span style="color:#1f377f;">at</span>,&nbsp;<span style="color:#1f377f;">email</span>,&nbsp;<span style="color:#1f377f;">quantity</span>)&nbsp;=&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">new</span>&nbsp;Reservation(id,&nbsp;at,&nbsp;email,&nbsp;<span style="color:blue;">new</span>&nbsp;Name(Name&nbsp;??&nbsp;<span style="color:#a31515;">&quot;&quot;</span>),&nbsp;quantity); &nbsp;&nbsp;&nbsp;&nbsp;Func&lt;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>,&nbsp;<span style="color:blue;">string</span>&gt;&nbsp;<span style="color:#1f377f;">combine</span>&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(<span style="color:#1f377f;">x</span>,&nbsp;<span style="color:#1f377f;">y</span>)&nbsp;=&gt;&nbsp;<span style="color:blue;">string</span>.Join(Environment.NewLine,&nbsp;x,&nbsp;y); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;createReservation &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Apply(TryParseAt(),&nbsp;combine) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Apply(TryParseEmail(),&nbsp;combine) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Apply(TryParseQuantity(),&nbsp;combine); }</pre> </p> <p> <code><span style="color:#1f377f;">createReservation</span></code> is a local function that closes over <code>id</code> and <code>Name</code>. Specifically, it uses the null coalescing operator (<code>??</code>) to turn a null name into the empty string. On the other hand, it takes <code>at</code>, <code>email</code>, and <code>quantity</code> as inputs, since these are the values that must first be parsed. </p> <p> A type like <code><span style="color:#2b91af;">Validated</span>&lt;<span style="color:#2b91af;">F</span>,&nbsp;<span style="color:#2b91af;">S</span>&gt;</code> is only an applicative functor when the failure dimension (<code>F</code>) gives rise to a semigroup. The way I've modelled it here is as a binary operation that you need to pass as a parameter to each <code>Apply</code> overload. This seems awkward, but is good enough for a proof of concept. </p> <p> The <code><span style="color:#1f377f;">combine</span></code> function joins two strings together, separated by a line break. </p> <p> The <code><span style="color:#74531f;">TryParse</span></code> function composes <code><span style="color:#1f377f;">createReservation</span></code> with <code>TryParseAt</code>, <code>TryParseEmail</code>, and <code>TryParseQuantity</code> using the various <code>Apply</code> overloads. The combination is a <code>Validated</code> value that's either a failure string or a properly encapsulated <code>Reservation</code> object. </p> <h3 id="04091776345e4f4b8ba4d446d8d80376"> Using the parser <a href="#04091776345e4f4b8ba4d446d8d80376" title="permalink">#</a> </h3> <p> Client code can now invoke the <code>TryParse</code> function on the DTO. Here is the code inside the <code><span style="color:#74531f;">Post</span></code> method on the <code><span style="color:#2b91af;">ReservationsController</span></code> class: </p> <p> <pre>[HttpPost(<span style="color:#a31515;">&quot;restaurants/{restaurantId}/reservations&quot;</span>)] <span style="color:blue;">public</span>&nbsp;Task&lt;ActionResult&gt;&nbsp;<span style="color:#74531f;">Post</span>(<span style="color:blue;">int</span>&nbsp;<span style="color:#1f377f;">restaurantId</span>,&nbsp;ReservationDto&nbsp;<span style="color:#1f377f;">dto</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">if</span>&nbsp;(dto&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:blue;">null</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;ArgumentNullException(nameof(dto)); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;<span style="color:#1f377f;">id</span>&nbsp;=&nbsp;dto.ParseId()&nbsp;??&nbsp;Guid.NewGuid(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;<span style="color:#1f377f;">parseResult</span>&nbsp;=&nbsp;dto.TryParse(id); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#8f08c4;">return</span>&nbsp;parseResult.Match( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">msgs</span>&nbsp;=&gt;&nbsp;Task.FromResult&lt;ActionResult&gt;(<span style="color:blue;">new</span>&nbsp;BadRequestObjectResult(msgs)), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">reservation</span>&nbsp;=&gt;&nbsp;TryCreate(restaurantId,&nbsp;reservation)); }</pre> </p> <p> When the <code>parseResult</code> matches a failure, it returns a <code><span style="color:blue;">new</span>&nbsp;BadRequestObjectResult</code> with all collected error messages. When, on the other hand, it matches a success, it invokes the <code><span style="color:#74531f;">TryCreate</span></code> helper method with the parsed <code>reservation</code>. </p> <h3 id="d260c38d1dd444e291868e377732fd24"> HTTP request and response <a href="#d260c38d1dd444e291868e377732fd24" title="permalink">#</a> </h3> <p> A client will now receive all relevant error messages if it posts a malformed reservation: </p> <p> <pre>POST /restaurants/1/reservations?sig=1WiLlS5705bfsffPzaFYLwntrS4FCjE5CLdaeYTHxxg%3D HTTP/1.1 Content-Type: application/json {&nbsp;<span style="color:#2e75b6;">&quot;at&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;large&quot;</span>,&nbsp;<span style="color:#2e75b6;">&quot;name&quot;</span>:&nbsp;<span style="color:#a31515;">&quot;Kerry&nbsp;Onn&quot;</span>,&nbsp;<span style="color:#2e75b6;">&quot;quantity&quot;</span>:&nbsp;-1&nbsp;} HTTP/1.1 400 Bad Request Invalid date or time: large. Email address is missing. Quantity must be a positive integer, but was: -1.</pre> </p> <p> Of course, if only a single element is wrong, only that error message will appear. </p> <h3 id="fada4ef8e64648b5a2d90e47082acfde"> Conclusion <a href="#fada4ef8e64648b5a2d90e47082acfde" title="permalink">#</a> </h3> <p> The changes described in this article were entirely local to the two involved types: <code><span style="color:#2b91af;">ReservationsController</span></code> and <code><span style="color:#2b91af;">ReservationDto</span></code>. Once I'd expanded <code><span style="color:#2b91af;">ReservationDto</span></code> with the <code><span style="color:#74531f;">TryParse</span></code> function and its helper functions, and changed <code><span style="color:#2b91af;">ReservationsController</span></code> accordingly, the rest of the code base compiled and all tests passed. The point is that this isn't a big change, and that's why I believe that the original design (returning null or non-null) doesn't invalidate anything else I had to say in the book. </p> <p> The change did, however, take quite a bit of boilerplate code, as witnessed by the <code>Validated</code> code dump. That API is, on the other hand, completely reusable, and you can find packages on the internet that already implement this functionality. It's not much of a burden in terms of extra code, but it would have taken a couple of extra chapters to explain in the book. It could easily have been double the size if I had to include material about functors, applicative functors, semigroups, Church encoding, etcetera. </p> <p> To fix two lines of code, I didn't think that was warranted. After all, it's not a major blocker. On the contrary, validation is a solved problem. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="22b961d6ecb84e6f8af7232b09a445fc"> <div class="comment-author">Dan Carter</div> <div class="comment-content"> <blockquote>you can find packages on the internet that already implement this functionality</blockquote> <p> Do you have any recommendations for a library that implements the <code>Validated<F, S></code> type? </p> </div> <div class="comment-date">2022-08-15 11:15 UTC</div> </div> <div class="comment" id="03273eecd6e749188106e8caef68d82e"> <div class="comment-author"><a href="/">Mark Seemann</a></div> <div class="comment-content"> <p> Dan, thank you for writing. The following is not a recommendation, but the most comprehensive C# library for functional programming currently seems to be <a href="https://github.com/louthy/language-ext">LanguageExt</a>, which includes a <a href="https://louthy.github.io/language-ext/LanguageExt.Core/Monads/Alternative%20Value%20Monads/Validation/index.html">Validation</a> functor. </p> <p> I'm neither recommending nor arguing against LanguageExt. </p> <ul> <li>I've never used it in a real-world code base.</li> <li>I've been answering questions about it on <a href="https://stackoverflow.com">Stack Overflow</a>. In general, it seems to stump C# developers, since it's very Haskellish and quite advanced.</li> <li>Today is just a point in time. Libraries come and go.</li> </ul> <p> Since all the ideas presented in these articles are universal abstractions, you can safely and easily implement them yourself, instead of taking a dependency on a third-party library. If you stick with lawful implementations, the only variation possible is with naming. Do you call a functor like this one <code>Validation</code>, <code>Validated</code>, or something else? Do you call monadic <em>bind</em> <code>SelectMany</code> or <code>Bind</code>? Will you have a <code>Flatten</code> or a <code>Join</code> function? </p> <p> When working with teams that are new to these things, I usually start by adding these concepts as source code as they become useful. If a type like <code>Maybe</code> or <code>Validated</code> starts to proliferate, sooner or later you'll need to move it to a shared library so that multiple in-house libraries can use the type to communicate results across library boundaries. Eventually, you may decide to move such a dependency to a NuGet package. You can, at such time, decide to use an existing library instead of your own. </p> <p> The maintenance burden for these kinds of libraries is low, since the APIs and behaviour are defined and locked in advance by mathematics. </p> </div> <div class="comment-date">2022-08-16 5:54 UTC</div> </div> <div class="comment" id="fa7fc6662aee4889bcc9f84bc5db1b39"> <div class="comment-author"><a href="https://about.me/tysonwilliams">Tyson Williams</a></div> <div class="comment-content"> <blockquote> If you stick with lawful implementations, the only variation possible is with naming. </blockquote> <p> There are also language-specific choices that can vary. </p> <p> One example involves applicative functors in C#. The "standard" API for applicative functors works well in <a href="https://blog.ploeh.dk/2018/10/01/applicative-functors/#6173a96aedaa4e97ad868c159e6d06fa">Haskell</a> and <a href="https://blog.ploeh.dk/2018/10/01/applicative-functors/#6f9b2f13951e475d8c4fc9682ad96a94">F#</a> because it is designed to be used with curried functions, and both of those languages curry their functions by default. In contrast, <a href="https://blog.ploeh.dk/2018/10/01/applicative-functors/#cef395ee19644f30bfd1ad7a84b6f912:~:text=Applicative%20functors%20push%20the%20limits%20of%20what%20you%20can%20express%20in%20C%23">applicative functors push the limits of what you can express in C#</a>. I am impressed with <a href="https://github.com/louthy/language-ext/blob/ba16d97d4909067222c8b134a80bfd6b7e54c424/LanguageExt.Tests/ValidationTests.cs#L277">the design that Language Ext uses for applicative functors</a>, which is an extension method on a (value) tuple of applicative functor instances that accepts a lambda expression that is given all the "unwrapped" values "inside" the applicative functors. </p> <p> Another example involves monads in TypeScript. To avoid the <a href="https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming)">Pyramid of doom</a> when performing a sequence of monadic operations, Haskell has <a href="https://en.wikibooks.org/wiki/Haskell/do_notation">do notation</a> and F# has <a href="https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/computation-expressions">computation expressions</a>. There is no equivalent language feature in TypeScript, but it has <a href="https://en.wikipedia.org/wiki/Row_polymorphism">row polymorphism</a>, which <a href="https://gcanti.github.io/fp-ts/guides/do-notation.html">pf-ts uses to effectively implement do notation</a>. </p> <p> A related dimension is how to approximate high-kinded types in a language that lacks them. Language Ext passes in the monad as a type parameter as well as the "lower-kinded" type parameter and then constrains the monad type parameter to implement a monad interface parametereized by the lower type parameter as well as being a struct. I find that second constraint very intersting. Since the type parameter has a struct constraint, it has a default constructor that can be used to get an instance, which then implements methods according to the interface constraint. For more infomration, see <a href="https://github.com/louthy/language-ext/wiki/Does-C%23-Dream-Of-Electric-Monads%3F">this wiki article</a> for a gentle introduction and <a href="https://github.com/louthy/language-ext/blob/ba16d97d4909067222c8b134a80bfd6b7e54c424/LanguageExt.Core/Class%20Instances/Trans/Trans.cs#L74-L80">Trans.cs</a> for how Language Ext uses this approach to only implement traverse once. Similarly, F#+ has a feature called <a href="https://fsprojects.github.io/FSharpPlus/generic-doc.html">generic functions</a> that enable one to write F# like <code>map aFoo</code> instead of the typical <code>Foo.map aFoo</code>. </p> </div> <div class="comment-date">2022-09-20 02:00 UTC</div> </div> <div class="comment" id="5619079f7c994fc0bd0dbbdbfeec9e4a"> <div class="comment-author"><a href="/">Mark Seemann</a></div> <div class="comment-content"> <p> Tyson, thank you for writing. I agree that details differ. Clearly, this is true across languages, where, say, <a href="https://www.haskell.org/">Haskell</a>'s <code>fmap</code> has a name different from C#'s <code>SelectMany</code>. To state the obvious, the syntax is also different. </p> <p> Even within the same language, you can have variations. Functor mapping in Haskell is generally called <code>fmap</code>, but you can also use <code>map</code> explicitly for lists. The same could be true in C#. I've seen functor and monad implementations in C# that use method names like <code>Map</code> and <code>Bind</code> rather than <code>Select</code> and <code>SelectMany</code>. </p> <p> To expand on this idea, one may also observe that what one language calls <em>Option</em>, another language calls <em>Maybe</em>. The same goes for <code>Result</code> versus <code>Either</code>. </p> <p> As you know, the names <code>Select</code> and <code>SelectMany</code> are special because they enable C# query syntax. While methods named <code>Map</code> and <code>Bind</code> are 'the same' functions, they don't light up that language feature. Another way to enable syntactic sugar for monads in C# is via <code>async</code> and <code>await</code>, as <a href="https://eiriktsarpalis.wordpress.com/2020/07/20/effect-programming-in-csharp/">shown by Eirik Tsarpalis and Nick Palladinos</a>. </p> <p> I do agree with you that there are various options available to an implementer. The point I was trying to make is that while implementation details differ, the concepts are the same. Thus, as a <em>user</em> of one of these APIs (monads, monoids, etc.) you only have to learn the mental model once. You still have to learn the implementation details. </p> <p> I recently heard a professor at <a href="https://en.wikipedia.org/wiki/UCPH_Department_of_Computer_Science">DIKU</a> state that once you know one programming language, you should be able to learn another one in a week. That's the same general idea. </p> <p> (I do, however, have issues with that statement about programming languages as a universal assertion, but I agree that it tends to hold for mainstream languages. When I read <a href="/ref/mazes-for-programmers">Mazes for Programmers</a> I'd never programmed in <a href="https://www.ruby-lang.org/en/">Ruby</a> before, but I had little trouble picking it up for the exercises. On the other hand, most people don't learn Haskell in a week.) </p> </div> <div class="comment-date">2022-09-20 17:42 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2022/07/25/an-applicative-reservation-validation-example-in-c