<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Passing Curiosity: Posts tagged patterns</title>
    <link href="https://passingcuriosity.com/tags/patterns/patterns.xml" rel="self" />
    <link href="https://passingcuriosity.com" />
    <id>https://passingcuriosity.com/tags/patterns/patterns.xml</id>
    <author>
        <name>Thomas Sutton</name>
        
        <email>me@thomas-sutton.id.au</email>
        
    </author>
    <updated>2015-02-12T00:00:00Z</updated>
    <entry>
    <title>Multiple JSON encodings in Haskell</title>
    <link href="https://passingcuriosity.com/2015/multiple-json-representations-haskell/" />
    <id>https://passingcuriosity.com/2015/multiple-json-representations-haskell/</id>
    <published>2015-02-12T00:00:00Z</published>
    <updated>2015-02-12T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’m currently working on a small RESTful API to control a system with
a command-line interface. The command produces JSON output but it’s not really
ideal to expose in an API. This post describes the approach I took to
supporting two different JSON encodings for the same set of data types – one
for communicating with API clients and another for communicating with the
upstream system.</p>
<p>I’ll start with some data types to represent the data my API manages. In this
post I’ll use the example of a painting robot. The robot can carry several
colours of paint but can only paint with one “active” colour at a time. Here
are some data types to represent these details:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">ColourName</span> <span class="ot">=</span> <span class="dt">ColourName</span> {<span class="ot"> unColourName ::</span> <span class="dt">Text</span> }</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Show</span>)</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Colour</span> <span class="ot">=</span> <span class="dt">Colour</span></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a>    {<span class="ot"> colorName ::</span> <span class="dt">ColourName</span></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>    ,<span class="ot"> colourRGB ::</span> (<span class="dt">Word8</span>, <span class="dt">Word8</span>, <span class="dt">Word8</span>)</span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a>    }</span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Show</span>)</span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a><span class="kw">newtype</span> <span class="dt">RobotName</span> <span class="ot">=</span> <span class="dt">RobotName</span> {<span class="ot"> unRobotName ::</span> <span class="dt">Text</span> }</span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a>  <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Show</span>)</span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Robot</span> <span class="ot">=</span> <span class="dt">Robot</span></span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a>    {<span class="ot"> robotName ::</span> <span class="dt">RobotName</span></span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a>    ,<span class="ot"> robotActiveColour ::</span> <span class="dt">ColourName</span></span>
<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a>    ,<span class="ot"> robotAvailableColours ::</span> [<span class="dt">Colour</span>]</span>
<span id="cb1-17"><a href="#cb1-17" aria-hidden="true" tabindex="-1"></a>    }</span></code></pre></div>
<h2 id="json-for-the-api-clients">JSON for the API clients</h2>
<p>The JSON encoding of <code>Robot</code> that I’d like to provide to API clients is pretty
straightforward:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode json"><code class="sourceCode json"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="fu">{</span> <span class="dt">&quot;name&quot;</span> <span class="fu">:</span> <span class="st">&quot;Rosie the robot&quot;</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="fu">,</span> <span class="dt">&quot;activeColour&quot;</span> <span class="fu">:</span> <span class="st">&quot;red&quot;</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a><span class="fu">,</span> <span class="dt">&quot;availableColours&quot;</span> <span class="fu">:</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>    <span class="fu">{</span> <span class="dt">&quot;red&quot;</span>   <span class="fu">:</span> <span class="fu">{</span> <span class="dt">&quot;R&quot;</span><span class="fu">:</span> <span class="dv">255</span><span class="fu">,</span> <span class="dt">&quot;G&quot;</span><span class="fu">:</span>   <span class="dv">0</span><span class="fu">,</span> <span class="dt">&quot;B&quot;</span><span class="fu">:</span>   <span class="dv">0</span><span class="fu">}</span></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>    <span class="fu">,</span> <span class="dt">&quot;green&quot;</span> <span class="fu">:</span> <span class="fu">{</span> <span class="dt">&quot;R&quot;</span><span class="fu">:</span>   <span class="dv">0</span><span class="fu">,</span> <span class="dt">&quot;G&quot;</span><span class="fu">:</span> <span class="dv">255</span><span class="fu">,</span> <span class="dt">&quot;B&quot;</span><span class="fu">:</span>   <span class="dv">0</span><span class="fu">}</span></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>    <span class="fu">,</span> <span class="dt">&quot;blue&quot;</span>  <span class="fu">:</span> <span class="fu">{</span> <span class="dt">&quot;R&quot;</span><span class="fu">:</span>   <span class="dv">0</span><span class="fu">,</span> <span class="dt">&quot;G&quot;</span><span class="fu">:</span>   <span class="dv">0</span><span class="fu">,</span> <span class="dt">&quot;B&quot;</span><span class="fu">:</span> <span class="dv">255</span><span class="fu">}</span></span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a>    <span class="fu">}</span></span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a><span class="fu">}</span></span></code></pre></div>
<p>The Haskell code to parse this JSON using <a href="https://hackage.haskell.org/package/aeson">aeson</a> is straightforward too
(though please note that the instances derived for the <code>newtype</code> are only safe
to use <em>within</em> a larger JSON structure as they result in bare JSON strings,
not objects or arrays):</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="kw">deriving</span> <span class="kw">instance</span> <span class="dt">FromJSON</span> <span class="dt">ColourName</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="kw">deriving</span> <span class="kw">instance</span> <span class="dt">ToJSON</span> <span class="dt">ColourName</span></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">FromJSON</span> [<span class="dt">Colour</span>] <span class="kw">where</span></span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a>    parseJSON (<span class="dt">Object</span> v) <span class="ot">=</span> <span class="fu">mapM</span> (<span class="fu">uncurry</span> colour) <span class="op">$</span> HashMap.toList v</span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a>      <span class="kw">where</span></span>
<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a>        colour name (<span class="dt">Object</span> o) <span class="ot">=</span> <span class="dt">Colour</span></span>
<span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a>                <span class="op">&lt;$&gt;</span> parseJSON (<span class="dt">String</span> name)</span>
<span id="cb3-9"><a href="#cb3-9" aria-hidden="true" tabindex="-1"></a>                <span class="op">&lt;*&gt;</span> ((,,) <span class="op">&lt;$&gt;</span> o <span class="op">.:</span> <span class="st">&quot;R&quot;</span> <span class="op">&lt;*&gt;</span> o <span class="op">.:</span> <span class="st">&quot;G&quot;</span> <span class="op">&lt;*&gt;</span> o <span class="op">.:</span> <span class="st">&quot;B&quot;</span>)</span>
<span id="cb3-10"><a href="#cb3-10" aria-hidden="true" tabindex="-1"></a>        colour _ _ <span class="ot">=</span> <span class="fu">fail</span> <span class="st">&quot;Colour must be a JSON object&quot;</span></span>
<span id="cb3-11"><a href="#cb3-11" aria-hidden="true" tabindex="-1"></a>    parseJSON _ <span class="ot">=</span> <span class="fu">fail</span> <span class="st">&quot;Colours must be a JSON object&quot;</span></span>
<span id="cb3-12"><a href="#cb3-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-13"><a href="#cb3-13" aria-hidden="true" tabindex="-1"></a><span class="kw">deriving</span> <span class="kw">instance</span> <span class="dt">FromJSON</span> <span class="dt">RobotName</span></span>
<span id="cb3-14"><a href="#cb3-14" aria-hidden="true" tabindex="-1"></a><span class="kw">deriving</span> <span class="kw">instance</span> <span class="dt">ToJSON</span> <span class="dt">RobotName</span></span>
<span id="cb3-15"><a href="#cb3-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-16"><a href="#cb3-16" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">FromJSON</span> <span class="dt">Robot</span> <span class="kw">where</span></span>
<span id="cb3-17"><a href="#cb3-17" aria-hidden="true" tabindex="-1"></a>    parseJSON (<span class="dt">Object</span> v) <span class="ot">=</span> <span class="dt">Robot</span></span>
<span id="cb3-18"><a href="#cb3-18" aria-hidden="true" tabindex="-1"></a>        <span class="op">&lt;$&gt;</span> v <span class="op">.:</span> <span class="st">&quot;name&quot;</span></span>
<span id="cb3-19"><a href="#cb3-19" aria-hidden="true" tabindex="-1"></a>        <span class="op">&lt;*&gt;</span> v <span class="op">.:</span> <span class="st">&quot;activeColour&quot;</span></span>
<span id="cb3-20"><a href="#cb3-20" aria-hidden="true" tabindex="-1"></a>        <span class="op">&lt;*&gt;</span> v <span class="op">.:</span> <span class="st">&quot;availableColours&quot;</span></span>
<span id="cb3-21"><a href="#cb3-21" aria-hidden="true" tabindex="-1"></a>    parseJSON _ <span class="ot">=</span> <span class="fu">fail</span> <span class="st">&quot;Robot must be a JSON object&quot;</span></span></code></pre></div>
<p>To talk to the upstream system I’ll use the <a href="https://hackage.haskell.org/package/process">process</a> library to execute
a command which produces JSON on its standard output. A simple function to
invoke a command, parse the JSON, and return the value (or an error) keeps the
boilerplate contained:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>shellOutJSON</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> (<span class="dt">MonadError</span> <span class="dt">String</span> m, <span class="dt">MonadIO</span> m, <span class="dt">FromJSON</span> a)</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=&gt;</span> <span class="dt">String</span></span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> [<span class="dt">String</span>]</span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> m a</span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a>shellOutJSON cmd args <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- Execute the command.</span></span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a>    (exit_code, out, _err) <span class="ot">&lt;-</span> liftIO <span class="op">$</span> readProcessWithExitCode cmd args <span class="st">&quot;&quot;</span></span>
<span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-10"><a href="#cb4-10" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- Check it succeeded.</span></span>
<span id="cb4-11"><a href="#cb4-11" aria-hidden="true" tabindex="-1"></a>    output <span class="ot">&lt;-</span> <span class="kw">case</span> exit_code <span class="kw">of</span></span>
<span id="cb4-12"><a href="#cb4-12" aria-hidden="true" tabindex="-1"></a>        <span class="dt">ExitSuccess</span> <span class="ot">-&gt;</span> <span class="fu">return</span> <span class="op">$</span> BS.pack out</span>
<span id="cb4-13"><a href="#cb4-13" aria-hidden="true" tabindex="-1"></a>        <span class="dt">ExitFailure</span> err <span class="ot">-&gt;</span> throwError <span class="op">$</span></span>
<span id="cb4-14"><a href="#cb4-14" aria-hidden="true" tabindex="-1"></a>            <span class="st">&quot;Could not execute command: error &quot;</span> <span class="op">&lt;&gt;</span> <span class="fu">show</span> err</span>
<span id="cb4-15"><a href="#cb4-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-16"><a href="#cb4-16" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- Decode the JSON.</span></span>
<span id="cb4-17"><a href="#cb4-17" aria-hidden="true" tabindex="-1"></a>    <span class="kw">case</span> eitherDecode output <span class="kw">of</span></span>
<span id="cb4-18"><a href="#cb4-18" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Left</span> e <span class="ot">-&gt;</span> throwError <span class="op">$</span> <span class="st">&quot;Error decoding JSON: &quot;</span> <span class="op">&lt;&gt;</span> e</span>
<span id="cb4-19"><a href="#cb4-19" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Right</span> v <span class="ot">-&gt;</span> <span class="fu">return</span> v</span></code></pre></div>
<p>It’s important to note that the <em>call site</em> is responsible for fixing the type
<code>a</code> of value to be parsed from the JSON. This means that <code>shellOutJSON</code> will
happily attempt to parse the JSON into <em>any</em> type you ask it to (so long as it
has a <code>FromJSON</code> instance), whether or not you should expect the command to
produce such JSON. The obvious potential problem – a caller asking for data in
the wrong format – occurred twice in a dozen lines of code in my current
project.</p>
<h2 id="json-for-the-upstream-system">JSON for the upstream system</h2>
<p>The second JSON encoding is the one used to communicate with the command-line
application. The main difference from the API encoding is that it represents
the active colour by adding a <code>status</code> property to each colours; exactly one of
them is <code>active</code> and the rest are <code>available</code>. Rosie the robot is looks like
this:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode json"><code class="sourceCode json"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="fu">{</span> <span class="dt">&quot;name&quot;</span> <span class="fu">:</span> <span class="st">&quot;Rosie the robot&quot;</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="fu">,</span> <span class="dt">&quot;colours&quot;</span> <span class="fu">:</span></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>    <span class="fu">{</span> <span class="dt">&quot;red&quot;</span>   <span class="fu">:</span> <span class="fu">{</span> <span class="dt">&quot;R&quot;</span><span class="fu">:</span> <span class="dv">255</span><span class="fu">,</span> <span class="dt">&quot;G&quot;</span><span class="fu">:</span>   <span class="dv">0</span><span class="fu">,</span> <span class="dt">&quot;B&quot;</span><span class="fu">:</span>   <span class="dv">0</span><span class="fu">,</span> <span class="dt">&quot;status&quot;</span><span class="fu">:</span> <span class="st">&quot;active&quot;</span><span class="fu">}</span></span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a>    <span class="fu">,</span> <span class="dt">&quot;green&quot;</span> <span class="fu">:</span> <span class="fu">{</span> <span class="dt">&quot;R&quot;</span><span class="fu">:</span>   <span class="dv">0</span><span class="fu">,</span> <span class="dt">&quot;G&quot;</span><span class="fu">:</span> <span class="dv">255</span><span class="fu">,</span> <span class="dt">&quot;B&quot;</span><span class="fu">:</span>   <span class="dv">0</span><span class="fu">,</span> <span class="dt">&quot;status&quot;</span><span class="fu">:</span> <span class="st">&quot;available&quot;</span><span class="fu">}</span></span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>    <span class="fu">,</span> <span class="dt">&quot;blue&quot;</span>  <span class="fu">:</span> <span class="fu">{</span> <span class="dt">&quot;R&quot;</span><span class="fu">:</span>   <span class="dv">0</span><span class="fu">,</span> <span class="dt">&quot;G&quot;</span><span class="fu">:</span>   <span class="dv">0</span><span class="fu">,</span> <span class="dt">&quot;B&quot;</span><span class="fu">:</span> <span class="dv">255</span><span class="fu">,</span> <span class="dt">&quot;status&quot;</span><span class="fu">:</span> <span class="st">&quot;available&quot;</span><span class="fu">}</span></span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>    <span class="fu">}</span></span>
<span id="cb5-7"><a href="#cb5-7" aria-hidden="true" tabindex="-1"></a><span class="fu">}</span></span></code></pre></div>
<p>This is structure is great if you are using the data to output a nice table for
a human to read but not so great in an API.</p>
<p>This additional format could be implemented with new data types to represent
robots and colours and a few conversion functions (probably using the excellent
<a href="https://hackage.haskell.org/package/lens">lens</a> package) to represent the weirdly formatted versions of our types. Or
I could keep the same data types but create a <code>newtype</code> wrapper around each of
them with new <code>FromJSON</code> instances implementing the new format.</p>
<p>Instead I’ll add a “wrapper” type with which to distinguish a normal <code>Robot</code>
from one which should be formatted for the upstream system.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Upstream</span> a <span class="ot">=</span> <span class="dt">Upstream</span> {<span class="ot"> unwrapUpstream ::</span> a }</span></code></pre></div>
<p>This new type doesn’t “do” anything, it just tags the value it wraps and lets
me distinguish a <code>Robot</code> from an <code>Upstream Robot</code> which should be formatted for
the API and the upstream system respectively. (This is not strictly true: it
does take up memory and does cost an additional pointer dereference to
traverse). With the new <code>Upstream</code> type I can write a second <code>FromJSON</code>
instance each of my types.</p>
<p>If there is no special upstream format for a type the new instance can just
call the existing instance and stuff the result in an <code>Upstream</code> wrapper:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">FromJSON</span> (<span class="dt">Upstream</span> [<span class="dt">Colour</span>]) <span class="kw">where</span></span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>    parseJSON j <span class="ot">=</span> <span class="dt">Upstream</span> <span class="op">&lt;$&gt;</span> parseJSON j</span></code></pre></div>
<p>When the upstream encoding and the API encoding do differ, I write a <code>FromJSON</code>
instance in exactly the same way I normally would (making sure to use the
<code>Upstream</code> version of any other <code>FromJSON</code> instances I use):</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="kw">instance</span> <span class="dt">FromJSON</span> (<span class="dt">Upstream</span> <span class="dt">Robot</span>) <span class="kw">where</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>    parseJSON (<span class="dt">Object</span> v) <span class="ot">=</span> <span class="dt">Upstream</span> <span class="op">&lt;$&gt;</span></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>        (<span class="dt">Robot</span></span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a>            <span class="op">&lt;$&gt;</span>  v <span class="op">.:</span> <span class="st">&quot;name&quot;</span></span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a>            <span class="op">&lt;*&gt;</span> (v <span class="op">.:</span> <span class="st">&quot;colours&quot;</span> <span class="op">&gt;&gt;=</span> activeColours <span class="op">&gt;&gt;=</span> exactlyOne)</span>
<span id="cb8-6"><a href="#cb8-6" aria-hidden="true" tabindex="-1"></a>            <span class="op">&lt;*&gt;</span> (unwrapUpstream <span class="op">&lt;$&gt;</span> v <span class="op">.:</span> <span class="st">&quot;colours&quot;</span>))</span>
<span id="cb8-7"><a href="#cb8-7" aria-hidden="true" tabindex="-1"></a>      <span class="kw">where</span></span>
<span id="cb8-8"><a href="#cb8-8" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- Parse a JSON object of colours into a list of 'ColourName's which</span></span>
<span id="cb8-9"><a href="#cb8-9" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- have @status == &quot;active&quot;.</span></span>
<span id="cb8-10"><a href="#cb8-10" aria-hidden="true" tabindex="-1"></a><span class="ot">        activeColours ::</span> <span class="dt">Value</span> <span class="ot">-&gt;</span> <span class="dt">Parser</span> [<span class="dt">ColourName</span>]</span>
<span id="cb8-11"><a href="#cb8-11" aria-hidden="true" tabindex="-1"></a>        activeColours (<span class="dt">Object</span> o) <span class="ot">=</span> (<span class="fu">fmap</span> <span class="fu">fst</span> <span class="op">.</span> <span class="fu">filter</span> <span class="fu">snd</span>) <span class="op">&lt;$&gt;</span></span>
<span id="cb8-12"><a href="#cb8-12" aria-hidden="true" tabindex="-1"></a>            <span class="fu">mapM</span> (<span class="fu">uncurry</span> colour) (HM.toList o)</span>
<span id="cb8-13"><a href="#cb8-13" aria-hidden="true" tabindex="-1"></a>        activeColours _ <span class="ot">=</span> <span class="fu">fail</span> <span class="st">&quot;Colours must be a JSON object.&quot;</span></span>
<span id="cb8-14"><a href="#cb8-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-15"><a href="#cb8-15" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- Given a name and a JSON value, parse a pair containing the name and</span></span>
<span id="cb8-16"><a href="#cb8-16" aria-hidden="true" tabindex="-1"></a>        <span class="co">-- whether the colour has @status == &quot;active&quot;@.</span></span>
<span id="cb8-17"><a href="#cb8-17" aria-hidden="true" tabindex="-1"></a><span class="ot">        colour ::</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Value</span> <span class="ot">-&gt;</span> <span class="dt">Parser</span> (<span class="dt">ColourName</span>, <span class="dt">Bool</span>)</span>
<span id="cb8-18"><a href="#cb8-18" aria-hidden="true" tabindex="-1"></a>        colour name (<span class="dt">Object</span> o) <span class="ot">=</span> (,)</span>
<span id="cb8-19"><a href="#cb8-19" aria-hidden="true" tabindex="-1"></a>            <span class="op">&lt;$&gt;</span> parseJSON (<span class="dt">String</span> name)</span>
<span id="cb8-20"><a href="#cb8-20" aria-hidden="true" tabindex="-1"></a>            <span class="op">&lt;*&gt;</span> ((<span class="dt">String</span> <span class="st">&quot;active&quot;</span> <span class="op">==</span>) <span class="op">&lt;$&gt;</span> (o <span class="op">.:</span> <span class="st">&quot;status&quot;</span>))</span>
<span id="cb8-21"><a href="#cb8-21" aria-hidden="true" tabindex="-1"></a>        colour _ _ <span class="ot">=</span> <span class="fu">fail</span> <span class="st">&quot;Colour must be a JSON object.&quot;</span></span>
<span id="cb8-22"><a href="#cb8-22" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-23"><a href="#cb8-23" aria-hidden="true" tabindex="-1"></a>    parseJSON _ <span class="ot">=</span> <span class="fu">fail</span> <span class="st">&quot;Robot must be a JSON object&quot;</span></span>
<span id="cb8-24"><a href="#cb8-24" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-25"><a href="#cb8-25" aria-hidden="true" tabindex="-1"></a><span class="co">-- | Parser to check that a list contains exactly one value.</span></span>
<span id="cb8-26"><a href="#cb8-26" aria-hidden="true" tabindex="-1"></a><span class="ot">exactlyOne ::</span> [a] <span class="ot">-&gt;</span> <span class="dt">Parser</span> a</span>
<span id="cb8-27"><a href="#cb8-27" aria-hidden="true" tabindex="-1"></a>exactlyOne [] <span class="ot">=</span> <span class="fu">fail</span> <span class="st">&quot;Missing value&quot;</span></span>
<span id="cb8-28"><a href="#cb8-28" aria-hidden="true" tabindex="-1"></a>exactlyOne [a] <span class="ot">=</span> <span class="fu">pure</span> a</span>
<span id="cb8-29"><a href="#cb8-29" aria-hidden="true" tabindex="-1"></a>exactlyOne _ <span class="ot">=</span> <span class="fu">fail</span> <span class="st">&quot;More than one value&quot;</span></span></code></pre></div>
<p>With all these instances written I can update <code>shellOutJSON</code> to use the
<code>Upstream</code> instances when it interacts with the command-line program. Two small
changes – adding <code>Upstream</code> to the <code>FromJSON</code> constraint and the “success”
pattern match – are enough to ensure that <em>all</em> communication with the
upstream system uses the <code>Upstream</code> JSON encoding:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>shellOutJSON</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a><span class="ot">    ::</span> (<span class="dt">MonadError</span> <span class="dt">String</span> m, <span class="dt">MonadIO</span> m, <span class="dt">FromJSON</span> (<span class="dt">Upstream</span> a))</span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a>    <span class="ot">=&gt;</span> [<span class="dt">String</span>]</span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a>    <span class="ot">-&gt;</span> m a</span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a>shellOutJSON cmd <span class="ot">=</span> <span class="kw">do</span></span>
<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- Execute the command.</span></span>
<span id="cb9-7"><a href="#cb9-7" aria-hidden="true" tabindex="-1"></a>    (exit_code, out, _err) <span class="ot">&lt;-</span> liftIO <span class="op">$</span> readProcessWithExitCode cmd [] <span class="st">&quot;&quot;</span></span>
<span id="cb9-8"><a href="#cb9-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-9"><a href="#cb9-9" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- Check it succeeded.</span></span>
<span id="cb9-10"><a href="#cb9-10" aria-hidden="true" tabindex="-1"></a>    output <span class="ot">&lt;-</span> <span class="kw">case</span> exit_code <span class="kw">of</span></span>
<span id="cb9-11"><a href="#cb9-11" aria-hidden="true" tabindex="-1"></a>        <span class="dt">ExitSuccess</span> <span class="ot">-&gt;</span> <span class="fu">return</span> <span class="op">$</span> BS.pack out</span>
<span id="cb9-12"><a href="#cb9-12" aria-hidden="true" tabindex="-1"></a>        <span class="dt">ExitFailure</span> err <span class="ot">-&gt;</span> throwError <span class="op">$</span></span>
<span id="cb9-13"><a href="#cb9-13" aria-hidden="true" tabindex="-1"></a>            <span class="st">&quot;Could not execute command: errno = &quot;</span> <span class="op">&lt;&gt;</span> <span class="fu">show</span> err</span>
<span id="cb9-14"><a href="#cb9-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-15"><a href="#cb9-15" aria-hidden="true" tabindex="-1"></a>    <span class="co">-- Decode the JSON.</span></span>
<span id="cb9-16"><a href="#cb9-16" aria-hidden="true" tabindex="-1"></a>    <span class="kw">case</span> eitherDecode output <span class="kw">of</span></span>
<span id="cb9-17"><a href="#cb9-17" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Left</span> e <span class="ot">-&gt;</span> throwError <span class="op">$</span> </span>
<span id="cb9-18"><a href="#cb9-18" aria-hidden="true" tabindex="-1"></a>            <span class="st">&quot;Error decoding JSON: &quot;</span> <span class="op">&lt;&gt;</span> e</span>
<span id="cb9-19"><a href="#cb9-19" aria-hidden="true" tabindex="-1"></a>        <span class="dt">Right</span> (<span class="dt">Upstream</span> v) <span class="ot">-&gt;</span> <span class="fu">return</span> v</span></code></pre></div>
<p>Now any call to <code>shellOutJSON</code> will automatically parse using the correct JSON
encoding and any existing code using <code>shellOutJSON</code> doesn’t have to change.
Even better, any call which needs a type without an <code>Upstream</code> instance of
<code>FromJSON</code> will result in a type error at run time:</p>
<pre><code>lib/Server.hs:115:5:
    Could not deduce (FromJSON (Upstream Colour))
      arising from a use of ‘shellOutJSON’
    from the context (MonadError String m, MonadIO m)
      bound by the type signature for
                 getColour :: (MonadError String m, MonadIO m) =&gt;
                                      ColourName -&gt; m Colour
      at lib/Server.hs:(109,8)-(112,18)
    In a stmt of a 'do' block: shellOutJSON cmd [&quot;colour&quot;, &quot;list&quot;, colour_name]
    In the expression:
      shellOutJSON cmd [&quot;colour&quot;, &quot;list&quot;, color_name]
    In an equation for ‘getColour’:
        getColour name
          = do { let colour_name = T.unpack $ unColourName name
                 shellOutJSON cmd [&quot;colour&quot;, ....] }</code></pre>
<p>The second line of the error tells you exactly what’s missing: the compiler
can’t find a <code>FromJSON</code> instance for <code>Upstream Colour</code>.</p>
<h2 id="conclusion">Conclusion</h2>
<p>By using a “wrapper” type like <code>Upstream a</code> I reduced the amount of code I need
to write and maintain (in particular, there’s no converting back and forth
between <code>Colour</code> and <code>WeirdlyFormattedColour</code> data types). The values of my
various types are clearly still related and <code>Upstream</code> is completely agnostic
to the type being wrapped – an <code>Upstream Robot</code> is just a <code>Robot</code> inside an
<code>Upstream</code> and neither the <code>Robot</code> not the <code>Upstream</code> cares about the other
part at all.</p>
<p>Making the wrapper parametric like this (as opposed to, for example, creating
a different <code>newtype</code> wrapper around each of the particular types) makes i
possible to write code which – like the modified <code>shellOutJSON</code> – doesn’t
care about the <em>what</em> is being wrapped, just that it <em>is</em> wrapped.</p>
<p>Adding and removing the <code>Upstream</code> wrapper at the system boundary minimises the
amount code which can incorrectly use the wrong representation and, in
particular, makes it impossible for these bugs to happen in the many places
I use <code>shellOutJSON</code>. This forces me to define wrapped <code>FromJSON</code> instances for
<em>all</em> the types, even the ones that use the same JSON representation, but this
is a price I’m willing to pay for an interface that makes a class of errors
impossible.</p>
<p>Using this approach in my current project made the code shorter, simpler (in
terms of number of data types and functions defined), fixed two “wrong format”
bugs, and made it impossible to reintroduce them.</p>]]></summary>
</entry>

</feed>
