<?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>python &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/python/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Wed, 18 Mar 2020 13:35:44 +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>python &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Write Unbreakable Python</title>
		<link>https://jessewarden.com/2020/03/write-unbreakable-python.html</link>
					<comments>https://jessewarden.com/2020/03/write-unbreakable-python.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Tue, 17 Mar 2020 16:34:14 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[either]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[lenses]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[result]]></category>
		<guid isPermaLink="false">https://jessewarden.com/?p=5890</guid>

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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


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


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



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


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

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


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



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



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


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

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


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


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


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


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


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


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


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



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



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



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



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



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



<p>Dictionaries can work:</p>


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


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


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


<p>Wat do!?</p>



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



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


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


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


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


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



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



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



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


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


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


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


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


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


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



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



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



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


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


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



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


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


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



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


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


<p>Cool.</p>


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


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


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


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


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


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



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



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


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


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


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


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


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

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


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



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


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


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



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


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


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


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


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



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



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



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



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



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



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



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


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


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


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


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


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


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


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


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


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


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


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


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


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


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



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



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


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


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



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



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


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


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



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



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



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



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



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



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


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


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



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



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



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



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



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


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


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


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


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


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


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


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


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


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

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

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

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


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


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


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



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


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


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



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


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


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



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



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



<p>Get dat key:</p>


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


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



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


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


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



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


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


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


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


<p>When you go:</p>


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


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



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


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


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



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



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



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



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



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



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


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


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

					<description><![CDATA[Introduction There are various ways of handling errors in programming. This includes not handling it. Many languages have created more modern ways of error handling. An error is when the program, intentionally, but mostly not, breaks. Below, I&#8217;ll cover the 4 main ones I know: try/catch, explicit returns, either, and supervising crashes. We&#8217;ll compare various [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>There are various ways of handling errors in programming. This includes not handling it. Many languages have created more modern ways of error handling. An error is when the program, intentionally, but mostly not, breaks. Below, I&#8217;ll cover the 4 main ones I know: try/catch, explicit returns, either, and supervising crashes. We&#8217;ll compare various languages on how they approach errors: Python, JavaScript, Lua, Go, Scala, Akka, and Elixir. Once you understand how the newer ways work, hopefully this will encourage you to abandon using potentially program crashing errors via the dated <code>throw</code>/<code>raise</code> in your programs.<br />
<span id="more-5373"></span></p>
<h2>Contents</h2>
<ul>
<li><a href="#whyevencare">Why Even Care</a></li>
<li><a href="#throwtrycatch">Throw, Try, Catch, Finally</a></li>
<li><a href="#explicitreturn">Explicit Return</a>
<ul>
<li><a href="#variouslanguageexamples">Various Language Examples of Explicit Returns</a></li>
<li><a href="#effectsoncoding">Effects On Coding</a></li>
<li><a href="#consonexplicitreturns">Cons on Explicit Returns</a></li>
</ul>
</li>
<li><a href="#either">Either, Left or Right, and Pattern Matching</a>
<ul>
<li><a href="#eithertype">The Either Type</a></li>
<li><a href="#eitherexamples">Either Examples</a></li>
<li><a href="#patternmatching">Pattern Matching</a></li>
</ul>
</li>
<li><a href="#letitcrash">Let It Crash</a></li>
<li><a href="#conclusions">Conclusions</a></li>
</ul>
<p><a name="whyevencare"></a></p>
<h1>Why Even Care?</h1>
<p>When programs crash, log/print/trace statements and errors aren&#8217;t always helpful to quickly know what went wrong. Logs, if there are at all, tell a story you have to decipher. Errors, if there, sometimes give you a long stack trace, which often isn&#8217;t long enough. Asynchronous code can make this harder. Worse, both are often completely unrelated to the root cause, or lie and point you in the completely wrong debugging direction. Overall, most crashes aren&#8217;t always helpful in debugging why your code broke.</p>
<p>Various error handling strategies can prevent these problems.<br />
<a name="throwtrycatch"></a></p>
<h1 id="throw-try-catch-finally">Throw, Try, Catch, Finally</h1>
<p>The original way to implement an error handling strategy is to throw your own errors.</p>
<pre><code class="lang-javascript">// a type example
validNumber = n =&gt; _.isNumber(n) &amp;&amp; _.isNaN(n) === false;
add = (a, b) =&gt; {
   if(validNumber(a) === false) {
     throw new Error(`a is an invalid number, you sent: ${a}`);
   }
   if(validNumber(b) === false) {
     throw new Error(`b is an invalid number, you sent: ${b}`);
   }
   return a + b;
};
add('cow', new Date()); // throws
</code></pre>
<p>They have helpful and negative effects that take pages of text to explain. The reason you shouldn&#8217;t use them is they can crash your program. While often this is often intentional by the developer, you could negatively affect things outside your code base like a user&#8217;s data, logs, and this often trickles down to user experience. It also makes it more difficult for the developer debugging to pinpoint exactly where it failed and why.</p>
<p>I jokingly call them explosions because they accidentally can affect completely unrelated parts of the code when they go off. Compilers and runtime errors in sync and async code still haven&#8217;t gotten good enough (except maybe <a href="http://elm-lang.org/">Elm</a>) to help us immediately diagnose what we, or someone else, did wrong.</p>
<p>We don&#8217;t want to crash a piece of code or entire programs.</p>
<p>We want to correctly identify what went wrong, give enough information for the developer to debug and/or react, and ensure that error is testable. Intentional developer throws attempt to tell you what went wrong and where, but they don&#8217;t play nice together, often mask the real issue in cascading failures, and while sometimes testable in isolation, they are harder to test in larger composed programs.<br />
<a name="explicitreturn"></a></p>
<h1 id="explicit-return">Explicit Return</h1>
<p>The second option is what Go, Lua, and sometimes Elixir do, where you handle the possible error on a per function basis. They return information if the function worked or not along with the regular return value. Basically they return 2 values instead of 1. These are different for asynchronous calls per language so let&#8217;s focus on synchronous for now.</p>
<p><a name="variouslanguageexamples"></a></p>
<h2 id="various-langauge-examples-of-explicit-returns">Various Language Examples of Explicit Returns</h2>
<p>Lua functions will throw errors just like Python and JavaScript. However, using a function called protected call, <code class="lang-lua">pcall</code> it will capture the exception as part of a 2nd return value:</p>
<pre><code class="lang-lua">function datBoom()
  error({reason='kapow'})
end
ok, error = pcall(datBoom)
print("did it work?", ok, "error reason:", error.reason)
-- did it work? false, error: kapow
</code></pre>
<p>Go has this functionality natively built in:</p>
<pre><code class="lang-go">func datBoom() (err error)
ok, err := datBoom()
if err != nil {
  log.Fatal(err)
}
</code></pre>
<p>&#8230; and so does Elixir (with the ability to opt out using a ! at the end of a function invocation):</p>
<pre><code class="lang-elixir">def datBoom do
  {:error, "kapow"}
end

{:error, reason} = datBoom()
IO.puts "Error: #{reason}" ## kapow
</code></pre>
<p>While Python and JavaScript do not have these capabilities built into the language, you can easily add them.</p>
<p>Python can do the same using tuples:</p>
<pre><code class="lang-python">def datBoom():
  return (False, 'kapow')

ok, error = datBoom()
print("ok:", ok, "error:", error) # ('ok:', False, 'error:', 'kapow')
</code></pre>
<p>JavaScript can do the same using Object destructuring:</p>
<pre><code class="lang-javascript">const datBoom = () =&gt; ({ok: false, error: 'kapow'});
const {ok, error} = datBoom();
console.log("ok:", ok, "error:", error); // ok: false error: kapow
</code></pre>
<p><a name="effectsoncoding"></a></p>
<h2 id="effects-on-coding">Effects On Coding</h2>
<p>This causes a couple of interesting things to happen. First, developers are forced to handle errors when and where they occur. In the throw scenario, you run a lot of code, and sprinkle throws where you think it&#8217;ll break. Here, even if the functions aren&#8217;t pure, every single one could possibly fail. There is no point continuing to the next line of code because you already failed at the point of running the function and seeing it failed (<code>ok</code> is false) an error was returned telling you why. You start to really think how to architect things differently.</p>
<p>Second, you know WHERE the error occurred (mostly). The &#8220;why&#8221; is still always up for debate.</p>
<p>Third, and most important, if the functions are pure, they become easier to unit test. Instead of &#8220;I get my data, else it possibly blows up&#8221;, it immediately tells you: &#8220;I worked, and here&#8217;s your data&#8221;, or &#8220;I broke, and here&#8217;s what could be why&#8221;.</p>
<p>Fourth, these errors DO NOT (in most cases if your functions are pure) negatively affect the rest of the application. Instead of a throw which could take other functions down with it, you&#8217;re not throwing, you&#8217;re simply returning a different value from a function call. The function &#8220;worked&#8221; and reported its &#8220;results&#8221;. You&#8217;re not crashing applications just because a function didn&#8217;t work.</p>
<p><a name="consonexplicitreturns"></a></p>
<h2 id="cons-on-explicit-returns">Cons on Explicit Returns</h2>
<p>Excluding language specifics (i.e. Go panics, JavaScript&#8217;s async/await), you have to look in 2 to 3 places to see what went wrong. It&#8217;s one of the arguments against Node callbacks. People say not to use <code>throw</code> for control flow, yet all of you done is create a dependable <code>ok</code> variable. A positive step for sure, but still not a hugely helpful leap. Errors, if detected to be there, mold your code&#8217;s flow.</p>
<p>For example, let&#8217;s attempt to parse some JSON in JavaScript. You&#8217;ll see the absence of a <code>try/catch</code> replaced with an <code>if(ok === false)</code>:</p>
<pre><code class="lang-javascript">const parseJSON = string =&gt; {
  try {
    const data = JSON.parse(string);
    return {ok: true, data};
  } catch(error) {
    return {ok: false, error};
  }
};
const {ok, error, data} = parseJSON(new Date());
if(ok === false) {
  console.log("failed:", error);
} else {
  console.log("worked:", data);
}
</code></pre>
<p><a name="either"></a></p>
<h1 id="either-left-or-right-and-pattern-matching">Either, Left or Right, and Pattern Matching</h1>
<p><a name="eithertype"></a></p>
<h2 id="the-either-type">The Either Type</h2>
<p>Functions that can return 2 types of values are solved in functional programming by using the <code>Either</code> type, aka a disjoint union. <a href="https://www.typescriptlang.org/">Typescript</a> (strongly typed language &amp; compiler for JavaScript) supports a <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html">psuedo Either</a> as an <a href="https://leanpub.com/purescript/read#leanpub-auto-algebraic-data-types">Algebraic Data Type</a> (aka ADT).</p>
<p>For example, this TypeScript <code>getPerson</code> function will return <code>Error</code> or <code>Person</code> and your compiler helps you with that:</p>
<pre><code class="lang-typescript">// Notice TypeScript allows you to say 2 possible return values
function getPerson() : Error | Person
</code></pre>
<p>The <code>getPerson</code> will return either <code>Error</code>, or <code>Person</code>, but never both.</p>
<p>However, we&#8217;ll assume, regardless of language, you&#8217;re concerned with runtime, not compile time. You could be an API developer dealing with JSON from some unknown source, or a front end engineer dealing with user input. In functional programming they have the concept of a &#8220;left or right&#8221; in an Either type, or an object depending on your language of choice.</p>
<p>The convention is &#8220;Right is Correct&#8221; and &#8220;Left is Incorrect&#8221; (Right is right, Left is wrong).</p>
<p>Many languages already support this in one form or another:</p>
<p>JavaScript through Promises as values: <code>.then</code> is right, <code>.catch</code> is left) and Python via deferred values via the <a href="https://twistedmatrix.com/documents/16.5.0/core/howto/defer.html">Twisted</a> networking engine: <code>addCallback</code> is right, <code>addErrback</code> is left.</p>
<p><a name="eitherexamples"></a></p>
<h2 id="either-examples">Either Examples</h2>
<p>You can do this using a class or object in Python and JavaScript. We&#8217;ve already shown you the Object version above using <code>{ok: true, data}</code> for the right, and <code>{ok: false, error}</code> for the left.</p>
<p>Here&#8217;s a JavaScript Object Oriented example:</p>
<pre><code class="lang-javascript">class Either {
  constructor(right=undefined, left=undefined) {
    this._right = right;
    this._left = left;
  }
  isLeft() {
    return this.left !== undefined;
  }
  isRight() {
    return this.right !== undefined;
  }
  get left() {
    return this._left;
  }
  get right() {
    return this._right;
  }
}

const datBoom = () =&gt; new Either(undefined, new Error('kapow'));
const result = datBoom();
if(result.isLeft()) {
  console.log("error:", result.left);
} else {
  console.log("data:", result.right);
}
</code></pre>
<p>&#8230; but you can probably already see how a <code>Promise</code> is a much better data type (despite it implying async). It&#8217;s an immutable value, and the methods <code>then</code> and <code>catch</code> are already natively there for you. Also, no matter how many <code>then</code>&#8216;s or &#8220;rights&#8221;, 1 left can mess up the whole bunch, and it allllll flows down the single <code>catch</code> function for you. This is where composing Eithers (Promises in this case) is so powerful and helpful.</p>
<pre><code class="lang-javascript">const datBoom = () =&gt; Promise.reject('kapow');
const result = datBoom();
result
.then(data =&gt; console.log("data:", data))
.catch(error =&gt; console.log("error:", error));
</code></pre>
<p><a name="patternmatching"></a></p>
<h2 id="pattern-matching">Pattern Matching</h2>
<p>Whether synchronous or not, though, there&#8217;s a more powerful way to match the Either &#8216;esque types through pattern matching. If you&#8217;re an OOP developer, think of replacing your:</p>
<p><code>if ( thingA instanceof ClassA ) {</code></p>
<p>with:</p>
<p><code>ClassA: ()=&gt; "it's ClassA",<br />
ClassB: ()=&gt; "it's ClassB"</code>.</p>
<p>It&#8217;s like a <code>switch</code> and <code>case</code> for types.</p>
<p>Elixir does it with almost all of their functions (the _ being the traditional <code>default</code> keyword):</p>
<pre><code class="lang-elixir">case datBoom do
  {:ok, data}      -&gt; IO.puts "Success: #{data}"
  {:error, reason} -&gt; IO.puts "Error: #{reason}"
  _                -&gt; IO.puts "No clue, brah..."
end
</code></pre>
<p>In JavaScript, you can use the <a href="http://folktale.origamitower.com/api/v2.0.0/en/folktale.result.html">Folktale library</a>.</p>
<pre><code class="lang-javascript">const datBoom = () =&gt; Result.Error('kapow');
const result = datBoom();
const weGood = result.matchWith({
  Error: ({value}) =&gt; "negative...",
  Ok: ({value}) =&gt; "OH YEAH!"
});
console.log("weGood:", weGood); // negative...
</code></pre>
<p>Python has pattern matching with <a href="https://github.com/billpmurphy/hask">Hask</a> (although it&#8217;s dead project, <a href="https://github.com/evhub/coconut">Coconut</a> is an alternative):</p>
<pre><code class="lang-python">def datBoom():
  return Left('kapow')

def weGood(value):
    return ~(caseof(value)
                | m(Left(m.n)) &gt;&gt; "negative..."
                | m(Right(m.n)) &gt;&gt; "OH YEAH!")

result = datBoom()
print("weGood:", weGood(result)) # negative...
</code></pre>
<p>Scala does it as well, looking more like a traditional switch statement:</p>
<pre><code class="lang-scala">def weGood(value: Either): String = value match {
  case Left =&gt; "negative..."
  case Right =&gt; "OH YEAH!"
  case _ =&gt; "no clue, brah..."
}
weGood(Left('kapow'))  // negative...
</code></pre>
<p><a name="letitcrash"></a></p>
<h1 id="let-it-crash">Let It Crash</h1>
<p>The Mathematicians came up with Either. Three cool kats at Ericsson in 1986 came up with a different strategy in Erlang: let it crash. Later in 2009, <a href="https://akka.io/">Akka</a> took the same idea for the Java Virtual Machine in Scala and Java.</p>
<p>This flies in the face of the overall narrative of this article: don&#8217;t intentionally cause crashes. Technically it&#8217;s a supervised crash. The Erlang / Akka developers know errors are a part of life, so embrace they will will happen, and give you a safe environment to react to them happening without bringing down the rest of your application.</p>
<p>It also only becomes relatable if you do the kind of work where uptime with lots of traffic is the number one goal. Erlang (or Elixir) create processes to manage your code. If you know <a href="http://redux.js.org/">Redux</a> or <a href="http://elm-lang.org/">Elm</a>, the concept of a store to keep your (mostly) immutable data, then you&#8217;ll understand the concept of a Process in Elixir, and an Actor in Akka. You create a process, and it runs your code.</p>
<p>Except, the framework developers knew that if you find a bug, you&#8217;ll fix it and upload new code to the server. If the server needs to keep running to serve a lot of customers, then it needs to immediately restart if something crashes. If you upload new code, it needs to restart your new code as the older code processes shut down when they are done (or crash).</p>
<p>So, they created supervisors <a href="https://elixir-lang.org/getting-started/mix-otp/supervisor-and-application.html">Elixir</a>|<a href="https://doc.akka.io/docs/akka/current/scala/general/supervision.html">Scala</a>. Instead of creating 1 process that runs your code, it creates 2: one to run your code, and another to supervise it if it crashes, to restart a new one. These processes are uber lightweight (0.5kb of memory in Elixir, 0.3kb in Akka).</p>
<p>While Elixir has support for <a href="https://elixir-lang.org/getting-started/try-catch-and-rescue.html">try, catch, and raise</a>, error handling in Erlang/Elixir is a code smell. Let it crash, the supervisor will restart the process, you can debug the code, upload new code to a running server, and the processes spawned from that point forward will use your new code. This is similar to the immutable infrastructure movement around Docker in <a href="https://aws.amazon.com/ecs/">Amazon&#8217;s EC2 Container Service</a> and <a href="https://kubernetes.io/">Kubernetes</a>.</p>
<p><a name="conclusions"></a></p>
<h1 id="conclusions">Conclusions</h1>
<p>Intentionally crashing programs is a bad programming practice. Using <code>throw</code> is not the most effective way to isolate program problems, they aren&#8217;t easy to test, and can break other unrelated things.</p>
<p>Next time you think of using <code>throw</code>, instead, try doing an explicit return or an Either. Then unit test test it. Make it return an error in a larger program and see if it&#8217;s easier for you to find it given you are the one who caused it. I think you&#8217;ll find explicit returns or Eithers are easier to debug, easier to unit test, and can lead to more well thought out applications.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Functional Programming for OOP Developers: Part 2 &#8211; No Errors and Getting Things</title>
		<link>https://jessewarden.com/2016/12/functional-programming-for-oop-developers-part-2-no-errors-and-getting-things.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Sun, 11 Dec 2016 15:15:49 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[errors]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[get]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[listcomprehensions]]></category>
		<category><![CDATA[lodash]]></category>
		<category><![CDATA[pydash]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5244</guid>

					<description><![CDATA[Introduction In my journey to learn functional programming and drink deep of the kool-aid, I wanted to share my latest learnings. Specifically around the quest for no errors and how you get things. I&#8217;ve also just recently applied these same concepts in Python, not just JavaScript, so I&#8217;ll mix and match the examples to show [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1 id="functional-programming-for-oop-developers-part-2-no-errors-and-getting-things">Introduction</h1>
<p>In my journey to learn functional programming and drink deep of the kool-aid, I wanted to share my latest learnings. Specifically around the quest for no errors and how you get things.</p>
<p>I&#8217;ve also just recently applied these same concepts in <a href="https://www.python.org/">Python</a>, not just JavaScript, so I&#8217;ll mix and match the examples to show how the concepts are universal.</p>
<p>After reading this article, you should understand why errors aren&#8217;t helpful embedded in your code &amp; avoiding them is good and why we use functions to get things instead of the old way of assigning variables. <a href="http://jessewarden.com/2016/08/beginners-guide-to-functional-programming-part-1.html">Check out the first</a> article if you missed it.<br />
<span id="more-5244"></span></p>
<h1 id="recap-of-pure-functions">Recap of Pure Functions</h1>
<p>If you&#8217;ve <a href="http://jessewarden.com/2016/08/beginners-guide-to-functional-programming-part-1.html">read my previous article</a>, and hopefully <a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976#.oq7o4dbl9">Eric Elliot&#8217;s Pure Function</a> one as well, you should know what pure functions are, and why are they are important in functional programming.</p>
<p>If not, a quick recap. Pure functions are functions that always give the same output given the same input.</p>
<pre><code>function alwaysTrue()
{
   return true;
}
</code></pre>
<p>The function <code>alwaysTrue</code> will always return <code>true</code> no matter what you pass it, or don&#8217;t, or what order you call that function amongst other functions.</p>
<pre><code>console.log(alwaysTrue()); // true
console.log(alwaysTrue('cow')); // true
</code></pre>
<p>This function is not pure:</p>
<pre><code>function addStuff(a, b)
{
  return a + b + data;
}
</code></pre>
<p>If we call it with 1 and 1, we get an error:</p>
<pre><code>var result = addStuff(1, 1); // goes boom
</code></pre>
<p>If we set <code>data</code> to <code>1</code>, it gives us <code>3</code>:</p>
<pre><code>var data = 1;
var result = addStuff(1, 1); // 3
</code></pre>
<p>If we change <code>data</code> to <code>2</code>, we get <code>4</code>:</p>
<pre><code>var data = 2;
var result = addStuff(1, 1); // 4
</code></pre>
<p>Finally, if we change <code>data</code> after we call it, and call it again, we get different results from both function calls:</p>
<pre><code>var data = 1;
var result1 = addStuff(1, 1); // 3
data = 2;
var result2 = addStuff(1, 1); // 4
</code></pre>
<p>An impure function is not predictable, cannot be re-used without dragging a bunch of other variables and functions that make sure all the state is correct, and cannot be combined with other functions reliably because we don&#8217;t know how it will react.</p>
<p>Programming is supposed to be fun, so creating pure functions ensures what you make actually works and allows you to make bigger software programs that run (somewhat) predictably.</p>
<h1 id="the-quest-for-no-errors">The Quest for No Errors</h1>
<p>As you&#8217;ve seen above, errors make a function not pure. Some languages attempt to make this pure. <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html">Java</a> has throwable and <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/declaring.html">throws</a> to ensure the code only compiles of the caller has ensured all possible error types are handled. Python, while dynamic, still has this philosophy of catching specific types of errors first, then unknowns after. These don&#8217;t catch all errors at compile time, however. <a href="http://book.realworldhaskell.org/read/error-handling.html">Haskell uses Maybe</a> to balance this with pure functions.</p>
<p>Runtimes errors arise from when you load data such as JSON from REST API&#8217;s, use 3rd party libraries that do not indicate they throw errors yet do, or you&#8217;re using dynamic languages which have little to no compiler help.</p>
<p>You have 2 choices: Know all potential errors, or don&#8217;t use errors.</p>
<p>I&#8217;ve talked in the past about <a href="http://jessewarden.com/2009/06/error-handling-in-actionscript-3-dont-make-grenades-or-how-to-not-crash-safari.html">not creating errors</a> using exceptions, and instead indicating in an opt-in way of what went wrong for programmers consuming your code. The reason for this is usually all errors are unrecoverable. The best you can, and should, do is log it so you or others can see it and either know what&#8217;s going on, or debug the code and fix it later. Once you mix your code with other code, you&#8217;re part of the solution, not part of the problem.</p>
<p>If errors make the code less pure, then how do we not use errors?</p>
<h1 id="how-do-you-avoid-using-errors-">How Do You Avoid Using Errors?</h1>
<p>Let me demonstrate using the Amazon AWS Python API. They have an awesome API that&#8217;s mostly consistent. For Python, the library is called <a href="https://aws.amazon.com/sdk-for-python/">Boto3</a>, and unlike JavaScript, Python is a blocking language so asynchronous code will stop on the line making asynchronous calls (like calling an AWS server) until it&#8217;s complete.</p>
<p>If you don&#8217;t know AWS, just know that an &#8220;EC2&#8221; or &#8220;ee-sea-two&#8221; is Amazon&#8217;s word for a &#8220;server&#8221;. You can easily create and destroy these things. You get instances of them, just like you get instances of an object in normal programming.</p>
<p>The following code searches my Amazon account for any servers that are owned by me. When I create new EC2&#8217;s, I tag them with metadata, in this case owner is my name. That way, if I have thousands of servers, I can easily find mine.</p>
<pre><code>response = ec2.describe_instances(
    Filters=[
        {
            'Tag': 'owner',
            'Values': [
                'jesterxl',
            ]
        },
    ]
)
</code></pre>
<p>The above code isn&#8217;t pure. The Node API will follow the standard <a href="https://docs.nodejitsu.com/articles/errors/what-are-the-error-conventions/">Node callback convention</a>. The Boto3 Python API, in this case, either:</p>
<ol>
<li>works and your response is a dictionary with search result information (JavaScript Object)</li>
<li>doesn&#8217;t work, and raises a Python Exception (JavaScript throw)</li>
<li>doesn&#8217;t work, and response isn&#8217;t a dictionary (rare, depends on API call such as <a href="http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.head_bucket">S3.head_bucket</a>)</li>
</ol>
<p>Let&#8217;s make this pure by defining a pure Python function:</p>
<pre><code>from pydash import is_dict

def are_my_servers_there(ec2):
    try:
        response = ec2.describe_instances(
            Filters=[
                {
                    'Tag': 'owner',
                    'Values': [
                        'jesterxl',
                    ]
                },
            ]
        )
        return is_dict(response)
    except Exception as e:
        print("find_my_servers failed:", e)
        return False

result = are_my_servers_there()
# result will always be True or False
</code></pre>
<p>This function always returns <code>True</code> or <code>False</code>. Here&#8217;s 2 example <a href="http://nose2.readthedocs.io/en/latest/">nose2</a> unit tests:</p>
<pre><code>def test_works:
  value = are_my_servers_there(ec2_mock_good)
  self.assertTrue(value)

def test_fails:
  value = are_my_servers_there(ec2_mock_bad)
  self.assertFalse(value)
</code></pre>
<p>If the Python syntax is throwing you off, here is the equivalent JavaScript Node syntax for comparison:</p>
<pre><code>const _ = require('lodash');
const areMyServersThere = (ec2, callback)=&gt;
{
    try
    {
        var params = {
            Filters: [
                {
                    Name: 'owner',
                    Values: [
                        'jesterxl',
                    ]
                }
            ]
        };
        ec2.describeInstances(params, (err, data)=&gt;
        {
            if(err)
            {
                console.log("describeInstances failed in callback:", err);
                callback(false);
                return;
            }
            callback(_.isObject(data));
        });
    }
    catch(boom)
    {
        console.log("describeInstances failed:", boom);
        callback(false);
    }
};
const result = findMyServers();
// result is always true or false
</code></pre>
<p>This function always calls the callback with <code>true</code> or <code>false</code>. And the <a href="https://mochajs.org/">Mocha</a>/<a href="http://chaijs.com/">Chai</a> tests:</p>
<pre><code>it('should find my servers', (done)=&gt;
{
  areMyServersThere(ec2MockGood, (foundThem)=&gt;
  {
    if(foundThem)
    {
      done();
    }
    else
    {
      done(new Error("Couldn't find them.");
    }
  });
});
it('should not find my servers if not there', (done)=&gt;
{
  areMyServersThere(ec2MockBad, (foundThem)=&gt;
  {
    if(foundThem === false)
    {
      done();
    }
    else
    {
      done(new Error("Somehow succeeded when it shouldn't.");
    }
  });
});
</code></pre>
<p>If you search for Python code online, sometimes it will write <code>except</code> for a couple of types of <code>Exceptions</code> first, and then default to the generic one like I did last. This is often for clean up code in the case of database connections, file/folder shuffling, or networking handles. Low level stuff requires low-level error checking, heh!</p>
<p>Node, on the other hand, at least in API development still can&#8217;t escape try/catch. Inside of callbacks developers will parse data. Outside they&#8217;ll create it for requests. The call that accepts a callback may not have proper error handling internally and throws before it can call the callback. Global error handling is still a challenge, both in browsers and in Node.</p>
<p>The good news is not all functions you use throw. Some are pure by default (<a href="https://lodash.com/docs">Lodash</a> and <a href="http://pydash.readthedocs.io/en/latest/">Pydash</a> for example). Some native API&#8217;s are predictable and only 1 or a few errors. Some are small predicates which you know won&#8217;t throw errors. In those cases, if you need to know about specific ones, you can handle those. How you go about that in a pure way, however, is up to you. As long as you call the same function with the same inputs and it produces the same outputs, then however you&#8217;re handling the exceptions is probably pure.</p>
<p>Things get fuzzy with I/O &amp; databases. At that point you have to ask <a href="http://stackoverflow.com/questions/39834458/why-this-implementation-of-a-pure-function-isnt-considered-to-have-external-dep/39834974#39834974">how pure do you want to make things</a>? Easy answers are:</p>
<ul>
<li>If it works, and deadline is approaching, then pure enough.</li>
<li>If it works, isn&#8217;t pure, and deadline is far away, then not pure enough.</li>
</ul>
<h1 id="getting-things">Getting Things</h1>
<p>Python and JavaScript throw errors when you attempt to access nested properties on an Object and misspell something, or the property simply isn&#8217;t there. This is lessened if you utilize a strongly typed language like <a href="https://www.typescriptlang.org/">TypeScript</a>, and have good code editors that have intellisense and help you explore the Object before you type.</p>
<p>Property access is impure. Since you don&#8217;t have an &#8216;input&#8217;, there is no way to ensure you&#8217;re always getting the same result. This is used all the time in REST API&#8217;s where you get JSON back and start digging into the yummy data only to realize it&#8217;s missing things.</p>
<pre><code>someRestCall()
.then((results)=&gt;
{
  // should be results.data.user
    const user = results.user;
})
.catch((err)=&gt;
{
  // either we failed to make the call,
  // or we failed to parse the data.
});
</code></pre>
<p>Another is lower-level API&#8217;s, such as detecting if you have the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/performance">Performance API</a> to <a href="http://stackoverflow.com/questions/5004978/check-if-page-gets-reloaded-or-refreshed-in-javascript">detect browser refresh</a>:</p>
<pre><code>if(window.performance)
{
    if(performance.navigation.type  == 1 )
    {
        console.log('page reloaded');
    }
}
</code></pre>
<p>That code is all well in good in the latest browsers&#8230; except for Node where it throws an exception since she doesn&#8217;t have a <code>window</code>. You&#8217;ll run into this when you start using <a href="https://babeljs.io/">Babel</a> extensions that were meant to only work for Node, but you want to test your browser code outside of <a href="https://karma-runner.github.io/1.0/index.html">Karma</a>.</p>
<p>Another area is when you start combining functions and list comprehensions together for the above. Once you throw higher order functions together, while pure, you may not know <a href="https://medium.com/javascript-scene/you-might-not-need-typescript-or-static-types-aa7cb670a77b#.tv56ohicp">exactly what you&#8217;re getting</a>. This could just be too much cognitive load, you&#8217;re dealing with 3rd party impure code in the mix, or you&#8217;re dealing with I/O like asynchronous REST API&#8217;s. Even in this mostly pure world, you still can&#8217;t trust your Objects.</p>
<p>To state it clearly: Objects are not pure functions.</p>
<p>Lodash&#8217; <a href="https://lodash.com/docs/4.17.2#get">get</a> is, though. Pydash has <a href="http://pydash.readthedocs.io/en/latest/api.html#pydash.objects.get">get</a> as well.</p>
<p>In the above REST API, instead of accessing the response data impurely, we can use <code>get</code>:</p>
<pre><code>const user = _.get(results, 'user');
</code></pre>
<p>&#8230; now when I first saw <code>get</code>, I thought it was stupid. I had no idea what pure functions were, nor was I using a lot of <a href="http://jessewarden.com/2016/08/beginners-guide-to-functional-programming-part-1.html#arraycomprehensions">list comprehensions</a> together. I&#8217;ve been accessing Objects for ages, why use a function?</p>
<p>Now you know why:</p>
<ol>
<li><code>_.get</code> is pure</li>
<li>it doesn&#8217;t throw errors</li>
<li>You can default what you want so if it&#8217;s not there, you always get a black and white result: it&#8217;s either there, or it ain&#8217;t.</li>
</ol>
<p>For example, single dots on things you know exist are ok:</p>
<pre><code>var result = {
    data: {
        user: {
            name: 'Jesse'
        }
    }
};

var user = result.user;
console.log("user:", user); // user: undefined
</code></pre>
<p>However, here we misspell <code>data</code> to <code>dat</code>, and it throws:</p>
<pre><code>var result = {
    data: {
        user: {
            name: 'Jesse'
        }
    }
};

var user = result.dat.user;
console.log("user:", user); // never run
</code></pre>
<p>Watch when happens when we use <code>_.get</code>:</p>
<pre><code>var user = _.get(result, 'dat.user');
console.log("user:", user); // user: undefined
</code></pre>
<p>You can even delete result:</p>
<pre><code>var user = _.get(undefined, 'dat.user');
console.log("user:", user); // user: undefined
</code></pre>
<p>Outside of pure functions in the mutable state world, they can still save you from uncaught exceptions!</p>
<p>Combine that with it&#8217;s 3rd parameter which is a default value, and you can get even more predictable results:</p>
<pre><code>expect(_.get(undefined, 'dat.user', undefined).to.equal(undefined);
expect(_.get(result, 'data.user.name', 'chicken')).to.not.equal('chicken');
</code></pre>
<p>We&#8217;ll see more of <code>get</code>&#8216;s 3rd parameter when we start composing functions in a future article.</p>
<h1 id="et-tu-array-">Et tu, Array?</h1>
<p>(Arrays are <a href="https://en.wikipedia.org/wiki/Et_tu,_Brute%3F">full of holes</a>&#8230; get it? lol!)</p>
<p>Even Arrays, a type of Object in JavaScript, are impure when you access them. This is part of the reason you see functions in Lodash for <a href="https://lodash.com/docs/4.17.2#head">head</a>, <a href="https://lodash.com/docs/4.17.2#last">last</a>, and <a href="https://lodash.com/docs/4.17.2#tail">tail</a> (Although, tail is more for those coming from functional backgrounds where the first Array element is t3h special, a la Erlang/<a href="http://elixir-lang.org/">Elixir</a>).</p>
<p>Here&#8217;s a common error:</p>
<pre><code>var list;
result = list[2];
console.log("result:", result); // never runs
</code></pre>
<p>Solve that by using <code>get</code> instead:</p>
<pre><code>var list;
result = _.get(list, '2');
console.log("result:", result); // undefined
</code></pre>
<p>A side benefit is that <code>get</code> works with Objects and Arrays so is flexible in that you can pass either.</p>
<h1 id="conclusions">Conclusions</h1>
<p>The <code>get</code> function allows us a pure way to access Objects &amp; Arrays in JavaScript and Dictionaries &amp; Lists in Python. With reasonable defaults, you can use this to build and compose pure functions instead of littering them with impure property access.</p>
<p>Once you start composing functions like we&#8217;ll be doing in the next article, you want to ensure the main ones are as pure as possible. Debugging composed pure functions can be hard at first, so getting it right in the beginning helps.</p>
<p>You&#8217;ve also seen how errors are just that: something to be avoided instead of embraced. They make your functions impure, and confuse those who were expecting specific return values from your functions.</p>
<p>You do not need to use try/catch everywhere. In your own code, you&#8217;ll know when there could be areas which are out of your control and you need to. If using 3rd party code, if you have the time, see at what points they fail intentionally through unit and integration tests. This ensures you only use try/catch in areas you either don&#8217;t know (yet) or are intentional like in Python&#8217;s Boto3 library.</p>
<p>One important part of errors that shouldn&#8217;t be missed, however, is intentional ones. As you start creating higher level functions like the <a href="http://jessewarden.com/2016/08/beginners-guide-to-functional-programming-part-1.html#checkers">checkers</a> in my previous article, giving good feedback is important. The reason(s) why predicates return <code>false</code>, or why composed functions return an error result instead of success help mitigate debugging, and ensure those learning your API know what&#8217;s really going on. Anyone who has used both React and Angular knows how superior React&#8217;s error messaging is.</p>
<p>Verbose, helpful errors are great and those SHOULD be embraced. However, you don&#8217;t have to raise/throw them unless it truly is an error that you want developers to know about it early.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Launch a Small Software Product Slides</title>
		<link>https://jessewarden.com/2010/11/how-to-launch-a-small-software-product-slides.html</link>
					<comments>https://jessewarden.com/2010/11/how-to-launch-a-small-software-product-slides.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Sat, 13 Nov 2010 17:16:34 +0000</pubDate>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[agile]]></category>
		<category><![CDATA[air]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[entrepreneur]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[ironman]]></category>
		<category><![CDATA[product]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[service]]></category>
		<category><![CDATA[small]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[startup]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=2514</guid>

					<description><![CDATA[My slides from speaking atÂ RIA Unleashed and 360 Flex conferences. How to Launch a Small Software Product View more presentations from Jesse Warden. Download &#8211; Keynote &#124;Â PDF &#124; JPEG&#8217;s &#124; Slideshare Resources Referenced: Steve Krug&#8217;s Book &#8220;Don&#8217;t Make Me Think&#8221; Gary Vaynerchuk&#8217;s Book &#8220;Crush It!&#8221; &#8220;Minimum Viable Product&#8221; blog post Startup Book &#8220;Start Small, Stay [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>My slides from speaking atÂ <a href="http://riaunleashed.com">RIA Unleashed</a> and <a href="http://360flex.com">360 Flex</a> conferences.</p>
<div id="__ss_5768715" style="width: 425px;"><strong><a title="How to Launch a Small Software Product" href="http://www.slideshare.net/jesterxl/how-to-launch-a-small-software-product">How to Launch a Small Software Product</a></strong><object id="__sse5768715" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="355" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="src" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=preso-jxl-ria-unleashed-2010-101113101719-phpapp02&amp;stripped_title=how-to-launch-a-small-software-product&amp;userName=jesterxl" /><param name="name" value="__sse5768715" /><param name="allowfullscreen" value="true" /><embed id="__sse5768715" type="application/x-shockwave-flash" width="425" height="355" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=preso-jxl-ria-unleashed-2010-101113101719-phpapp02&amp;stripped_title=how-to-launch-a-small-software-product&amp;userName=jesterxl" name="__sse5768715" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<div style="padding: 5px 0 12px;">View more <a href="http://www.slideshare.net/">presentations</a> from <a href="http://www.slideshare.net/jesterxl">Jesse Warden</a>.</div>
</div>
<p><span id="more-2514"></span>Download &#8211; <a href="http://jessewarden.com/archives/preso-jxl-ria-unleashed-2010-slide-images.key.zip">Keynote</a> |Â <a href="http://jessewarden.com/archives/preso-jxl-ria-unleashed-2010.pdf">PDF</a> | <a href="http://jessewarden.com/archives/preso-jxl-ria-unleashed-2010-slide-images.zip">JPEG&#8217;s</a> | <a href="http://www.slideshare.net/jesterxl/how-to-launch-a-small-software-product">Slideshare</a></p>
<p>Resources Referenced:</p>
<ul>
<li><a href="http://www.amazon.com/Dont-Make-Me-Think-Usability/dp/0321344758/ref=sr_1_1?ie=UTF8&amp;qid=1289664864&amp;sr=8-1">Steve Krug&#8217;s Book &#8220;Don&#8217;t Make Me Think&#8221;</a></li>
<li><a href="http://www.amazon.com/Crush-Time-Cash-Your-Passion/dp/0061914177/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1289664912&amp;sr=1-1">Gary Vaynerchuk&#8217;s Book &#8220;Crush It!&#8221;</a></li>
<li><a href="http://www.startuplessonslearned.com/2009/08/minimum-viable-product-guide.html">&#8220;Minimum Viable Product&#8221; blog post</a></li>
<li><a href="ttp://www.startupbook.net">Startup Book &#8220;Start Small, Stay Small&#8221;</a></li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2010/11/how-to-launch-a-small-software-product-slides.html/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>D2W and Roundtable with Joel Hooks &#038; Nick Joyce &#8211; JXLTV Episode #006</title>
		<link>https://jessewarden.com/2010/02/roundtable-with-joel-hooks-nick-joyce-jxltv-episode-006.html</link>
					<comments>https://jessewarden.com/2010/02/roundtable-with-joel-hooks-nick-joyce-jxltv-episode-006.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Fri, 26 Feb 2010 04:10:33 +0000</pubDate>
				<category><![CDATA[jxltv]]></category>
		<category><![CDATA[d2w]]></category>
		<category><![CDATA[dee]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[hooks]]></category>
		<category><![CDATA[joel]]></category>
		<category><![CDATA[joyce]]></category>
		<category><![CDATA[nick]]></category>
		<category><![CDATA[pyamf]]></category>
		<category><![CDATA[pycon]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[robotlegs]]></category>
		<category><![CDATA[sadler]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=2087</guid>

					<description><![CDATA[Announcements: D2W Conference Dee Sadler &#8211; Twitter &#124; Site RIA Radio &#8211; Episode 8: Jesse Warden DebugWindow v2 &#8211; Log window for Flex apps References: PyCon &#8211; Atlanta Python Conference Joel Hooks &#8211; Twitter &#124; Blog Robotlegs &#8211; MVCS Framework for AS3 and Flex Nick Joyce on Twitter PyAMF &#8211; AMF support for Python Universal [&#8230;]]]></description>
										<content:encoded><![CDATA[<div id="viddler_cb438f21" name="viddler_cb438f21">
<pre style="border: 0px; margin: 0px;">
<object type="video/mp4" data="http://jessewarden.com/archives/jxltv/jxltv-episode-006.jpg" width="460" height="258">
			<param name="controller" value="false" />
			<param name="src" value="http://jessewarden.com/archives/jxltv/jxltv-episode-006.jpg" />
			<param name="href" value="http://jessewarden.com/archives/jxltv/jxltv-episode-006-iphone.mp4" />
			<param name="target" value="myself" />
				<img decoding="async" src="http://jessewarden.com/archives/jxltv/jxltv-episode-006.jpg" alt="JXL TV Episode 6"></img>
		</object>
</pre>
</div>
<pre style="border: 0px; margin: 0px;"><script type="text/javascript">

var flashvars = {};
var params = {
	allowScriptAccess: "always",
	allowFullScreen: "true"
};
var attributes = {
  id: "viddler_cb438f21",
  name: "viddler_cb438f21"
};

swfobject.embedSWF("http://www.viddler.com/player/cb438f21/", "viddler_cb438f21", "437", "287", "9.0.0","http://www.jessewarden.com/expressInstall.swf", flashvars, params, attributes);

</script></pre>
<p><span id="more-2087"></span><br />
<b>Announcements:</b></p>
<ul>
<li><a href="http://www.d2wc.com/default/index.cfm">D2W Conference</a></li>
<li>Dee Sadler &#8211; <a href="http://twitter.com/deesadler">Twitter</a> | <a href="http://aboxofpixels.com/">Site</a></li>
<li><a href="http://www.insideria.com/2010/02/ria-radio---episode-7-jesse-wa.html">RIA Radio &#8211; Episode 8: Jesse Warden</a></li>
<li><a href="http://jessewarden.com/2010/02/debug-window-v2-simple-flex-debug-window.html">DebugWindow v2 &#8211; Log window for Flex apps</a></li>
</ul>
<p><b>References:</b></p>
<ul>
<li><a href="http://us.pycon.org/2010/about/">PyCon &#8211; Atlanta Python Conference</a></li>
<li>Joel Hooks &#8211; <a href="http://twitter.com/jhooks">Twitter</a> | <a href="http://joelhooks.com/">Blog</a></li>
<li><a href="http://robotlegs.org/">Robotlegs &#8211; MVCS Framework for AS3 and Flex</a></li>
<li><a href="http://twitter.com/nick_joyce">Nick Joyce</a> on Twitter</li>
<li><a href="http://pyamf.org/">PyAMF</a> &#8211; AMF support for Python</li>
<li><a href="http://universalmind.com/">Universal Mind</a> &#8211; RIA Consulting Firm</a></li>
<li><a href="http://jessewarden.com/2007/12/mix-n-mash-2k7-bill-gates-web-blend-and-silverlight.html" title="Mix n Mash 2007 - Bill Gates n Bloggers by jesterxl, on Flickr"><img decoding="async" src="http://farm3.static.flickr.com/2276/2092951645_934a0ece66_m.jpg" width="240" height="160" alt="Mix n Mash 2007 - Bill Gates n Bloggers" /></a></li>
<p><b>Beer</b> &#8211; <a href="http://beeradvocate.com/beer/profile/418/3434">Milk Stout</a> by <a href="http://www.lefthandbrewing.com/">Left Hand Brewing Company</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2010/02/roundtable-with-joel-hooks-nick-joyce-jxltv-episode-006.html/feed</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		<enclosure url="http://jessewarden.com/archives/jxltv/jxltv-episode-006-iphone.mp4" length="279814530" type="video/mp4" />

			</item>
	</channel>
</rss>
