<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>functionalprogramming &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/functionalprogramming/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Fri, 11 Dec 2020 14:11:48 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://jessewarden.com/wp-content/uploads/2016/08/cropped-Lambda2-32x32.png</url>
	<title>functionalprogramming &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Strictly Typed Functional Programming for Roblox</title>
		<link>https://jessewarden.com/2020/12/strictly-typed-functional-programming-for-roblox.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Fri, 11 Dec 2020 14:11:48 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[hypatia]]></category>
		<category><![CDATA[roblox]]></category>
		<guid isPermaLink="false">https://jessewarden.com/?p=6058</guid>

					<description><![CDATA[I managed to get Hypatia, an Elm and PureScript like typed Functional Programming language that compiles to Lua, running in Roblox. Roblox is a 3D game engine that has a ton of already built games and editor where games are built in Lua. My kids spend way too much time and our money in it. [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>I managed to get <a href="https://github.com/kindl/Hypatia">Hypatia</a>, an <a href="https://elm-lang.org/">Elm</a> and <a href="https://www.purescript.org/">PureScript</a> like typed Functional Programming language that compiles to <a href="https://www.lua.org/">Lua</a>, running in <a href="https://www.roblox.com/">Roblox</a>. Roblox is a 3D game engine that has a ton of already built games and editor where games are built in Lua. My kids spend way too much time and our money in it. I couldn&#8217;t get <a href="https://amulet.works/">Amulet</a>, another similar language, too compile, but Hypatia &#8220;spoke to me&#8221; more. <a href="https://adventofcode.com/">Advent of Code 2020</a> this year taught me dealing with no types and race conditions is painful. I really wanted to explore what other language options there are that compile to Lua.</p>



<span id="more-6058"></span>



<p>The workflow is you write in Hypatia, compile, make the compiled Lua require statements to the Roblox version, and <a href="https://rojo.space/">Rojo</a>, a <a href="https://www.rust-lang.org/">Rust</a> built development tool, will sync your Lua directly into Roblox. You can then call the exposed functions directly from other Lua (i.e. Buttons, events, etc). I&#8217;m thinking of automating that require change with Python&#8230; or maybe Lua.</p>



<p>Compiling Hypatia required a couple of smart <a href="https://www.haskell.org/">Haskell</a> devs at work to help me compile. <a href="https://www.haskell.org/cabal/">Cabal</a> didn&#8217;t work but <a href="https://docs.haskellstack.org/en/stable/README/">Stack</a> worked no problem on my Mac M1. Hypatia might compile JavaScript too, not sure.</p>



<p>Anyway, still need to figure out side effects (still learning what the heck a f -> Unit is), and how to deal with coroutines and various other side effects since Hypatia doesn&#8217;t handle them like Elm does, but super excited to continue exploring this.</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="758" height="528" src="https://jessewarden.com/wp-content/uploads/2020/12/1607567400967.jpeg" alt="" class="wp-image-6059" srcset="https://jessewarden.com/wp-content/uploads/2020/12/1607567400967.jpeg 758w, https://jessewarden.com/wp-content/uploads/2020/12/1607567400967-300x209.jpeg 300w" sizes="(max-width: 758px) 100vw, 758px" /></figure>



<figure class="wp-block-image size-large"><img decoding="async" width="800" height="431" src="https://jessewarden.com/wp-content/uploads/2020/12/1607567400793.jpeg" alt="" class="wp-image-6060" srcset="https://jessewarden.com/wp-content/uploads/2020/12/1607567400793.jpeg 800w, https://jessewarden.com/wp-content/uploads/2020/12/1607567400793-300x162.jpeg 300w, https://jessewarden.com/wp-content/uploads/2020/12/1607567400793-768x414.jpeg 768w" sizes="(max-width: 800px) 100vw, 800px" /></figure>



<figure class="wp-block-image size-large"><img decoding="async" width="800" height="336" src="https://jessewarden.com/wp-content/uploads/2020/12/1607567401935.jpeg" alt="" class="wp-image-6061" srcset="https://jessewarden.com/wp-content/uploads/2020/12/1607567401935.jpeg 800w, https://jessewarden.com/wp-content/uploads/2020/12/1607567401935-300x126.jpeg 300w, https://jessewarden.com/wp-content/uploads/2020/12/1607567401935-768x323.jpeg 768w" sizes="(max-width: 800px) 100vw, 800px" /></figure>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Handling Noop Infrastructure in AWS Step Functions</title>
		<link>https://jessewarden.com/2020/04/handling-noop-infrastructure-in-aws-step-functions.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Tue, 07 Apr 2020 04:21:21 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[aws]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[statemachine]]></category>
		<category><![CDATA[states]]></category>
		<category><![CDATA[stepfunction]]></category>
		<guid isPermaLink="false">https://jessewarden.com/?p=5921</guid>

					<description><![CDATA[Spent a month on this and I think I figured out how to get JSON to &#8220;roll over&#8221; a Step Function step that is a noop (no operation: function that doesn&#8217;t return a value), like say AWS Batch. Noop&#8217;s (no operation) are steps that basically are full of side effects, but really don&#8217;t have a [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Spent a month on this and I think I figured out how to get JSON to &#8220;roll over&#8221; a <a href="https://aws.amazon.com/step-functions/">Step Function</a> step that is a noop (no operation: function that doesn&#8217;t return a value), like say <a href="https://aws.amazon.com/batch/">AWS Batch</a>. Noop&#8217;s (no operation) are steps that basically are full of side effects, but really don&#8217;t have a useful return value beyond &#8220;SUCCESS&#8221;.</p>



<span id="more-5921"></span>



<p>If you code Batch in <a href="https://golang.org/">Go</a> for example, the main method has it right there in the return value: void. Meaning… there <em>is</em> no return value.</p>



<p>How, then, do you use something like a noop in your mostly Functional Programming style Step Function that assumes you&#8217;re composing infrastructure like you&#8217;d compose functions? Basically tap. If you&#8217;re not familiar, tap is a quick way to debug pure function chains.</p>



<p>If you&#8217;ve ever heard of the identity function, it basically gives you back what you give it, like this in Python:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def identity(oh_yeah):
  <span class="hljs-keyword">return</span> oh_yeah</code></span></pre>


<p>Or this in JavaScript:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> identity = <span class="hljs-function"><span class="hljs-params">ohYeah</span> =&gt;</span>
  ohYeah</code></span></pre>


<p>That seems like a ridiculous function, no doubt. But watch what happens when you combine it with composed functions, say, parsing some JSON.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def parse(str):
  <span class="hljs-keyword">return</span> json_parse(str) \
  &gt;&gt; parse_people \
  &gt;&gt; filter_humans \
  &gt;&gt; format_names</code></span></pre>


<p>Parse composes 4 functions together. If they&#8217;re pure, how do you &#8220;see&#8221; inside that pipeline? You &#8220;tap&#8221; into it. We can take our identity function, and convert to a tap function like this:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">def tap(oh_yeah):
  <span class="hljs-keyword">print</span>(<span class="hljs-string">"oh_yeah:"</span>, oh_yeah)
  <span class="hljs-keyword">return</span> oh_yeah</code></span></pre>


<p>Then we can &#8220;tap into&#8221; the pipeline.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def parse(str):
  <span class="hljs-keyword">return</span> json_parse(str) \
  &gt;&gt; tap \
  &gt;&gt; parse_people \
  &gt;&gt; tap \
  &gt;&gt; filter_humans \
  &gt;&gt; tap \
  &gt;&gt; format_names</code></span></pre>


<p>Sick, ya? Now the normal way to do that in Step Functions is via a <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-pass-state.html">Pass state</a>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-string">"Tap"</span>: {
  <span class="hljs-string">"Type"</span>: <span class="hljs-string">"Pass"</span>,
  <span class="hljs-string">"Next"</span>: <span class="hljs-string">"NextStep"</span>
}</code></span></pre>


<p>You can then see the output in the Step Function console, or tweak the inputs/outputs if you wish.</p>



<p>… but that&#8217;s for Lambdas, Step Functions, SQS, and SNS steps that not only return a result like a pure function, but do so using your JSON. In JavaScript, that&#8217;s pretty easy to merge properties:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> addYoSelf = <span class="hljs-function"><span class="hljs-params">json</span> =&gt;</span>
  ({ …json, <span class="hljs-attr">name</span>: <span class="hljs-string">"Jesse was here"</span> })</code></span></pre>


<p>Batch, and even Step Functions, don&#8217;t always work like this. You typically have to define <a href="https://docs.aws.amazon.com/step-functions/latest/dg/input-output-inputpath-params.html">Parameters</a> manually depending upon the input… meaning you lose your JSON tree. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f622.png" alt="😢" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>… UNLESS it&#8217;s just 1 branch. You can create siblings that are collected in a single spot using the <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-parallel-state.html">Parallel task</a>.</p>



<p>If you think <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all">Promise.all</a> like in JavaScript or <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.gather">gather</a> in Python, multiple results, but a single, Array filled result. This allows you to keep context at least in 1 spot using a Pass, and you don&#8217;t care about the rest.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">a = stuff
identity = <span class="hljs-function"><span class="hljs-params">stuff</span> =&gt;</span> stuff
addSelf = <span class="hljs-function"><span class="hljs-params">stuff</span> =&gt;</span> ({… stuff, <span class="hljs-attr">name</span>: <span class="hljs-string">'Jesse'</span>})
destroy = <span class="hljs-function"><span class="hljs-params">stuff</span> =&gt;</span> <span class="hljs-literal">undefined</span>
end = <span class="hljs-function"><span class="hljs-params">a</span> =&gt;</span> <span class="hljs-built_in">Promise</span>.all(&#91;identity(a), addSelf(a), destroy(a)])</code></span></pre>


<p>Notice how <code>end</code> will result in an Array like:<br><code>[stuff, stuff + name Jesse, undefined]</code></p>



<p>Undefined is often what we get with noops that return no value. BUT, we need the first part to continue our Step Function with &#8220;context&#8221;. Using a Parallel + Pass, you can keep that context.</p>



<p>Until Batch gets the .waitForTaskToken feature (I mean… ECS has it…), you can wrap her in a Parallel to keep context. Just watch those catches….</p>



<p>tl;dr; JSON use Parallel and in next state go:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-string">"OutputPath"</span>: <span class="hljs-string">"$&#91;0]"</span></code></span></pre>


<p>BTW, I know you can use <code>ResultPath</code> and just attach to your existing JSON, but AWS Batch is HUGE, and we&#8217;re already getting super close to our JSON size limit with our immense Array size I refuse to read from S3. You could just export and then rip off from a Pass state, but you&#8217;ll get a size exception before that happens sadly. Twice now I&#8217;ve got an exception when it completes the Batch because the JSON is too large, and using this technique has worked every time. </p>



<figure class="wp-block-gallery columns-1 is-cropped wp-block-gallery-1 is-layout-flex wp-block-gallery-is-layout-flex"><ul class="blocks-gallery-grid"><li class="blocks-gallery-item"><figure><img loading="lazy" decoding="async" width="372" height="317" src="https://jessewarden.com/wp-content/uploads/2020/04/stepfunctions_graph-8.png" alt="" data-id="5922" data-full-url="https://jessewarden.com/wp-content/uploads/2020/04/stepfunctions_graph-8.png" data-link="https://jessewarden.com/?attachment_id=5922" class="wp-image-5922" srcset="https://jessewarden.com/wp-content/uploads/2020/04/stepfunctions_graph-8.png 372w, https://jessewarden.com/wp-content/uploads/2020/04/stepfunctions_graph-8-300x256.png 300w" sizes="auto, (max-width: 372px) 100vw, 372px" /></figure></li></ul></figure>



<p>And Step Function JSON for above (supply your own Lambda):</p>


<pre class="wp-block-code"><span><code class="hljs language-json">{
  <span class="hljs-attr">"Comment"</span>: <span class="hljs-string">"A Hello World example of the Amazon States Language using Pass states"</span>,
  <span class="hljs-attr">"StartAt"</span>: <span class="hljs-string">"Both"</span>,
  <span class="hljs-attr">"States"</span>: {
    <span class="hljs-attr">"Both"</span>: {
      <span class="hljs-attr">"Type"</span>: <span class="hljs-string">"Parallel"</span>,
      <span class="hljs-attr">"Next"</span>: <span class="hljs-string">"Keep JSON"</span>,
      <span class="hljs-attr">"Branches"</span>: &#91;
        {
          <span class="hljs-attr">"StartAt"</span>: <span class="hljs-string">"Good Function Returns Value"</span>,
          <span class="hljs-attr">"States"</span>: {
            <span class="hljs-attr">"Good Function Returns Value"</span>: {
              <span class="hljs-attr">"Type"</span>: <span class="hljs-string">"Task"</span>,
              <span class="hljs-attr">"Resource"</span>: <span class="hljs-string">"arn:aws:lambda:us-east-1:0000000:function:jesse-identity"</span>,
              <span class="hljs-attr">"Parameters"</span>: {
                <span class="hljs-attr">"uno"</span>: <span class="hljs-string">"yup"</span>
              },
              <span class="hljs-attr">"ResultPath"</span>: <span class="hljs-string">"$.datLambdaResult"</span>,
              <span class="hljs-attr">"End"</span>: <span class="hljs-literal">true</span>
            }
          }
        },
        {
          <span class="hljs-attr">"StartAt"</span>: <span class="hljs-string">"Bad Noop"</span>,
          <span class="hljs-attr">"States"</span>: {
            <span class="hljs-attr">"Bad Noop"</span>: {
              <span class="hljs-attr">"Type"</span>: <span class="hljs-string">"Pass"</span>,
              <span class="hljs-attr">"Result"</span>: <span class="hljs-string">"World"</span>,
              <span class="hljs-attr">"End"</span>: <span class="hljs-literal">true</span>
            }
          }
        }
      ]
    },
    <span class="hljs-attr">"Keep JSON"</span>: {
      <span class="hljs-attr">"Type"</span>: <span class="hljs-string">"Pass"</span>,
      <span class="hljs-attr">"OutputPath"</span>: <span class="hljs-string">"$&#91;0]"</span>,
      <span class="hljs-attr">"End"</span>: <span class="hljs-literal">true</span>
    }
  }
}</code></span></pre>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Write Unbreakable Python</title>
		<link>https://jessewarden.com/2020/03/write-unbreakable-python.html</link>
					<comments>https://jessewarden.com/2020/03/write-unbreakable-python.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Tue, 17 Mar 2020 16:34:14 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[either]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[lenses]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[result]]></category>
		<guid isPermaLink="false">https://jessewarden.com/?p=5890</guid>

					<description><![CDATA[In this article, I&#8217;ll show you how to write Python with no runtime exceptions. This&#8217;ll get you partway to writing code that never breaks and mostly does what it&#8217;s supposed to do. We&#8217;ll do this by learning how to apply functional programming to Python. We&#8217;ll cover: ensure functions always work by learning Pure Functions avoid [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In this article, I&#8217;ll show you how to write Python with no runtime exceptions. This&#8217;ll get you partway to writing code that never breaks and mostly does what it&#8217;s supposed to do. We&#8217;ll do this by learning how to apply functional programming to Python. We&#8217;ll cover:</p>



<ul class="wp-block-list"><li>ensure functions always work by learning Pure Functions</li><li>avoid runtime errors by return Maybes</li><li>avoid runtime errors in deeply nested data using Lenses</li><li>avoid runtime errors by return Results</li><li>creating pure programs from pure functions by Pipeline Programming</li></ul>



<span id="more-5890"></span>



<h2 class="wp-block-heading">Why Care?</h2>



<p>Writing code that doesn&#8217;t break is much like ensuring your teeth remain healthy. Both have proven ways to prevent problems, yet people still act irresponsibly, either by eating bad foods and not brushing, or in programming being lured by &#8220;getting things working quickly with what they know&#8221;.</p>



<p>For example, to prevent cavities in your teeth, you should avoid food high in sugar, drink public water supplies with fluoride, and brush your teeth twice a day. At least in the USA, many still have <a href="https://www.today.com/health/most-us-have-tooth-decay-study-finds-t20781">teeth problems</a>. The access problem for dental hygiene can be an economic one. For others, they just aren&#8217;t responsible and don&#8217;t keep up on teeth health.</p>



<p>For programming, I can help with the access problem. This article will provide proven ways to equip you with the knowledge to help yourself.</p>



<p>For the responsibility, however, I empathize it&#8217;s harder. I&#8217;ll teach you the techniques, but <em>you</em> have to practice them. Brushing your teeth everyday, you can master it quite quickly. Utilizing functional programming techniques in a non-functional programming language takes a lot more practice and hard work.</p>



<p>Your teeth thank you for brushing often. Your code will thank you by consistently working.</p>



<h2 class="wp-block-heading">What Does &#8220;Never Break&#8221; Mean Exactly?</h2>



<p>The &#8220;Never Break&#8221; means the function will always work, will always return a value, won&#8217;t ever raise an Exception, nor will it ever exit the Python process unless you want it to. It doesn&#8217;t matter what order you call these functions or program in, how many times you call it, they are always predictable, and can be depended on.</p>



<h2 class="wp-block-heading">What Does &#8220;Mostly Work&#8221; Mean Exactly?</h2>



<p>Just because your functions work all the time doesn&#8217;t mean your software works. Pass the wrong environment variable for a Docker container, a downstream API is down, or perhaps you just did the math wrong. You still need unit, fuzz, feature tests, formal methods if you&#8217;re able, and good ole manual testing to verify your software works. Not having to worry about your software exploding randomly allows you to focus 100% on those.</p>



<p>Also, no amount of FP will save you from badly formatted code. You&#8217;ll still need things like PyLint to ensure you wrote <code>print("Sup")</code> instead of <code>print("Sup)</code></p>



<h2 class="wp-block-heading">If this is so obvious, when do I _not_ do this?</h2>



<p>In order of priority:</p>



<ol class="wp-block-list"><li>When you&#8217;re exploring ideas.</li><li>When you&#8217;re committing code amongst those who aren&#8217;t trained in FP.</li><li>When you&#8217;re on a deadline.</li><li>When you&#8217;re modifying legacy code with no unit tests.</li></ol>



<p>The allure and draw of Python is it is a dynamic language. While not as forgiving as JavaScript, Lua, or Ruby, it still allows a lot of freedom to play with ideas, various data types, and provide a variety of ways to run your code efficiently on various infrastructure architectures. With types only enforced (mostly) at runtime, you can try various ideas, quickly run them, correct mistakes you find after running them, and repeat this until you&#8217;ve locked down an implementation. While you _can_ use FP concepts for this, if you&#8217;re still learning, they can slow you down. Other times, this is a fun time to learn.</p>



<p>Commiting FP code to a Github repo where others aren&#8217;t familiar with FP, or have no clue why you&#8217;re coding things that don&#8217;t seem <a href="https://www.python.org/dev/peps/pep-0008/">PEP Compliant</a> can really cause problems. Typically a team adopts their own rules, patterns, and styles&#8230; and they don&#8217;t always have reasonable reasons. It&#8217;s best to learn why they code the way they do things, and adopt those standards. If you&#8217;re in a position to teach the team, great, but FP is quite alien, already has a reputation for being obtuse with horrible evangelists. Tread slowly here. Breaking trust in the team is one way to ensure your software never works correctly. Bad working relationships result in horrible software.</p>



<p>If you&#8217;re on a deadline, learning anything new can slow you down and risk not hitting it. Alternatively, it&#8217;s also the guaranteed way to ensure you learn something quickly, heh.</p>



<p>FP or not, you shouldn&#8217;t add or modify code in a large codebase you&#8217;re responsible for if it doesn&#8217;t have unit tests. Otherwise, you have no good idea if you&#8217;ve broken something, sometimes for days or weeks. Add tests first, THEN refactor things.</p>



<h2 class="wp-block-heading">Functions That Always Work: Writing Pure Functions</h2>



<p>Pure functions always work. They reason they always work is that they always return values. They don&#8217;t raise Exceptions. They&#8217;re technically not supposed to have side effects. They&#8217;re desired because they always return the same value, so are close to math in that you can depend on their result, or &#8220;answer&#8221;. Unit testing them also doesn&#8217;t require mocks, only stubs.</p>



<p>The 2 official rules go like this:</p>



<ol class="wp-block-list"><li>same input, same output</li><li>no side effects</li></ol>



<p>Returning <code>None</code> is ok. The first function most Python devs are introduced too, <code>print</code> doesn&#8217;t appear to return value, much like <code>console.log</code> in JavaScript. However, it does: <code>None</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">result = <span class="hljs-keyword">print</span>(<span class="hljs-string">"Sup"</span>)
<span class="hljs-keyword">print</span>(result == None) <span class="hljs-comment"># True</span></code></span></pre>


<p>Typically a function that returns no value, or <code>None</code> in Python&#8217;s case, is considered a &#8220;no operation&#8221; function, or &#8220;noop&#8221; for short (pronounced no-op). Noop&#8217;s are usually a sign the function has side effects. Noops are not pure functions. We know that <code>print</code> does produce side effects; the whole point of calling it is to produce the side effect of writing to standard out so we can see what the heck our code is doing.</p>



<p>For classes, however, it&#8217;s more subtle and now that you know the rules, you&#8217;ll see what&#8217;s wrong. Here&#8217;s how you stop verifying SSL certs for rest calls using a class to wrap <code>urllib</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">import</span> request.rest
<span class="hljs-keyword">import</span> ssl

req = request.rest()
req.disable_ssl()
res = req.get(<span class="hljs-string">"https://some.server.com"</span>)</code></span></pre>


<p>Note the <code>disable_ssl()</code> class method. It takes no parameters, and returns no value. Why? Probably because like most classes, it&#8217;s changing a setting internally in the class instance to turn off SSL stuff so the next person who does a REST call won&#8217;t have to have certs validated.</p>



<p>You do the complete opposite in functional programming. Although, in this case, it&#8217;s probably ok to call <code>disable_ssl()</code> multiple times without any harm. Things like <code>get</code> are more tricky.</p>



<p>So, <strong>impure</strong> function:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">ssl = enabled

def <span class="hljs-keyword">get</span>(url):
  return requests.<span class="hljs-keyword">get</span>(url, ssl_enabled=ssl)</code></span></pre>


<p>And a <strong>pure</strong> function:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def <span class="hljs-keyword">get</span>(ssl, url):
  return requests.<span class="hljs-keyword">get</span>(url, ssl_enabled=ssl)</code></span></pre>


<p>And one that&#8217;s even <strong>more pure</strong>, and unit testable:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def <span class="hljs-keyword">get</span>(requests, ssl, url):
  return requests.<span class="hljs-keyword">get</span>(url, ssl_enabled=ssl)</code></span></pre>


<p>And the <strong>most pure function you can possibly write in Python in a reasonable way</strong>:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">def get(requests, ssl, url):
  <span class="hljs-keyword">try</span>:
    result = requests.get(url, ssl_enabled=ssl)
    <span class="hljs-keyword">return</span> result
  except <span class="hljs-keyword">Exception</span> <span class="hljs-keyword">as</span> e:
    <span class="hljs-keyword">return</span> e</code></span></pre>


<p>Write functions like that, and you&#8217;re well on your way to understanding how <a href="https://golang.org/">Golang</a> is written.</p>



<h2 class="wp-block-heading">Avoiding None by using Maybes</h2>



<p>Python doesn&#8217;t offer a lot of guarantee&#8217;s, that&#8217;s why risk takers like it. If you&#8217;re writing software, you might not want risk. There are 3 main places this comes from when calling functions:</p>



<ol class="wp-block-list"><li>getting data from Dictionaries (cause you&#8217;re using them now, not Classes, right?)</li><li>getting data from Lists</li><li>getting data from outside of Python</li></ol>



<h3 class="wp-block-heading">Safer Dictionaries: Maybe Tuple</h3>



<p>Let&#8217;s talk about dictionaries.</p>



<p>Dictionaries can work:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">person = { firstName: <span class="hljs-string">"Jesse"</span> }
<span class="hljs-keyword">print</span>(person&#91;<span class="hljs-string">"firstName"</span>]) <span class="hljs-comment"># Jesse</span></code></span></pre>


<p>Dictionaries can also fail:</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-keyword">print</span>(person&#91;<span class="hljs-string">"lastName"</span>])
<span class="hljs-comment"># KeyError: 'lastName'</span></code></span></pre>


<p>Wat do!?</p>



<p>You need to change how you think Python in 2 ways. First, how you access objects safely, such as using <code>key in dictionary</code> or lenses. Second, how you return values from functions, such as using the Golang syntax by returning multiple values which lets you know if the function worked or not, or a Maybe/Result type.</p>



<p>You can safely access dictionaries by creating a getter function:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">def get_last_name(object):
  <span class="hljs-keyword">if</span> <span class="hljs-string">"lastName"</span> in object:
    <span class="hljs-keyword">return</span> (<span class="hljs-keyword">True</span>, object&#91;<span class="hljs-string">"lastName"</span>], None)
  <span class="hljs-keyword">return</span> (<span class="hljs-keyword">False</span>, None, f<span class="hljs-string">"lastName does not exist in {object}"</span>)
</code></span></pre>


<p>This function is pure, and safe and will work with any data without blowing up. It also uses a nice trick Python has when you return a <code>Tuple</code> (read only List) from a function; you can destructure it to get 3 variables out in a terse syntax, making it feel like it is returning multiple values. We&#8217;ve chosen something similar to the Golang syntax where they return <code>value, error</code>, we&#8217;re returning <code>didItWork, value, error</code>. You can use the Golang syntax if you wish, I just don&#8217;t like writing <code>if error != None</code>. </p>


<pre class="wp-block-code"><span><code class="hljs language-php">ok, lastName, error = get_last_name(person)
<span class="hljs-keyword">if</span> ok == <span class="hljs-keyword">False</span>:
  <span class="hljs-keyword">return</span> (<span class="hljs-keyword">False</span>, None, f<span class="hljs-string">"Failed to get lastName from {person}"</span>)</code></span></pre>


<p>So this is your first <code>Maybe</code> at a raw level. It&#8217;s a <code>Tuple</code> that contains if the function had your data or not, the data if it did, and if not why. Note if <code>ok</code> is <code>False</code>, your program is probably done at this point.</p>



<p>Developers are encouraged to create <code>Exceptions</code> for everything that isn&#8217;t necessarily exceptional, and <code>raise</code> them so others can catch them or different types of them and react accordingly, usually higher up the function chain. The problem with this is you can&#8217;t easily read your code and see errors as they could be coming from completely different files. Using maybes in this way, it&#8217;s very clear what function failed, and your don&#8217;t have to wrap things in try/catch &#8220;just in case&#8221;.</p>



<h3 class="wp-block-heading">Safer Dictionaries: Maybe Type</h3>



<p>Tuples are ok, but are verbose. A shorter option is the Maybe type. We&#8217;ll use <a href="https://pypi.org/project/PyMonad/">PyMonad&#8217;s</a> version because they did a lot of hard work for us. First import it:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">from</span> pymonad.Maybe <span class="hljs-keyword">import</span> *</code></span></pre>


<p>Then, we&#8217;ll create our <code>getLastName</code> function to return a <code>Maybe</code> type instead of a Tuple like we did before:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def get_last_name(object):
  <span class="hljs-keyword">if</span> <span class="hljs-string">"lastName"</span> <span class="hljs-keyword">in</span> object:
    <span class="hljs-keyword">return</span> Just(object&#91;<span class="hljs-string">"lastName"</span>])
  <span class="hljs-keyword">return</span> Nothing</code></span></pre>


<p>I say the word &#8220;type&#8221;, but in Python, it feels like a function. Replace <code>(True, data, None)</code> with <code>Just(data)</code> and <code>(False, None, Exception('reason'))</code> with <code>Nothing</code>. You can then use it:</p>


<pre class="wp-block-code"><span><code class="hljs">lastNameMaybe = get_last_name(person)</code></span></pre>


<p>You first instinct will be &#8220;cool, if it&#8217;s a <code>Just</code>, how do I get my data out?&#8221;. Well, you don&#8217;t.</p>



<p>&#8220;Wat!?&#8221;</p>



<p>Trust me, we&#8217;ll cover this in Pipeline Programming below, for now, just know this function will never fail, and you&#8217;ll always get a <code>Maybe</code> back, ensuring your code doesn&#8217;t throw errors, and is more predictable and testable.</p>



<p>Speaking of which, here&#8217;s <a href="https://docs.pytest.org/en/latest/">Pytest</a>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def test_get_last_name_happy():
  result = get_last_name({<span class="hljs-string">'lastName'</span>: <span class="hljs-string">'cow'</span>})
  assert result == Just(<span class="hljs-string">'cow'</span>)</code></span></pre>


<p>&#8220;Wat&#8230;&#8221;</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f601.png" alt="😁" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Ok, till you get more comfortable, try this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def test_get_last_name_happy():
  result = get_last_name({<span class="hljs-string">'lastName'</span>: <span class="hljs-string">'cow'</span>})
  assert result.value == <span class="hljs-string">'cow'</span></code></span></pre>


<h3 class="wp-block-heading">Safer Lists: Maybe Type</h3>



<p>The same thing can be said for <code>Lists</code>in Python.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">people = &#91;{<span class="hljs-string">'firstName'</span>: <span class="hljs-string">'Jesse'</span>}]
first = people&#91;<span class="hljs-number">0</span>]</code></span></pre>


<p>Cool.</p>


<pre class="wp-block-code"><span><code class="hljs language-php">people = &#91;]
first = people&#91;<span class="hljs-number">0</span>]
<span class="hljs-comment"># IndexError: list index out of range</span></code></span></pre>


<p>Uncool. There are many ways to do this; here&#8217;s the quickfix you&#8217;ll end up repeating a lot:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">def get_first_person(<span class="hljs-keyword">list</span>):
  <span class="hljs-keyword">try</span>:
    result = <span class="hljs-keyword">list</span>&#91;<span class="hljs-number">0</span>]
    <span class="hljs-keyword">return</span> Ok(result)
  except <span class="hljs-keyword">Exception</span>:
    <span class="hljs-keyword">return</span> Nothing
</code></span></pre>


<p>You&#8217;ll see this implemented in a more re-usable way as <code>nth</code>, except instead of returning <code>None</code>, it&#8217;ll return a <code>Maybe</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">def nth(<span class="hljs-keyword">list</span>, index);
  <span class="hljs-keyword">try</span>:
    result = <span class="hljs-keyword">list</span>&#91;index]
    <span class="hljs-keyword">return</span> OK(result)
  except <span class="hljs-keyword">Exception</span>:
    <span class="hljs-keyword">return</span> Nothing</code></span></pre>


<h2 class="wp-block-heading">Pure Deeply Nested Data Using Lenses</h2>



<p>You know how to make unbreakable functions by making them pure. You know how to access <code>Dictionaries</code> and <code>Lists</code> safely using <code>Maybes</code>.</p>



<p>In real-world applications, you usually get larger data structures that are nested. How does that work? Here&#8217;s some example data, 2 people with address info:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">people = &#91;
  { <span class="hljs-string">'firstName'</span>: <span class="hljs-string">'Jesse'</span>, <span class="hljs-string">'address'</span>: { <span class="hljs-attr">skreet</span>: <span class="hljs-string">'007 Cow Lane'</span> } },
  { <span class="hljs-string">'firstName'</span>: <span class="hljs-string">'Bruce'</span>, <span class="hljs-string">'address'</span>: { <span class="hljs-attr">skreet</span>: <span class="hljs-string">'Klaatu Barada Dr'</span> } }
]</code></span></pre>


<p>Let&#8217;s get the 2nd person&#8217;s address safely using a <code>Maybe</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">def get_second_street(<span class="hljs-keyword">list</span>):
  second_person_maybe = nth(<span class="hljs-keyword">list</span>, <span class="hljs-number">1</span>)
  <span class="hljs-keyword">if</span> isinstance(second_person_maybe, Just):
    address_maybe = get_address( second_person_maybe.value)
    <span class="hljs-keyword">if</span> isinstance(address_maybe, Just):
      street_maybe = get_street(address_maybe.value)
      <span class="hljs-keyword">return</span> street_maybe
  <span class="hljs-keyword">return</span> Nothing</code></span></pre>


<p>Yeahh&#8230;&#8230; no. Gross. Many have taken the time to do this with a better, easier to use API. PyDash has a <code>get</code> method:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">from</span> pydash <span class="hljs-keyword">import</span> <span class="hljs-keyword">get</span>

def get_second_street(list):
  return <span class="hljs-keyword">get</span>(list, '&#91;1].address.skreet')</code></span></pre>


<p>Cool, eh? Works for Dictionaries, Lists, and both merged together.</p>



<p>Except&#8230; one small issue. If it doesn&#8217;t find anything, it returns a <code>None</code>. None will cause runtime Exceptions. You can provide a default as the 3rd parameter. We&#8217;ll wrap it with a <code>Maybe</code>; less good looking, but MOAR STRONG AND PURE.</p>


<pre class="wp-block-code"><span><code class="hljs language-php">def get_second_street(<span class="hljs-keyword">list</span>):
  result = get(<span class="hljs-keyword">list</span>, <span class="hljs-string">'&#91;1].address.skreet'</span>)
  <span class="hljs-keyword">if</span> result is None:
    <span class="hljs-keyword">return</span> Nothing
  <span class="hljs-keyword">return</span> Just(result)</code></span></pre>


<h2 class="wp-block-heading">Returning Errors Instead of Raising Exceptions</h2>



<p> Dictionaries and Arrays not having data is ok, but sometimes things really do break or don&#8217;t work&#8230; what do we do without Exceptions? We return a <code>Result</code>. You have 2 options on how you do this. You can use the <code>Tuple</code>we showed you above, doing it Golang style:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">def ping():
  <span class="hljs-keyword">try</span>:
    result = requests.get(<span class="hljs-string">'https://google.com'</span>)
    <span class="hljs-keyword">if</span> result.status_code == <span class="hljs-number">200</span>:
      <span class="hljs-keyword">return</span> (<span class="hljs-keyword">True</span>, <span class="hljs-string">"pong"</span>, None)
    <span class="hljs-keyword">return</span> (<span class="hljs-keyword">False</span>, None, <span class="hljs-keyword">Exception</span>(f<span class="hljs-string">"Ping failed, status code: {result.status_code}"</span>)
  except <span class="hljs-keyword">Exception</span> <span class="hljs-keyword">as</span> e:
    <span class="hljs-keyword">return</span> (<span class="hljs-keyword">False</span>, None, e)</code></span></pre>


<p>However, there are advantages to use a true type which we&#8217;ll show later in Pipeline Programming. PyMonad has a common one called an <code>Either</code>, but <code>Left</code> and <code>Right</code> make no sense, so I made my own called <code>Result</code> based on JavaScript Folktale&#8217;s Result because &#8220;Ok&#8221; and &#8220;Error&#8221; are words people understand, and associate with functions working or breaking. Left and Right are like&#8230; driving&#8230; or your arms&#8230; or dabbing&#8230; or gaming&#8230; or anything other than programming.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def ping():
  <span class="hljs-keyword">try</span>:
    result = requests.get(<span class="hljs-string">'https://google.com'</span>)
    <span class="hljs-keyword">if</span> result.status_code == <span class="hljs-number">200</span>:
      <span class="hljs-keyword">return</span> Ok(<span class="hljs-string">"pong"</span>)
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Error</span>(Exception(f<span class="hljs-string">"Ping failed, status code: {result.status_code}"</span>))
  except Exception <span class="hljs-keyword">as</span> e:
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Error</span>(e)</code></span></pre>


<p>You don&#8217;t have to put Exceptions in <code>Error</code>; you can just put a String. I like Exception&#8217;s because they have helpful methods, info, stack trace info, etc.</p>



<h2 class="wp-block-heading">Pipeline Programming: Building Unbreakable Programs</h2>



<p>You know how to build <strong>Pure Functions</strong> that don&#8217;t break. You can safely get data that has no guarantee it&#8217;ll be there using <strong>Maybes</strong> and <strong>Lenses</strong>. You can call functions that do side effects like HTTP requests, reading files, or parsing user input strings safely by returning <strong>Results</strong>. You have all the core tools of Functional Programming.. how do you build Functional Software?</p>



<p>By composing functions together. There are a variety of ways to do this purely. Pure functions don&#8217;t break. You build larger functions that are pure that use those pure functions. You keep doing this until your software emerges.</p>



<h3 class="wp-block-heading">Wait&#8230; What do you mean by &#8220;Composing&#8221;?</h3>



<p>If you&#8217;re from an Object Oriented Background, you may think of Composing as the opposite of Inheritance; uses class instances inside of another class. That&#8217;s not what we mean here.</p>



<p>Let&#8217;s parse some JSON! The goal is to format the names of humans from a big ole List of Dictionaries. In doing this you&#8217;ll learn how to compose functions. Although these aren&#8217;t pure, the concept is the same.</p>



<p>Behold, our JSON string:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">peopleString = <span class="hljs-string">""</span><span class="hljs-string">"&#91;
	{
		"</span>firstName<span class="hljs-string">": "</span>jesse<span class="hljs-string">",
		"</span>lastName<span class="hljs-string">": "</span>warden<span class="hljs-string">",
		"</span>type<span class="hljs-string">": "</span>Human<span class="hljs-string">"
	},
	{
		"</span>firstName<span class="hljs-string">": "</span>albus<span class="hljs-string">",
		"</span>lastName<span class="hljs-string">": "</span>dumbledog<span class="hljs-string">",
		"</span>type<span class="hljs-string">": "</span>Dog<span class="hljs-string">"
	},
	{
		"</span>firstName<span class="hljs-string">": "</span>brandy<span class="hljs-string">",
		"</span>lastName<span class="hljs-string">": "</span>fortune<span class="hljs-string">",
		"</span>type<span class="hljs-string">": "</span>Human<span class="hljs-string">"
	}
]"</span><span class="hljs-string">""</span></code></span></pre>


<p>First we must parse the JSON:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def parse_people(json_string):
  <span class="hljs-keyword">return</span> json.loads(json_string)</code></span></pre>


<p>Next up, we need to filter only the Humans in the <code>List</code>, no Dogs.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def filter_human(animal):
  <span class="hljs-keyword">return</span> animal&#91;<span class="hljs-string">'type'</span>] == <span class="hljs-string">'Human'</span></code></span></pre>


<p>And since we have a <code>List</code>, we&#8217;ll use that predicate in the <code>filter</code> function from PyDash:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def filter_humans(animals):
  <span class="hljs-keyword">return</span> filter_(animals, filter_human)</code></span></pre>


<p>Next up, we have to extract the names:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def format_name(person):
  <span class="hljs-keyword">return</span> f<span class="hljs-string">'{person&#91;'</span>firstName<span class="hljs-string">']} {person&#91;'</span>lastName<span class="hljs-string">']}'</span></code></span></pre>


<p>And then do that on all items in the <code>List</code>; we&#8217;ll use <code>map</code> from PyDash for that:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def format_names(people):
  <span class="hljs-keyword">return</span> map_(people, format_name)</code></span></pre>


<p>Lastly, we need to upper case all the names, so we&#8217;ll <code>map</code> yet again and <a href="https://pydash.readthedocs.io/en/latest/api.html#pydash.strings.start_case">start_case</a> from PyDash:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def uppercase_names(people):
  <span class="hljs-keyword">return</span> map_(people, start_case)</code></span></pre>


<p>Great, a bunch of functions, how do you use &#8217;em together?</p>



<h4 class="wp-block-heading">Nesting</h4>



<p>Nesting is the most common.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def parse_people_names(str):
  <span class="hljs-keyword">return</span> uppercase_names(
    format_names(
      filter_humans(
        parse_people(str)
      )
    )
  )</code></span></pre>


<p>Oy&#8230; that&#8217;s why you often hear &#8220;birds nest&#8221; being the negative connotation to describe code.</p>



<h4 class="wp-block-heading">Flow</h4>



<p>While PyDash and Lodash call it <a href="https://pydash.readthedocs.io/en/latest/api.html#pydash.functions.flow">flow</a>, this is the more common way to build larger functions out of smaller ones via composing them, and gives you your first insight into &#8220;pipeline&#8221; style programming.</p>


<pre class="wp-block-code"><span><code class="hljs">parse_people = flow(parse_people, filter_humans, format_names, uppercase_names)</code></span></pre>


<h4 class="wp-block-heading">Pipeline: PyMonad Version</h4>



<p>Now Flow is quite nice, but hopefully you saw some problems. Specifically, none of those functions are super pure. Yes, same input, same output and no side effects&#8230; but what happens when one of them returns a <code>Nothing</code>? When happens if you&#8217;re doing dangerous stuff and one returns a <code>Result</code> that contains an <code>Error</code> instead of an <code>Ok</code>?</p>



<p>Well, each of those types are tailor made to pipe together. You saw how the functions I made for <code>flow</code> worked together; they just needed 3 rules:</p>



<ol class="wp-block-list"><li>be a mostly pure function</li><li>have a single input</li><li>return an output</li></ol>



<p>The <code>Maybe</code> and <code>Result</code> can wired together too, but they have a few extra special features. The only 4 we care about for this article are:</p>



<ol class="wp-block-list"><li>if a <code>Maybe</code> gets a <code>Just</code>, it&#8217;s smart enough to get the <code>Just(thing).value</code> and pass it to the next function. The <code>Result</code> is the same unwrapping the value in the <code>Ok</code> and and passing it to the next function. </li><li>Each expects you to return the same type back. If you chain <code>Maybe</code>&#8216;s together like you do in <code>flow</code>, then it&#8217;s expected you return your <code>Just(thing)</code> or <code>Nothing</code>.</li><li>Both handle bad things. If a chain of <code>Maybe</code>&#8216;s suddenly gets a <code>Nothing</code>, the entire thing will give you a <code>Nothing</code>. If any of the functions you&#8217;ve wired together get a <code>Result</code> and suddenly one gets an <code>Error</code> in the chain, the entire chain gets an <code>Error</code>.  </li><li>They have <code>flow</code> built in; but instead of calling it, you use weird, new, non-Python symbols to confuse you, look impressive, and make the code feel less verbose despite increased brain activity.</li></ol>



<p>That&#8217;s a lot, ignore it. Just look at the example:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def parse_people_names(str):
  <span class="hljs-keyword">return</span> parse_people(str) \
  &gt;&gt; filter_humans \
  &gt;&gt; format_names \
  &gt;&gt; uppercase_names</code></span></pre>


<h3 class="wp-block-heading">Goodbye! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f44b-1f3fc.png" alt="👋🏼" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h3>



<p>If that&#8217;s a bit alien and strange, that&#8217;s because:</p>



<ul class="wp-block-list"><li>you&#8217;re doing Functional Programming in a Object Oriented + Imperative language; you rock!</li><li>&gt;&gt; isn&#8217;t Pythonic nor PEP Compliant®</li><li>Most Python devs see a \ and think &#8220;Aw man, this code is too long&#8230;&#8221;</li><li>&#8220;&#8230; wait, you&#8217;re putting functions there, but not calling them, nor giving them parameters, what in the&#8230;&#8221;</li></ul>



<p>This is why many Functional Programmers are nice even if they are not-so-great evangelists. Many non-FP destined people see that kind of code, freakout and leave. This makes many FP&#8217;ers lonely, thus they are more than happy to be cordial and polite when people talk to them in the programming community.</p>



<h3 class="wp-block-heading">Manual Pipeline</h3>



<p>Remember that nasty example of getting deeply nested properties before you learned Lenses? Let&#8217;s replace that with a pipeline using a <code>Maybe</code>; it&#8217;ll give you a better sense of how these things are wired together, like <code>flow</code> is above.</p>


<pre class="wp-block-code"><span><code class="hljs language-php">def get_second_street(<span class="hljs-keyword">list</span>):
  second_person_maybe = nth(<span class="hljs-keyword">list</span>, <span class="hljs-number">1</span>)
  <span class="hljs-keyword">if</span> isinstance(second_person_maybe, Just):
    address_maybe = get_address( second_person_maybe.value)
    <span class="hljs-keyword">if</span> isinstance(address_maybe, Just):
      street_maybe = get_street(address_maybe.value)
      <span class="hljs-keyword">return</span> street_maybe
  <span class="hljs-keyword">return</span> Nothing</code></span></pre>


<p>Gross. Ok, let&#8217;s start from the top, first we need <code>lastName</code> (btw, I&#8217;m glad you ignored the &#8216;Goodbye&#8217; and are still here, YOU GOT WHAT IT TAKES, OH YEAH):</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def get_second_person(object):
  <span class="hljs-keyword">return</span> nth(object, <span class="hljs-number">1</span>)</code></span></pre>


<p>Cool, next up, get the address:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def get_address(object):
  <span class="hljs-keyword">if</span> <span class="hljs-string">'address'</span> <span class="hljs-keyword">in</span> object:
    <span class="hljs-keyword">return</span> Just(object&#91;<span class="hljs-string">'address'</span>])
  <span class="hljs-keyword">return</span> Nothing</code></span></pre>


<p>Finally, get dat skreet skreet!</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def get_street(object):
  <span class="hljs-keyword">if</span> <span class="hljs-string">'skreet'</span> <span class="hljs-keyword">in</span> object:
    <span class="hljs-keyword">return</span> Just(object&#91;<span class="hljs-string">'skreet'</span>]
  <span class="hljs-keyword">return</span> Nothing</code></span></pre>


<p>Now let&#8217;s compose &#8217;em together.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def get_second_street(object):
  second_person_maybe = get_second_person(object)
  <span class="hljs-keyword">if</span> isinstance(second_person_maybe, Nothing):
    <span class="hljs-keyword">return</span> Nothing

  address_maybe = get_address(second_person_maybe.value)
  <span class="hljs-keyword">if</span> isinstance(address_maybe, Nothing):
    <span class="hljs-keyword">return</span> Nothing

  street_maybe = get_street(address_maybe)
  <span class="hljs-keyword">if</span> isinstance(street_maybe, Nothing)
    <span class="hljs-keyword">return</span> Nothing

  <span class="hljs-keyword">return</span> street_maybe</code></span></pre>


<p>Essh&#8230; ok, let&#8217;s test her out:</p>


<pre class="wp-block-code"><span><code class="hljs">second_street_maybe = get_second_street(people)</code></span></pre>


<p>Note a couple things. Each time you call a function, you then inspect if the return value is a <code>Nothing</code>. If it is, you immediately just return that and stop running everything else. Otherwise, you call the next one in the chain and unwrap the value. Here we&#8217;re doing that manually via <code>maybe.value</code>. Also, the <code>return street_maybe</code> at the end is a bit redundant; no need to check for <code>Nothing</code> there, just return it, but I wanted you to see the repeating pattern 3 times.</p>



<p>That pattern is what the <code>&gt;&gt;</code> does for you: checks for <code>Nothing</code> and aborts early, else unwraps the value and gives to the function in the chain. Rewriting it using that bind operator:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def get_second_street(object):
  <span class="hljs-keyword">return</span> get_second_person(object) \
  &gt;&gt; second_person_maybe \
  &gt;&gt; get_address \
  &gt;&gt; get_street</code></span></pre>


<p>It&#8217;s easy to forget the \. This is because Python is super strict on whitespace and only occasionally lets you do line breaks with code. </p>



<p>If you don&#8217;t want to use that, just put her all on 1 line:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def get_second_street(object):
  <span class="hljs-keyword">return</span> get_second_person(object) &gt;&gt; second_person_maybe &gt;&gt; get_address &gt;&gt; get_street</code></span></pre>


<h3 class="wp-block-heading">Manual Result Pipeline</h3>



<p>Let&#8217;s do some dangerous shit. We&#8217;re going to load our encryption key from AWS, then fetch our OAuth token, then load in a list of Loan products from an API that requires that token to work, and finally snag off just the ID&#8217;s.</p>



<p>Dangerous stuff? Potential Exceptions? A job for <code>Result</code>.</p>



<p>Get dat key:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def get_kms_secret():
  <span class="hljs-keyword">try</span>:
    result = client.generate_data_key(
      KeyId=<span class="hljs-string">'dev/cow/example'</span>
    )
    key = base64.b64decode(result&#91;<span class="hljs-string">'Plaintext'</span>]).decode(<span class="hljs-string">'ascii'</span>)
    <span class="hljs-keyword">return</span> Ok(key)
  except Exception <span class="hljs-keyword">as</span> e:
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Error</span>(e)</code></span></pre>


<p>Don&#8217;t worry if you don&#8217;t know what the heck <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/kms.html#KMS.Client.generate_data_key">KMS</a> is, it&#8217;s just Amazon&#8217;s encryption stuff, and gives you keys that you&#8217;re only allowed to get. If you&#8217;re not, that function will fail. It just gives us a temporary private encryption key as text. We&#8217;ll use that to get our OAuth token.</p>



<p>Next up, get our OAuth token via the <a href="https://requests.readthedocs.io/en/master/">requests</a> library:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def get_oauth_token(key):
  <span class="hljs-keyword">try</span>:
    response = requests.post(oauth_url, json={<span class="hljs-string">'key'</span>: key})
    <span class="hljs-keyword">if</span> response&#91;<span class="hljs-string">'status_code'</span>] == <span class="hljs-number">200</span>:
      <span class="hljs-keyword">try</span>:
        token_data = response.json()
        <span class="hljs-keyword">return</span> Ok(token_data&#91;<span class="hljs-string">'oauth_token'</span>])
      except Exception <span class="hljs-keyword">as</span> parse_error:
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">Error</span>(parse_error)
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Error</span>(Exception(response.text))
  except Exception <span class="hljs-keyword">as</span> e:
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Error</span>(e)</code></span></pre>


<p>You have a style choice here. If you look above, there are 4 potential failures: status code not being a 200, failing to parse the JSON, failing to find the oauth token in the JSON you parsed, or a networking error. You can just &#8220;handle it all in the same function&#8221; like I did above. The point of mashing it together is &#8220;Did I get a token or not?&#8221;. However, if you don&#8217;t like the nested <code>ifs</code> and <code>trys</code> then you can split that into 4 functions, each taking a <code>Result</code> as well to wire them together in order.</p>



<p>Now that we have our token, let&#8217;s call the last API to get a list of Loan products. We&#8217;ll get a list potentially, but all we want is the id&#8217;s, so we&#8217;ll map to pluck those off:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">def get_loan_ids(token):
  <span class="hljs-keyword">try</span>:
    auth_header = {<span class="hljs-string">'authentication'</span>: f<span class="hljs-string">'Bearer {token}'</span>}
    response = requests.get(loan_url, headers=auth_header)
    <span class="hljs-keyword">if</span> response.status_code == <span class="hljs-number">200</span>:
      <span class="hljs-keyword">try</span>:
        loans = response.json()
        ids = map_(loans, lambda loan: get(loan, <span class="hljs-string">'id'</span>, <span class="hljs-string">'???'</span>))
        <span class="hljs-keyword">return</span> Ok(ids)
      except <span class="hljs-keyword">Exception</span> <span class="hljs-keyword">as</span> e:
        <span class="hljs-keyword">return</span> Error(e)
    <span class="hljs-keyword">return</span> Error(<span class="hljs-keyword">Exception</span>(response.text))
  <span class="hljs-keyword">exception</span> <span class="hljs-keyword">Exception</span> <span class="hljs-keyword">as</span> overall_error:
    <span class="hljs-keyword">return</span> Error(overall_error)</code></span></pre>


<p>If everything goes well, you&#8217;ll get a list of strings. Otherwise, and Error. Let&#8217;s wire all 3 up:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def get_loan_ids():
  <span class="hljs-keyword">return</span> get_kms_secret() \
  &gt;&gt; get_oauth_token \
  &gt;&gt; get_loan_ids</code></span></pre>


<p>When you go:</p>


<pre class="wp-block-code"><span><code class="hljs">loan_ids_result = get_load_ids()</code></span></pre>


<p>Either it works, and that <code>loan_ids_result</code> is an <code>Ok</code>, or it failed somewhere in there and it&#8217;s an <code>Error</code> containing the Exception or error text.</p>



<p>&#8230; now, one cheat I did, and you&#8217;re welcome to mix and match <code>Maybes</code> and <code>Results</code> together. You see when we attempt to get the loan id?</p>


<pre class="wp-block-code"><span><code class="hljs language-php">get(loan, <span class="hljs-string">'id'</span>, <span class="hljs-string">'???'</span>)</code></span></pre>


<p>That 3rd parameter is a default value if the property isn&#8217;t there or is <code>None</code>. The _right_ thing to do is use a <code>Maybe</code> instead. You can be pragmatic like this if you wish, just be aware, these are the types of things you&#8217;ll see where &#8220;the code has no errors but doesn&#8217;t work&#8221; <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f92a.png" alt="🤪" class="wp-smiley" style="height: 1em; max-height: 1em;" />.  Also, I tend to like <code>Errors</code> more than <code>Nothing</code> in these scenarios because they give you an opportunity to provide an Exception or text with a lot of context as to WHY. Why is huge for a programmer, especially when you&#8217;re close to the error and know why it probably failed in a large set of functions that could all possibly break. </p>



<h2 class="wp-block-heading">Conclusions</h2>



<p>Functions are fine, but Exceptions can cause a lot of indirection. Meaning, you think you know the 3 ways a function, or even a program can fail, but then another unexpected Exception comes from some other deeply nested function. Completely removing these, and locking down the ones you know, or don&#8217;t know, will blow up using <code>try/catch</code> via <strong>pure functions</strong> removes that problem for you. You now know for a fact what paths your functions take. This is the power of pure functions.</p>



<p>However, that doesn&#8217;t protect you from using null (i.e. <code>None</code>) data. You&#8217;ll get all kinds of runtime Exceptions in functions that were expecting good data. If you force all of your functions to handle that eventuality via <strong>Maybes</strong>, then you never get null pointers. This includes using <strong>Lenses</strong> to access deeply nested data.</p>



<p>Once you go outside of your program via side effects such as making REST calls, reading files, or parsing data, things can go wrong. Errors are fine, and good, and educational. Having a function return a <strong>Result</strong> instead of raising an <code>Exception</code> is how you ensure the function is pure. You can also abort early if there is a problem vs having cascading effects with other functions not having their data in a state they need. You also, much like <a href="https://golang.org/">Golang</a> and <a href="https://www.rust-lang.org/">Rust</a>, have the opportunity to document what the error is where it happens with helpful context vs. guessing at a long stack trace.</p>



<p>Finally, once you&#8217;ve written pure functions, you can build larger pure functions that compose those together. This is how you build pure software via <strong>pipeline programming</strong> (also called <a href="https://fsharpforfunandprofit.com/rop/">railroad programming</a>, a style of streaming, etc).</p>



<p>Python provides the <a href="https://pydash.readthedocs.io/en/latest/api.html">PyDash</a> library to give you the basics of pure functions with working with data and lists. <a href="https://pypi.org/project/PyMonad/">PyMonad</a> provides the basics in creating <code>Maybe</code> and <code>Either</code> (what I call Result). If you&#8217;re interested, there is the <a href="https://coconut.readthedocs.io/en/latest/">Coconut programming language</a> that integrates and compiles to Python, allowing you to write in a more Functional Programming style.  Here&#8217;s a taste re-writing our example above:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">def get_loan_ids():
  <span class="hljs-keyword">return</span> get_kms_secret()
  |&gt; get_oauth_token
  |&gt; get_loans
  |&gt; map( .id )</code></span></pre>


<p>Don&#8217;t fret if all of this seems overwhelming. Functional Programming is a completely different way of thinking, Python is not a functional language, and these are all super advanced concepts I just covered the basics of. Just practice the pure functions and writing tests for them. Once you get the basics of that, you&#8217;ll start to get a feel, like a <a href="https://sixthsensereader.org/about-the-book/abcderium-index/spidey-sense/">Spidey Sense,</a>  of when something is impure and has side effects. With Maybes, you&#8217;ll love them at first, then realize once you start using them responsibly, how much extra work you have to do to avoid null pointers. Eithers/Results can be challenging to debug at first as you won&#8217;t be wading through stacktraces, and you learn what error messages are best to write, and how to capture various failures. Stick with it, it&#8217;s ok if you use only a little; the little you use will still help your code be more solid.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2020/03/write-unbreakable-python.html/feed</wfw:commentRss>
			<slash:comments>17</slash:comments>
		
		
			</item>
		<item>
		<title>React Redux Thunk vs Elm</title>
		<link>https://jessewarden.com/2019/10/react-redux-thunk-vs-elm.html</link>
					<comments>https://jessewarden.com/2019/10/react-redux-thunk-vs-elm.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Sat, 05 Oct 2019 19:20:44 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[elm]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[react]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5848</guid>

					<description><![CDATA[Introduction It’s a bit easier to learn Elm if you compare it to things you know. If you know React and Redux, then comparing them can help a lot to understand Elm concepts. I’ve built the same application in React Redux Thunk and Elm so we can compare them together. The end result is a [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Introduction</h2>



<p>It’s a bit easier to learn Elm if you compare it to things you know. If you know React and Redux, then comparing them can help a lot to understand Elm concepts. I’ve built the same application in React Redux Thunk and Elm so we can compare them together. The end result is a table of things you can paginate through. Comparing these 2 applications is apples to apples. They’re identical to the end user. Yet the technologies behind them are apples to oranges. Seeing those deviations using familiar tech in the same application can help your understanding.</p>



<span id="more-5848"></span>



<p>Below, I&#8217;ve linked to both applications code bases which you can download and run locally if you wish.</p>



<p><a href="https://github.com/JesterXL/react-vs-elm-react-redux-thunk">Company Dashboard Code &#8211; React Redux Thunk</a></p>



<p><a href="https://github.com/JesterXL/react-vs-elm-elm">Company Dashboard Code &#8211; Elm</a></p>



<h2 class="wp-block-heading">What is React, Redux, Thunk, and Elm?</h2>



<p><a href="https://reactjs.org/">React</a> is a JavaScript library that allows you to ensure your HTML and CSS are in sync with your data. You use this to build single page web applications.</p>



<p><a href="https://redux.js.org/">Redux</a> is a library that allows you have a single variable for your data model. This ensures your applications are predictable and testable. It is the core of the Elm architecture and is often used in React.</p>



<p><a href="https://github.com/reduxjs/redux-thunk">Thunk</a> is a library that allows your Redux actions to be asynchronous.</p>



<p><a href="https://elm-lang.org/">Elm</a> is a functional programming language, compiler, repl, package manager, and a set of libraries to build single page applications. You write in Elm and it compiles to <a href="https://en.wikipedia.org/wiki/JavaScript">JavaScript</a>.</p>



<h2 class="wp-block-heading">Building and Compiling React</h2>



<p>You build React applications using <a href="https://nodejs.org/en/">Node.js</a>. Using a package manager like <a href="https://yarnpkg.com/lang/en/">Yarn</a> or <a href="https://www.npmjs.com/">npm</a> to install libraries, and run commands to test and build your application for production. Yarn and Node utilize npm, the Node Package Manager, to install libraries and interface with Node. Yarn is used mainly because it has advanced features that npm doesn&#8217;t have, and it can yield more deterministic installs and builds compared to npm. Front-end applications tend to have more libraries than back-end Node API ones. Yarn is used more often in React given it&#8217;s front-end. The source of truth is usually a <code>package.json</code>, a JSON file that contains all the libraries to be installed and commands needed to test and build the application. This holds true whether the application is regular JavaScript, using advanced <a href="https://www.freecodecamp.org/news/write-less-do-more-with-javascript-es6-5fd4a8e50ee2/">ES6</a> features, using advanced compilation tools like <a href="https://babeljs.io/">Babel</a> and <a href="https://webpack.js.org/">Webpack</a>, and/or utilizing typed languages like as <a href="https://flow.org/">Flow</a> and <a href="http://www.typescriptlang.org/">TypeScript</a>.</p>



<p>The easiest way to build them at the time of this writing is using <a href="https://github.com/facebook/create-react-app">create-react-app</a>, which abstracts most of the compilation and build toolchain away into simple commands with updates being usually as simple as updating the <code>react-scripts</code> library.</p>



<p>Like Elm, React can compile to simple components embedded in other web applications. It can also compile too large, single page applications.</p>



<h2 class="wp-block-heading">Building and Compiling Elm</h2>



<p>For simple applications, Elm the language is compiled to JavaScript and HTML through the Elm compiler via <code>elm make</code>. For more advanced applications, the compiler will output just JavaScript that you embed in your HTML. Libraries are installed through <code>elm install</code> and written in <code>elm.json</code>. While there is a local web server called <code>elm reactor</code>, it lacks many basic features such as auto-refresh that many other JavaScript tools have. Use elm-live instead.</p>



<p>Like React, you&#8217;ll use Node, npm, and/or yarn to various degrees of complexity.  Like React, Elm can compile to simple components embedded into other web applications. Elm can also be used to build large, single page applications. The common ways to build at the time of this writing is create-elm-app which isn&#8217;t very friendly behind corporate proxies, and the simpler <a href="https://github.com/wking-io/elm-live">elm-live</a>. If you&#8217;re not on a corporate network, <a href="https://github.com/halfzebra/create-elm-app">create-elm-app</a> is also an option.</p>



<p>Although Elm is fully featured, it&#8217;s still missing features native to JavaScript. As such you&#8217;ll sometimes interface with JavaScript. At the time of this writing for Elm version 0.19.0, this includes binary file upload, and application storage to name just two. This ensures you can benefit from Elm&#8217;s features, but not have to wait on them or the open source community to build Elm versions of those features.</p>



<h2 class="wp-block-heading">HTML in React</h2>



<p><a href="https://en.wikipedia.org/wiki/HTML">HTML</a> in React is rendered by React via <a href="https://reactjs.org/docs/introducing-jsx.html">JSX</a>. They handle all the efficient ways of updating it, the cross-browser challenges, etc. All you do is provide a function or class with a render function that returns this JSX.</p>



<p><code>const Message = () =&gt; (&lt;div&gt;Sup&lt;/div&gt;)</code></p>



<p>Then you can use this &#8220;component&#8221; like a normal HTML tag in your other React JSX:</p>



<p><code>&lt;Message /&gt;</code></p>



<p>React became popular with functional programmers because it was basically a pure function for the DOM. A pure function is a function that always outputs the same thing if you give it the same arguments with no side effects. You give the <code>Message</code> component above an Object, and React will render the same DOM each time. This input in React is called &#8220;props&#8221; or properties.</p>



<p><code>const Message = props =&gt; (&lt;div&gt;Sup {props.name}&lt;/div&gt;</code></p>



<p>Whenever that <code>props.name</code> value changes, so too will the HTML React renders. You can embed JavaScript or just values like the above using the squiggle braces ({}). There are a variety of rules that make JSX not exactly like HTML. There are a host of them, but examples include event objects are a custom copy to prevent certain bugs, and using <code>onClick</code> instead of <code>onclick</code> for events. That said, React has done a great job to make it feel and work like you&#8217;d expect HTML to work.</p>



<h2 class="wp-block-heading">HTML in Elm</h2>



<p>Everything in Elm is a function. HTML is no different. Each HTML element has a corresponding function name. All HTML elements typically have attributes and contents. Below, the <code>div</code> tag has a style attribute and text contents:</p>



<p><code>&lt;div style="color: red;"&gt;Sup&lt;/div&gt;</code></p>



<p>In Elm, you&#8217;d import and use the <code>div</code>, <code>style</code>, and <code>text</code> functions to accomplish the same thing:</p>



<p><code>div [ style "color" "red"] [ text "Sup" ]</code></p>



<p>Elm functions do not use commas, and parenthesis are optional in most cases. Above the <code>div</code> function takes 2 list arguments, the style function 2 string arguments, and text 1 string. Rewritten in JavaScript that&#8217;d be:</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">div</span>(<span class="hljs-selector-attr">&#91;style(<span class="hljs-string">'color'</span>, <span class="hljs-string">'red'</span>)]</span>, <span class="hljs-selector-attr">&#91;text(<span class="hljs-string">'Sup'</span>)]</span>)</code></span></pre>


<h2 class="wp-block-heading">Working With CSS in React</h2>



<p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS">Cascading Style Sheets</a> have a lot of different ways of working in React depending on what you&#8217;re building, and the team&#8217;s style. Component based styles have risen in popularity in React. The first reason for this is it&#8217;s easier for modern tools to &#8220;only compile what you use&#8221;; if you don&#8217;t use the component, it won&#8217;t compile the CSS in. Larger websites that have accrued many shared styles from many teams over years have this issue. Since the tools aren&#8217;t very good to ensure modifying styles doesn&#8217;t break something else unintentionally, teams end up adding new styles of their own to prevent breakage which just adds to the file size and speed slow down despite not being inline. The second reason for this is co-location. The styles that handle the component are right next to it; you don&#8217;t have to hunt around various css, sass, or externalized html template files to &#8220;piece together&#8221; how a component is supposed to look.</p>



<p>React supports normal <code>className</code> attributes to emulate how the <code>class</code> attribute works. You can also use <code>style</code> create CSS through JavaScript Objects. This is popularized by the &#8220;CSS-in-JS&#8221; movement, and keeps your styles co-located to the components they are affecting. There are libraries that take this concept to the nth degree such as <a href="https://emotion.sh/docs/introduction">Emotion</a>. Teams will either standardize on one approach depending on team make up, and/or use a multitude depending upon what they&#8217;re building and interfacing with. Beyond the <code>className</code> and <code>style</code> attributes for JSX, React&#8217;s version of HTML, React doesn&#8217;t prescribe how you handle CSS.</p>



<p>Styling with <code>className</code>:<br><code>&lt;div className="textColor"&gt;Sup&lt;/div&gt;</code></p>



<p>Styling with <code>style</code>:<br><code><code><code><br>const myStyles = {<br>  color: 'red'<br>}<br>&lt;div style={myStyles}&gt;Sup&lt;/div&gt;</code></code></code></p>



<h2 class="wp-block-heading">Working with CSS in Elm</h2>



<p>Elm, like React, doesn&#8217;t prescribe a way how you handle CSS. Elm&#8217;s version of HTML is functions. There is a function for each html element. If you&#8217;re adding styles to a <code>div [] []</code>, then you&#8217;d go <code>div [ style "color" "red"] []</code>. If you want to use a css class, you&#8217;d go <code>div [ class "textColor" ] []</code>.</p>



<p>The only modification is if you wish to have stronger compiler help with your CSS, you can use the <a href="https://github.com/rtfeldman/elm-css">elm-css</a> library. The normal Elm style function doesn&#8217;t give you much help from the compiler given both arguments are strings. The elm-css library on the other hand ensures both types and argument order which really makes the most of the Elm compiler.</p>



<h2 class="wp-block-heading">Coding in React</h2>



<p>In React, you typically write in JavaScript. It&#8217;s a dynamic, interpreted language that is native in all browsers. Dynamic means you can change a variable that is a number to string or any type you want. Interpreted means you can write some code, put in the browser, and it&#8217;ll run. You do not need to compile yourself. The browser handles converting that to machine code that it can run quickly. You can debug the code, in the browser, using both logs and breakpoints which stop the code from running and allow you to step through each part line by line.</p>



<p>This also means that most styles of programming are supported. This includes Imperative, Object Oriented, and Functional. Imperative being many lines of code in a file that run from top to bottom in a procedural way. Object Oriented mean classes that encapsulate state, message passing, and a variety of design patterns.  Functional meaning pure functions.</p>



<p>React allows both CSS and HTML to be written in JavaScript. This means that everything that makes up the visual elements on the screen can be put right next to each other, giving you a clearer picture of how each visual thing works. Sometimes. </p>



<p>The pros of a dynamic language are speed of development. You can quickly play with new ideas using only a little code. You don&#8217;t need any tools to make it work beyond a web browser. If you need a server, you can write the same language, JavaScript, to make Node do this for you.</p>



<h3 class="wp-block-heading">Prop Types</h3>



<p>The cons of a dynamic language is you have to run it to know if it works. While running can be fast, sometimes you have to click through the UI to trigger some part of the code, and that process isn&#8217;t that fast, or is tediously manual. Many tools can automate these kind of checks. For UI development in the browser, this is often verifying the components attributes (their inputs) and their events (change handlers).</p>



<p><code>&lt;CrayButton label={datText} onGo={clickHandler} /&gt;</code></p>



<p>However, you won&#8217;t know if <code>datText</code> is actually a String, nor if <code>clickHandler</code> is a Function with proper scoping and no negative down stream effects till you actually test it. To help a bit with these problems, React has <code>propTypes</code> which has a bit of runtime type checking. You still have to run the code, and it only works in development mode, BUT it quickly aborts the code with correct errors vs. errors which may not be clear what went wrong.</p>


<pre class="wp-block-code"><span><code class="hljs">CrayButton.propTypes = {
  label: PropTypes.string,
  onGo: PropTypes.func
}</code></span></pre>


<h3 class="wp-block-heading">Flow or TypeScript</h3>



<p>Computers are much better than humans at finding, storing, and quickly accessing large amounts of numbers. For code, there are many different paths that could happen, and compilers are good at quickly verifying if your code is going to work or not in milliseconds to microseconds. One of the ways they do this is through types. You write in a different language entirely, then the compiler will convert it to JavaScript. Like the <code>propTypes</code> above, except the code won&#8217;t actually compile if it finds errors. Once you fix all the errors, it&#8217;ll then compile. The theory is in the little time it takes you to add types to the code, the compiler can find errors in microseconds to minutes. These milliseconds/minutes are supposed to be much shorter than the time it takes you to track down bugs.</p>



<p><a href="https://flow.org/">Flow</a> and <a href="http://www.typescriptlang.org/">TypeScript</a> both offer really nice types with the ability to integrate with existing JavaScript and libraries. If a library was coding in JavaScript, many will offer TypeScript definitions which give the public API functions it exposes types. This allows TypeScript to offer type checking on it even though the library is JavaScript and has no types. For large codebases that already exist, including libraries, it&#8217;s much easier to create a definition file.</p>



<p>The create-react-app generator offers a TypeScript option, again abstracting away all the work to setup and maintain the compiler. The TypeScript/Flow flexibility, however, means that you have less guarantees that when your code actually compiles, it&#8217;ll work. Flow and TypeScript both compile to JavaScript, and have no runtime type checking.</p>



<h2 class="wp-block-heading">Coding in Elm</h2>



<p>In Elm, you write in the Elm language. It is functional and strongly typed. Functional means pure functions with no side effects. In fact, you cannot create side effects at all in Elm. The Elm framework handles all side effects for you. Everything from creating HTML to REST calls are simply pure functions. The types use Haskell style Hindly-Milner types. You put the function&#8217;s input(s) and output up top, and that&#8217;s all the compiler needs. This as opposed to TypeScript and ReasonML for example, where you put next to the variables at the end of the function. The function below is a simple add function, taking in 2 numbers, and returning whatever they are added together.</p>


<pre class="wp-block-code"><span><code class="hljs">add : Int -&gt; Int -&gt; Int
add first second = first + second</code></span></pre>


<p>That said, the compiler is pretty smart, so you can omit them and it&#8217;ll &#8220;know what you meant&#8221;.</p>


<pre class="wp-block-code"><span><code class="hljs">add first second = first + second</code></span></pre>


<p>In JavaScript, that&#8217;d be:</p>



<p><code>add = (first, second) =&gt; first + second</code></p>



<p>&#8230; sort of. Since all Elm functions are curried by default, a more accurate JavaScript representation would be:</p>



<p><code>add = first =&gt; second =&gt; first + second</code></p>



<p>Unlike Flow or TypeScript, Elm ensures when it compiles, you will not get any null pointer exceptions. There are only 2 ways to break this guarantee. The first is integrating with JavaScript through ports and you aren&#8217;t careful, or you are, but the JavaScript is just obnoxious. The second way is in development mode sending large amounts of text into the <code>Debug.log</code> function, using all of the browser&#8217;s memory.</p>



<p>As a functional language, there are no exceptions. This means all <code>Error</code>&#8216;s are return values. More on error handling below.</p>



<p>In React, it&#8217;s not uncommon to see functions, classes, strings, numbers, modules, and images all in the same code base. In Elm, everything is a function or a type.</p>



<h2 class="wp-block-heading">Side Effects in JavaScript</h2>



<p>In JavaScript, you have control over some side effects. You can even create them yourself. This includes logging to the console, creating HTTP requests, reading from various storage locations such as files, listening for push requests on web sockets, various events from user interactions such as mouse clicks, and when the browser URL changes.</p>



<p>The ways these work varies from return values, callbacks, event handlers, to Promises. Some of these have built-in error handling and some do not.</p>



<p>To parse JSON from an outside source, it does a return value. If it fails, it&#8217;ll throw an exception you catch via <code>try/catch</code>.<br><code>result = JSON.parse('{"sup": "yo" }')</code> </p>



<p>To listen to mouse events in React, it&#8217;s common to use inline callbacks:</p>


<pre class="wp-block-code"><span><code class="hljs language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> console.log("Clicked, sucka!")}&gt;Sup<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></code></span></pre>


<p>However, you can do it the event based way as well. We use a class method below so it can be cleaned up later.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">theButton.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-keyword">this</span>.clickHandler)</code></span></pre>


<p>Many newer API&#8217;s offer Promises, and Promises have built-in try/catch. Here&#8217;s how to make an HTTP GET request using <code>fetch</code> which returns a Promise:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">fetch(someURL)
.then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.json())
.then(<span class="hljs-function"><span class="hljs-params">json</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"json is:"</span>, json))
.catch(<span class="hljs-built_in">console</span>.log)</code></span></pre>


<p>When unit testing, you&#8217;ll typically either mock the concretes using something like <a href="https://sinonjs.org/">Sinon</a> or <a href="https://github.com/testdouble/testdouble.js/">Test Double</a> to make the code more predictable. If you&#8217;re using functional style, you&#8217;ll pass in the module/class as one of the function parameters, and then a stub in your unit tests.</p>



<h2 class="wp-block-heading">Side Effects in Elm</h2>



<p>All side effects in Elm, with the exception of <code>Debug.log</code> in development, and JavaScript ports, are handled by Elm itself. You cannot create side effects in Elm. You merely create functions that return data. The Elm Architecture handles the actual side effects, allowing all of your code to be pure. We&#8217;ll talk more about how you get actual things done in the Elm Architecture section below. For now, just know that you can make the Elm Architecture create and handle side effects via one of the 3:</p>



<ol class="wp-block-list"><li>Messages (think onClick + Redux Action Creator)</li><li>Commands (think Redux Action Creator)</li><li>Subscriptions (think Thunks or Sagas triggered from <code>window.onlocationchange</code> or web sockets)</li></ol>



<h2 class="wp-block-heading">Closures in React</h2>



<p>Closures are a way for functions inside of functions retain scope and values. It&#8217;s mainly used for OOP developers to have hack around <code>this</code> changing.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">someMethod</span>(<span class="hljs-params">input</span>) </span>{
  <span class="hljs-keyword">const</span> me = <span class="hljs-keyword">this</span>;
  $(<span class="hljs-string">'.thing'</span>).click(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> me.otherMethod())
}</code></span></pre>


<p>It also allows JavaScript developers to have more predictable state, especially with asynchronous code:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">let</span> state = <span class="hljs-string">'ready'</span>
<span class="hljs-keyword">const</span> loadData = <span class="hljs-function"><span class="hljs-params">url</span> =&gt;</span> {
  state = <span class="hljs-string">'loading'</span>
  fetch(url)
  .then(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
    state = <span class="hljs-string">'done'</span>
  })
  .catch(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
    state = <span class="hljs-string">'error'</span>
  })</code></span></pre>


<p>They also can play an important role of reducing how many parameters your functions need as the inner functions can just access the outer/wrapping function values. They play pivotal role in how curried functions work in JavaScript. For asynchronous code such as nested callbacks and Promises, they can significantly help in reducing the code size, and keeping track of asynchronous processes in 1 place.</p>



<p>For React, they&#8217;re the primary way you utilize Hooks.</p>



<h2 class="wp-block-heading">Closures in Elm</h2>



<p>Closures in Elm work differently. While you can nest functions, and have inner functions access outer function parameters:</p>


<pre class="wp-block-code"><span><code class="hljs">-- note we're referencing model.label inside the button function
view model =
  div &#91;] &#91;
    button model.label
  ]</code></span></pre>


<p>&#8230;they do not propagate &#8220;later&#8221;. Since there is no async in Elm, you cannot &#8220;keep things around&#8221; long after a function has finished executing like you&#8217;d normally do in JavaScript with the exception of partial applications.</p>



<p>For example, if you&#8217;re doing many of the same HTTP calls on the client, they could come back in different orders. Often you&#8217;ll give each a different id so you can tell which call was which, and in what order it was sent. This allows you to do different versions of queues and concurrency. If you&#8217;re refreshing a table over and over, you may make 5 calls one after the other, but you really only care about the last one.  In a chat for example, you actually care about FIFO, first in first out. You want to ensure you&#8217;ve handled all the calls in order to the best of your ability, and want to ensure the chat messages show in order assuming you&#8217;re lacking a timestamp to order them. </p>



<p>That control of state in JavaScript allows you to add a unique identifier using closures. Here is how you create a correlation ID in some JavaScript <code>fetch</code> code:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> load = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
  <span class="hljs-keyword">const</span> correlationID = uuidv4()
  <span class="hljs-keyword">return</span> fetch(url, {<span class="hljs-attr">headers</span>: {<span class="hljs-string">'x-correlation-id'</span>: correlationID })
  .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.json())
  .then(<span class="hljs-function"><span class="hljs-params">json</span> =&gt;</span> (&#91; json, correlationID ]) )
}</code></span></pre>


<p>In Elm, you could reference the <code>correlationID</code> above in the request, but NOT in the response like you can in JavaScript. Since the actual side effect is handled by the framework, you&#8217;d have to user their built in <a href="https://package.elm-lang.org/packages/elm/http/latest/Http#request">trackers</a>. The Elm API > v0.19.0 at the time of this writing is still figuring out how to handling concurrency for a variety of things. </p>



<h2 class="wp-block-heading">Errors in React</h2>



<p>Like <a href="https://dart.dev/">Dart</a> and <a href="https://angularjs.org/">Angular</a> before it, React really has done some interesting things with Error handling. The first was <a href="https://reactjs.org/docs/error-boundaries.html">error boundaries</a>. Anyone who&#8217;s built UI&#8217;s knows that handling errors when drawing things is rough. Doing it in an async way is even harder since it&#8217;s hard to track where and when it may have occurred. Building errors into the components was a great first step in ensuring a single error didn&#8217;t bring down a whole application. Using throw in <a href="https://github.com/acdlite/react-fiber-architecture">Fiber</a>, their architecture that builds their own call stack, they can create <a href="https://overreacted.io/algebraic-effects-for-the-rest-of-us/">Algebraic Effects</a>. This means errors can be resumed safely from anywhere. </p>



<p>That said, errors in React are basically errors in JavaScript. They have tons of problems.</p>



<p>First, they aren&#8217;t pure. Pure functions have no side effects. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">Errors</a>, even in the browser, cause side effects. They can put code currently, or later, into an unknown state. This could be from synchronous UI code, asynchronous <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">WebWorkers</a>, or some 3rd party library you&#8217;re not even sure is involved. If your web application has monitoring such as <a href="https://www.catchpoint.com/">Catchpoint</a>, you can get a text message at 3am because of an uncaught null pointer. Thus, they&#8217;re hard to predict and make your code flaky.</p>



<p>Second, JavaScript doesn&#8217;t really have good error handling facilities. They make it really easy to hurt yourself, the code, and the browser (or Node.js). Some languages languages such as Java have <code>throwable</code>. If a function has that, the compiler forces you to catch it. JavaScript has no such facilities, and is interpreted so you don&#8217;t know about errors until you run the code, see them, and get screwed over by them. Adding try/catch everywhere is not fun to write, nor read, and slows your code down. The asynchronous ones are a bit better in that <code>catch</code> on Promises only has to be written once, but with the popularity of <code>async</code> <code>await</code> syntax, people forego even writing those. They let explosions happen there uncaught as well. The <code>window.onerror</code> is a strange method with various browser support intricacies that can sometimes affect how bad the crash is based on what you return. This is still great to have it, but it has the same thing in common with <code>try</code> <code>catch</code> and the <code>catch</code> on a Promise: you can screw those up, and cause another error with no language/compiler support.</p>



<p>Third, the stack traces aren&#8217;t always accurate to what&#8217;s going on. They&#8217;ve greatly improved over the years since I abandoned Flash Player for JavaScript. Still, errors don&#8217;t always originate from the exact line of code that caused the error, or do but say something inaccurate to what&#8217;s actually causing the problem.</p>



<h2 class="wp-block-heading">Errors in Elm</h2>



<p>Elm doesn&#8217;t throw errors, that&#8217;s one of the draws of using it. Instead, if a function can fail, you return a <a href="https://package.elm-lang.org/packages/elm/core/latest/Result">Result</a>. The compiler will ensure you&#8217;re handling it correctly. There are a few types that you can chain together like Promises such as <a href="https://package.elm-lang.org/packages/elm/core/latest/Maybe">Maybe</a> and Result. If they fail, you handle the error in 1 place. These errors are return values and do not negatively affect the rest of your program.</p>



<p>If you&#8217;re in debug mode and send too much text, you can use all of the browser&#8217;s available memory and crash the program that way. Elm will not compile for production builds unless logs are removed.</p>



<p>If you&#8217;re using 3rd party JavaScript libraries on the page, or using ports with volatile JavaScript, they will also crash your program.</p>



<h2 class="wp-block-heading">Redux in React</h2>



<p><a href="https://redux.js.org/">Redux</a> is a framework inspired by Elm to help bring predictability to larger React applications. At some point when you outgrow <a href="https://reactjs.org/docs/context.html">Context</a>, or just want the predictability that Functional Programming can bring, you reach for Redux. It ensures only 1 variable is in your entire application, and that 1 variable is all the data your application needs. You can use the <a href="https://github.com/zalmoxisus/redux-devtools-extension">Redux Dev tools</a> to see your data change over time and clearly see the state changes, the order, and how they affect your UI. Since React components are pure functions that take in props and render DOM, Redux scales this concept for for the data.</p>



<p>Below is a crash course in Redux. You are welcome to skip it. I include it here for those who do not know Redux very well, nor why you even use it. Knowing how Redux works helps you understand how Elm works since they&#8217;re based on the same ideas.</p>



<h3 class="wp-block-heading">Reducers</h3>



<p>In Redux you have <code>store</code>; this is the main variable that stores your data. You get it via <code>store.getState()</code> and change it via <code>store.dispatch({action})</code>. The dispatch will call you reducers, or a function that takes in the state and the action. If you know the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">Array.reduce</a> function, it&#8217;s the same thing. It&#8217;s assumed that your reducers do not mutate data, and simply return a copy of the store with whatever changes you need. Updating a person&#8217;s name for example would go like this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> firstNameReducer = <span class="hljs-function">(<span class="hljs-params">person, action</span>) =&gt;</span> ({ ...person, <span class="hljs-attr">firstName</span>: action.firstName })</code></span></pre>


<p>If I pass in <code>firstNameReducer( { firstName: 'cow' }, { type: 'updateFirstName', firstName: 'Albus' } )</code>, then it&#8217;ll return a brand new Object <code>{ firstName: 'Albus' }</code>. This is important because it means the code returns immutable data, doesn&#8217;t mutate anything, and is easily testable. Thus, predictable. When you start building an application full of those reducer functions, your application becomes more predictable.</p>



<p>If you&#8217;re from an <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">OOP</a> background, you&#8217;re probably wondering why in the heck you can&#8217;t just go <code>UserModel.getInstance().firstName = 'Albus'</code> or even <code>UserController.getInstance().setFirstName('Albus')</code>. Or even just modifying on the variable in general. Remember, Redux uses pure functions. Pure functions do not mutate or &#8220;change&#8221; data. If you use immutable data, this ensures you&#8217;re following pure function rules. If you mutate things, then it&#8217;s not predictable who changes things, and where. If you use pure functions in Redux, the only mutation occurs in the store. You can predict which actions, in order, change your data and can visualize it using browser tools or simple logs. Yes, you can set a breakpoint in Java or JavaScript, and follow all the getter/setters for one code path, but not all. This is where you get &#8220;who&#8217;s changing my data, where, and when&#8221;. Redux has the same challenges, but it&#8217;s super clear &#8220;who&#8221; is doing it, and &#8220;how&#8221;. Since each change is immutable, there is no weird references going on.</p>



<h3 class="wp-block-heading">Store</h3>



<p>If data is immutable, then how do you change it? VERY carefully. Redux does this via reducer functions.</p>



<p>We know how to write pure functions that return immutable data, but nothing in the real world is immutable. Someone, somewhere has to hold the data we get back from the server, the changes the user makes on the UI, etc. That 1 <code>var</code> is the Store.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> store = createStore(firstNameReducer, { <span class="hljs-attr">firstName</span>: <span class="hljs-string">'???'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Warden'</span> })</code></span></pre>


<p>This store holds your data. Notice we&#8217;ve put our reducer function for it as the 1st parameter. </p>



<p>You get it out via <code>getState</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> person = store.getState() <span class="hljs-comment">// { firstName: '???', lastName: 'Warden' }</span></code></span></pre>


<p>To change the data, we call the dispatch method and pass in an Object:</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">store</span><span class="hljs-selector-class">.dispatch</span>({ <span class="hljs-attribute">type</span>: <span class="hljs-string">'updateFirstName'</span>, firstName: <span class="hljs-string">'Jesse'</span> })</code></span></pre>


<p>Now when we get our data out, it&#8217;ll be changed:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> updated = store.getState() <span class="hljs-comment">// { firstName: 'Jesse', lastName: 'Warden' }</span></code></span></pre>


<h3 class="wp-block-heading">Action Creator</h3>



<p>The Object you pass as the 1st and only parameter to <code>dispatch</code> is called the &#8220;Action&#8221;. However, purist Functional people get mad creating random Objects, so they create a pure function. Those are suddenly called &#8220;Action Creators&#8221;:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">firstNameAction = <span class="hljs-function"><span class="hljs-params">firstName</span> =&gt;</span> ({ <span class="hljs-attr">type</span>: <span class="hljs-string">'updateFirstName'</span>, firstName })</code></span></pre>


<p>An Action Creator is a function that return an Object. It&#8217;s assumed that Object, at a minimum, has a type property. You&#8217;ll use that <code>type</code> in your reducer function to know what data you want to change.</p>



<h3 class="wp-block-heading">Many Types</h3>



<p>As your application grows, you&#8217;ll probably need to change many aspects of your data model. For our person, we want to change the last name as well. So we create another reducer for changing the last name, but using a pure function. This means a copy of the data is returned vs. mutating it:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> lastNameReducer = <span class="hljs-function">(<span class="hljs-params">person, action</span>) =&gt;</span> ({ ...person, <span class="hljs-attr">lastName</span>: action.lastName })</code></span></pre>


<p>To trigger it, we need another action creator for updating lastName:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">lastNameAction = <span class="hljs-function"><span class="hljs-params">lastName</span> =&gt;</span> ({ <span class="hljs-attr">type</span>: <span class="hljs-string">'updateLastName'</span>, lastName })</code></span></pre>


<p>When we created our store above, we put the <code>firstNameReducer</code> with our store to handle all dispatches. Now we need both reducers, and each needs to run based on the <code>type</code> of Action Creator. Let&#8217;s create a new one that uses a switch statement.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> personReducer = <span class="hljs-function">(<span class="hljs-params">person, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span>(action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'updateFirstName'</span>:
      <span class="hljs-keyword">return</span> firstNameReducer(person, action)
    <span class="hljs-keyword">case</span> <span class="hljs-string">'updateLastName'</span>:
      <span class="hljs-keyword">return</span> lastNameReducer(person, action)
  }
}</code></span></pre>


<p>In a unit test, if we call <code>personReducer</code> with <code>{}, { type: 'updateFirstName', firstName: 'Joe' }</code> then we&#8217;ll get back <code>{ firstName: 'Joe' }</code>. If we call it with <code>{}, { type: 'updateLastName', lastName: 'Hall' }</code>, then we&#8217;ll get back <code>{ lastName: 'Hall' }</code>. </p>



<p>To call it in your application, or even in a unit test, you&#8217;d go <code>store.dispatch(lastNameAction('Warden'))</code> to update the <code>lastName</code> to &#8220;Warden&#8221;.</p>



<p>As that switch statement grows, there are other ways to scale it, and improve it overall. That&#8217;s the gist of Redux.</p>



<h3 class="wp-block-heading">Why Are We Using This?</h3>



<p>When building applications in React, you need some sort of state and need it placed somewhere. For some applications, most of it can reside in the URL in the form of GET variables. For others, it&#8217;s simply a global variable.  For others, if you load a list from the server, you&#8217;ll store that in a components <code>props</code> or even <code>state</code> for class components, or a closure for Hooks. Some keep it in sessions.</p>



<p>Eventually, though, some applications need 2 things that the above doesn&#8217;t provide: the ability to share the same data between multiple components, and the ability to update that data from any place you need. Sometimes an <a href="https://sourcemaking.com/design_patterns/mediator">OOP Mediator design pattern</a>, <a href="https://reactjs.org/docs/higher-order-components.html">higher order components</a>, or even just component composition works. You do this to avoid passing props down many component levels, or the components themselves via higher order components. You have a parent component who&#8217;s sole job is to handle communication between a bunch of children components.</p>



<p>As things grow, rather than utilize a <a href="https://martinfowler.com/eaaDev/uiArchs.html">Model View Controller</a> style architecture, React provided <a href="https://reactjs.org/docs/context.html">Context</a>. They describe it as a &#8220;tree&#8221;, from the idea that a component made of many components forms a tree, much like html within html forms a tree of nodes. When many in the tree, or even sibling components need to share the same data, and communicate up and down, performance aside, Context is the go to.</p>



<p>If, however, you want something deterministic without any state that can be mutated or &#8220;changed&#8221;, you use Redux. While people will often use Redux for the same reasons they use Context, the whole point is to ensure predictable code. If you only have 1 variable, you can ensure that the rest of your code is pure functions. If the rest of your code is pure functions, they&#8217;re predictable and easier to test. That means the bugs are typically type related, race conditions, CSS, or null pointers in your component code or 3rd party libraries. If your component code is intentionally dumb, small, and using Hooks in function components over classes, then you&#8217;re significantly reducing the places bugs can hide.</p>



<p>In short, all your code uses <code>const</code> and pure functions as much as possible, and all the hard work is in Redux reducers with as little code as possible in your React components and Hooks. Redux hides from you the only <code>var</code> (or <code>let</code>, heh) in the entire application. Now your application has only 1 variable which is your Model. All data is there, easy to find, and as your application grows, your Model just gets more branches on the Object. Given how JavaScript works, creating immutable versions of just pieces of tree means components see only the part they care about, and in turn the reducers only change the part they care about.</p>



<h2 class="wp-block-heading">Redux Thunk</h2>



<p>The above code is all synchronous. JavaScript applications are often asynchronous. The web browser is asynchronous because the code that renders the screen is also the code that loads image.</p>



<p>Redux&#8217; default <code>store</code> doesn&#8217;t have the ability to deal with <code>Promises</code> or any type of callback async style. The <a href="https://github.com/reduxjs/redux-thunk">redux-thunk library</a> was created to make that as simple as possible.</p>



<p>An example would be <a href="http://jessewarden.com/2019/02/easier-asynchronous-state-modelling-in-react-redux-or-hooks.html">modelling ajax calls</a>. For example, the UI below shows the 3 possible states: loading, error, success:</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1441" height="820" src="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1.png" alt="" class="wp-image-5798" srcset="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1.png 1441w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1-300x171.png 300w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1-768x437.png 768w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1-1024x583.png 1024w" sizes="auto, (max-width: 1441px) 100vw, 1441px" /></figure>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1441" height="820" src="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM.png" alt="" class="wp-image-5799" srcset="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM.png 1441w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM-300x171.png 300w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM-768x437.png 768w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM-1024x583.png 1024w" sizes="auto, (max-width: 1441px) 100vw, 1441px" /></figure>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="623" src="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM-1024x623.png" alt="" class="wp-image-5800" srcset="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM-1024x623.png 1024w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM-300x183.png 300w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM-768x467.png 768w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM.png 1441w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Putting that in a Redux Store would look something like:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">{
  <span class="hljs-attr">loadingState</span>: {
    <span class="hljs-attr">loading</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">isError</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">error</span>: <span class="hljs-literal">undefined</span>,
    <span class="hljs-attr">data</span>: <span class="hljs-literal">undefined</span>
  }
}</code></span></pre>


<p>Or using Algebraic Data Types:</p>


<pre class="wp-block-code"><span><code class="hljs language-css">{
  <span class="hljs-attribute">loadingState</span>: <span class="hljs-built_in">LoadingFoods</span>()
}</code></span></pre>


<p>You dispatch an Action Creator before the AJAX call to put it in a loading state, when it fails you dispatch an error Action Creator, or when it succeeds, you dispatch a success Action Creator.  Using a Promise, it looks like this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">dispatch(loadingFoods())
fetch(<span class="hljs-string">'/foods'</span>)
.then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.json())
.then(<span class="hljs-function"><span class="hljs-params">foods</span> =&gt;</span> dispatch(foodsLoaded(foods))
.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> dispatch(foodsFailed(error))</code></span></pre>


<h3 class="wp-block-heading">Connecting Redux to React</h3>



<p>Now that you have Redux and Thunks for async calls, you now wire up to React, usually using the <a href="https://redux.js.org/basics/usage-with-react">connect library</a>. A pattern emerges where you&#8217;ll have &#8220;dumb&#8221; components who take data, render it, or are just simple UI elements like &lt;buttons&gt;, etc. You then have &#8220;connected&#8221; components that know about Redux. Their sole job is to provide an interface for a React component to get its data from the current state, and when the component has events, those trigger Action Creators. This requires 2 functions called <code>mapStateToProps</code> and <code>mapDispatchToProps</code> and put you those 2 in the <code>connect</code> call with your Component, and it smooshes them together into a &#8220;ConnectedComponent&#8221;. If you have a <code>Cow</code> component, and connect it to Redux, it&#8217;ll be a <code>ConnectedCow</code>. </p>



<p>An example React component that would show 3 screens needs 1 piece of data to know what screen to show, and 1 click handler when the user clicks &#8220;reload&#8221;. </p>


<pre class="wp-block-code"><span><code class="hljs language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">Screen</span> <span class="hljs-attr">loading</span>=<span class="hljs-string">{true}</span> <span class="hljs-attr">reloadClicked</span>=<span class="hljs-string">{reloadClicked}</span> /&gt;</span></code></span></pre>


<p>To get data, you create a function called <code>mapStateToProps</code>. The longer version is &#8220;Yo, I&#8217;ll give you the current Redux state in the store; you can either use it as is, even if it&#8217;s a gigantic Object, or you can snag off the pieces you want. Whatever you return to me, I&#8217;ll set as the props to your component for you. Also, don&#8217;t worry, I&#8217;ll get called every time the data you care about changes.&#8221; Since the whole point of using React is to keep your DOM in sync with your data, this is a perfect match.</p>



<p>Given our example Object above of modelling the loading state, it&#8217;d be:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> mapStateToProps = <span class="hljs-function"><span class="hljs-params">state</span> =&gt;</span> state.loadingState</code></span></pre>


<p>Second, we need a <code>mapDispatchToProps</code>. This function takes any events that come out of our React component, and makes it fire the <code>dispatch</code> action creator we want. If we want to click a &lt;button&gt; in the component and have it go <code>dispatch(reloadActionCreator())</code>, then we need to give our component a function to do that. The <code>mapDispatchToProps</code> wants you to return an Object that it&#8217;ll put on the component&#8217;s <code>props</code> for you, and it gives you the Redux <code>dispatch</code> function so you can use it in a sync or async way. We&#8217;ve got just 1 event in our React component that looks like this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> Screen = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading: {props.loading}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{props.reloadClicked}</span>&gt;</span>Reload<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)</code></span></pre>


<p>So we&#8217;ll create that <code>reload</code> function for it like so:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> mapDispatchToProps = <span class="hljs-function"><span class="hljs-params">dispatch</span> =&gt;</span>
    ({
        <span class="hljs-attr">reloadClicked</span>: <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> dispatch(reloadActionCreator())
    })</code></span></pre>


<p>Last part is to smoosh them together via <code>connect</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> ConnectedScreen = connect(
  mapStateToProps,
  mapDispatchToProps
)(Screen)</code></span></pre>


<h2 class="wp-block-heading">Elm Architecture</h2>



<p>Below is a crash course in the Elm Architecture. It can be a LOT to take in, even if you&#8217;ve had extensive Redux experience. Don&#8217;t fret, and read the <a href="https://guide.elm-lang.org/">Elm Guide</a> multiple times, it&#8217;ll click.</p>



<p>Elm comes built-in with the Elm Architecture. There is no way to NOT use the Elm architecture, unless you&#8217;re playing around with Elm code in the <code>elm repl</code>. If you&#8217;re familiar with Redux, then you&#8217;ll understand the Elm architecture.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="804" height="758" src="https://jessewarden.com/wp-content/uploads/2019/10/elm-architecture.001.png" alt="" class="wp-image-5876" srcset="https://jessewarden.com/wp-content/uploads/2019/10/elm-architecture.001.png 804w, https://jessewarden.com/wp-content/uploads/2019/10/elm-architecture.001-300x283.png 300w, https://jessewarden.com/wp-content/uploads/2019/10/elm-architecture.001-768x724.png 768w" sizes="auto, (max-width: 804px) 100vw, 804px" /></figure>



<p>Similar to Redux, you have a model that is your data. In Redux, it&#8217;s some Object that grows over time. In Elm, it&#8217;s a <a href="https://elm-lang.org/docs/records">Record</a> that grows over time. The difference is Elm has types to ensure the Model&#8217;s values are changed correctly.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">type alias Model =
  { <span class="hljs-attr">firstName</span> : <span class="hljs-built_in">String</span>
  , <span class="hljs-attr">lastName</span> : <span class="hljs-built_in">String</span> }

initialModel =
  { firstName = <span class="hljs-string">"???"</span>
  , lastName = <span class="hljs-string">"Warden"</span> }</code></span></pre>


<p>Think of <code>type alias</code> as a JavaScript <code>class</code>. You can instantiate new <code>type alias</code> things. To change the <code>Model</code>, you send <code>Messages</code>. They&#8217;re just types too. They&#8217;re like Redux Actions. Instead of <code>{ type: 'UpdateFirstName' }</code>, it&#8217;s <code>UpdateFirstName</code>. You don&#8217;t need Action Creators like you do in JavaScript since the compiler will ensure you create them correctly.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">type Msg
  = UpdateFirstName <span class="hljs-built_in">String</span>
  | UpdateLastName <span class="hljs-built_in">String</span></code></span></pre>


<p>You handle those Messages in the <code>update</code> function just like you handle Actions in Redux reducer functions. Elm will not compile unless you handle all of them. In JavaScript you can intentionally ignore Actions you don&#8217;t understand by using <code>default</code> at the bottom of the switch statement. You can also forget as your application grows and you miss one and have no compiler to yell at you. The code below ignores an action with the type &#8220;updateLastName&#8221;.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> personReducer = <span class="hljs-function">(<span class="hljs-params">person, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span>(action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'updateFirstName'</span>:
      <span class="hljs-keyword">return</span> firstNameReducer(person, action)
    <span class="hljs-attr">default</span>:
      <span class="hljs-keyword">return</span> person
  }
}</code></span></pre>


<p>Not so in Elm. This only handles <code>UpdateFirstName</code>. Elm won&#8217;t compile until you implement it correctly.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">update message model =
  <span class="hljs-keyword">case</span> message <span class="hljs-keyword">of</span>
    UpdateFirstName firstName -&gt;
      { model | firstName = firstName }</code></span></pre>


<p>Check out this beastly compiler error:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">Missing Patterns
Line <span class="hljs-number">26</span>, Column <span class="hljs-number">5</span>
This <span class="hljs-string">`case`</span> does not have branches <span class="hljs-keyword">for</span> all possibilities:

<span class="hljs-number">26</span>|&gt;    <span class="hljs-keyword">case</span> msg <span class="hljs-keyword">of</span>
<span class="hljs-number">27</span>|&gt;        UpdateFirstName firstName -&gt;
<span class="hljs-number">28</span>|&gt;          { model | firstName = firstName }

Missing possibilities include:

    UpdateLastName _

I would have to crash <span class="hljs-keyword">if</span> I saw one <span class="hljs-keyword">of</span> those. Add branches <span class="hljs-keyword">for</span> them!

Hint: If you want to write the code <span class="hljs-keyword">for</span> each branch later, use <span class="hljs-string">`Debug.todo`</span> <span class="hljs-keyword">as</span> a
placeholder. Read &lt;https:<span class="hljs-comment">//elm-lang.org/0.19.0/missing-patterns&gt; for more</span>
guidance on <span class="hljs-keyword">this</span> workflow.</code></span></pre>


<p>Fixing our code to handle both Messages by now including the <code>UpdateLastName</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">update message model =
  <span class="hljs-keyword">case</span> message <span class="hljs-keyword">of</span>
    UpdateFirstName firstName -&gt;
      { model | firstName = firstName }
    UpdateLastName lastname -&gt;
      { model | lastName = lastName }</code></span></pre>


<p>The <code>view</code> function gets the <code>Model</code> as the first parameter. There&#8217;s no need to setup components to be aware of it like in React via the connect function for Redux. They are just functions and can take the Model as a parameter, or parts of it. It&#8217;s up to you. In Redux, you&#8217;d use <code>mapStateToProps</code>. The connect library will then spread all the data you need on your React component <code>props</code>. In Elm, you just get the whole model. You&#8217;re welcome to snip off the pieces you want, though.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">view model =
  div &#91;] &#91; text <span class="hljs-string">"First Name: "</span> ++ model.firstName ]</code></span></pre>


<p>When you&#8217;re ready to make HTTP calls, your update function is returned to send back 2 values instead of just the model. In Redux, you get the model and action, but only have to return the model. Below is the Redux reducer for the loading state:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> loadingState = <span class="hljs-function">(<span class="hljs-params">state, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span>(action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'loading'</span>:
      <span class="hljs-keyword">return</span> {...state, <span class="hljs-attr">loading</span>: <span class="hljs-literal">true</span>}
    <span class="hljs-keyword">case</span> <span class="hljs-string">'error'</span>:
    <span class="hljs-keyword">case</span> <span class="hljs-string">'success'</span>:
      <span class="hljs-keyword">return</span> {...state, <span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>}
  }
}</code></span></pre>


<p>You&#8217;ll then have code elsewhere that dispatches the Action, then makes the <code>fetch</code> call, then dispatches either an Error or Success Action.</p>



<p>In Elm, you can&#8217;t make HTTP calls on your own since those are side effects. Instead, you use a Command. You don&#8217;t typically create Commands on your own. Rather, things that cause side effects like HTTP calls create them for you, you just return them in your <code>update</code> function so Elm knows what to do.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">update model =
  LoadData -&gt;
    ( { model | state = <span class="hljs-string">"loading"</span> }
      , Http.get
      { url = <span class="hljs-string">"/companies"</span>
      , expect = Http.expectString CompaniesHTTPResult
      }
    )
  ...</code></span></pre>


<p>That <code>Http.get</code> returns a Command. Elm internally will make the call for you. Whenever the HTTP result is successful or fails, your <code>update</code> will be called again some time later with your <code>CompaniesHTTPResult</code> message. Think of the <code>error</code> and <code>success</code> in the JavaScript Redux reducer above as one <code>CompaniesHTTPResult</code> below. The <code>result</code> parameter lets you know if it worked or not.</p>


<pre class="wp-block-code"><span><code class="hljs">update model =
  CompaniesHTTPResult result -&gt;
    -- it's either Ok or Err</code></span></pre>


<p>This concept of just having functions either return data or Commands seems weird at first. In JavaScript you&#8217;re used to &#8220;making it do&#8221;. Things like &#8220;make this GET request and wait for it&#8221;, or &#8220;Read this data from Application Cache&#8221;. In Elm, you can do those things, but it&#8217;s all through returning Commands in the <code>update</code> function. Elm will handle the nitty gritty of making the actual XHR call, or reading from the browser&#8217;s storage. You&#8217;ll typically have a <code>Message</code> to &#8220;kick it off&#8221;. This means there is no need for a Thunk. No need for a mapping function of events to dispatches. Your UI will trigger messages, and inside the update function, you can then return Commands to do side effect things. </p>



<h2 class="wp-block-heading">Bugs in React</h2>



<p>Bugs in React are usually because of JavaScript. The language is fast to develop in and run with no compile step. This speed comes at the cost of having little to no correctness guarantees when you run. Maybe it&#8217;ll work, maybe it won&#8217;t. That is a adrenaline rush for some people, myself included.</p>



<p>However, some errors aren&#8217;t even reported. They&#8217;re &#8220;swallowed&#8221;. Meaning, your application doesn&#8217;t work like you expect, but you don&#8217;t get an exception. No stack trace, no error, no red in the console, no error breakpoint triggered&#8230; just &#8220;what&#8230; the&#8230;.&#8221;. These are the worst because at least Exceptions give you a possible hint and path to follow. At least returned Errors from more functional code can also give a hint and a path.</p>



<p>Below, I&#8217;ve listed some common ones not always caught by ESLint plugins via misspellings, lack of types, null pointers, missing case statements, and logic errors.</p>



<h3 class="wp-block-heading">Swallowed Errors via Misspellings</h3>



<p>In JavaScript, you can name Object properties just about anything you want. The problem is when it&#8217;s accidental and <code>onClick</code> becomes <code>onClck</code>. JavaScript doesn&#8217;t know you meant  <code>onClick</code>, and if you pass React event handlers <code>undefined</code>, they&#8217;ll assume you want nothing to happen. One mispelling, 2 miscommunications. Worse? It&#8217;s silent; you won&#8217;t get any runtime exception. You click a button and nothing happens. </p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="730" height="400" src="https://jessewarden.com/wp-content/uploads/2019/10/accounts-no-click-1.gif" alt="" class="wp-image-5870"/></figure>



<p><a href="https://eslint.org/">ESLint</a> plugins can only help so much. Some code can only be known to work together if it&#8217;s run, and some variables aren&#8217;t known to each other unless you had types and a compiler.</p>



<p>In Elm, every single variable&#8217;s spelling must match a known type, or it won&#8217;t compile. With the exception of magic strings, this completely solves swallowed errors via misspellings.</p>



<h3 class="wp-block-heading">Null Pointers Because of the Lack of Types</h3>



<p>You can use Algebraic Data Types in JavaScript. This allows you to return a <a href="https://folktale.origamitower.com/api/v2.3.0/en/folktale.result.html">Result</a> from an operation that could fail, either success or failure. It&#8217;s called an <code>Either</code> in some Functional languages, but in JavaScript, the default one is a <code>Promise</code>. However, Promises don&#8217;t come with the popular matching syntax where as something like <code>Result</code> from Folktale or <a href="https://github.com/true-myth/true-myth">true-myth</a> do.</p>



<p>Downside? You have to memorize the variable names, specifically how you destructure. Without types, you can get subtle bugs that can inadvertently get swallowed. In Redux, since all of the code is synchronous, it&#8217;s easier and more fun to use <code>Result</code> as opposed to <code>Promise</code> because the code is synchronous, can be chained like Promise, and has <a href="https://github.com/tc39/proposal-pattern-matching">matching syntax</a>. In our reducer below, if the ajax call to load the accounts works, great, we parse it and return a success. If not, we return a failure. The UI can match on this to know what to draw. </p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> accounts = <span class="hljs-function">(<span class="hljs-params">state=AccountsNotLoaded(</span>), <span class="hljs-params">action</span>) =&gt;</span> {
      ...
      case <span class="hljs-string">'fetchAccountsResult'</span>:
          <span class="hljs-keyword">return</span> action.fetchResult.matchWith({
            <span class="hljs-attr">Ok</span>: <span class="hljs-function">(<span class="hljs-params">{ value }</span>) =&gt;</span> {
                ...
                AccountsLoadSuccess(...)
            },
            <span class="hljs-attr">Error</span>: <span class="hljs-function">(<span class="hljs-params">{ error }</span>) =&gt;</span>
              AccountsLoadFailed(error)
          })</code></span></pre>


<p>The bug is both <code>Ok</code> and <code>Error</code> have a <code>value</code> to destructure. That means <code>AccountsLoadFailed(error)</code> is actually <code>AccountsLoadFailed(undefined)</code>. This ends up on the React UI and causes a null pointer:</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="244" src="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-12.33.04-PM-1024x244.png" alt="" class="wp-image-5859" srcset="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-12.33.04-PM-1024x244.png 1024w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-12.33.04-PM-300x72.png 300w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-12.33.04-PM-768x183.png 768w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-12.33.04-PM.png 1804w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>That&#8217;s because the <code>error</code> is actually <code>undefined</code> and when you go <code>undefined.anything</code> it blows up. Types in Elm won&#8217;t compile if you misspell things or spell the wrong thing because you haven&#8217;t learned the API yet.</p>



<p>In Elm, you have types and a compiler to help ensure that never happens.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">FetchAccountsResult result -&gt;
        <span class="hljs-keyword">case</span> result <span class="hljs-keyword">of</span>
          Ok accountJSONs -&gt;
            ...
            { model | accountState = AccountsLoadSuccess accounts }
          Err datError -&gt;
            { model | accountState = AccountsLoadFailed (httpErrorToString datError) }</code></span></pre>


<p>In the Elm code above, the <code>AccountsLoadFailed</code> is defined as <code>AccountsLoadFailed String</code>. If you were to pass the error itself like <code>AccountsLoadFailed datError</code>, the compiler wouldn&#8217;t compile your code, saying you&#8217;re passing an <code>Error</code> when you should be passing a <code>String</code>.  Using types and a compiler, Elm ensures you&#8217;ll never get null pointers at runtime. You still have to do the work to build an error UI and format the errors for viewing.</p>



<h3 class="wp-block-heading">Missing Case Statements</h3>



<p>Missing case statements can bite you in 2 places in React. The first is in your reducers. If you miss a case statement, you get no indication you did beyond your application doesn&#8217;t work correctly. Below is a reducer that handles all 4 things you can do in the example app; loading the data, parsing the response, and pressing the next/back buttons.</p>


<pre class="wp-block-code"><span><code class="hljs language-php">accounts = (state=AccountsNotLoaded(), action) =&gt; {
  <span class="hljs-keyword">switch</span>(action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'fetchAccounts'</span>:
      ...
    <span class="hljs-keyword">case</span> <span class="hljs-string">'fetchAccountsResult'</span>:
      ...
    <span class="hljs-keyword">case</span> <span class="hljs-string">'previousAccountPage'</span>:
      ...
    <span class="hljs-keyword">case</span> <span class="hljs-string">'nextAccountPage'</span>:
      ...
    <span class="hljs-keyword">default</span>:
      ...
  }
}</code></span></pre>


<p>What happens when you forget one? We&#8217;ll comment out the <code>'fetchAccountsResult'</code> one.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="225" src="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-1.57.36-PM-1024x225.png" alt="" class="wp-image-5862" srcset="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-1.57.36-PM-1024x225.png 1024w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-1.57.36-PM-300x66.png 300w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-1.57.36-PM-768x169.png 768w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-1.57.36-PM.png 1908w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>You&#8217;ll now see the loading UI forever. You won&#8217;t know if this is because the server is slow or your code is broken. If you&#8217;re using TypeScript in strict-mode, and you convert your case strings to actual <code>type</code>&#8216;s, TypeScript won&#8217;t compile because you haven&#8217;t handled every potential case.</p>



<p>The 2nd place is forgetting the <code>default</code>. Again, TypeScript can help here.</p>



<p>The 3rd place, and is more dealing with Algebraic Data Types, is the matching syntax. For example, if our server is down, but we forget to render that part of the UI in the React component:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> AccountStates = <span class="hljs-function">(<span class="hljs-params">{ accountsState }</span>) =&gt;</span>
  accountsState.matchWith({
    <span class="hljs-attr">AccountsNotLoaded</span>: <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Accounts not fetched yet.<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>),
    <span class="hljs-attr">AccountsLoading</span>: <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading accounts...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>),
    <span class="hljs-attr">AccountsLoadNothing</span>: <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>No accounts.<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>),
    <span class="hljs-comment">// AccountsLoadFailed: ({ value }) =&gt; (&lt;div&gt;{value.message}&lt;/div&gt;),</span>
    <span class="hljs-attr">AccountsLoadSuccess</span>: <span class="hljs-function">(<span class="hljs-params">{ accountView }</span>) =&gt;</span> (...)
  })</code></span></pre>


<p>Notice the above code has <code>AccountsLoadFailed</code> commented out. That means, if the server fails, you get the following null pointer error:</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="715" src="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.01.59-PM-1024x715.png" alt="" class="wp-image-5863" srcset="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.01.59-PM-1024x715.png 1024w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.01.59-PM-300x209.png 300w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.01.59-PM-768x536.png 768w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.01.59-PM.png 1768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>In Elm, every case statement is basically the matching syntax. With the compiler, this ensures you will never miss a case. Below, I have a <code>Result</code> when the Account REST call returns. It either worked or it didn&#8217;t:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">FetchAccountsResult result -&gt;
      <span class="hljs-keyword">case</span> result <span class="hljs-keyword">of</span>
        Ok json -&gt;
          ...
        Err error -&gt;
          ...</code></span></pre>


<p>However, if I forget the <code>Err</code>, then I&#8217;ll get a compiler error: </p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="830" height="336" src="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.09.20-PM.png" alt="" class="wp-image-5864" srcset="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.09.20-PM.png 830w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.09.20-PM-300x121.png 300w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.09.20-PM-768x311.png 768w" sizes="auto, (max-width: 830px) 100vw, 830px" /></figure>



<p>Elm ensures you never forget a case statement, including <code>default</code>. </p>



<h3 class="wp-block-heading">Logic Error: Off By 1</h3>



<p>Even if all your code doesn&#8217;t have null pointer exceptions, and you handle all possible case statements, you can still have logic errors. It&#8217;s where your code doesn&#8217;t explode, but doesn&#8217;t work like you want it to. Both the React app and Elm app can have this same bug.</p>



<p>When you click the next and back buttons in the application, they increment what page you are in. If we can&#8217;t increment anymore, we do nothing and stay on the same page. There is a bug in this function, specifically the  <code>accountView.currentPage &lt; accountView.pageSize</code>. We&#8217;ll come back to this below. We&#8217;ve implemented this in the Redux reducer:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> nextPage = <span class="hljs-function"><span class="hljs-params">accountView</span> =&gt;</span> {
    <span class="hljs-keyword">if</span>(accountView.currentPage &lt; accountView.pageSize) {
      <span class="hljs-keyword">return</span> {...accountView, <span class="hljs-attr">currentPage</span>: accountView.currentPage + <span class="hljs-number">1</span>}
    }
    <span class="hljs-keyword">return</span> accountView
  }</code></span></pre>


<p>Using that number as the index to the Array, you can determine which page you should show. We use this awesome <a href="https://lodash.com/docs/4.17.15#chunk">chunk</a> function from Lodash that takes your Array and automatically creates pages from it. So if you&#8217;re array is <code>[1, 2, 3, 4, 5, 6, 7]</code> and you want 3 pages, you go <code>chunk(3, yourArray)</code> and it&#8217;ll give you an Array that looks like <code>[ [1, 2, 3], [4, 5, 6], [7] ]</code>. If your current page is 0, then you&#8217;ll draw a list of <code>[1, 2, 3]</code>. If you&#8217;re current page is 2, then you&#8217;ll draw a list of <code>[7]</code>.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> getCurrentPage = <span class="hljs-function"><span class="hljs-params">pageSize</span> =&gt;</span> <span class="hljs-function"><span class="hljs-params">currentPage</span> =&gt;</span> <span class="hljs-function"><span class="hljs-params">accounts</span> =&gt;</span> {
  <span class="hljs-keyword">const</span> chunked = chunk(pageSize)(accounts)
  <span class="hljs-keyword">if</span>(isNil(chunked&#91;currentPage])) {
    <span class="hljs-keyword">return</span> &#91;]
  }
  <span class="hljs-keyword">return</span> chunked&#91;currentPage]
}</code></span></pre>


<p>When you run the application, it allow works, and you can click the next button to cycle through the pages. However, a logic error arises at the end. Once there, the screen goes blank, the numbers show 11 of 10, and you can no longer click the back button. There are no null pointers caught by React, and the console doesn&#8217;t show any issues. Wat.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="356" src="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-6.26.58-PM-1024x356.png" alt="" class="wp-image-5868" srcset="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-6.26.58-PM-1024x356.png 1024w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-6.26.58-PM-300x104.png 300w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-6.26.58-PM-768x267.png 768w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-6.26.58-PM.png 1912w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>The first bug as explained above is how you increment the pages:</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">if</span>(<span class="hljs-selector-tag">accountView</span><span class="hljs-selector-class">.currentPage</span> &lt; <span class="hljs-selector-tag">accountView</span><span class="hljs-selector-class">.pageSize</span>) {</code></span></pre>


<p>That means you can increment the current page, which starts at 0, to 10 since there are 10 pages and pageSize is 10. The problem is, Array&#8217;s are 0 based, and 0 counts as a number. So now you have the ability to next to 11 pages. That logically should not be allowed, but your code allows it. The function the way it is written, being typed with TypeScript, or even Elm would still result in the same logic error of being off by 1 number.</p>



<p>We fix it by adding a 1 to our page size:</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">if</span>(<span class="hljs-selector-tag">accountView</span><span class="hljs-selector-class">.currentPage</span> &lt; <span class="hljs-selector-tag">accountView</span><span class="hljs-selector-class">.pageSize</span> + 1) {</code></span></pre>


<p>Now the current page will never exceed 9 which is the last item in the Array of 10 items.</p>



<h2 class="wp-block-heading">Errors in Elm</h2>



<p>There are no null pointers in Elm; that&#8217;s one of the main draws to using it. When you compile, you will NOT get runtime errors.</p>



<p>Sort of. The marketing isn&#8217;t as clear as it could be on this. Let&#8217;s break down the 3 types of errors you can and cannot get in Elm. You won&#8217;t get null pointers like you do in JavaScript. There are 2 exceptions to this. The first is when you are in development mode and log out enough JSON that you cause the browser to run out of memory eventually causing the page to crash. The second is when you are integrating with JavaScript through ports and the JavaScript crashes the application by either throwing an error or disobeying the port&#8217;s rules.</p>



<p>The third errors are built into Elm as an Algebraic Data Type: <code>Error</code>. They&#8217;re just like Folktale/true-myth&#8217;s Error type and are encouraged to be used, returning them from functions that can fail. The lack of data such as <code>undefined</code> which typically causes errors in JavaScript is called a <code>Maybe</code> in Elm. It&#8217;s actually embraced in Elm as a type, just like <code>Error</code> to prevent null pointers from ever occurring.</p>



<p>We&#8217;ll focus on the <code>Maybe</code>, <code>Error</code>, and logic errors below since ports and safely working with JavaScript is beyond this article&#8217;s scope. You can <a href="https://guide.elm-lang.org/interop/ports.html">read more about ports</a> in the official guide.</p>



<h3 class="wp-block-heading">Null Pointers</h3>



<p>Most null pointers you get in JavaScript result from trying to dot on an <code>undefined</code> like <code>this.someMethod()</code> in a <code>class</code> or:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> value = getSomething()
<span class="hljs-keyword">const</span> result = value.something</code></span></pre>


<p>If the <code>value</code> returned is <code>undefined</code>, then instead of <code>value.something</code>, what actually happens is <code>undefined.something</code> and that causes a null pointer.</p>



<p>Null pointers also happen because you misspell things. Either the code fails immediately, or later with some subtle bug because the name you placed was on an Object property name instead of a variable or instance, and you don&#8217;t find out till later.</p>



<p>None of those bugs can&#8217;t happen in Elm. You&#8217;ll never have scope problems because Elm doesn&#8217;t have any. Classes hide state, and Elm is a functional language that doesn&#8217;t allow you to create any state. No classes, no <code>this</code>. You can store things in the Model and it feels like a variable (<code>let</code> or <code>var</code>), but any changes you make are immutable. There are no classes to hide mutations.</p>



<p>The second reason the dots never fail in Elm is because of the type system. If you can guarantee that all Objects (called Records in Elm) match the types exactly, then you know exactly if you can dot or something or not. Here is a <code>Person</code> type alias; think of it like a class you can instantiate:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">type alias Person =
  { <span class="hljs-attr">firstName</span> : <span class="hljs-built_in">String</span>
  , <span class="hljs-attr">age</span> : Int }</code></span></pre>


<p>Now you can create a <code>Person</code> by simply going:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">myPerson = Person <span class="hljs-string">"Jesse"</span> <span class="hljs-number">40</span></code></span></pre>


<p>The compiler will check this for you and allow it. If you did this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">myPerson = Person <span class="hljs-string">'Jesse'</span> <span class="hljs-number">40</span></code></span></pre>


<p>It wouldn&#8217;t compile because single quotes are used for characters. If you did this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">myPerson = Person <span class="hljs-string">"Jesse"</span> <span class="hljs-number">40.2</span></code></span></pre>


<p>It wouldn&#8217;t work because 40.2 is a <code>Float</code>, not an <code>Int</code>. If you did this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">myPerson = Person <span class="hljs-string">"Jesse"</span>
msg = log <span class="hljs-string">"firstName: "</span> myPerson.firstName</code></span></pre>


<p>It wouldn&#8217;t work because myPerson is a partial application; it&#8217;s a function waiting for you to give it an <code>Int</code> so it can make a person. Since it&#8217;s a function, it has no <code>firstName</code> property so the program won&#8217;t compile. Technically it&#8217;s type is <code>Int -&gt; Person</code>.</p>



<p>If you log out the name, it works fine:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">myPerson = Person <span class="hljs-string">"Jesse"</span> <span class="hljs-number">40</span>
msg = log <span class="hljs-string">"firstName: "</span> myPerson.firstName</code></span></pre>


<p>But if you misspell <code>firstName</code> to have a missing &#8220;i&#8221;:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">myPerson = Person <span class="hljs-string">"Jesse"</span> <span class="hljs-number">40</span>
msg = log <span class="hljs-string">"firstName: "</span> myPerson.frstName</code></span></pre>


<p>Elm won&#8217;t compile and will suggest maybe you meant <code>firstName</code>.</p>



<p>The third place you can get null pointers in JavaScript is when your code is good, and the data it creates is good and predictable, but then you get JSON from some other place like a web service. When the JSON changes, or they send you HTML instead of JSON, suddenly your functions are acting weird because they don&#8217;t know what HTML is, or the Objects they thought they were getting in JSON have slightly different names or a slightly different structure.</p>



<p>In Elm, all JSON into Elm is parsed using strict decoders. This ensures that no untyped values that could cause a null pointer get into Elm from HTTP calls and JavaScript. If JavaScript passes you a <code>Person</code> like the above, it&#8217;ll either work, or fail to parse. There is no middle ground here.</p>



<h3 class="wp-block-heading">Maybe</h3>



<p>Since there is no way to create an <code>undefined</code> or <code>null</code> in Elm, then how do you deal with things that don&#8217;t return anything? In cases where you might not get a value back, Elm provides a <code>Maybe</code> type. It allows you get a value wrapped in something called a <code>Just</code> or when you don&#8217;t have a value, it&#8217;s a <code>Nothing</code>. This forces your functions to suddenly handle the case when they get nothing back. Our JavaScript function above for getting the current page, you saw that it handled if it got <code>undefined</code> back, then it defaulted to an empty <code>Array</code>. This is a great practice and acts like a <code>Maybe</code>. However, not all functions in JavaScript handle this case and all you have to do is miss one, and POW, null pointer.</p>



<p>Since Elm has types, it knows what a <code>Maybe</code> is. This means if you mess up, misspell it, or only handle the <code>Just</code>, it won&#8217;t compile until you fix it. For example, if you get an item from an Array but the Array is empty, you&#8217;ll get a <code>Nothing</code> back. If the Array is full of things, and you ask for the first item, you&#8217;ll get a <code>Just</code> back. There is no way to know until runtime, though, so Elm ensures you handle both:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">getFirstPersonsName = 
  <span class="hljs-keyword">case</span> <span class="hljs-built_in">Array</span>.get <span class="hljs-number">0</span> peopleList <span class="hljs-keyword">of</span>
    Just item -&gt;
      item.firstName
    Nothing -&gt;
      <span class="hljs-string">"Nobody is in the list."</span></code></span></pre>


<p>If you leave out the <code>Nothing</code>, Elm won&#8217;t compile your code, letting you know you need to handle the <code>Nothing</code> case. This is true for all functions, and ensures your entire program cannot be broken by 1 missing value.</p>



<h3 class="wp-block-heading">Error Type</h3>



<p>There are functions that can work or fail. These are different than <code>Maybe</code>&#8216;s. In the case of loading data from a back-end web service, it&#8217;ll either work or it won&#8217;t. Sure, you could get back an empty <code>Array</code> which could count as a <code>Nothing</code>, but there are a litany of things that could go wrong instead. All you want to know is &#8220;Did it work? Let me know and give me the value, otherwise give the error so I can show it.&#8221;</p>



<p>Unlike exceptions in JavaScript, however, there is no <code>throw</code> in Elm, nor any <code>try/catch</code>. There are also no <a href="https://reactjs.org/docs/error-boundaries.html">error boundaries</a> like in React. If a function can fail, you return an <code>Ok</code> or an <code>Err</code>. If you need to handle that in your UI, you do a case statement to draw a different UI for each piece:</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">case</span> <span class="hljs-selector-tag">httpResult</span> <span class="hljs-selector-tag">of</span>
  <span class="hljs-selector-tag">Ok</span> <span class="hljs-selector-tag">data</span> <span class="hljs-selector-tag">-</span>&gt;
    <span class="hljs-selector-tag">div</span> <span class="hljs-selector-attr">&#91;]</span> <span class="hljs-selector-attr">&#91; text (<span class="hljs-string">"Yay, data: "</span> ++ data) ]</span>
  <span class="hljs-selector-tag">Err</span> <span class="hljs-selector-tag">reason</span> <span class="hljs-selector-tag">-</span>&gt;
    <span class="hljs-selector-tag">div</span> <span class="hljs-selector-attr">&#91;]</span> <span class="hljs-selector-attr">&#91; text (<span class="hljs-string">"Bummer, an error: "</span> ++ (httpErrorToString reason))]</span></code></span></pre>


<h2 class="wp-block-heading">Logic Errors</h2>



<p>Null pointers are fixed by types and <code>Maybe</code>&#8216;s. Errors are handled by the <code>Error</code> type. Encoding/decoding is handled by the JSON Decoder/Encoder modules to ensure only typed data gets in. If you&#8217;re going to use Port&#8217;s, you already accepted you&#8217;re in dangerous territory. So no more bugs right?</p>



<p>Sadly, Elm too can still have logic errors. Types CAN help here, but they&#8217;re not a panacea. Either you don&#8217;t know the data type your need, or haven&#8217;t written the appropriate unit test, or didn&#8217;t know you needed to.</p>



<p>Our Elm code can have the same bug as the React app where it increments the next page too high:</p>


<pre class="wp-block-code"><span><code class="hljs language-xml">nextPage accountView =
  if accountView.currentPage <span class="hljs-tag">&lt; <span class="hljs-attr">accountView.pageSize</span> <span class="hljs-attr">then</span>
    { <span class="hljs-attr">accountView</span> | <span class="hljs-attr">currentPage</span> = <span class="hljs-string">accountView.currentPage</span> + <span class="hljs-attr">1</span>}
  <span class="hljs-attr">else</span>
    <span class="hljs-attr">accountView</span></span></code></span></pre>


<p>Again, you need to remember Array&#8217;s are 0 based, so have to ensure <code>currentPage</code> can only be 0 through 9. You fix that by <code>accountView.currentPage &lt; accountView.pageSize + 1</code>.</p>



<p>Before you start writing unit and functional tests, though, remember you have a pretty good type system in Elm. Can you create a type that prevents this bug from happening? Making an impossible state, impossible to happen? <a href="https://www.youtube.com/watch?v=IcgmSRJHu_8">Richard Feldman talks about these types of data types in his talk</a>. There are a lot of these types of data types that, once learned, ensure you&#8217;ll never get into an impossible state, and don&#8217;t even need unit tests for it.</p>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="&quot;Making Impossible States Impossible&quot; by Richard Feldman" width="500" height="281" src="https://www.youtube.com/embed/IcgmSRJHu_8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Conclusions</h2>



<h3 class="wp-block-heading">React, JavaScript, Redux, and Thunks</h3>



<p>React uses JavaScript, Redux, and Thunks. JavaScript is a dynamic language that, even with various tooling, you still have to run it to see if it works. The speed of development is great for fleshing out ideas and quickly iterating. The cost of that speed is null pointer exceptions, swallowed errors, many are just because of misspellings. This is compounded by the most libraries installed via npm being also written in JavaScript.</p>



<p>React helps with a few of these challenges by optionally providing PropTypes which allow better error messages at runtime. It also allows global error handling via error boundaries with fallback UI&#8217;s in the case of problems. By encouraging pure functions via propTypes in function components, and Algebraic Effects via Hooks, they&#8217;ve abstracted many of the side effects away from you which is often the causes of many bugs. It still runs on JavaScript so can only help so much. The create-react-app project generator and build system now offers TypeScript to help here.</p>



<p>Redux helps ensure your application only has 1 variable as your data model. You only change it via pure functions which means all data is immutable. This means the data that runs your application is predictable and removes a ton of possibilities for bugs that arise from side effects, race conditions, and mutable state.</p>



<p>Redux is just for synchronous changes, though. Redux Thunks handle all the asynchronous changes you need to make in reasonable to learn Promise style.</p>



<h3 class="wp-block-heading">Elm</h3>



<p>Elm is a typed, functional language that compiles to JavaScript, a framework, has a compiler, and a repl. The elevator pitch for Elm is once your application compiles, you won&#8217;t get null pointer errors. Although I still recommend <a href="https://www.youtube.com/watch?v=EZ05e7EMOLM">Test Driven Development / Red Green Refactor</a>, using the type system, you can refactor with confidence. Simply changing your Model makes the compiler find errors everywhere. Once you fix those and it compiles again&#8230; it works with confidence. It&#8217;s amazing. At first you feel you code Elm 5% of your time, and battle with the compiler 95%. In actuality, that 95% is the best part because once you&#8217;re done, you KNOW YOUR&#8217;RE DONE. As opposed to JS where you go &#8220;Let&#8217;s run it and see&#8230;&#8221;.</p>



<p>The types also help you model your application to ensure it can avoid some logic errors. You can model states that prevent the application from getting in a bad state or an impossible one.</p>



<p>Given that the language is functional, you never have scope problems or other mutable state changing things on you. There are no classes, nor variables, and every function is pure. All changes are immutable and this makes writing unit tests for the hairier parts of your application easier.</p>



<p>Elm does not allow you to create side effects. This further purifies your code making all functions taking inputs and producing outputs. While you can write pure functions in JavaScript, at some point, some function has to do the actual side-effect. The Elm framework handles that.</p>



<p>Like Redux, the Elm framework ensures you only have 1 model, and all changes to it are immutable, and thus predictable. Unlike Redux Thunks, the Elm framework handles both sync and asynchronous changes as normal.</p>



<p>Like React, Elm views are pure functions, taking in data, and returning DOM. Like React,  Elm also doesn&#8217;t care how your do your CSS, although using the <a href="https://github.com/rtfeldman/elm-css">elm-css</a> library can help leverage the type system for it. Like React, Elm doesn&#8217;t care how your organize your code and files.</p>



<p>Like JavaScript, Elm also can have logic errors. Unit tests are still valuable. Property/fuzz tests are still valuable. End to end tests are still valuable. Like JavaScript, Elm can also have race conditions. Elm solves a host of problems JavaScript does not, but you&#8217;ll still have to do work. While you may enjoy your job coding Elm more, it&#8217;s still a job requiring work.</p>



<p>Finally, Elm is an ongoing project. JavaScript has had explosive growth in terms of API&#8217;s implemented in the browser the past decade. Elm purifies them. This means not all API&#8217;s are yet implemented in Elm. As new ones come out, someone has to build those Elm equivalents. Thus, if you&#8217;re doing any Elm app, you&#8217;ll probably still be writing JavaScript. JavaScript doesn&#8217;t go away. How you write that JavaScript, however, is probably much more functional and predictable. Much to the chagrin of many Elm purists, npm/yarn doesn&#8217;t go away. But a ton of problems do!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2019/10/react-redux-thunk-vs-elm.html/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Maybe a Default Good Idea</title>
		<link>https://jessewarden.com/2019/07/maybe-a-default-good-idea.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Sun, 14 Jul 2019 18:24:07 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[default]]></category>
		<category><![CDATA[elm]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[maybe]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5834</guid>

					<description><![CDATA[Introduction You&#8217;ve learned that using Maybe&#8216;s allows you to get rid of null pointer exceptions (i.e. &#8220;undefined is not a function&#8221;). However, now your application fails and gives no indication as to why. At least errors would leave a stack trace that may provide a hint as to where the problem originated. How does this [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Introduction</h2>



<p>You&#8217;ve learned that using <code>Maybe</code>&#8216;s allows you to get rid of null pointer exceptions (i.e. &#8220;undefined is not a function&#8221;). However, now your application fails and gives no indication as to why. At least errors would leave a stack trace that may provide a hint as to where the problem originated. How does this happen and what should you be doing instead?</p>



<span id="more-5834"></span>



<h2 class="wp-block-heading">Null Pointers in Python vs Ruby, Lua, and JavaScript</h2>



<p>Let&#8217;s define what we mean by null pointers first, and how you usually encounter them. Most null pointers you&#8217;ll run into as a developer are from either accessing a property of an Object to show on the screen or calling a method on an Object or <code>class</code> instance. </p>



<h3 class="wp-block-heading">Python&#8217;s Strict</h3>



<p>Accessing Objects (Dictionaries in Python) is very strict. If the dictionary exists but the name doesn&#8217;t or you spell it wrong, you&#8217;ll get an exception:</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment"># Python</span>
cow = { <span class="hljs-string">"firstName"</span> : <span class="hljs-string">"Jesse"</span> }
<span class="hljs-keyword">print</span>(cow&#91;<span class="hljs-string">"fistName"</span>])
KeyError: <span class="hljs-string">'firstNam'</span></code></span></pre>


<h3 class="wp-block-heading">Ruby, Lua, and JavaScript are Not Strict</h3>



<p>Ruby, Lua, and JavaScript, however, will return a <code>nil</code> or <code>undefined</code> if you access a property that doesn&#8217;t exist on the Hash/Table/Object:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// JavaScript</span>
cow = { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Jesse"</span> }
<span class="hljs-built_in">console</span>.log(cow&#91;<span class="hljs-string">"fistName"</span>]) <span class="hljs-comment">// undefined</span></code></span></pre>


<h3 class="wp-block-heading">Benefits of Getting Null/Nil vs. Exceptions</h3>



<p>All 3 languages will return their version of &#8220;nothing&#8221;. For some applications, this works out quite well:</p>



<ul class="wp-block-list"><li>UI applications when displaying data</li><li>API&#8217;s that are for orchestrating many API&#8217;s or solely exist to get around CORS</li><li>any code dealing with NoSQL type of data</li></ul>



<p>For UI&#8217;s, you typically do not control your data; you&#8217;re often loading it form some API. Even if you write this yourself, the names can get out of sync with the UI if you change things.</p>



<p>For API&#8217;s, you&#8217;ll often write <a href="https://samnewman.io/patterns/architectural/bff/">orchestration API&#8217;s for UI&#8217;s</a> to access 1 or many API&#8217;s to provide a simpler API for your UI. Using yours, you&#8217;ll make 1 request with efficient, formatted data how your UI needs it vs. 3 where you have to do all the error handling and data formatting on the client. Other times you want to use an API, but it has no support for CORS. The only way your website can access it is if you build your own API to call since API&#8217;s are not prevented from accessing data out of their domains like UI applications are.</p>



<p>For NoSQL type data, you&#8217;ll often have many Objects with the same or similar type fields, but either it&#8217;s low quality, inconsistent, or both. Often this is user entered and thus there is no guarantee that a record has &#8220;firstName&#8221; as a property.</p>



<h3 class="wp-block-heading">Careful For What You Wish For</h3>



<p>However, this has downstream effects. Sometimes code will be expecting a <code>String</code> or a <code>Number</code> and instead get <code>undefined</code> and blow up. Worse, the exceptions it throws are indicating the wrong place; the error occurred upstream but the stacktrace might not show that. The reverse can happen without a type system where it returns a String but the downstream is expecting an Array and queries length getting weird results&#8230;</p>



<p>While the benefits to being flexible are good, using a <code>Maybe</code> to force a developer to handle the case where <code>undefined</code> is returned instead is better.</p>



<h2 class="wp-block-heading">Maybe&#8217;s To the Rescue</h2>



<p>The way to solve this to use the Algebraic Data Type, <code>Maybe</code>. This gives you 2 ways to deal with null data. You can either get a default value:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// Lodash/fp's getOr</span>
getOr(<span class="hljs-string">'unknown name'</span>, <span class="hljs-string">'fistName'</span>, cow) <span class="hljs-comment">// unknown name</span></code></span></pre>


<p> Or you can match, whether using a <a href="https://folktale.origamitower.com/api/v2.3.0/en/folktale.maybe.html">match syntax</a> provided by a library, or a switch statement using <a href="https://www.typescriptlang.org/">TypeScript</a> in strict-mode which ensures you&#8217;ve handled all possible values:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// Folktale's Maybe</span>
cowsFirstNameMaybe.matchWith({
  <span class="hljs-attr">Just</span>: <span class="hljs-function">(<span class="hljs-params">{ value }</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"First name is:"</span>, value),
  <span class="hljs-attr">Nothing</span>: <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"unknown name"</span>)
})</code></span></pre>


<p>This, in theory, is one of the keys to ensuring you don&#8217;t get null pointer exceptions because you ensure in any case you normally would, you now get a type, and force your code to handle what happens if it gets a null value, even if that so happens to be throwing a custom error.</p>



<h2 class="wp-block-heading">Downstream Still Suffers</h2>



<p>However, <code>Maybe</code>&#8216;s can still causing suffering downstream just like <code>undefined</code> can. They do this via default values. In the <code>getOr</code> example above, we just provided &#8220;unknown name&#8221;. If we get nothing back, we just default to &#8220;unknown name&#8221; and handle the problem later, or don&#8217;t if it&#8217;s a database data quality issue we can&#8217;t fix. For a UI developer, that&#8217;s often perfect as they can usually blame the back-end developers for the problem, and their code is working perfectly, and thus fire-drill averted, blame diverted.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="315" height="180" src="http://jessewarden.com/wp-content/uploads/2019/07/nan.png" alt="" class="wp-image-5835" srcset="https://jessewarden.com/wp-content/uploads/2019/07/nan.png 315w, https://jessewarden.com/wp-content/uploads/2019/07/nan-300x171.png 300w" sizes="auto, (max-width: 315px) 100vw, 315px" /><figcaption>Hey, at least it didn&#8217;t explode, right? I mean, the user finished the test, their results were submitted, and they can ignore the weird score&#8230;</figcaption></figure>



<p>However, other times, it ends up hiding bugs. For non-FP codebases, a downstream function/class method will get null data and break.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="522" height="108" src="http://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-12.05.41-PM.png" alt="" class="wp-image-5836" srcset="https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-12.05.41-PM.png 522w, https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-12.05.41-PM-300x62.png 300w" sizes="auto, (max-width: 522px) 100vw, 522px" /></figure>



<p>For FP codebases, they&#8217;ll get default data which often the developer never intended, and something goes awry. This is what we&#8217;ll focus on below.</p>



<h2 class="wp-block-heading">Examples of Default Value Causing UI Drama</h2>



<p>Let&#8217;s define what we mean by default value as there is the imperative version where function arguments have default values for arguments if the user doesn&#8217;t supply a value, or a <code>Maybe</code> which will often come with a default value through <code>getOr</code> in Lodash, <code>getOrElse</code> in Folktale, or <code>withDefault</code> in Elm.</p>



<h3 class="wp-block-heading">Default Values For Function Parameters</h3>



<p>Default values are used by developers when methods have a common value they use internally. They&#8217;ll expose the parameter in the function, but give it a default value if the user doesn&#8217;t supply anything.</p>



<p>The date library moment does this. If you supply a date, it&#8217;ll format it:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">moment(<span class="hljs-string">'2019-02-14'</span>).format(<span class="hljs-string">'MMM Do YY'</span>)
<span class="hljs-comment">// Feb 14th 19</span></code></span></pre>


<p>However, if you supply no date, they&#8217;ll default to &#8220;now&#8221;, aka <code>new Date()</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">moment().format(<span class="hljs-string">'MMM Do YY'</span>)
<span class="hljs-comment">// Jul 14th 19</span></code></span></pre>


<p>Think of the function definition something like this. If they don&#8217;t supply a maybeDate parameter, JavaScript will just default that parameter to now.</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">moment</span><span class="hljs-params">(maybeDate=new Date<span class="hljs-params">()</span>)</span> </span>{</code></span></pre>


<h3 class="wp-block-heading">Default Values for Maybes</h3>



<p>While useful, things can get dangerous when you don&#8217;t know what the default values are, or if there are more than one, or what their relationship to each other is.  In Moment&#8217;s case, it&#8217;s very clear what no input means: now. Other times, however, it&#8217;s not clear at all. Let&#8217;s revisit our default value above:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">getOr(<span class="hljs-string">'unknown name'</span>, <span class="hljs-string">'fistName'</span>, cow) <span class="hljs-comment">// unknown name</span></code></span></pre>


<p>What could possibly be the reason we put default value &#8220;unknown name&#8221;? Is it a passive aggressive way for the developer to let Product know the back-end data is bad? Is it a <a href="https://www.snopes.com/fact-check/brown-out/">brown M&amp;M</a> for the developer to figure out later? The nice thing about string is you have a lot of freedom to be very verbose in why that string is there.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">getOr(<span class="hljs-string">'Bad Data - our data is user input without validation plus some of it is quite old being pulled from another database nightly so we cannot guarantee we will ever have first name'</span>, <span class="hljs-string">'fistName'</span>, cow)</code></span></pre>


<p>Oh&#8230; ok. Much more clear why. However, that clarity suddenly spurs ideas and problem solving. If you don&#8217;t get a name, the Designer can come up with a way to display that vs &#8220;unknown name&#8221; which could actually be the wrong thing to show a user. We do know, for a fact, the downstream database never received a first name inputted by the user. It&#8217;s not our fault there is no first name, it&#8217;s the user&#8217;s. Perhaps a read-only UI element that lets the user know this? It doesn&#8217;t matter if that&#8217;s correct, the point here is you are investing your team&#8217;s resources to solve these default values. You all are proactively attacking what would usually be a reaction to a null pointer.</p>



<h3 class="wp-block-heading">Downstream Functions Not Properly Handling the Default Value</h3>



<p>Strings for UI elements won&#8217;t often cause things to break per say, but other data types where additional code later expects to work with them will.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> phone = getOr(<span class="hljs-string">'no default phone number'</span>, <span class="hljs-string">'address.phoneNumber&#91;0]'</span>, person)
<span class="hljs-keyword">const</span> formatted = formatPhoneNumber(phone)
<span class="hljs-comment">// TypeError</span></code></span></pre>


<p>The code above fails because <code>formatPhoneNumber</code> is not equipped to handle strings that aren&#8217;t phone numbers. Types in <a href="https://www.typescriptlang.org/">TypeScript</a> or <a href="https://elm-lang.org/">Elm</a> or perhaps property tests using <a href="https://github.com/jsverify/jsverify">JSVerify</a> could have found this earlier.</p>



<h3 class="wp-block-heading">Default Values for Maybes Causing Bugs</h3>



<p>Let&#8217;s take a larger example where even super strong types and property tests won&#8217;t save us. We have an application for viewing many accounts. Notice the pagination buttons at the bottom.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="658" src="http://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-12.31.20-PM-1024x658.png" alt="" class="wp-image-5837" srcset="https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-12.31.20-PM-1024x658.png 1024w, https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-12.31.20-PM-300x193.png 300w, https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-12.31.20-PM-768x493.png 768w, https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-12.31.20-PM.png 1650w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>We have 100 accounts, and can view 10 at a time. We&#8217;ve written 2 functions to handle the pagination, both have bugs. We can trigger the bug by going to page 11.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="497" src="http://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-12.55.51-PM-1024x497.png" alt="" class="wp-image-5838" srcset="https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-12.55.51-PM-1024x497.png 1024w, https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-12.55.51-PM-300x146.png 300w, https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-12.55.51-PM-768x373.png 768w, https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-12.55.51-PM.png 1702w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>I thought you just said we have 10 pages, not 11? Why is the screen blank? How does it say 11 of 10? I thought strong types and functional programming meant no bugs?</p>



<p>The first bug, allowing you to page beyond the total pages, is an easy fix. Below is the Elm code and equivalent JavaScript code:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">-- Elm
nextPage currentPage totalPages =
  <span class="hljs-keyword">if</span> currentPage &lt; totalPages then
    currentPage + <span class="hljs-number">1</span>
  <span class="hljs-keyword">else</span>
    currentPage</code></span></pre>

<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// JavaScript</span>
<span class="hljs-keyword">const</span> nextPage = <span class="hljs-function">(<span class="hljs-params">currentPage, totalPages</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span>(currentPage &lt; totalPages) {
    <span class="hljs-keyword">return</span> currentPage + <span class="hljs-number">1</span>
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> currentPage
  }
}</code></span></pre>


<p>We have 100 accounts <a href="https://lodash.com/docs/4.17.11#chunk">chunked</a> into an Array containing 9 child Arrays, or our &#8220;pages&#8221;. We&#8217;re using that <code>currentPage</code> as an Array index. Since Array&#8217;s in JavaScript are 0 based, we get into a situation where <code>currentPage</code> gets set to 10. Our Array only has 9 items. In JavaScript, that&#8217;s <code>undefined</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">accountPages&#91;<span class="hljs-number">9</span>] <span class="hljs-comment">// &#91;account91, account92, ...]</span>
accountPages&#91;<span class="hljs-number">10</span>] <span class="hljs-comment">// undefined</span></code></span></pre>


<p>If you&#8217;re using <code>Maybe</code>&#8216;s, then it&#8217;s <code>Nothing</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">accountPages&#91;<span class="hljs-number">9</span>] <span class="hljs-comment">// Just &#91;account91, account92, ...]</span>
accountPages&#91;<span class="hljs-number">10</span>] <span class="hljs-comment">// Nothing</span></code></span></pre>


<p>Ok, that&#8217;s preventable, just ensure currentPage can never be higher than the total pages? Instead, just subtract one from <code>totalPages</code>:</p>


<pre class="wp-block-code"><span><code class="hljs">-- Elm
if currentPage &lt; totalPages - 1 then</code></span></pre>

<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// JavScript</span>
<span class="hljs-keyword">if</span>(currentPage &lt; totalPages - <span class="hljs-number">1</span>) {</code></span></pre>


<p>Great, that fixes the bug; you can&#8217;t click next beyond page 10, which is the last page.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="712" src="http://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-1.11.28-PM-1024x712.png" alt="" class="wp-image-5839" srcset="https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-1.11.28-PM-1024x712.png 1024w, https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-1.11.28-PM-300x209.png 300w, https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-1.11.28-PM-768x534.png 768w, https://jessewarden.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-14-at-1.11.28-PM.png 1602w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>&#8230; but what about that 2nd bug? How did you get a blank page? Our UI code, if it gets an empty Array, won&#8217;t render anything. Cool, so empty Array == blank screen, but why did we get an empty Array? Here&#8217;s the offending, abbreviated Elm or JavaScript code:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">-- Elm
getCurrentPage totalPages currentPage accounts =
  chunk totalPages accounts
  |&gt; <span class="hljs-built_in">Array</span>.get currentPage
  |&gt; Maybe.withDefault &#91;]</code></span></pre>

<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// JavaScript</span>
<span class="hljs-keyword">const</span> getCurrentPage = <span class="hljs-function">(<span class="hljs-params">totalPages, currentPage, accounts</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> pages = chunk(totalPages, accounts)
  <span class="hljs-keyword">const</span> currentPageMaybe = pages&#91;currentPage]
  <span class="hljs-keyword">if</span>(currentPageMaybe) {
      <span class="hljs-keyword">return</span> currentPageMaybe
  }
  <span class="hljs-keyword">return</span> &#91;]
}</code></span></pre>


<p>Both provide an empty Array as a default value if you get <code>undefined</code>. It could be either bad data the index <code>currentPage</code> but in our case, we were out of bounds; accessing index 10 in an Array that only has 9 items. </p>



<p>This is where lazy thought,  as to how a <code>Nothing</code> could happen results in downstream pain. This is also where types, even in JavaScript which doesn&#8217;t have them but can be enhanced with libraries, really can help prevent these situations. I encourage you to watch <a href="https://www.youtube.com/watch?v=IcgmSRJHu_8">Making Impossible States Impossible by Richard Feldman</a> to get an idea of how to do this.</p>



<h2 class="wp-block-heading">Conclusions</h2>



<p>Really think about 4 things when you&#8217;re using Maybes and you&#8217;re returning a Nothing.</p>



<p>If it truly is something you cannot possibly control, it truly requires someone upstream to handle it, then that is the perfect use case, and why Object property access, and Array index access are the 2 places you see it used most. </p>



<p>Second, have you thought enough about how the <code>Nothing</code> can occur? The below is obvious:</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-keyword">const</span> <span class="hljs-keyword">list</span> = &#91;]
console.log(<span class="hljs-keyword">list</span>&#91;<span class="hljs-number">2</span>]) <span class="hljs-comment">// undefined</span></code></span></pre>


<p>But what about this one?</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> listFromServerWith100Items = <span class="hljs-keyword">await</span> getData()
<span class="hljs-built_in">console</span>.log(list&#91;<span class="hljs-number">34</span>]) <span class="hljs-comment">// undefined</span></code></span></pre>


<p>If accessing data is truly integral to how your application works, then you are probably better served being more thorough in your data parsing, and surfacing errors when the data comes in incorrectly. Having a parse error clearly indicate where data is missing is much more preferable than having an unexpected <code>Nothing</code> later but &#8220;hey, everything says it parsed ok&#8230;.&#8221;</p>



<p>Third, be cognizant about your default values. If you&#8217;re not going to use a <code>Result</code>, which can provide a lot more information about why something failed, then you should probably use a better data type instead that comes embedded with information. Watch  <a href="https://www.youtube.com/watch?v=6TDKHGtAxeg">&#8220;Solving the Boolean Identity Crisis&#8221; by Jeremy Fairbank</a> to get a sense at how primitive data types don&#8217;t really help us understand what methods are doing and how creating custom types can help. Specifically, instead of <code>[]</code> for our <code>getCurrentPage</code> functions above, use types to describe how you could even have empty pages. Perhaps instead you should return a <code>Result</code> Error that describes accessing a page that doesn&#8217;t exist, or an <code>EmptyPage</code> type vs. an empty Array leaving us to wonder if our parsing is broke, we have a default value somewhere like above, or some other problem.</p>



<p>Fourth, this default values will have downstream effects. Even if you aren&#8217;t practicing Functional Programming, using default values means your function will assume something. This function will then be used in many other functions/class methods. She&#8217;ll provide some default value others further down the function call stack won&#8217;t expect. Your function is part of a whole machine, and it&#8217;s better to be explicit about what the default value is you&#8217;re returning. Whether that&#8217;s a verbose String explaining the problem, or a Number that won&#8217;t negatively affect math (such as 0 instead of the common -1), or a custom type like <code>DataDidntLoadFromServer</code>.</p>



<p>Making assumptions to help yourself or other developers is powerful, but be sure to take responsibility with that power and think through the downstream affects of those default values. </p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
