<?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>programming &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/programming-2/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Mon, 07 Oct 2019 14:40:51 +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>programming &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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 fetchpriority="high" 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="(max-width: 1441px) 100vw, 1441px" /></figure>



<figure class="wp-block-image"><img 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="(max-width: 1441px) 100vw, 1441px" /></figure>



<figure class="wp-block-image"><img 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="(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>Advent of Code 2018 in Elm Review</title>
		<link>https://jessewarden.com/2019/01/advent-of-code-2018-in-elm-review.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Mon, 28 Jan 2019 02:38:29 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[2018]]></category>
		<category><![CDATA[adventofcode]]></category>
		<category><![CDATA[elm]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5765</guid>

					<description><![CDATA[Introduction I participated briefly in the Advent of Code 2018. Every year, they post 31 coding puzzles, 2 per day. You have to solve them before you can proceed to next one. I wanted to post about what I learned. I&#8217;ve never participated before, and wanted to use it an excuse to force myself to [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Introduction</h2>



<p>I participated briefly in the <a href="https://adventofcode.com/">Advent of Code</a> 2018. Every year, they post 31 coding puzzles, 2 per day. You have to solve them before you can proceed to next one. I wanted to post about what I learned. I&#8217;ve never participated before, and wanted to use it an excuse to force myself to use a Functional Programming language. I use Functional Programming concepts in my day job, but never had the opportunity to immerse myself, and force myself, to accomplish harder challenges in a pure FP language. It was doubly hard because the exercises are NOT what I do at my day job at all and are challenging. They were very hard in a fun way, though. Below I&#8217;ll cover the 6 exercises I did (I threw in the towel on Day 7), and explain some of the interesting nuances I found either with the exercise and thinking in FP&#8230; and thinking in Elm.</p>



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



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



<p><a href="https://elm-lang.org/">Elm</a> is a <a href="https://en.wikipedia.org/wiki/Functional_programming">Functional Programming</a> language for building web applications. It&#8217;s like <a href="https://www.haskell.org/">Haskell</a>, but has little to no <a href="https://ncatlab.org/nlab/show/category+theory">Category Theory</a> nonsense, and is sort of tailored for traditional UI/web developers. Given I&#8217;d been away from front-end development for awhile dealing with <a href="https://www.python.org/">Python</a>, <a href="https://nodejs.org/en/">Node</a>, and <a href="https://golang.org/">Go</a> for the past 2 years, I figured Elm was a great choice to get back into front-end. I had struggles in the past with Elm, especially around random numbers, and the figuring out what the compilation type errors meant.</p>



<h2 class="wp-block-heading">Overall Challenges With Elm</h2>



<p>I had a few challenges with the Elm language I&#8217;d like to highlight that I found interesting. I&#8217;ve played with Elm a couple of times in the past, and while time away learning more FP did help a lot, I still had struggles.</p>



<h3 class="wp-block-heading">Out of Practice with Types</h3>



<p>When I thought <a href="http://jessewarden.com/2012/10/typescript-for-actionscript-developers.html">TypeScript was cool</a>, the rest of the JavaScript industry did not, so I learned to live without types for a long time. I came from ActionScript 2 and 3 which are like Java, so I had spent years getting comfortable and happy with types. Getting into JavaScript, the industry wasn&#8217;t ready for them, so I learned to go without.</p>



<p>Going back is super rough after spending years in JavaScript, Lua, Python, and even a brief stint in Go. Trying to <a href="https://medium.com/@kavehmz/currying-in-go-and-a-bit-of-interfacing-a79b74b948fc">do currying in Go</a> was an exercise in pure masochism whereas it is built in in Elm and falls in the background, almost unnoticed. I think in 6 exercises I used 1 partial application without composing (which in Elm doesn&#8217;t really count).</p>



<p>My main challenge though with the types is playing with ideas now has another, huge cost. I only care if the code mostly works; I&#8217;m just trying to validate some ideas and approaches. Elm, and the <a href="https://drboolean.gitbooks.io/mostly-adequate-guide-old/content/ch7.html">Hindley-Milner</a> type system specifically, help ensure no runtime errors which means they pull no punches with letting you know how your code is &#8220;incorrect&#8221;. There is no <code>any</code> like there is in <a href="https://www.typescriptlang.org/docs/handbook/basic-types.html">TypeScript</a>. While this is great for production code, it&#8217;s awful for when you &#8220;have a day to vet a solution(s) and come up with a mostly working prototype&#8221;.</p>



<p>Time and time again I would break out JavaScript and Node either locally or in <a href="https://codesandbox.io/">Code Sandbox IO</a> to play with ideas and test algorithms, THEN I&#8217;d rewrite in Elm. Starting in Elm was harder for some algorithms I couldn&#8217;t wrap my head around just yet.</p>



<h3 class="wp-block-heading">No Loops, Only Recursion</h3>



<p>Elm being purely functional means there are no loops for programming. You can only use recursion to ensure no side effects. Given a lot of the Advent of Code 2018 exercises were around parsing large arrays/lists multiple times, it was very common to see JavaScript and Python solutions use <code>while(true)</code> with a <code>break</code> when some condition was met and nested <code>for</code> loops often.</p>



<p>Elm has no loops.  Instead, you either use manual recursion where a function calls itself, or a <a href="https://elm-lang.org/docs/syntax#conditionals">case statement</a> (which is not a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch">JavaScript switch statement</a> and more like an <a href="https://elixir-lang.org/getting-started/case-cond-and-if.html#case">Elixir pattern matching case</a>). I&#8217;ll cover a few examples below. I point this out because that way of thinking is SUPER HARD after 15+ years of my brain being wired to think in loops and nested loops. You do a lot of that in GUI programming for layout and it&#8217;s amazing how hard it was for even simple things to think recursively.</p>



<h3 class="wp-block-heading">Syntax Whitespace</h3>



<p>Elm is almost as strict about whitespace as Python. I say almost because it&#8217;s still unclear when a return statement will completely break compilation or it&#8217;s fine and suddenly things are much more readable. I failed to find a good guide on what you&#8217;re allowed do and suggestions beyond commas before items in lists.</p>



<p>I bring this up because&#8230;</p>



<h3 class="wp-block-heading">Verbose Anonymous Functions</h3>



<p>&#8230; anonymous functions are a bit verbose. You NEED them when you&#8217;re playing with ideas, especially when you&#8217;re porting from Python or JavaScript. I don&#8217;t just mean the ideas, I also mean the types specifically. You may like your chain of parsing code&#8230; but aren&#8217;t sure yet if you&#8217;re going to commit to a <a href="https://package.elm-lang.org/packages/elm/core/latest/List">List</a> or an <a href="https://package.elm-lang.org/packages/elm/core/latest/Array">Array</a>, nor do you know what types will be in that list yet. Anon functions allow a lot of flexibility in Elm combined with <code>let</code> statements to log things out before you&#8217;re ready to commit to types and more normal, non-anonymous functions.</p>



<p>Now, the syntax itself is nice: <code>(\arg -&gt; arg + 1)</code> </p>



<p>Compare that with JavaScript: <code>arg =&gt; arg + 1</code></p>



<p>However, once you start whipping out the <a href="https://package.elm-lang.org/packages/elm/core/latest/Array#foldl">foldl</a> (Elm&#8217;s version of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">Array.reduce</a>) function, things can get pretty gnarly to read pretty quickly. I never figured out a good spacing solution/convention here beyond &#8220;refactor it to normal functions so you can actually read it&#8221;. I&#8217;ll show some examples below of smushed anons and you&#8217;ll go &#8220;Oh&#8230; gross, refactor that, man!&#8221;</p>



<h3 class="wp-block-heading">Approaching Full Lisp with Tons of Parenthesis</h3>



<p>Applying FP concepts in JavaScript has resulted in my JavaScript looking <a href="https://www.youtube.com/watch?v=vGk_HFn_Bfo">a lot like Lisp</a> in the annoying way: tons of parenthesis because of curried functions everywhere.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">.then( <span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> something(<span class="hljs-built_in">JSON</span>)(request)(value) )</code></span></pre>


<p>Even when I took out anonymous functions, I still had nested functions, and sometimes Elm doesn&#8217;t know what you mean so you have to use parenthesis to tell it exactly. Still, it&#8217;s MUUUUCH more preferable to have to add them later vs. being required like you are in JavaScript/Python FP programming.</p>



<p>Here, we have a large chained set of functions and the parenthesis aren&#8217;t bad at all:</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="465" src="http://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-3.11.56-PM-1024x465.png" alt="" class="wp-image-5768" srcset="https://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-3.11.56-PM-1024x465.png 1024w, https://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-3.11.56-PM-300x136.png 300w, https://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-3.11.56-PM-768x349.png 768w, https://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-3.11.56-PM.png 1802w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Yet here, I&#8217;m just creating a simple type with parameters&#8230; but I have functions to ensure they are converted and&#8230; bleh:</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="47" src="http://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-3.12.03-PM-1024x47.png" alt="" class="wp-image-5769" srcset="https://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-3.12.03-PM-1024x47.png 1024w, https://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-3.12.03-PM-300x14.png 300w, https://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-3.12.03-PM-768x35.png 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Again, much better than JavaScript, I realize this is super nitpicking. </p>



<h3 class="wp-block-heading">Tooling Coloring</h3>



<p>I&#8217;ve always thrived on code coloring; it helps me quickly see the different parts of the code and help me comprehend what a function is doing. My <a href="https://github.com/Krzysztof-Cieslak/vscode-elm">current Elm plugin</a> for <a href="https://code.visualstudio.com/">VSCode</a> however doesn&#8217;t seem to highlight methods correctly, only the modules. This becomes a problem when you import both <code>Array</code> and <code>List</code> and they have many of the same method names like <code>map</code>. To ensure you don&#8217;t get a compilation error, it&#8217;s just easier to prefix the method with the module, which you start doing with unrelated things like <code>Maybe</code> just to be consistent. You make your code more verbose, though.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="746" height="278" src="http://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-2.52.33-PM.png" alt="" class="wp-image-5766" srcset="https://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-2.52.33-PM.png 746w, https://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-2.52.33-PM-300x112.png 300w" sizes="auto, (max-width: 746px) 100vw, 746px" /></figure>



<p> Notice how none of the methods, both mine and the native ones, are colored; the same gray color. It stays that way if you omit <code>List</code> and <code>Array</code> resulting in this:</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="528" height="290" src="http://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-2.53.51-PM.png" alt="" class="wp-image-5767" srcset="https://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-2.53.51-PM.png 528w, https://jessewarden.com/wp-content/uploads/2019/01/Screen-Shot-2019-01-27-at-2.53.51-PM-300x165.png 300w" sizes="auto, (max-width: 528px) 100vw, 528px" /></figure>



<p>Terse, yes, readable&#8230; sure, but I want my colors like I have with all the good Python and JavaScript code coloring plugins. It&#8217;d also get confused about exactly where the error is in the code when clicking the errors in the compilation/errors area and scroll to the wrong part. Still, I liked the red underline of problem areas + on the right side indicating where in the code issues were.</p>



<h3 class="wp-block-heading">Modern Web Compilation Toolchain</h3>



<p>In JavaScript, you can actually devote your entire career to <a href="https://d3js.org/">D3.js</a>, making data visualizations. The same can be said for compiling JavaScript using <a href="https://babeljs.io/">Babel</a> and <a href="https://webpack.js.org/">Webpack</a> together. For those of us who came from a world where companies build all that for you  such as C, Visual Studio Code for C#, ActionScript in Flash/Flash Builder Eclipse and nowadays <a href="https://github.com/facebook/create-react-app">Create React App</a>, <a href="https://cli.angular.io/">Angular CLI</a>, and <a href="https://cli.vuejs.org/">Vue CLI</a>&#8230; it&#8217;s ridiculous to think all of us are interested in, yet again, creating a custom compilation chain for Elm in the browser. For must of us, we have the same common need: convert this Elm to JS and put in an index.html.</p>



<p>Elm  Reactor never seems to work for me, and while you can survive for a little while using just a <code>Main.elm</code> file, eventually you&#8217;ll need a basic index.html&#8230; like&#8230; you know, every other web app today. I prefer Facebook to create, upgrade, and maintain my compilation toolchain (create react app) while I focus on building things. Elm doesn&#8217;t have that yet (or I just suck at Elm Reactor) so I hacked the minimal Webpack required possible and just copy pasta&#8217;d between projects. I bring this up because the big 3 realized awhile ago you need a cli to do this stuff for developers and it&#8217;s a huge time sink + duplicated effort without. Playing the waiting game has some benefits such at ES6 ALMOST works in modern browsers, heh, but&#8230; for those of us who want to code and deploy today&#8230; we need better.</p>



<h3 class="wp-block-heading">Type Hinting is &#8220;Ok&#8221;</h3>



<p>Considering we&#8217;re using one of the best in class type systems, shouldn&#8217;t the type hints I receive when using a function or module also be best in class? Apparently not. Observe me trying to use a previously defined function and a type; both give me pathetic code hints. I&#8217;ve seen it <em>sometimes work</em>; maybe I should be using some other extension or something other than VSCode.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="720" height="450" src="http://jessewarden.com/wp-content/uploads/2019/01/codehint.gif" alt="" class="wp-image-5770"/></figure>



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



<p>Many of the exercises are meant to get the performance nerds excited. As a FP programmer in dynamic languages, the last thing I care about is performance&#8230; because it&#8217;s not a problem I have. I&#8217;m building web applications to show 20 items in a table, or pulling 12kb of JSON from a Lambda web service. However, even some of the basic exercises would get you to tens of thousands to hundreds of thousands of iterations. I heard from my friends who were much farther along they were well into the millions and wondering how their Python would compare against the likes of Go and Rust for some of the exercises.</p>



<p>I noticed that the UI would get blocked for a lot of my code. Now, even the low hanging fruit of using a List over an Array, or a Set over an Array I could of made some big gains, but even the little things I ignored too. Perhaps it would help a lot, but above 10,000 iterations I highly doubt it. Since I was building UI&#8217;s for all my exercises and none of my loops needed I/O, this is a perfect use case for <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">WebWorkers</a>. Elm has a initial <a href="https://package.elm-lang.org/packages/elm/core/latest/Process">Process API</a>, but the documentation makes it sound like it&#8217;s not ready yet. The only time the long running loops broke my browser were because I was logging so much JSON it made Chrome run out of memory. However, if I turned logs off, Days 1 &#8211; 6 ran in a reasonable amount of time. As a UI developer, I know blocking the UI is amateur hour given the API&#8217;s we have in the browser, so I&#8217;d like to figure out the correct way to do that in Elm.</p>



<h2 class="wp-block-heading">Day 1 &#8211; 6 Review</h2>



<p>Below I&#8217;ll cover the code for each exercise. While you can read the code to see how I solved the challenges on your own, I&#8217;m just covering the parts I thought were interesting about learning Elm and FP in general.</p>



<p>Elm uses extensive use of the pipeline operator; you can <a href="http://jessewarden.com/2019/01/four-ways-to-compose-synchronous-functions-in-javascript.html#pipeline">learn more about</a> it if the use in the code below doesn&#8217;t make sense.</p>



<h3 class="wp-block-heading">Day 1: Frequency Parser</h3>



<p><a href="https://github.com/JesterXL/advent-of-code-2018/blob/master/day1/src/Main.elm">Source Code</a> | <a href="http://jessewarden.com/archives/adventofcode2018/day1/">Link to Application</a></p>



<p><iframe loading="lazy" src="http://jessewarden.com/archives/adventofcode2018/day1/" width="516px" height="400px"></iframe></p>



<p>Day 1, Challenge 1 was pretty straightforward: parse a list of positive and negative integers. The solution is basically taking all those numbers and adding them up. This is the kind of stuff list comprehensions were built for:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">frequency = <span class="hljs-keyword">List</span>.sum <span class="hljs-keyword">list</span></code></span></pre>


<p>That&#8217;s about the same as <code>sum</code> in <a href="https://lodash.com/docs/4.17.11#sum">Lodash</a>:</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-keyword">const</span> frequency = sum(<span class="hljs-keyword">list</span>)</code></span></pre>


<p>However, Challenge 2 you have to find when it reaches the same number twice. The easiest way in imperative coding is to simply use a <code>while(true)</code> and use a JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set">Set</a> to ensure no duplicates get added and just increment a counter. Yet, this is Elm, so it was my first taste of using recursion to solve a problem. It was also the first indication of a pattern: <code>foldl</code> is used for all the things. Seriously, since most of the challenges were looping through lots of items and changing them, you end up using <code>foldl</code> as your go to for everything. </p>



<p>This was also the first pattern of many where I gave up, whipped out JavaScript, then went back into Elm. The speed at which you can quickly prototype 1 line of code or 1 algorithm I cannot currently match in Elm, even in the elm repl. The Elm in browser editor <a href="https://ellie-app.com/new">Ellie App</a> helps, no doubt, but it&#8217;s not as fast as Node or Python are on the command line.</p>



<p>It ended up being:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">matchOrNot = reduceUntilMatch  { matched = <span class="hljs-keyword">False</span>, frequency = <span class="hljs-number">0</span>, match = <span class="hljs-number">0</span>, set = Set.singleton <span class="hljs-number">0</span> } <span class="hljs-keyword">list</span></code></span></pre>


<p>Where <code>reduceUntilMatch</code> keeps calling itself until it finds a match. All reduce functions have an initial state, and that <code>MatchOrNot</code> type I create was basically a collection of the 4 variables I created in the JavaScript loop version, heh.</p>



<h3 class="wp-block-heading">Day 2: Checksum Parser</h3>



<p><a href="https://github.com/JesterXL/advent-of-code-2018/blob/master/day2/src/Main.elm">Source Code</a> | <a href="http://jessewarden.com/archives/adventofcode2018/day2/">Link To Application</a></p>



<p><iframe loading="lazy" src="http://jessewarden.com/archives/adventofcode2018/day2/" width="360px" height="378px"></iframe></p>



<p>I don&#8217;t know much about checksums, but Day 2 was the only one I breezed through without having to think hard, debug for days, and/or whip out JavaScript or Python.</p>



<p>A few interesting things that started happening at this point in the exercises. First, I stopped caring about typing all my functions. The Elm compiler was good enough to infer what I needed and sometimes providing code hints in my code for me. Second, this then lead to more uses of anonymous functions.</p>


<pre class="wp-block-code"><span><code class="hljs language-php">filterOutSameLetters charList =
    <span class="hljs-keyword">List</span>.map (partitionSameLetters charList) charList
        |&gt; <span class="hljs-keyword">List</span>.filter (\matchList -&gt; <span class="hljs-keyword">List</span>.length matchList &gt; <span class="hljs-number">1</span>)</code></span></pre>


<p>Notice no type definition above <code>filterOutSameLetters</code> and I didn&#8217;t take the time to define the filter function.</p>



<p>Third, <code>Maybes</code> started to get annoying. Most type systems can&#8217;t type things in RAM like &#8220;what is item 3 in a List of Strings?&#8221; Instead they give you a <code>Maybe</code> value. However, once you start composing things, you can have start dealing with default values which can be a pain. You really really really have to think about the ramifications, both at the point you give a default value, and later down the line: what does this do to the correctness of my algorithm? I briefly had these problems in JavaScript, but I&#8217;m doing UI or API development, not Machine Learning/Data Science so I don&#8217;t deal with this level of data correctness in my job. Here in Elm, with types, it amplified.</p>



<p>Fourth, that really drove home I could have massive bugs in &#8220;code that compiles and has no runtime errors&#8221;. That was massive pill to swallow. I had gone down the FP path to create code that I kept hearing was better, more resilient, and had no errors. I had apparently missed the nuance around &#8220;no errors&#8221; still meaning you code could be &#8220;wrong&#8221; and &#8220;broken&#8221;, hah!</p>



<p>Finally, fifth, the <code>let</code> keyword is a godsend. I need to create imperative style code to play with my functions and algorithms in Elm. You write a variable, and then log it out a line below:</p>


<pre class="wp-block-code"><span><code class="hljs language-php">filteredMatches =
    <span class="hljs-keyword">Array</span>.filter (\item -&gt; item.match == <span class="hljs-keyword">True</span>) matches
filteredMatcheslog = log <span class="hljs-string">"filteredMatches"</span> filteredMatches</code></span></pre>


<p>In JavaScript, there is a trend hardcore FP&#8217;ers will ensure <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">fat arrow functions</a> don&#8217;t have squiggly braces {} because that implies the code is imperative and may hide side effects.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> doStuff = <span class="hljs-function"><span class="hljs-params">arg</span> =&gt;</span> someFunction(arg)</code></span></pre>


<p>However, as SOON AS something is weird, they&#8217;ll (myself included) change it back so they can debug what&#8217;s going on:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> doStuff = <span class="hljs-function"><span class="hljs-params">arg</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"arg:"</span>, arg)
    <span class="hljs-keyword">const</span> result = someFunction(arg)
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"result:"</span>, result)
    <span class="hljs-keyword">return</span> result
}</code></span></pre>


<p>I&#8217;m not sure why, but I felt a lot less guilty using <code>let</code> in Elm.</p>



<h3 class="wp-block-heading">Day 3: Claims Parser</h3>



<p><a href="https://github.com/JesterXL/advent-of-code-2018/blob/master/day3/src/Main.elm">Source Code</a> | <a href="http://jessewarden.com/archives/adventofcode2018/day3/">Link To Application</a></p>



<p><iframe loading="lazy" src="http://jessewarden.com/archives/adventofcode2018/day3/" width="320px" height="698px"></iframe></p>



<p>I&#8217;ve seen it stated the main difference between a senior developer and a junior is that the senior, when they write a line of code, it will live longer than the junior&#8217;s. The junior will write it, modify it, then later delete it as part of a larger refactoring effort. Day 3 confirmed that I am indeed a junior in Elm. After spending 5 days, and finally figuring things out in Python and JavaScript, I rewrote my 4 days of work in Elm and started from scratch because the algorithms I had created were too hard to untangle. I haven&#8217;t felt that n00b in a long time which was kind of cool, yet humbling.</p>



<p>The exercise is to calculate where all rectangles are drawn, and then the overlap, and the largest overlap. I used <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API">Canvas</a> to visualize since I feel at home there and liked to see my algorithms work or fail. That and most importantly, I&#8217;ve always dreamed what UI development would be without state, specifically drawing things. I don&#8217;t know how I&#8217;d do this in JavaScript, but in Elm it just feels super natural and not as alien as I thought.</p>



<p>Defining types in Elm is easy, but creating them has been challenging.</p>


<pre class="wp-block-code"><span><code class="hljs">type alias Claim = 
    { id : Int
    , rectangle : Rectangle 
    , calculated : Bool
    , overlaps : Bool }

type alias Rectangle =
    { left : Int
    , top : Int
    , width : Int
    , height : Int
    , right : Int
    , bottom : Int
    , overlaps : Bool }</code></span></pre>


<p>I started using helper functions to simply the creation and reduce how many parenthesis I had to use. Case in point, creating a <code>Rectangle</code>, and then creating a <code>Claim</code> which composes a Rectangle within it.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">-- easier <span class="hljs-keyword">if</span> I make a <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">so</span> <span class="hljs-title">I</span> <span class="hljs-title">can</span> <span class="hljs-title">generate</span> <span class="hljs-title">the</span> <span class="hljs-title">right</span> <span class="hljs-title">and</span> <span class="hljs-title">bottom</span> <span class="hljs-title">properties</span> <span class="hljs-title">when</span> <span class="hljs-title">you</span> <span class="hljs-title">make</span> <span class="hljs-title">the</span> <span class="hljs-title">rectangle</span>
<span class="hljs-title">getRectangle</span> : <span class="hljs-title">Int</span> -&gt; <span class="hljs-title">Int</span> -&gt; <span class="hljs-title">Int</span> -&gt; <span class="hljs-title">Int</span> -&gt; <span class="hljs-title">Rectangle</span>
<span class="hljs-title">getRectangle</span> <span class="hljs-title">left</span> <span class="hljs-title">top</span> <span class="hljs-title">width</span> <span class="hljs-title">height</span> = 
    <span class="hljs-title">Rectangle</span> <span class="hljs-title">left</span> <span class="hljs-title">top</span> <span class="hljs-title">width</span> <span class="hljs-title">height</span> (<span class="hljs-params">left + width</span>) (<span class="hljs-params">top + height</span>) <span class="hljs-title">False</span>

-- <span class="hljs-title">easier</span> <span class="hljs-title">to</span> <span class="hljs-title">create</span> <span class="hljs-title">a</span> <span class="hljs-title">claim</span> <span class="hljs-title">this</span> <span class="hljs-title">way</span>, <span class="hljs-title">less</span> <span class="hljs-title">parameters</span>
<span class="hljs-title">getClaim</span> : <span class="hljs-title">Int</span> -&gt; <span class="hljs-title">Int</span> -&gt; <span class="hljs-title">Int</span> -&gt; <span class="hljs-title">Int</span> -&gt; <span class="hljs-title">Int</span> -&gt; <span class="hljs-title">Claim</span>
<span class="hljs-title">getClaim</span> <span class="hljs-title">id</span> <span class="hljs-title">left</span> <span class="hljs-title">top</span> <span class="hljs-title">width</span> <span class="hljs-title">height</span> =
    <span class="hljs-title">Claim</span> <span class="hljs-title">id</span> (<span class="hljs-params">getRectangle left top width height</span>) <span class="hljs-title">False</span> <span class="hljs-title">False</span></span></code></span></pre>


<p>Seems like boilerplate, but man, using it was as simple as:</p>


<pre class="wp-block-code"><span><code class="hljs">getClaim id left top width height</code></span></pre>


<p>Sadly, I still had type cast the integers to floats when I went to draw them in the Canvas (note the <code>toFloat</code> ):</p>


<pre class="wp-block-code"><span><code class="hljs">renderFilledRectangle x y width height color cmds =
    cmds
        |&gt; Canvas.fillStyle color
        |&gt; Canvas.fillRect (toFloat x) (toFloat y) (toFloat width) (toFloat height)</code></span></pre>


<p>Which is ok. I started learning that most of the code had no care about floats; the only thing which consistently cared about that was the View so I made that a View problem to handle which makes my data code a lot easier to deal with. That and I don&#8217;t need high precision in the UI; we&#8217;re just visualizing things, not making important decisions based on a pixel&#8217;s location.</p>



<p>Finally, Day 3 is where the types in Elm really drive home why you can&#8217;t get runtime errors. The sheer amount of typing it took to parse the String JSON to an Elm type compared to zero effort on JavaScript&#8217;s part is night and day&#8230; like 1 line of JavaScript to 88 lines of Elm. In JavaScript, you just read the file via <code>fs.readFileSync</code> and then <code>JSON.parse</code> .</p>



<p>In Elm, however, <code>JSON.parse</code> is full of side effects, so they make you use lower-level primitives and you have to parse your way up. You can either parse raw Strings which I did in Day 3, or use their parser engine which I&#8217;ll talk about in another exercise below. Here&#8217;s parsing a single claim.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">parseClaimStrings : <span class="hljs-built_in">Array</span> <span class="hljs-built_in">String</span> -&gt; Claim
parseClaimStrings stringArray =
    <span class="hljs-keyword">let</span>
        id =
            <span class="hljs-built_in">Array</span>.get <span class="hljs-number">0</span> stringArray
            |&gt; Maybe.withDefault <span class="hljs-string">"#0"</span>
            |&gt; <span class="hljs-built_in">String</span>.replace <span class="hljs-string">"#"</span> <span class="hljs-string">""</span>
            |&gt; <span class="hljs-built_in">String</span>.toInt
            |&gt; Maybe.withDefault <span class="hljs-number">0</span>

        left =
            <span class="hljs-built_in">Array</span>.get <span class="hljs-number">2</span> stringArray
            |&gt; Maybe.withDefault <span class="hljs-string">","</span>
            |&gt; <span class="hljs-built_in">String</span>.split <span class="hljs-string">","</span>
            |&gt; <span class="hljs-built_in">Array</span>.fromList
            |&gt; <span class="hljs-built_in">Array</span>.get <span class="hljs-number">0</span>
            |&gt; Maybe.withDefault <span class="hljs-string">"0"</span>
            |&gt; <span class="hljs-built_in">String</span>.toInt
            |&gt; Maybe.withDefault <span class="hljs-number">0</span>
        top =
            <span class="hljs-built_in">Array</span>.get <span class="hljs-number">2</span> stringArray
            |&gt; Maybe.withDefault <span class="hljs-string">","</span>
            |&gt; <span class="hljs-built_in">String</span>.split <span class="hljs-string">","</span>
            |&gt; <span class="hljs-built_in">Array</span>.fromList
            |&gt; <span class="hljs-built_in">Array</span>.get <span class="hljs-number">1</span>
            |&gt; Maybe.withDefault <span class="hljs-string">"0"</span>
            |&gt; <span class="hljs-built_in">String</span>.replace <span class="hljs-string">":"</span> <span class="hljs-string">""</span>
            |&gt; <span class="hljs-built_in">String</span>.toInt
            |&gt; Maybe.withDefault <span class="hljs-number">0</span>

        width =
            <span class="hljs-built_in">Array</span>.get <span class="hljs-number">3</span> stringArray
            |&gt; Maybe.withDefault <span class="hljs-string">"x"</span>
            |&gt; <span class="hljs-built_in">String</span>.split <span class="hljs-string">"x"</span>
            |&gt; <span class="hljs-built_in">Array</span>.fromList
            |&gt; <span class="hljs-built_in">Array</span>.get <span class="hljs-number">0</span>
            |&gt; Maybe.withDefault <span class="hljs-string">"0"</span>
            |&gt; <span class="hljs-built_in">String</span>.toInt
            |&gt; Maybe.withDefault <span class="hljs-number">0</span>

        height =
            <span class="hljs-built_in">Array</span>.get <span class="hljs-number">3</span> stringArray
            |&gt; Maybe.withDefault <span class="hljs-string">"x"</span>
            |&gt; <span class="hljs-built_in">String</span>.split <span class="hljs-string">"x"</span>
            |&gt; <span class="hljs-built_in">Array</span>.fromList
            |&gt; <span class="hljs-built_in">Array</span>.get <span class="hljs-number">1</span>
            |&gt; Maybe.withDefault <span class="hljs-string">"0"</span>
            |&gt; <span class="hljs-built_in">String</span>.toInt
            |&gt; Maybe.withDefault <span class="hljs-number">0</span>

    <span class="hljs-keyword">in</span>
        getClaim id left top width height</code></span></pre>


<p>  I know that&#8217;s a bit insane, so let&#8217;s just take the <code>width</code> portion and do a side by side with JavaScript to see what we&#8217;re dealing with. In both languages, you have a string that looks like <code>#147 @ 570,688: 27x25</code>. That is a claim; an id number with an x and a y position divided by a comma, and finally a width and height divided by an x. For the width, we need that <code>570</code> number. For both Elm and JavaScript, if you split that on the space, you can pick out what you need from an Array by index. i.e. 0 will be the id, 2 will be x and y together, and 3 will be the width. That looks like <code>27x25</code>. Parsing that with pure functions that cannot throw errors, let&#8217;s break down the algorithm:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">width =
    <span class="hljs-built_in">Array</span>.get <span class="hljs-number">3</span> stringArray
    |&gt; Maybe.withDefault <span class="hljs-string">"x"</span>
    |&gt; <span class="hljs-built_in">String</span>.split <span class="hljs-string">"x"</span>
    |&gt; <span class="hljs-built_in">Array</span>.fromList
    |&gt; <span class="hljs-built_in">Array</span>.get <span class="hljs-number">0</span>
    |&gt; Maybe.withDefault <span class="hljs-string">"0"</span>
    |&gt; <span class="hljs-built_in">String</span>.toInt
    |&gt; Maybe.withDefault <span class="hljs-number">0</span></code></span></pre>


<ol class="wp-block-list"><li><code>Array.get 3 stringArray</code> gives you a <code>Maybe</code>; it&#8217;ll either be <code>Just(27x25)</code> or <code>Nothing</code></li><li>Because of the <code>Nothing</code>, we say &#8220;ok, default with an &#8216;x&#8217; then&#8221; so you can split and get nothing later down the line&#8221; using <code>Maybe.withDefault "x"</code></li><li><code>String.split "x"</code> will give us a List with 2 items. If it&#8217;s just &#8220;x&#8221;, well, it&#8217;ll be a List with 2 empty Strings&#8230; otherwise it&#8217;ll be <code>["27", "25"]</code></li><li>However, you can&#8217;t get individual items in an <code>List</code> (List has no <code>get</code> method) so we have to convert to an <code>Array</code> so we can get the first item, the width. (&#8220;Jesse, why didn&#8217;t you use <a href="https://package.elm-lang.org/packages/elm/core/latest/List#head">List.head</a>?&#8221; &#8220;Because I&#8217;m a n00b!&#8221;)</li><li>&#8230; however (again), <code>Array.get&nbsp;0</code> gives us a <code>Maybe</code> ; either <code>Just("27")</code> or <code>Nothing</code> so&#8230; we default to &#8220;0&#8221; knowing we&#8217;ll attempt to convert from a String to an integer later.</li><li> <code>String.toInt</code> will give you yet another bloody <code>Maybe</code> because there is no way to guarantee the String is parseable as an Integer using the types, so&#8230; we default to 0.</li></ol>



<p>JavaScript? <code>parseInt(str.split(' ')[3].split('x')[0])</code> although, a couple JavaScript and Python implementations I saw didn&#8217;t even parse it out; they just used those strings as lookups in an Object/Dictionary.</p>



<p>Now, the good news, that entire Elm pipeline is type safe. Meaning, I won&#8217;t get any exceptions at runtime no matter how bad the String is mangled. The bad news is you <em>really</em> need to think about the default values for the <code>Maybes</code>. What if 0 really is a valid value for example? I probably should have used <a href="https://package.elm-lang.org/packages/elm/core/latest/Result">Result</a> instead to be more strict with the parsing. You can see, however, that assuming your data is static, how JavaScript is a lot more terse, and easier to play with ideas if you don&#8217;t care about types and generally know your data is ok.</p>



<p>One side note is that the <a href="https://github.com/joakin/elm-canvas">Elm Canvas</a> version 3 uses <a href="https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame">requestAnimationFrame</a> for efficient rendering, but doesn&#8217;t work in Ellie App. Version 2 does work in Ellie App AND doesn&#8217;t require your Elm application to care about subscriptions (think <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">WebSockets</a> in <a href="https://redux.js.org/">Redux</a>). So I stuck with v2. Despite the fact they both require a JavaScript pipe (the 2nd way I found to crash an Elm app by writing crappy JavaScript in a pipe), I never had any Canvas issues at all; wonderful library.</p>



<h3 class="wp-block-heading">Day 4: Sleep Schedule</h3>



<p><a href="https://github.com/JesterXL/advent-of-code-2018/blob/master/day4/src/Main.elm">Source Code</a> | <a href="http://jessewarden.com/archives/adventofcode2018/day4/">Link To Application</a></p>



<p><iframe loading="lazy" src="http://jessewarden.com/archives/adventofcode2018/day4/" width="1440px" height="635px"></iframe></p>



<p>Day 4 was about parsing sleep times. Like many a programmer, I dread anything dealing with Date math. Elm, unlike JavaScript, has only Posix time, and &#8230; well, <a href="https://package.elm-lang.org/packages/elm/time/latest/">the API</a> sucks compared to JavaScript&#8217;s, especially with something like <a href="https://momentjs.com/">Moment</a> or <a href="https://date-fns.org/">date-fns</a>. There are a few Elm date  libraries, but I found I could get by doing integer math myself.</p>



<p>I struggled to get the sorting right, so dropped into the <a href="http://elmlang.herokuapp.com/">Elm Slack</a> where they had an Advent Of Code 2018 room to see how others were approaching it. I noticed one developer used a different type of String parsing I hand&#8217;t seen before part of the <a href="https://package.elm-lang.org/packages/elm/parser/latest/">Parser library</a>. It parses things string character by string character, but supports branching in case the strings don&#8217;t align up because of whitespace or some other reason. I used this as an opportunity to learn it vs. my traditional String to Array fu. The case-like statements it supports are&#8230; interesting. It felt a lot more flexible and &#8220;made for parsing&#8221; than good ole <a href="https://package.elm-lang.org/packages/elm/core/latest/String#split">String.split</a>.</p>



<p>I also liked some of the equality I was seeing to compare things. Since I had made up my own Date type, I had to figure out how to tell if it was greater than, equal, or less than something. Elm doesn&#8217;t have a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf">valueOf</a> for purity reasons, but they DO have an <a href="https://package.elm-lang.org/packages/elm/core/latest/Basics#Order">Order</a> type you can use the <a href="https://package.elm-lang.org/packages/elm/core/latest/Basics#compare">compare</a> function. My brain started melting (a common occurrence during these exercises) once I started having to further compare deeper parts of the date if something matched.</p>



<p>For example, comparing of 2017 equals 2018 is pretty straightforward:</p>


<pre class="wp-block-code"><span><code class="hljs">compareDateTimeYear : DateTime -&gt; DateTime -&gt; Order
compareDateTimeYear a b =
    compare a.year b.year</code></span></pre>


<p>If we call <code>compareDateTimeYear</code> with 2017 and 2018, it&#8217;ll return <code>LT</code>. But how do you compare the whole date? You make a bunch of those compare functions on the pieces, THEN put &#8217;em in a big, nested case statement:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">compareDateTimes : DateTime -&gt; DateTime -&gt; Order
compareDateTimes a b =
    <span class="hljs-keyword">case</span> compareDateTimeMonth a b <span class="hljs-keyword">of</span>
            EQ -&gt;
                <span class="hljs-keyword">case</span> compareDateTimeDate a b <span class="hljs-keyword">of</span>
                    EQ -&gt;
                        <span class="hljs-keyword">case</span> compareDateTimeHour a b <span class="hljs-keyword">of</span>
                            EQ -&gt;
                                compareDateTimeMinute a b
                            _ -&gt;
                                compareDateTimeHour a b
                    _ -&gt;
                        compareDateTimeDate a b
            _ -&gt;
                compareDateTimeMonth a b</code></span></pre>


<p> She&#8217;s a big &#8220;meh&#8221; in terms of nesting, but I was proud I made her and she works.</p>



<p>Finally, this was my first taste of Tuples and at first I thought they were the weirdest, dumbest thing, but I was wrong&#8230; more on them later.</p>



<h3 class="wp-block-heading">Day 5: Polymer Parser</h3>



<p><a href="https://github.com/JesterXL/advent-of-code-2018/blob/master/day5/src/Main.elm">Source Code</a> | <a href="http://jessewarden.com/archives/adventofcode2018/day5/">Link To Application</a></p>



<p><iframe loading="lazy" src="http://jessewarden.com/archives/adventofcode2018/day5/" width="420px" height="539px"></iframe></p>



<p>Day 5 was basically parsing letters. Like Day 2&#8217;s checksum parser, I don&#8217;t know why, but I found this one easy. For whatever reason, the recursion made more sense here since you&#8217;re basically &#8220;swimming over and over in a large string you keep shrinking&#8221;. I can always visualize recursion and String parsing.</p>



<p>The only thing I&#8217;ll point out for Day 5 is that Elm, currently, doesn&#8217;t tell you when you have dead code. For Day 5 that&#8217;s fine as even with the un-used imports, it&#8217;s still a small file. In JavaScript, the latest version of VSCode will darken the variable, showing it&#8217;s not used. However, you can sometimes have code you THINK is being used, but isn&#8217;t. I wish there was either a visual like there is with JavaScript, or some kind of compiler switch for it.</p>



<h3 class="wp-block-heading">Day 6: Coordinates Finder</h3>



<p><a href="https://github.com/JesterXL/advent-of-code-2018/blob/master/day6/src/Main.elm">Source Code</a> | <a href="http://jessewarden.com/archives/adventofcode2018/day6/">Link To Application</a></p>



<p><iframe loading="lazy" src="http://jessewarden.com/archives/adventofcode2018/day6/" width="940px" height="745px"></iframe></p>



<p>Day 6 was one of the tougher ones. My math kept being slightly off, and I haven&#8217;t yet gotten good about extracting small parts of my algorithms&#8230; which incidentally is exactly what Functional Programming is all about; small, re-usable functions and yet here I am struggling, hah! I referred to a co-workers Python, and one simple trick he did was loading in 4 coordinates instead of all 50. This made my code a ton faster and easier to test. I also determined I was 99% there, I just had 1 bad line of code saying a coordinate didn&#8217;t belong.</p>



<p>In retrospect, had I known ahead of time they were looking for a <a href="https://github.com/d3/d3-voronoi">Voronoi graph</a>, I would have started there first. I did end up with some pretty looking mistakes, though.</p>



<p>Again, I found I made more progress prototyping algorithms in JavaScript than Elm, mainly because it was easier to debug, faster to play without types yelling at me, and I could quickly test and create new scenarios. Maybe that will change over time like it did with ActionScript 2 and 3 and types just became &#8220;second nature&#8221; when coding.</p>



<p>The one thing I liked about Day 6 beyond creating cool looking visualizations was getting familiar with <a href="https://package.elm-lang.org/packages/elm/core/latest/Tuple">Tuples</a>. They&#8217;re like an Elm List, but you can get values from them and you don&#8217;t get <code>Maybes</code> back! This makes working with them super convenient and a lot less code. It seemed strange at first a special list type only having 2 things and I thought it was so dumb, but then I started seeing them everywhere, and made an effort to build them into my types just because they were so worth it, being easy to use. Think of <code>{:ok, value}</code> in Elixir or <code>err, value</code> in Go function return values, and you&#8217;ll get it.</p>



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



<p>Advent of Code 2018 was not easy, it&#8217;s quite advanced. The types of challenges are not something I&#8217;ve ever had to deal with in my 19 years of software development. Coupled with trying to learn a new language with a new way of thinking about programming, it was a recipe for pain. I&#8217;m glad I did it, though.</p>



<p>I&#8217;m convinced Elm for front-end is still the best. I like <a href="https://reactjs.org/">React</a> + <a href="https://redux.js.org/">Redux</a>, but the magic and lack of determinism and challenges of testing of JavaScript in general always have rubbed me the wrong way ONCE I LEARNED there was another way. For context, I was &#8220;done and happy&#8221; in my Model View Controller, Object Oriented Programming world of strong compiler and runtime types back in my Flash and Flex days. Taking what I&#8217;ve learned from FP, and even Elm, back to JavaScript I felt has brought a strong level of determinism in my code, made it easier to test, and made it a ton easier to blame the back-end or Ops for all of my problems. While writing UI&#8217;s in Elm without components can be painful (i.e. invest in <a href="https://material.io/design/">Material Design</a>, <a href="https://getbootstrap.com/">Bootstrap</a>, or your own Company&#8217;s design system), it&#8217;s nice to know even without unit tests your application won&#8217;t explode in production. It&#8217;s nice to know I can write unit tests strictly on my business logic vs. &#8220;do all the things talk to each other correctly&#8221;. I haven&#8217;t done it yet (trying to at work), but I bet if I used Cypress for end to end tests, it&#8217;d be&#8230; boring&#8230; because they&#8217;d always work. Anyway, I love that level of confidence in my software.</p>



<p>At first I felt a little down on myself for not using <a href="http://www.purescript.org/">PureScript</a> at this year&#8217;s Advent of Code since it would of been a wonderful opportunity, but this has been proof that I don&#8217;t need to know Category Theory to be awesome at Functional Programming on the web.</p>



<p>I should point out some of the funny comments from friends online and off. Specifically about Elm&#8217;s verbosity, especially when compared to JavaScript and Python&#8230; and even Swift.</p>



<p>First, Elm is for the front-end. This means you&#8217;ll have GUI code mixed in with your algorithm code. A lot of people who participated in Advent of Code did not build UI&#8217;s.</p>



<p>Second, I have types to ensure no runtime errors; JavaScript/Python do not (yes, I know about Python 3&#8217;s opt in ones).</p>



<p>Third, the types are compile time only; I don&#8217;t have a runtime like Java/Swift to enforce while the code is running.</p>



<p>Fourth, I&#8217;m new to Elm, heh! Perhaps if I had better colors and more experience I could make her a lot more terse.</p>



<p>I look forward to participating this holiday season in 2019, although I have no clue what language/tech stack I&#8217;ll use.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Functional Programming Unit Testing in Node &#8211; Part 6</title>
		<link>https://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-6.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Fri, 22 Jun 2018 16:29:15 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[curry]]></category>
		<category><![CDATA[fp]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[imperative]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[objectorientedprogramming]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[partial]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[stubs]]></category>
		<category><![CDATA[unittesting]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5566</guid>

					<description><![CDATA[Next, Logging, and Conclusions Welcome to Part 6, the final installment in this series. Below we cover unit testing the noop next, how to create pure functions that wrap noop so you can compose them, and finally using code coverage to strategically hit the last code that&#8217;s not covered. Contents This is a 6 part [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Next, Logging, and Conclusions</h1>
<p>Welcome to Part 6, the final installment in this series. Below we cover unit testing the noop <code>next</code>, how to create pure functions that wrap <code>noop</code> so you can compose them, and finally using code coverage to strategically hit the last code that&#8217;s not covered.<br />
<span id="more-5566"></span></p>
<h2>Contents</h2>
<p>This is a 6 part series on refactoring imperative code in Node to a functional programming style with unit tests. You are currently on Part 6.</p>
<ul>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-1.html">Part 1 &#8211; Ground Rules, Export, and Server Control</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-2.html">Part 2 &#8211; Predicates, Async, and Unsafe</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-3.html">Part 3 &#8211; OOP, Compose, Curry</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-4.html">Part 4 &#8211; Concurrency, Compose, and Coverage</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-5.html">Part 5 &#8211; Noops, Stub Soup, and Mountebank</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-6.html">Part 6 &#8211; Next, Logging, and Conclusions</a></li>
</ul>
<h1>Next is Next</h1>
<p>The last part is deal with <code>next</code>. THIS is where I&#8217;d say it&#8217;s ok to use mocks since it&#8217;s a <code>noop</code>, but you do want to ensure it was called at least once, without an <code>Error</code> in the happy path, and with an <code>Error</code> in the bad path.</p>
<p>&#8230; but you&#8217;ve made it this far which means you are FAR from ok, you&#8217;re amazing. NO MOCKS!</p>
<p>Here&#8217;s the basic&#8217;s of testing noops. You sometimes KNOW if they did something, or how they can affect things based on their arguments. In <code>next</code>&#8216;s case, he&#8217;ll signal everything is ok if passed no arguments, and something went wrong and to stop the current connect middleware chain if an <code>Error</code> is passed, much like a <code>Promise</code> chain. We also know that <code>next</code> always returns <code>undefined</code>.</p>
<h2>Ors (Yes, Tales of Legendia was bad)</h2>
<p>One simple way is to just inject it into the existing Promise chain we have:</p>
<pre><code class="javascript">.then( info =&gt; next() || Promise.resolve(info))
.catch( error =&gt; next(error) || Promise.reject(error)))
</code></pre>
<p>This&#8217;ll make the connect middleware happy as well as satisfying our unit tests expecting either an email info out, or a rejected promise with error.</p>
<h2>Pass Through</h2>
<p>Much like you log <code>Promise</code> or other Monad chains, simply make a pass through function.</p>
<pre><code class="javascript">const nextAndResolve = curry((next, info) =&gt; next() || Promise.resolve(info))
const nextAndError = curry((next, error) =&gt; next(error) || Promise.reject(error))
</code></pre>
<p>And since we already know what the <code>next</code> is, we can just attach &#8217;em to the end of the <code>Promise</code> chain, similar to above:</p>
<pre><code class="javascript">.then(nextAndResolve(next))
.catch(nextAndError(next))
</code></pre>
<p>&#8220;Wat!?&#8221; you may be saying, &#8220;all you did was wrap that previous example in functions&#8221;. Yup, they&#8217;re pure, and you can test those in isolation vs. test that gigantic Promise chain with 20 billion stubs.</p>
<pre><code class="javascript">describe('nextAndResolve when called', ()=&gt; {
    it('should fulfill', () =&gt; {
        return expect(nextAndResolve(noop, 'info')).to.be.fulfilled
    })
    it('should resolve', () =&gt; {
        return expect(nextAndResolve(noop, 'info')).to.become('info')
    })
})
</code></pre>
<p>Let&#8217;s do the same for error:</p>
<pre><code class="javascript">describe('nextAndError when called', ()=&gt; {
    it('should fulfill', () =&gt; {
        return expect(nextAndError(noop, new Error('they know what is what'))).to.be.rejected
    })
    it('should resolve', () =&gt; {
        const datBoom = new Error('they just strut')
        return expect(nextAndError(noop, datBoom)).to.rejectedWith(datBoom)
    })
})
</code></pre>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-7.43.09-PM.png" alt="" width="424" height="236" class="alignleft size-full wp-image-5544" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-7.43.09-PM.png 424w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-7.43.09-PM-300x167.png 300w" sizes="auto, (max-width: 424px) 100vw, 424px" /></p>
<p style="clear: both;">&nbsp;</p>
<p style="clear: both;">If you&#8217;re Spidey Sense left over from your Imperative/OOP days is tingling, and you really want to create a mock or <a href="http://sinonjs.org/releases/v6.0.0/spies/">spy</a>, go for it.</p>
<p>I would rather you focus your time on creating pure Promise chains vs. investing in better testing side effects using the connect middleware.</p>
<h1>Mopping Up</h1>
<p>Only 2 functions to go, and we&#8217;re up in dem hunneds <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4af.png" alt="💯" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>
<h2>sendEmail &#8230; or not</h2>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-7.51.29-PM-1024x108.png" alt="" width="525" height="55" class="alignleft size-large wp-image-5546" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-7.51.29-PM-1024x108.png 1024w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-7.51.29-PM-300x32.png 300w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-7.51.29-PM-768x81.png 768w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-7.51.29-PM.png 1704w" sizes="auto, (max-width: 525px) 100vw, 525px" /></p>
<p>The <code>sendEmailOrNext</code> is a textbook case of copy-pasta coding. We&#8217;ll duplicate our previous <code>sendEmail</code> unit tests since they have some yum yum stubs:</p>
<pre><code class="javascript">describe('sendEmailOrNext when called', ()=&gt; {
    ...
    const reqStubNoFiles = { cookie: { sessionID: '1' } }
    ...
    it('should work with good stubs', ()=&gt; {
        return expect(
            sendEmailOrNext(
                readFileStub,
                configStub,
                createTransportStub,
                getUserEmailStub,
                renderStub,
                reqStub,
                resStub,
                nextStub
            )
        ).to.be.fulfilled
    })
    it('should fail with bad stubs', ()=&gt; {
        return expect(
            sendEmailOrNext(
                readFileStubBad,
                configStub,
                createTransportStub,
                getUserEmailStub,
                renderStub,
                reqStub,
                resStub,
                nextStub
            )
        ).to.be.rejected
    })
    it('should resolve with false if no files', ()=&gt; {
        return expect(
            sendEmailOrNext(
                readFileStub,
                configStub,
                createTransportStub,
                getUserEmailStub,
                renderStub,
                reqStubNoFiles,
                resStub,
                nextStub
            )
        ).to.become(false)
    })
})
</code></pre>
<p>I&#8217;ve left out all the stubs, save the new one that shows, if we have no files, it just bypasses the entire thing, calls <code>next</code> with no value signaling to connect we&#8217;re good to go and finished, but still returning a useful value of <code>false</code> to say we didn&#8217;t do what we&#8217;re supposed to since we couldn&#8217;t find any files.</p>
<h2>There And Back Again</h2>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-7.55.12-PM-1024x117.png" alt="" width="525" height="60" class="alignleft size-large wp-image-5548" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-7.55.12-PM-1024x117.png 1024w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-7.55.12-PM-300x34.png 300w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-7.55.12-PM-768x88.png 768w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-7.55.12-PM.png 1386w" sizes="auto, (max-width: 525px) 100vw, 525px" /></p>
<p>Oh look, coverage found yet another <code>noop</code>, imagine that.</p>
<pre><code class="javascript">const logPort = port =&gt; console.log(`Example app listening on port ${port}!`) || true
</code></pre>
<p>And the 1 test:</p>
<pre><code class="javascript">describe('logPort when called', ()=&gt; {
    it('should be true with a port of 222', ()=&gt; {
        expect(logPort(222)).to.equal(true)
    })
})
</code></pre>
<h1>Should You Unit Test Your Logger!?</h1>
<p>If you really want to create a mock/spy for <code>console.log</code>, I admire your tenacity, <a href="https://www.haskell.org/">Haskell</a> awaits you with open arms in your future. Remember me when you&#8217;re at the top and you&#8217;ve bested <a href="http://dragonball.wikia.com/wiki/Mr._Popo">Mr. Popo</a> on the Lookout.</p>
<p>&#8230; however, if you&#8217;re not using <code>console.log</code>, and instead using a known Node logger like <a href="https://github.com/pinojs/pino">Pino</a>, well, heh, you SHOULD!</p>
<p>I should point out some well known <a href="https://clojure.org/">Clojure</a> guys think I&#8217;m going overboard:</p>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-8.04.34-PM-2.png" alt="" width="630" height="601" class="alignleft size-full wp-image-5549" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-8.04.34-PM-2.png 630w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-8.04.34-PM-2-300x286.png 300w" sizes="auto, (max-width: 630px) 100vw, 630px" /></p>
<p>If you read <a href="https://twitter.com/danielglauser/status/998228883034882049">the Twitter thread</a>, an <a href="http://elm-lang.org/">Elm</a> guy schools me, and the Haskell cats show me how even there you can trick Haskell, but still acknowledge (kind of?) the purity pain.</p>
<h1>Conclusions</h1>
<p>Running coverage, we get:</p>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-8.18.29-PM.png" alt="" width="976" height="144" class="alignleft size-full wp-image-5550" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-8.18.29-PM.png 976w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-8.18.29-PM-300x44.png 300w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-8.18.29-PM-768x113.png 768w" sizes="auto, (max-width: 976px) 100vw, 976px" /></p>
<p>Welcome to hunneds country. Congratulations on making this far, and not one import of <a href="http://sinonjs.org/">sinon</a> to be found. Don&#8217;t worry, deadlines and noops are all over the place in the JavaScript world, and sinon&#8217;s mock creation ability is not something to be shunned, but embraced as a helpful addition to your toolset. Like all technical debt, create it intentionally with notes about why, what to remove, context around creating it, etc in code comments around it.</p>
<p>Hopefully you&#8217;ve seen how creating small, pure functions, makes unit testing with small stubs a lot easier, faster, and leads to more predictable code. You&#8217;ve seen how you can use Functional Programming best practices, yet still co-exist with noops in imperative code, and classes and scope in OOP.</p>
<p>I should also point out that writing imperative or OOP code like this is a great way to learn how to write FP. Sometimes our brains are wired to flesh out ideas in those styles, and that&#8217;s great. Whatever works to get the ideas down. On the front-end, using vanilla React&#8217;s classes vs. <a href="https://github.com/acdlite/recompose">recompose</a>&#8230; or even just components functions only. Functional Programming will still hurt just as much as Imperative or OOP if you&#8217;ve got a not-so-figured out idea on how some problems should be solved and structured. Write it so it feels comfortable, the refactor &amp; test to purity.</p>
<p>You&#8217;ve seen how to compose these functions together synchronously via operands like <code>&amp;&amp;</code> and <code>||</code>, using <a href="https://lodash.com/docs/4.17.10#flow">flow</a>/<a href="https://ramdajs.com/docs/#compose">compose</a>. You&#8217;ve also seen how to compose them in <code>Promise</code> chains and <code>Promise.all</code>, curried or not.</p>
<p>You&#8217;ve also seen how 100% unit test coverage in a FP code base still has bugs that are only surfaced with concrete implementations using integration testing, such as with <a href="http://www.mbtest.org/">Mountebank</a>.</p>
<p>Node is often used for API&#8217;s that have little to no state and are just orchestration layers for a variety of XML <a href="https://en.wikipedia.org/wiki/SOAP">SOAP</a>, <a href="https://www.json.org/">JSON</a>, and text. The no mutable state of Functional Programming works nicely with that concept in ensuring those no state to debug.</p>
<p>Conversely, if you&#8217;re dealing with a lot of state such as database connections and streaming text files, not only can you see how you can test such challenging areas using pure functions, but also how many of those things can be run at the same time to speed things up with stepping on each other through global variables.</p>
<p>Props to <a href="http://cliffmeyers.com/">Cliff Meyers</a> for teaching me what <a href="http://www.mbtest.org/">Mountebank is</a>.</p>
<h1>Code &amp; Help</h1>
<p>The <a href="https://github.com/JesterXL/fp-node">Code is on Github</a>. Got any questions, hit me up on <a href="https://www.youtube.com/user/jesterxl">YouTube</a>, <a href="https://twitter.com/jesterxl">Twitter</a>, <a href="https://www.facebook.com/">Facebook</a> (I&#8217;m Jesse Warden), or <a href="jesterxl@jessewarden.com">drop me an email</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Functional Programming Unit Testing in Node &#8211; Part 5</title>
		<link>https://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-5.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Fri, 22 Jun 2018 16:28:48 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[curry]]></category>
		<category><![CDATA[fp]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[imperative]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[objectorientedprogramming]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[partial]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[stubs]]></category>
		<category><![CDATA[unittesting]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5564</guid>

					<description><![CDATA[Noops, Stub Soup, and Mountebank Welcome to Part 5 where we cover more about noops with a utility to test them, the &#8220;stub soup&#8221; that can happen if you don&#8217;t create small pure functions, and how we can utilize stubs instead of mocks to unit test larger functions. The most important part, though, is setting [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Noops, Stub Soup, and Mountebank</h1>
<p>Welcome to Part 5 where we cover more about noops with a utility to test them, the &#8220;stub soup&#8221; that can happen if you don&#8217;t create small pure functions, and how we can utilize stubs instead of mocks to unit test larger functions. The most important part, though, is setting up <a href="http://www.mbtest.org/">Mountebank</a> to show how integration tests can show problems in your unit tests despite 100% coverage. We use wrapping <code>class</code> instances as an example to show you the pitfalls <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">Object Oriented Programming</a> code can make for you.<br />
<span id="more-5564"></span></p>
<h2>Contents</h2>
<p>This is a 6 part series on refactoring imperative code in Node to a functional programming style with unit tests. You are currently on Part 5.</p>
<ul>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-1.html">Part 1 &#8211; Ground Rules, Export, and Server Control</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-2.html">Part 2 &#8211; Predicates, Async, and Unsafe</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-3.html">Part 3 &#8211; OOP, Compose, Curry</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-4.html">Part 4 &#8211; Concurrency, Compose, and Coverage</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-5.html">Part 5 &#8211; Noops, Stub Soup, and Mountebank</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-6.html">Part 6 &#8211; Next, Logging, and Conclusions</a></li>
</ul>
<h1>The Final Battle?</h1>
<p>At this point, we&#8217;ve shrunk our <a href="https://expressjs.com/en/guide/routing.html">Express route</a> as much as we&#8217;re going to without some serious refactoring. Let&#8217;s unit test it using (read copy pasta) all the stubs we&#8217;ve already made.</p>
<h2>Noops</h2>
<p>Before we proceed, let&#8217;s explain what a <code>noop</code> is. Pronounced &#8220;no awp&#8221;, it&#8217;s slang for &#8220;no operation&#8221;. It means a function that doesn&#8217;t return a value so it apparently has no effect because we have no proof it did any operation. That isn&#8217;t true; we all live and die by <code>console.log</code> which always returns <code>undefined</code>. If you run in <a href="https://aws.amazon.com/ecs/">ECS</a>, all those <code>console.log</code> calls are putting text in standard out and you&#8217;re probably collecting all those logs for into <a href="https://www.elastic.co/elk-stack">ELK</a> or <a href="https://aws.amazon.com/cloudwatch/">CloudWatch</a> or <a href="https://www.splunk.com/">Splunk</a>. That&#8217;s certainly an &#8220;operation with noticeable effect&#8221;. Functional Programmers call that a &#8220;side effect&#8221; of the function.</p>
<p>Often you&#8217;ll stub them in unit tests like <code>() =&gt; undefined</code> or the less clear, but shorter <code>() =&gt; {}</code>. Save yourself some typeing and use Lodash&#8217; <a href="https://lodash.com/docs/4.17.10#noop">noop</a>, Ramda <a href="https://ramdajs.com/docs/#always">always</a> if you&#8217;re a Ramda purist or <a href="https://char0n.github.io/ramda-adjunct/2.7.0/RA.html#.noop">noop</a> in Ramda Adjunct.</p>
<h2>My God, It&#8217;s Full Of Stubs</h2>
<p>Here&#8217;s the unit test with stubs needed above it for <code>sendEmail</code> t3h lelz:</p>
<pre><code class="javascript">describe('sendEmail when called', ()=&gt; {
    const readFileStub = (path, encoding, callback) =&gt; callback(undefined, 'email')
    const configStub = { has: stubTrue, get: () =&gt; 'email service' }
    const createTransportStub = () =&gt; ({
        sendEmail: (options, callback) =&gt; callback(undefined, 'info')
    })
    const getUserEmailStub = () =&gt; 'email'
    const renderStub = stubTrue
    const reqStub = {
        cookie: { sessionID: '1' },
        files: [{scan: 'clean', originalname: 'so fresh', path: '/o/m/g'}]
    }
    const resStub = {}
    const nextStub = noop
    it('should work with good stubs', ()=&gt; {
        return expect(
            sendEmail(
                readFileStub,
                configStub,
                createTransportStub,
                getUserEmailStub,
                renderStub,
                reqStub,
                resStub,
                nextStub
            )
        ).to.be.fulfilled
    })
})
</code></pre>
<p>A successful test, but the stubs, while succinct, almost outnumber the lines of code for the test. As you can see, Functional Programming, even when attempted with best effort, doesn&#8217;t necessarily &#8220;solve&#8221; your unit tests having to create a lot of &#8220;test code&#8221;. Mocks often get a bad rap for being verbose and hard to maintain. Stubs I believe are included in this, but at least with stubs they&#8217;re smaller, easier, and &#8220;mostly pure&#8221;. Still, as soon as you refactor your implementation, you&#8217;ll have to fix your tests, and sometimes your stubs will have to change too.</p>
<p>Trust me, this is much more preferable than to refactoring mocks.</p>
<p>The best thing to do is remember your training of the basics, like <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY: don&#8217;t repeat yourself</a>, and keep your tests organized with commonly used good and bad stubs within reach (meaning you don&#8217;t have to scroll too far to read them). Like OOP, FP functions should be short and focused to be re-usable, and most importantly, composeable. It&#8217;s hard and gets easier with practice. A fully fleshed out idea of the problem you&#8217;re trying to solve helps a lot, don&#8217;t be afraid to prototype in imperative code.</p>
<h2>sendEmail Unit Tests</h2>
<p>Let&#8217;s add the failing which is easy because basically any stub could fail and the whole function fails:</p>
<pre><code class="javascript">it('should fail when reading files fails', ()=&gt; {
    return expect(
        sendEmail(
            readFileStubBad,
            configStub,
            createTransportStub,
            getUserEmailStub,
            renderStub,
            reqStub,
            resStub,
            nextStub
        )
    ).to.be.rejected
})
</code></pre>
<p>And the most important, what <code>sendEmail</code> eventually resolves to. Yes, returning a Promise every time is important, but let&#8217;s ensure it resolves to something:</p>
<pre><code class="javascript">it('should resolve to an email sent', ()=&gt; {
    return sendEmail(
        readFileStub,
        configStub,
        createTransportStub,
        getUserEmailStub,
        renderStub,
        reqStub,
        resStub,
        nextStub
    )
    .then(result =&gt; {
        expect(result).to.equal('info')
    })
})
</code></pre>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-11.05.03-AM.png" alt="" width="586" height="178" class="alignleft size-full wp-image-5535" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-11.05.03-AM.png 586w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-11.05.03-AM-300x91.png 300w" sizes="auto, (max-width: 586px) 100vw, 586px" /></p>
<p>And coverage is now:</p>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-11.06.06-AM-1024x438.png" alt="" width="525" height="225" class="alignleft size-large wp-image-5536" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-11.06.06-AM-1024x438.png 1024w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-11.06.06-AM-300x128.png 300w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-11.06.06-AM-768x329.png 768w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-11.06.06-AM.png 1472w" sizes="auto, (max-width: 525px) 100vw, 525px" /></p>
<p>The feels.</p>
<h1>Class Composition is Hard, Get You Some Integration Tests</h1>
<p>Sadly, this is where Functional Programming and Object Oriented Programming stop working together. Our code has a bug that you won&#8217;t find in unit tests, only integration tests. In languages like JavaScript, <a href="https://www.python.org/">Python</a>, and <a href="https://www.lua.org/">Lua</a>, when you call functions on Classes without the class attached, they&#8217;ll often lose scope (<code>this</code> or <code>self</code> will be <code>undefined</code>/<code>nil</code>). Eric Elliot breaks down the details of a lot of these cases in his article <a href="https://medium.com/javascript-scene/why-composition-is-harder-with-classes-c3e627dcd0aa">Why Composition is Harder With Classes</a>.</p>
<p>Integration tests using <a href="https://github.com/visionmedia/supertest">Supertest</a> or <a href="http://www.mbtest.org/">Mountebank</a> help with different levels of integration tests. We&#8217;ll use Mountebank in this article. Suffice to say your unit tests are only as good as the stubs you provide. The stubs you provide basically fake or emulate functionality of the dependencies and are as small and simple as possible. Stubs are different code than the concrete (real) implementations, and unless they capture it exactly, don&#8217;t always test the same. You&#8217;ll see an example of this below testing OOP code.</p>
<h2>Pitfalls When Stubbing Class Methods</h2>
<p>Notice none of our stubs use any classes or Object.prototype, and yet, this is exactly how <code>nodemailer</code> works. It all comes down to class instances losing their <code>this</code> scope. Let&#8217;s write a basic pure wrapper around nodemailer, unit test it, show it pass, then setup Mountebank so we can show it breaks at runtime when you use the real nodemailer vs. stubs. Given Mountebank is a large topic, I won&#8217;t cover too much how it works, but the <a href="https://github.com/JesterXL/fp-node/blob/master/test-integration/setupMountebank.js">code is included</a>. Just know it&#8217;ll listen on the email port, act like an email server, and send real email responses so nodemailer believes it truly is sending an email.</p>
<p>Let&#8217;s create a <code>sandbox.js</code> file to play and a <code>sandbox.test.js</code> in the tests folder.</p>
<pre><code class="javascript">const nodemailer = require('nodemailer')

const sendEmailSafe = (createTransport, mailOptions, options) =&gt;
    new Promise((success, failure) =&gt; {
        const { sendMail } = createTransport({mailOptions})
        sendMail(options, (err, info) =&gt;
            err
            ? failure(err)
            : success(info))
    })

module.exports = sendEmailSafe
</code></pre>
<p>And the unit test:</p>
<pre><code class="javascript">...
describe.only('sendEmailSafe when called', ()=&gt; {
    it('should work with good stubs', () =&gt; {
        const createTransportStub = () =&gt; ({
            sendMail: (options, callback) =&gt; callback(undefined, 'email sent')
        })
        return sendEmailSafe(createTransportStub, {}, {})
        .then(result =&gt; {
            expect(result).to.equal('email sent')
        })
    })
})
...
</code></pre>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-12.12.12-PM.png" alt="" width="444" height="174" class="alignleft size-full wp-image-5537" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-12.12.12-PM.png 444w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-12.12.12-PM-300x118.png 300w" sizes="auto, (max-width: 444px) 100vw, 444px" /></p>
<h2>Integration Test</h2>
<p>So it passes. Let&#8217;s try with the integration test that uses a real nodemailer instance vs. our unit test stubs. I&#8217;ve setup mountebank to listen on port 2626 at localhost for emails. If someone sends an email with the from address equaling &#8220;jesterxl@jessewarden.com&#8221;, it&#8217;ll respond with an &#8220;ok the email was sent, my man&#8221;. Before we automate this, let&#8217;s do it manually first.</p>
<h3>Setting Up Mountebank</h3>
<p>Run <code>npm i mountebank --save-dev</code> first, then once it is complete, open your package.json and add this script:</p>
<pre><code class="json">"scripts": {
    ...
    "mb": "npx mb"
  },
...
</code></pre>
<p>Now when you run <code>npm run mb</code>, it&#8217;ll run Mountebank. It&#8217;ll basically start a Node server on port 2525. As long as it&#8217;s running, you can send it JSON to add imposters (mocks for running services).</p>
<h3>Setting Up Your Imposters</h3>
<p>An imposter is basically a mock or stub for services. Typically <a href="https://martinfowler.com/articles/mocksArentStubs.html">mocks and stubs</a> are used for unit tests and are created in code. In Mountebank, however, you create one by sending Mountebank REST calls. For example a POST call, typically on localhost:2525. You send it JSON describing what port it&#8217;s supposed to listen on, what other things to look for, and what JSON &amp; headers to respond with. Mountebank will then spawn a service on that port listening for incoming connections. If the request has attributes it recognizes (you do a GET on port 9001 with a path of <code>/api/health</code>, you send an email on port 2626 from &#8216;cow@moo.com&#8217;, etc), it&#8217;ll respond with whatever stub you tell it too. For example, some hardcoded JSON with an HTTP 200 status code. While stubs typically respond immediately or with Promises, these respond as a REST response.</p>
<p>Check out the import top part of our <code>setupMountebank.js</code> that I&#8217;ve placed in the &#8220;test-integration&#8221; folder:</p>
<pre><code class="javascript">...
const addNodemailerImposter = () =&gt;
    new Promise((success, failure)=&gt;
        request({
            uri: 'http://localhost:2525/imposters',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                protocol: 'smtp',
                port: 2626,
                stubs: [{
                    predicates: [
                        {
                            contains: {
                                from: 'jesterxl@jessewarden.com'
                            }
                        }
                    ]
                }]
            })
        },
    ...
</code></pre>
<p>As you can see, a simple POST request to tell Mountebank, &#8220;Yo, if any dude sends an email on port 2626 and it is from me, respond it worked&#8221;. Typically Mountebank wants to define that response in the stubs Array, but for emails, you can leave it blank and it&#8217;ll default to a success response. At the time of this writing, there is no way to make an email fail, only REST calls. As long as Mountebank is running, it&#8217;ll remember to do this unless you delete it, or close Mountebank.</p>
<p>Now, to play around, I&#8217;ve run it manually to register. Check the bottom code:</p>
<pre><code class="javascript">if (require.main === module) {
    Promise.all([
        addNodemailerImposter()
    ])
    .then(() =&gt; console.log('Mountebank Imposters initialized successfully.'))
    .catch(error =&gt; console.error('Mountebank Imposters failed:', error))
}
</code></pre>
<p>Open a new terminal, and run <code>node test-integration/setupMountebank.js</code>, and you should see the Mountebank terminal light up:</p>
<pre><code class="shell">&gt; npx mb

info: [mb:2525] mountebank v1.14.1 now taking orders - point your browser to http://localhost:2525 for help
info: [mb:2525] POST /imposters
info: [smtp:2626] Open for business...
</code></pre>
<p>That &#8220;Open for business&#8230;&#8221; line is key; that means Mountebank understood what you want and worked and you can now send emails to port 2626. Let&#8217;s do that.</p>
<h3>Sending the Email</h3>
<p>Open up <code>sandbox.js</code> and check the code that&#8217;ll run if we use Node to run it:</p>
<pre><code class="javascript">if (require.main === module) {
    sendEmailSafe(
        nodemailer.createTransport,
        {
            host: 'localhost',
            port: 2626,
            secure: false
        },
        {
            from: 'jesterxl@jessewarden.com',
            to: 'jesterxl@jessewarden.com',
            subject: 'what you hear, what you hear is not a test',
            body: 'Dat Body Rock'
        }
    )
    .then(result =&gt; {
        console.log("result:", result)
    })
    .catch(error =&gt; {
        console.log("error:", error)
    })
}
</code></pre>
<h3>Swing and a Miss</h3>
<p>Rad, now try to send an email via <code>node src/sandbox.js</code>:</p>
<pre><code class="javascript">error: TypeError: Cannot read property 'getSocket' of undefined
    at sendMail (/Users/jessewarden/Documents/_Projects/fp-node/node_modules/nodemailer/lib/mailer/index.js:143:25)
...
</code></pre>
<p>Whoa, wat? Let&#8217;s go into Nodemailer&#8217;s sourcecode and see what the heck is going on:</p>
<pre><code class="javascript">/* node_modules/nodemailer/lib/mailer/index.js line 134 */
sendMail(data, callback) {
    ...
        /* broken below this comment */
    if (typeof this.getSocket === 'function') {
        this.transporter.getSocket = this.getSocket;
        this.getSocket = false;
    }
...
</code></pre>
<p>It&#8217;s doing a type check to see if <code>this.getSocket</code> is a function vs. a Boolean. That&#8217;s fine, but they should of check for <code>this</code> being undefined first.</p>
<p>Or should they? Once you&#8217;re in class world, and you&#8217;ve been doing OOP for awhile, you shouldn&#8217;t have to check for <code>this</code>; it&#8217;s just a normal part of how classes work. If it doesn&#8217;t, something more fundamental is messed up, the most common being forgetting to setup <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind">bind</a> in the constructor for callbacks for example.</p>
<p>We&#8217;re not going to fix Nodemailer to make it more friendly to FP developers. In fact, this is a common trend in that many libraries you use both in Node and in the Browser (i.e. from node_modules) will be written in all sorts of ways. You need to be accommodating.</p>
<p>Instead, we&#8217;ll assume that we&#8217;re not allowed to call <code>sendEmail</code> alone, and ensure it&#8217;s always <code>something.sendEmail</code>; whatever to the left is the instance, and will retain scope if you call it like that. This is why a lot of my examples you&#8217;ll see I&#8217;ll make <code>fs</code> the dependency and then call <code>fs.readFile</code> vs. just <code>readFile</code>.</p>
<h3>FP-Fu</h3>
<p>Let&#8217;s first fix our implementation to be OOP friendly, and ensure the tests still work, else fix &#8217;em. The old code:</p>
<pre><code class="javascript">const { sendEmail } = createTransport({mailOptions})
        sendMail(options, (err, info) =&gt;
</code></pre>
<p>The new code:</p>
<pre><code class="javascript">const transport = createTransport({mailOptions})
        transport.sendMail(options, (err, info) =&gt;
</code></pre>
<p>Re-run the tests:</p>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-3.38.23-PM.png" alt="" width="476" height="186" class="alignleft size-full wp-image-5539" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-3.38.23-PM.png 476w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-3.38.23-PM-300x117.png 300w" sizes="auto, (max-width: 476px) 100vw, 476px" /></p>
<p style="clear: both;">&nbsp;</p>
<p style="clear: both;">Cool, the original public interface still works and hides the OOPy stuff. Let&#8217;s test the integration test now with sending a real email with real, concrete implementation vs. stubs:</p>
<pre><code class="shell">result: { accepted: [ 'jesterxl@jessewarden.com' ],
  rejected: [],
  envelopeTime: 3,
  messageTime: 3,
  messageSize: 590,
  response: '250 2.0.0 Ok: queued as f19f95e62da4afeade02',
  envelope:
   { from: 'jesterxl@jessewarden.com',
     to: [ 'jesterxl@jessewarden.com' ] },
  messageId: '&lt;ab0bab09-7628-007b-f497-3d53806704ae@jessewarden.com&gt;' }
</code></pre>
<p>I was like Whee!!! Let&#8217;s fix our original implementation now that we&#8217;ve proven we know how to wrangle OOP with FP now. We&#8217;ll change:</p>
<pre><code class="javascript">...
sendEmailSafe(
  createTransport(
    createTransportObject(emailService.host, emailBody.port)
  ).sendEmail,
...
</code></pre>
<p>To:</p>
<pre><code class="javascript">...
sendEmailSafe(
  createTransport(
    createTransportObject(emailService.host, emailBody.port)
  ),
...
</code></pre>
<p>And switch <code>sendEmailSafe</code>:</p>
<pre><code class="javascript">const sendEmailSafe = curry((sendEmailFunction, mailOptions) =&gt;
  new Promise((success, failure) =&gt;
    sendEmailFunction(mailOptions, (err, info) =&gt;
      err
      ? failure(err)
      : success(info)
    )
  )
)
</code></pre>
<p>To the new OOP-friendly version:</p>
<pre><code class="javascript">const sendEmailSafe = curry((transport, mailOptions) =&gt;
  new Promise((success, failure) =&gt;
    transport.sendEmail(mailOptions, (err, info) =&gt;
      err
      ? failure(err)
      : success(info)
    )
  )
)
</code></pre>
<p>This breaks 1 of the tests because the stub used to be a function; now it needs to be an Object with a function. However&#8230; we should be a little more honest and use a true <code>class</code> in the unit tests to be 100% sure. We&#8217;ll take the old 2 tests:</p>
<pre><code class="javascript">describe('sendEmailSafe when called', ()=&gt; {
    const sendEmailStub = (options, callback) =&gt; callback(undefined, 'info')
    const sendEmailBadStub = (options, callback) =&gt; callback(new Error('dat boom'))
    it('should work with good stubs', ()=&gt; {
        return expect(sendEmailSafe(sendEmailStub, {})).to.be.fulfilled
    })
    it('should fail with bad stubs', ()=&gt; {
        return expect(sendEmailSafe(sendEmailBadStub, {})).to.be.rejected
    })
})
</code></pre>
<p>And change &#8217;em to:</p>
<pre><code>describe('sendEmailSafe when called', ()=&gt; {
    class TransportStub {
        constructor(mailOptions) {
            this.mailOptions = mailOptions
        }
        sendEmail(options, callback) {
            callback(undefined, 'info')
        }
    }
    class TransportStubBad {
        constructor(mailOptions) {
            this.mailOptions = mailOptions
        }
        sendEmail(options, callback) {
            callback(new Error('dat boom'))
        }
    }
    it('should work with good stubs', ()=&gt; {
        return expect(sendEmailSafe(new TransportStub({}), {})).to.be.fulfilled
    })
    it('should fail with bad stubs', ()=&gt; {
        return expect(sendEmailSafe(new TransportStubBad({}), {})).to.be.rejected
    })
})
</code></pre>
<p>Notice once you go OOP, things get more verbose. Bleh.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Functional Programming Unit Testing in Node &#8211; Part 4</title>
		<link>https://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-4.html</link>
					<comments>https://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-4.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Fri, 22 Jun 2018 16:28:18 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[curry]]></category>
		<category><![CDATA[fp]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[imperative]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[objectorientedprogramming]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[partial]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[stubs]]></category>
		<category><![CDATA[unittesting]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5561</guid>

					<description><![CDATA[Concurrency, Compose, and Coverage Welcome to Part 4 where we show how to do concurrency which is a lot easier to get &#8220;for free&#8221; using pure functions, we compose both async and synchronous functions, we and utilize a test coverage report to where next to focus our refactoring and testing efforts. Contents This is a [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Concurrency, Compose, and Coverage</h1>
<p>Welcome to Part 4 where we show how to do concurrency which is a lot easier to get &#8220;for free&#8221; using pure functions, we compose both async and synchronous functions, we and utilize a test coverage report to where next to focus our refactoring and testing efforts.<br />
<span id="more-5561"></span></p>
<h2>Contents</h2>
<p>This is a 6 part series on refactoring imperative code in Node to a functional programming style with unit tests. You are currently on Part 4.</p>
<ul>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-1.html">Part 1 &#8211; Ground Rules, Export, and Server Control</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-2.html">Part 2 &#8211; Predicates, Async, and Unsafe</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-3.html">Part 3 &#8211; OOP, Compose, Curry</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-4.html">Part 4 &#8211; Concurrency, Compose, and Coverage</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-5.html">Part 5 &#8211; Noops, Stub Soup, and Mountebank</a></li>
<li><a href="http://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-6.html">Part 6 &#8211; Next, Logging, and Conclusions</a></li>
</ul>
<h1>Compose Again</h1>
<p>Assuming <code>getUserEmail</code> succeeded, we&#8217;ll have the user&#8217;s information so we can send an email. We now need to read the text email template to inject that information into. We&#8217;ll compose that <code>readFile</code> function we wrote. The existing code is imperatively inside the <code>getUserEmail</code>&#8216;s then:</p>
<pre><code class="javascript">...
userModule.getUserEmail(get('cookie.sessionID', req))
    .then(value =&gt; {
        fs.readFile('./templates/email.html', 'utf-8', (err, template) =&gt; {
            if (err) {
                console.log(err)
                    err.message = 'Cannot read email template'
                    err.httpStatusCode = 500
                    return next(err)
            }
...
</code></pre>
<p>Let&#8217;s fix that and compose them together #connectDemTrainTrax:</p>
<pre><code class="javascript">...
userModule.getUserEmail(get('cookie.sessionID', req))
.then(userInfo =&gt; readEmailTemplate(fs)))
.then(template =&gt; ...)
...
</code></pre>
<p>Great! We even removed all the error handling as that&#8217;s built into our pure <code>readEmailTemplate</code> function.</p>
<h2>Parallelism, Not Concurrency (Who Cares)</h2>
<p>However, that&#8217;s one new problem; we need <code>userInfo</code> later on once we&#8217;ve gotten all the email info setup and ready. Since it&#8217;s only in scope for this function it&#8217;s now gone. One of JavaScript&#8217;s most powerful and taken for granted features, <a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36">closures</a>, we just threw out the window to remain &#8220;pure&#8221; for purity&#8217;s sake.</p>
<p>We can fix it, though, with one of JavaScript&#8217;s other features: <a href="https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/">non-blocking I/O</a>. We can return 3 Promises and wait for all 3 to complete, and use all 3 values in the same function. It doesn&#8217;t matter if one takes longer than the others; <code>Promise.all</code> will wait for all 3 to be done, then give us an Array with all 3 values in order. If even 1 has an error, it&#8217;ll just pop out the <code>.catch</code>. This has 2 bad problems, but we&#8217;ll tackle that in another article. This also has the benefit of being faster in that we don&#8217;t have to wait for each in line, they all happen &#8220;at the same time Node style&#8221; which is not the same as &#8220;happening at the same time <a href="https://blog.codeship.com/comparing-elixir-go/">Elixir/Erlang or Go style</a>&#8221; but that&#8217;s ok, we can get into the same <a href="https://www.youtube.com/watch?v=6scxiuiftKY">dance club</a>.</p>
<p>For now, we&#8217;ll refactor to:</p>
<pre><code class="javascript">...
Promise.all([
      getUserEmail(get('cookie.sessionID', req)),
      readEmailTemplate(readFile),
      mapFilesToAttachments(filterCleanFiles(get('files', req)))
    ])
    .then( ([userEmailAddress, emailTemplate, fileAttachments]) =&gt; ...)
...
</code></pre>
<p>Now we&#8217;re talking. Loading from an external web service, reading from a local file, and a synchronous function call all can happen &#8220;at the same time&#8221;, and we don&#8217;t have to worry about how long each one takes. We use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Array Destructuring</a> to get our arguments out. Note they come in the same order we put the functions into the <code>Promise.all</code>.</p>
<p>We now have our user&#8217;s email address, the text template to inject information into, along with the file attachments used for both in the same function scope.</p>
<h2>Synchronous Compose</h2>
<p>One thing to nitpick. Sometimes you refactor FP code for readability purposes, not just for the mathematical purity reasons. In this case, check out the 3 levels of nesting:</p>
<pre><code class="javascript">mapFilesToAttachments(filterCleanFiles(get('files', req)))
</code></pre>
<p>In imperative code, if you see if/then statements nested more than 2 levels deep, that tends raise concern. Developers are sometimes fine with creating that code to ensure they truly understand the different cases in playing with ideas, but once complete, they don&#8217;t like LEAVING it that way. Nested if statements are hard to read and follow. If you DO follow them, you can sometimes get a rush or high in &#8220;figuring it out&#8221;. That&#8217;s not the goal, though; nested if&#8217;s are considered bad practice.</p>
<p>For FP, deeply nested functions like this have the same problem. It&#8217;s compounded by the fact we attempted to use verbose names for the functions to make what they do more clear vs. short names. This ends up making the problem worse.</p>
<p>For Promises, it&#8217;s not so bad; you just shove them in the <code>.then</code>. But what about synchronous code?</p>
<p>You have 2 options:</p>
<ol>
<li>Simply wrap in them in a Promise; most promises except for a couple of edge cases are fine getting a return value of a <code>Promise</code> or a value as long as the value isn&#8217;t an <code>Error</code>.</li>
<li>Use Lodash&#8217; <code>flow</code> function, or Ramda&#8217;s <code>compose</code>.</li>
<li>Use the pipeline operator.</li>
</ol>
<p>Sadly, at the time of this writing, the <a href="https://github.com/tc39/proposal-pipeline-operator">pipeline operator</a> is only at Stage 1 for JavaScript, meaning it&#8217;s not even considered a possibility for inclusion in the ECMA Standard yet. None of this code is asynchronous so we&#8217;ll use the Lodash <code>flow</code> (I like Ramda&#8217;s compose name better).</p>
<p>Let&#8217;s put the functions in order, just like we would with a Promise chain:</p>
<pre><code class="javascript">const filterCleanFilesAndMapToAttachments = flow([
  get('files'),
  filterCleanFiles,
  mapFilesToAttachments
])
</code></pre>
<p>Note the use of <code>get('files')</code>. The <code>get</code> function takes 2 arguments, but we only supply 1. We know it&#8217;s curried by default, meaning it&#8217;ll be a partial application if we just say <code>get('files')</code>; it&#8217;s waiting for the 2nd argument. Once it gets that, it&#8217;ll search for the &#8216;files&#8217; property on it, else give <code>undefined</code>. If it DOES find <code>undefined</code>, <code>filterCleanFiles</code> will just spit out an empty Array, and <code>mapFilesToAttachments</code> will spit out an empty Array when you give it an empty Array. Otherwise, they&#8217;ll get the good Array full of files, and both of those functions will do their thang.</p>
<p>See how we use curried functions that create partial applications to help compose other functions? I know&#8230; for you guys, not a good pickup line, but you never know, she me might be a Data Scientist who digs Scala. Or she&#8217;s lit and you look good and anything you say doesn&#8217;t really matter at that point. Either way, it&#8217;s alllll good.</p>
<p>Now to use that composed function, we take what we had:</p>
<pre><code class="javascript">Promise.all([
  getUserEmail(get('cookie.sessionID', req)),
  readEmailTemplate(readFile),
  mapFilesToAttachments(filterCleanFiles(get('files', req)))
])
</code></pre>
<p>And replace it with our composed function:</p>
<pre><code class="javascript">Promise.all([
  getUserEmail(get('cookie.sessionID', req)),
  readEmailTemplate(readFile),
  filterCleanFilesAndMapToAttachments(req)
])
</code></pre>
<p>Much better eh? Speaking of lit, I&#8217;m feeling that hard root beer right now, but I STILL remember we need to unit test our composed function. Let&#8217;s do that&#8230; and with confidence because we already have 3 unit tested pure functions, and we composed them together with a Lodash pure function. DAT CONFIDENCE BUILDING! Also, you MAY have to install config and nodemailer: <code>npm i config nodemailer</code> and then require them up top. Also, depending on the order of functions, you may have to move some functions around giving while we&#8217;re creating pure functions, they&#8217;re defined IN an imperative way, and so order matters. i.e. you have to create the <code>const app = express()</code> first before you can <code>app.post</code>.</p>
<pre><code class="javascript">describe('filterCleanFilesAndMapToAttachments when called', ()=&gt; {
    it('should give an attachment from a request with clean file', ()=&gt;{
        const reqStub = {files: [{scan: 'clean', originalname: 'so fresh', path: '/o/m/g'}]}
        const result = filterCleanFilesAndMapToAttachments(reqStub)
        expect(result[0].filename).to.equal('so fresh')
    })
    it('should give an empty Array with no files', ()=&gt;{
        const reqStub = {files: [{scan: 'dirty south', originalname: 'so fresh', path: '/o/m/g'}]}
        const result = filterCleanFilesAndMapToAttachments(reqStub)
        expect(result).to.be.empty
    })
    it('should give an empty Array with undefined', ()=&gt;{
        const result = filterCleanFilesAndMapToAttachments(undefined)
        expect(result).to.be.empty
    })
})
</code></pre>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-14-at-7.10.46-PM-300x68.png" alt="" width="300" height="68" class="alignleft size-medium wp-image-5524" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-14-at-7.10.46-PM-300x68.png 300w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-14-at-7.10.46-PM-768x175.png 768w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-14-at-7.10.46-PM.png 780w" sizes="auto, (max-width: 300px) 100vw, 300px" /></p>
<p>:: chink chunk :: <a href="https://www.youtube.com/watch?v=3ATBJGkdYgI">NIIIIICCCE!</a></p>
<h2>Composing the Promise Way</h2>
<p>You can also just compose the Promise way, and they&#8217;ll work for Promise based functions as well as synchronous ones allowing you to use interchangeably. Let&#8217;s first delete all the no-longer-needed imperative code:</p>
<pre><code class="javascript">let attachments = []
files.map(file =&gt; {
  if (file.scan === 'clean') {
    attachments.push({ filename: file.originalname, path: file.path })
  }
})

value.attachments = attachments
req.attachments = attachments
</code></pre>
<p>And we&#8217;ll take the remaining mix of synchronous and imperative code, and one by one wire together:</p>
<pre><code class="javascript">let emailBody = Mustache.render(template, value)
let emailService = config.get('emailService')
const transporter = nodemailer.createTransport({
  host: emailService.host,
  port: emailService.port,
  secure: false,
})

const mailOptions = {
  from: emailService.from,
  to: emailService.to,
  subject: emailService.subject,
  html: emailBody,
  attachments: attachments,
}

transporter.sendMail(mailOptions, (err, info) =&gt; {
  if (err) {
    err.message = 'Email service unavailable'
    err.httpStatusCode = 500
    return next(err)
  } else {
    return next()
  }
})
</code></pre>
<p>You hopefully are getting trained at this point to start noticing &#8220;globals in my function&#8221;. Note our current line of code is:</p>
<pre><code class="javascript">let emailBody = Mustache.render(template, value)
</code></pre>
<p>But nowhere in the function arguments do we pass the <code>render</code> function to use. Let&#8217;s quickly modify the ever-growing Express route function signature from:</p>
<pre><code class="javascript">const sendEmail = curry((readFile, config, createTransport, getUserEmail, req, res, next) =&gt;
</code></pre>
<p>to:</p>
<pre><code class="javascript">const sendEmail = curry((readFile, config, createTransport, getUserEmail, render, req, res, next) =&gt;
</code></pre>
<p>We&#8217;re already in a Promise at this point, so we can return a value here, or a Promise and we&#8217;ll be sure we can add another <code>.then</code> if we need to. One trick <a href="https://code.visualstudio.com/">VSCode</a>, a free text and code editor by Microsoft, has is highlighting variables. Before we shove this rendered email template variable in the Monad train, let&#8217;s see if anyone down the tracks needs it. We&#8217;ll select the whole variable, and watch how VSCode will highlight usage of it as well:</p>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-14-at-7.26.52-PM.png" alt="" width="652" height="780" class="alignleft size-full wp-image-5525" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-14-at-7.26.52-PM.png 652w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-14-at-7.26.52-PM-251x300.png 251w" sizes="auto, (max-width: 652px) 100vw, 652px" /></p>
<p>Crud&#8230; it&#8217;s a ways down, AND it&#8217;s mixed in with this <code>emailService</code> thing. Let&#8217;s highlight him and see where he&#8217;s grouped:</p>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-14-at-7.28.56-PM.png" alt="" width="656" height="778" class="alignleft size-full wp-image-5526" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-14-at-7.28.56-PM.png 656w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-14-at-7.28.56-PM-253x300.png 253w" sizes="auto, (max-width: 656px) 100vw, 656px" /></p>
<p>This&#8217;ll be tricky. Good news, rendering the email and loading the email service configuration can be done at the same time. Let&#8217;s keep that INSIDE the Promise now until we feel comfortable we no longer need the <code>userEmailAddress</code>, <code>emailTemplate</code>, <code>fileAttachments</code> in scope. A lot more pragmatic people would be fine with keeping the code this way, and using JavaScript&#8217;s built in feature of closures, and move on with life. However, imperative code is harder to test, and results in LONGER code vs. smaller, pure functions that are easier to test. You don&#8217;t always START there, though. It&#8217;s fine to write imperative, then write &#8220;kind of pure&#8221; and keep refactoring your way there. That&#8217;s part of learning, figuring our the idea of how your code should work, or both.</p>
<pre><code class="javascript">...
.then( ([userEmailAddress, emailTemplate, fileAttachments]) =&gt; {
    return Promise.all([
      render(render, template, userEmailAddress),
      getEmailService(config)
    ])
    .then( ([emailBody, emailService]) =&gt; ...
...
</code></pre>
<p>And we&#8217;ll clean up the code below to use our pure functions first imperatively:</p>
<pre><code class="javascript">...
.then( ([emailBody, emailService]) =&gt; {
  const transportObject = createTransportObject(emailService.host, emailBody.port)
  const transport = createTransport(transportObject)
  const sendEmailFunction = transport.sendEmail
  const mailOptions = createMailOptions(
    emailService.from,
    emailService.to,
    emailService.subject,
    emailBody,
    fileAttachments
  )
  return sendEmailSafe(sendEmailFunction, mailOptions)
})
</code></pre>
<p>&#8230; and then refactor to more functional:</p>
<pre><code class="javascript">...
.then( ([emailBody, emailService]) =&gt;
  sendEmailSafe(
    createTransport(
      createTransportObject(emailService.host, emailBody.port)
    ).sendEmail,
    createMailOptions(
      emailService.from,
      emailService.to,
      emailService.subject,
      emailBody,
      fileAttachments
    )
  )
})
...
</code></pre>
<p>Note the <code>fileAttachments</code> comes from the scope higher up. The <code>sendEmailSafe</code> function requires a nodemailer <code>transport</code>. We create that from our function that creates the Object from the <code>emailService</code>. Once created we need that <code>sendEmail</code> function to pass it to the <code>sendEmailSafe</code> so we just immediately go <code>.sendEmail</code> in the first parameter. The <code>createMailOptions</code> is another function that simply creates our Object from the <code>emailService</code> object, the rendered via Mustache <code>emailBody</code>, and the virus scanned <code>fileAttachements</code>. One last touch is to remove the squiggly braces <code>{}</code> as we&#8217;re no longer writing imperative code, and the <code>return</code> statement as Arrow functions have an implicit return when you remove the squiggly braces.</p>
<p>This last part is left over from the callback:</p>
<pre><code class="javascript">), reason =&gt; {
      return next(reason)
    })
</code></pre>
<p>Typically you defer <code>Promise</code> error handling higher up the call stack; meaning, &#8220;let whoever is calling me deal with error handling since Promises that call Promises have their errors propagate up&#8221;. That&#8217;s fine, so&#8230; we&#8217;ll delete it.</p>
<p>After all that refactoring, here&#8217;s what we&#8217;re left with:</p>
<pre><code class="javascript">const sendEmail = curry((readFile, config, createTransport, getUserEmail, render, req, res, next) =&gt;
    Promise.all([
      getUserEmail(get('cookie.sessionID', req)),
      readEmailTemplate(readFile),
      filterCleanFilesAndMapToAttachments(req)
    ])
    .then( ([userEmailAddress, emailTemplate, fileAttachments]) =&gt; 
      Promise.all([
          render(render, template, userEmailAddress),
          getEmailService(config)
        ])
        .then( ([emailBody, emailService]) =&gt;
          sendEmailSafe(
            createTransport(
              createTransportObject(emailService.host, emailBody.port)
            ).sendEmail,
            createMailOptions(
              emailService.from,
              emailService.to,
              emailService.subject,
              emailBody,
              fileAttachments
            )
          )
        )
    ))
</code></pre>
<h1>Coverage Report</h1>
<p>Let&#8217;s unit test it; it&#8217;ll be hard because we have a lot of stubs, but we can borrow from the ones we&#8217;ve already created in the other tests. I&#8217;m not going to DRY the code at all in the tests as that would require too much brainpower at this point, but when you get an Agile Sprint or time to pay down technical debt, this is one of the stories/tasks you add to that list.</p>
<p>&#8230; before we do, let&#8217;s run a coverage report to see how much work we have cut out for us (we&#8217;re ignoring my fake npm module and the user stuff for now). Run <code>npm run coverage &amp;&amp; open coverage/lcov-report/index.html</code>:</p>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-9.26.09-AM-1024x79.png" alt="" width="525" height="41" class="alignleft size-large wp-image-5530" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-9.26.09-AM-1024x79.png 1024w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-9.26.09-AM-300x23.png 300w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-9.26.09-AM-768x59.png 768w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-9.26.09-AM.png 1950w" sizes="auto, (max-width: 525px) 100vw, 525px" /></p>
<p>And the details around our particular function:</p>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-9.28.27-AM-1024x600.png" alt="" width="525" height="308" class="alignleft size-large wp-image-5531" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-9.28.27-AM-1024x600.png 1024w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-9.28.27-AM-300x176.png 300w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-9.28.27-AM-768x450.png 768w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-9.28.27-AM.png 1462w" sizes="auto, (max-width: 525px) 100vw, 525px" /></p>
<h2>Status Quo at This Point</h2>
<p>Wonderful; the only thing we need to test is the composition of those functions in <code>Promise.all</code>. Rather than create 20 billion stubs, and ensure they&#8217;re setup &#8220;just so&#8221; so the <code>sendEmail</code> unit test passes or fails, we&#8217;ll continue to our strategy of pulling out teency pieces, wrapping them in pure functions, testing those, repeat. Let&#8217;s start with the first <code>Promise.all</code>:</p>
<pre><code class="javascript">const getSessionIDFromRequest = get('cookie.sessionID')
const getEmailTemplateAndAttachments = curry((getUserEmail, readFile, req) =&gt;
  Promise.all([
    getUserEmail(getSessionIDFromRequest(req)),
    readEmailTemplate(readFile),
    filterCleanFilesAndMapToAttachments(req)
  ]))
</code></pre>
<p>Then we&#8217;ll unit test the <code>getEmailTemplateAndAttachments</code> (he&#8217;ll end up ensuring we&#8217;ve tested the new <code>getSessionIDFromRequest</code>):</p>
<pre><code class="javascript">describe('getEmailTemplateAndAttachments when called', ()=&gt; {
    const reqStub = {
        cookie: { sessionID: '1' },
        files: [{scan: 'clean', originalname: 'so fresh', path: '/o/m/g'}]
    }
    const getUserEmailStub = () =&gt; 'email'
    const readFileStub = (path, encoding, callback) =&gt; callback(undefined, 'email')
    const readFileStubBad = (path, encoding, callback) =&gt; callback(new Error('b00mz'))
    it('should succeed with good stubs', ()=&gt; {
        return expect(
            getEmailTemplateAndAttachments(getUserEmailStub, readFileStub, reqStub)
        ).to.be.fulfilled
    })
    it('should succeed resolve to having an email', ()=&gt; {
        return getEmailTemplateAndAttachments(getUserEmailStub, readFileStub, reqStub)
        .then( ([userEmail, emailBody, attachments]) =&gt; {
            expect(userEmail).to.equal('email')
        })
    })
    it('should fail if reading file fails', ()=&gt; {
        return expect(
            getEmailTemplateAndAttachments(getUserEmailStub, readFileStubBad, reqStub)
        ).to.be.rejected
    })
})
</code></pre>
<p>And we&#8217;ll then swap it out for the raw <code>Promise.all</code>:</p>
<pre><code class="javascript">const sendEmail = curry((readFile, config, createTransport, getUserEmail, render, req, res, next) =&gt;
    getEmailTemplateAndAttachments(getUserEmail, readFile, req)
    .then( ([userEmailAddress, emailTemplate, fileAttachments]) =&gt; 
      Promise.all([
          render(render, template, userEmailAddress),
          getEmailService(config)
        ])
        .then( ([emailBody, emailService]) =&gt;
          sendEmailSafe(
            createTransport(
              createTransportObject(emailService.host, emailBody.port)
            ).sendEmail,
            createMailOptions(
              emailService.from,
              emailService.to,
              emailService.subject,
              emailBody,
              fileAttachments
            )
          )
        )
    ))
</code></pre>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-9.58.21-AM.png" alt="" width="622" height="184" class="alignleft size-full wp-image-5532" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-9.58.21-AM.png 622w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-9.58.21-AM-300x89.png 300w" sizes="auto, (max-width: 622px) 100vw, 622px" /></p>
<p>&#8230; and then re-run coverage. Just run <code>npm run coverage</code> and you can refresh the coverage in the browser:</p>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-10.00.31-AM-1024x504.png" alt="" width="525" height="258" class="alignleft size-large wp-image-5533" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-10.00.31-AM-1024x504.png 1024w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-10.00.31-AM-300x148.png 300w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-10.00.31-AM-768x378.png 768w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-10.00.31-AM.png 1466w" sizes="auto, (max-width: 525px) 100vw, 525px" /></p>
<p>As you can see, coverage isn&#8217;t going to let us off that easy. That&#8217;s ok, we can re-use these stubs for the final battle. Let&#8217;s do the last <code>Promise.all</code>.</p>
<pre><code class="javascript">describe('renderEmailAndGetEmailService when called', ()=&gt; {
    const configStub = { has: stubTrue, get: () =&gt; 'email service' }
    const renderStub = stubTrue
    const renderStubBad = () =&gt; { throw new Error('intentionally failed render')}
    it('should work with good stubs', ()=&gt; {
        return expect(
            renderEmailAndGetEmailService(configStub, renderStub, 'template', 'user email')
        ).to.be.fulfilled
    })
    it('should resolve to an email', ()=&gt; {
        return renderEmailAndGetEmailService(configStub, renderStub, 'template', 'user email')
        .then( ([emailRendered, emailService]) =&gt; {
            expect(emailRendered).to.equal(true)
        })
    })
    it('should fail if rendering fails', ()=&gt; {
        return expect(
            renderEmailAndGetEmailService(configStub, renderStubBad, 'template', 'user email')
        ).to.be.rejected
    })
})
</code></pre>
<p><img loading="lazy" decoding="async" src="http://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-10.20.15-AM.png" alt="" width="572" height="184" class="alignleft size-full wp-image-5534" srcset="https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-10.20.15-AM.png 572w, https://jessewarden.com/wp-content/uploads/2018/06/Screen-Shot-2018-06-16-at-10.20.15-AM-300x97.png 300w" sizes="auto, (max-width: 572px) 100vw, 572px" /></p>
<p>And swap it out:</p>
<pre><code class="javascript">const sendEmail = curry((readFile, config, createTransport, getUserEmail, render, req, res, next) =&gt;
    getEmailTemplateAndAttachments(getUserEmail, readFile, req)
    .then( ([userEmailAddress, emailTemplate, fileAttachments]) =&gt; 
      renderEmailAndGetEmailService(config, render, emailTemplate, userEmailAddress)
      .then( ([emailBody, emailService]) =&gt;
        sendEmailSafe(
          createTransport(
            createTransportObject(emailService.host, emailBody.port)
          ).sendEmail,
          createMailOptions(
            emailService.from,
            emailService.to,
            emailService.subject,
            emailBody,
            fileAttachments
          )
        )
      )
    ))
</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2018/06/functional-programming-unit-testing-in-node-part-4.html/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
	</channel>
</rss>
