<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ian Davidson on Medium]]></title>
        <description><![CDATA[Stories by Ian Davidson on Medium]]></description>
        <link>https://medium.com/@ian.davidson?source=rss-7460eecb5534------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*u6AS8CbbyVXK6Xi1akhK7A.jpeg</url>
            <title>Stories by Ian Davidson on Medium</title>
            <link>https://medium.com/@ian.davidson?source=rss-7460eecb5534------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:27:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ian.davidson/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Art of Failing Fast with Option and Either]]></title>
            <link>https://medium.com/peloton-engineering/the-art-of-failing-fast-with-option-and-either-4baff43ff841?source=rss-7460eecb5534------2</link>
            <guid isPermaLink="false">https://medium.com/p/4baff43ff841</guid>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Ian Davidson]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 19:47:22 GMT</pubDate>
            <atom:updated>2021-01-22T20:54:18.038Z</atom:updated>
            <content:encoded><![CDATA[<h3>The art of failing fast with Option and Either</h3><h4>We ditched “null” and throwables once and for all. Here’s what we do instead.</h4><p><em>Co-authored by </em><a href="https://medium.com/@bholmesdev"><strong><em>Ben Holmes</em></strong></a></p><pre>if (variable == null) {…} else {…}</pre><p>If you’ve built anything at scale, you’ve definitely started a function with this at least once. Maybe you’re checking an optional function parameter. Maybe you’re calling a find that might not find anything. Maybe you have “falsy” values like an empty string you want to match against. The list goes on and on…</p><p>And then there’s this pattern:</p><pre>try {…} catch (e) {…}</pre><p>Exceptions are always bound to happen, but you never <em>really </em>know where they’re gonna crop up. Maybe you wrap this around some database queries that might bomb out. Heck, maybe you’re catching “null pointer exceptions” when you forget to check!</p><p>Bottom line, handling when functions <em>don’t </em>go your way can feel like an overly-cautious ritual. Just throw 50 null checks here, wrap some try / catch-es around those, duct tape some unit tests onto everything… and hope nothing bombs out in production 🤷‍♀️</p><p>This used to be our own, Python-heavy codebase at Peloton. But as we’ve branched into strictly typed languages and functional programming techniques, we’ve discovered some great patterns to ditch these unexpected explosions for good. In this post, we’ll explore:</p><ol><li>The inherent problem with null</li><li>The road from nullable types to “Option” / “Maybe” wrappers</li><li>Adapting Option-al values to error messages</li><li>Mixing and matching approaches to write the sound-est logic 🚀</li></ol><p>Alright, let’s ride 🚴‍♀️</p><h3>Why null is scary</h3><p>Before talking about exceptions and throwables, let’s discuss another elephant in the room: dealing with the great and powerful null. Programmers may consider it the necessary evil to represent anything that’s… nothing. It’s a convenient fallback for stubbing out new values, ignoring “absent” function parameters, quickly emptying an object, etc etc etc.</p><p>But there’s a reason behind this quote:</p><blockquote>I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.</blockquote><blockquote>- <a href="https://en.wikipedia.org/wiki/Tony_Hoare">Tony Hoare</a></blockquote><p>☝️ This is coming from the <em>inventor</em> of the null pointer. Pulling this apart, there are some major implications to consider:</p><ol><li>Null references are <strong>easy,</strong> but that doesn’t mean they are <strong>safe.</strong></li><li><strong>Uncaught pointers are easily overlooked</strong> (in dynamically typed languages, anyways). This causes costly errors when your unit tests aren’t <em>quite</em> thorough enough.</li></ol><p>Yes, you can write perfectly safe programs with the right null checks in place, but it’s hard to guarantee you’ll find all the faults! For more on this subject, “JavaScript Joel” <a href="https://dev.to/joelnet/null-the-billion-dollar-mistake-maybe-just-nothing-1cak">has some amazing examples here</a> coming from JS’s null vs. undefined problem.</p><h3>Okay, but my language has non-nullable types!</h3><p>Great! This goes a long way in solving the unexpected null problem. If you use a language like <a href="https://kotlinlang.org/">Kotlin</a> or <a href="https://www.typescriptlang.org/">TypeScript</a>, you can use type checking out-of-the-box to guarantee something is <em>never</em> null.</p><p>Using Peloton’s ecommerce store as an example, say a user wants to add a Bike package to their cart. When they hit “submit,” we’ll send off an order that looks something like this:</p><pre>// Package is our object type here</pre><pre>package: Package = {<br>  name: “bike-essentials”,<br>  accessories: [{<br>    name: “bike-shoes”,<br>    selection: “size-11-mens”<br>  }]<br>}</pre><p>In this case, we don’t want any of the accessory names or selections to be null; that means the user didn’t choose an accessory in the package! With a simple type, we can guarantee we can never make this assignment:</p><pre>// User doesn’t select a size for their shoes<br>let userSelection = null;</pre><pre>type Package = {<br>  name: string, // can only be a string, not a &quot;null&quot; string<br>  accessories: Array&lt;Accessories&gt;, // can be an empty array, but<br>                                   // not &quot;null&quot;<br>}</pre><pre>let package: Package = {<br>  name: &quot;bike-essentials&quot;,<br>  accessories: [{<br>    name: &quot;bike-shoes&quot;,<br>    selection: userSelection // 🚨 compilation error!<br>  }]<br>}</pre><p>Great! With this sort of type system, we don’t need to worry about unexpected errors. We’re good to go as long as we convert any <em>expected</em> nulls to some other default value.</p><p>In those places we <em>do</em> expect errors, we can define our type as “nullable” like so:</p><pre>type UserInput = {<br>  accessoryName: string,<br>  accessorySelection: string? // question mark to denote a &quot;nullable&quot; value<br>}</pre><pre>// later in the program…<br>function attemptAddToCart(userInput: UserInput) {</pre><pre>  if (userInput.accessorySelection == null) {</pre><pre>    // say, if the user hasn&#39;t selected anything,<br>    // just find a default selection for that accessory<br>    userInput.accessorySelection = getDefaultByName(accessoryName)<br>  }</pre><pre>  // safely do something with that userInput<br>}</pre><p>So now we get the best of both worlds, only using null when we’re ready to handle it 💪</p><h3>And some languages take it a step further</h3><p>Type checking for nulls is nice. But some language designers (functional programming languages in particular) have dared to ask: what if we get rid of null altogether? This would mean tackling the same problem of eliminating uncaught nulls with type checking… but using a different set of vocabulary.</p><p>We’ll use the <a href="https://arrow-kt.io/">ArrowKT Kotlin library</a> as an example. We use this across all our new backend microservices at Peloton, so it feels like a natural source of inspiration!</p><p>In short, Arrow has the concept of an Option type you can use with your standard Kotlin variables. This “wraps” around existing fields to denote that a variable <em>might not</em> have a value. In other words, <strong>it’s Option-al.</strong> Let’s see a before / after coming from nullable types:</p><pre>// with a nullable type<br>fun gimmeTheNewTread(userEmailForNewsletters: string?) {<br>  if (userEmailForNewsletters != null) {<br>    signUpForNewsletter(userEmailForNewsletters);<br>  }<br>  …<br>}</pre><pre>// with an &quot;Option&quot; type<br>fun gimmeTheNewTread(userEmailForNewsletters: Option&lt;string&gt;) {<br>  userEmailForNewsletters<br>    .map { unwrappedUserEmail -&gt;<br>       signUpForNewsletter(unwrappedUserEmail)<br>    }<br>  …<br>}</pre><p>That’s a new approach! Instead of our “if gating” ritual, we can use .map to retrieve the value.</p><ul><li>If it’s present, we can use it inside our .map function. In this case, that value will be of type “string.”</li><li>If it’s absent, we’ll just short circuit without running the block.</li></ul><p>Creating those “optional” values isn’t too bad either:</p><pre>// if the value is present, we &quot;wrap&quot; it in a Some object<br>val userEmailForNewsletters = Some(&quot;<a href="/service/mailto:johnfoley@onepeloton.com">johnfoley@onepeloton.com</a>&quot;);</pre><pre>// if it&#39;s absent, we wrap it in a None object<br>// (the value being, well, nothing)<br>val userEmailForNewsletters = None();</pre><p>In this case, Some and None are subtypes of an Option; the former representing the presence of a value, and the latter representing “nothing.” This idea of wrapping and unwrapping prevents you from making unsafe comparisons like this:</p><pre>val userEmailForNewsletters = None();</pre><pre>if (userEmailForNewsletters == &quot;<a href="/service/mailto:jesssims@onepeloton.com">jesssims@onepeloton.com</a>&quot;) {<br>  // 🚨 compilation error! You can&#39;t compare Option&lt;string&gt; -&gt; string<br>  println(&quot;Let&#39;s get that glazed donut look y&#39;all 🍩&quot;)<br>}</pre><p>Notice we haven’t “unwrapped” the userEmail using .map, so it won’t let us compare against a <em>regular, unwrapped string.</em> This avoids the issue of “falsy” values <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">you might find in other languages</a>, where, say, an empty string is “equal” to null.</p><p>Still, if you haven’t seen this concept before, you might be thinking <em>what? Why are we inventing a “None” type? That’s what null is for!</em> This isn’t a bad take to be honest. The idea of nullable vs. non-nullable types covers most of the same bases that Optional types do. In fact, the ArrowKT library <a href="https://github.com/arrow-kt/arrow-core/issues/114">is deprecating the Option type entirely</a> because Kotlin’s built-in nullables are just as good!</p><p>This doesn’t mean our “wrapping / unwrapping” paradigm is gone for good though. Let’s take this idea a step further with <strong>exception handling</strong> ✨</p><h3>What if a “nothing”… told you WHY it was nothing?</h3><p>This is a natural extension of our Option type. As you noticed, any Options with a value of None don’t really contain anything. In practice, this has the same bad implications for readability that a null stand-in might.</p><pre>retrieveBikePackageFromDB() -&gt; None()</pre><p>Wait, why is it None? Were there <em>really </em>no matching packages? Did our database query timeout? Was the user’s query params badly formed?</p><p>What’s worse, this “retrieveBikePackageFromDB” might throw an exception we’re unaware of! But in order to know for sure, we’d have to either:</p><ol><li>Be familiar enough with the codebase to <em>know </em>what exceptions might pop out</li><li>Preemptively wrap it in a try / catch just to be safe (even if it’s unnecessary).</li></ol><p>Now, we need to handle both None results <em>and </em>exceptions, whatever those exceptions even look like 😬</p><p>But let’s consider: If None() is a constructor that <em>could </em>wrap around something… why can’t we slap an error message in there? Or an error enum we can match up against? That would immediately let us know what sort of exceptions we could have, and let us differentiate between errors and “empty” responses!</p><p><a href="https://arrow-kt.io/docs/patterns/error_handling/">Enter: the Either type ✨</a></p><h3>Telling your Left from your Right</h3><p>Either is a bit like the Option type. But instead of None and Some, we have Left and Right. By convention, Left is used to represent the error path, and Right is used to represent the good path.</p><pre>val whoops = Left(“Something hasn’t gone according to plan”)</pre><pre>val good = Right(“Now that’s proper”)</pre><p>Let’s look at a typical example of exception throwing code for validating a user’s email and see how we can improve it with Either.</p><pre>typealias Email = String</pre><pre>fun validateEmail(email: Email): Email {<br>  if (!email.contains(&quot;@&quot;)) {<br>    throw Exception(&quot;Email doesn&#39;t have @&quot;)<br>  }<br>  return email<br>}</pre><p>Notice anything odd about the code? The type signature doesn’t <em>really</em> say what the function can do. Imagine an even more deeply nested bit of code, and having to read through it to determine what errors you need to catch. We’ve all been there. Just like Maybe, Either can be used to improve the safety and readability of your code.</p><pre>typealias Error = String<br>typealias Email = String</pre><pre>fun validateEmail(email: String): Either&lt;Error, Email&gt; {<br>  if (!email.contains(&quot;@&quot;)) {<br>    return Left(&quot;Email doesn&#39;t have @&quot;)<br>  }<br>  return Right(email)<br>}</pre><p>Now we can see from just the type signature what this code really does! Anyone calling this function doesn’t have to go on an Exception hunt, or add a catch-all-exceptions escape hatch.</p><p>Just like our trusty Option type from before, we can use .map to access the inner value.</p><pre>fun gimmeTheNewTread(userEmailForNewsletters: String): Either&lt;Error, Nothing&gt; =<br>  validateEmail(userEmailForNewsletters).map { <br>    unwrappedUserEmail -&gt; signUpForNewsletter(unwrappedUserEmail) <br>  }</pre><p>Now we’re validating the email before sending it. If validateEmail were to return a Left, the computation would stop and not send the email, while returning the Error. If it’s a Right, we’ll send the email as usual.</p><p>Can we combine the powers of Option <em>and</em> Either? Well, of course!</p><pre>fun gimmeTheNewTread(userEmailForNewsletters: Option&lt;String&gt;):    Either&lt;Error, Nothing&gt; =<br>  userEmailForNewsletters<br>    // remember, on Option of type &quot;None&quot; won&#39;t <br>    // have any errors attached!</pre><pre>    // this function lets us convert that &quot;None&quot; to an <br>    // error we can understand<br>    .toEither { &quot;Email is missing&quot; }<br>    .flatMap { unwrappedUserEmail -&gt;<br>      validateEmail(unwrappedUserEmail) <br>    }<br>    .map { unwrappedUserEmail -&gt;<br>      signUpForNewsletter(unwrappedUserEmail) <br>    }</pre><p>First we convert the userEmailForNewsletters to an Either. If it’s None, it turns into Left(“Email is missing”). If it’s Some, it turns into Right(unwrappedUserEmail). Then we flatMap instead of map to prevent overly nesting, since validateEmail returns an Either. Finally we map over that either and send the email or return the error.</p><p>Code like this can be extended simply with more maps, and at each step you are safe in the knowledge that all prior steps have succeeded — Since the wrong path stops computation and returns early.</p><h3>Wrapping up</h3><p>We’re still new to this shift away from nullables and throwables. But from our experience so far, it’s allowed us to be more thoughtful about handling our exceptions. With throwables, it was easy to just “catch everything” and say “Oops, something went wrong!” Now we have the power to write granular, descriptive error responses for all of our clients.</p><p>This has a promising future as we move towards a microservice architecture, where each team needs to understand the inputs and outputs of each service to cross-communicate. If we can be more descriptive with our error handling, we can <em>greatly </em>reduce confusion between teams and focus more on our user experience 😁</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4baff43ff841" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peloton-engineering/the-art-of-failing-fast-with-option-and-either-4baff43ff841">The Art of Failing Fast with Option and Either</a> was originally published in <a href="https://medium.com/peloton-engineering">Peloton-Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>