<?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 Matthias on Medium]]></title>
        <description><![CDATA[Stories by Matthias on Medium]]></description>
        <link>https://medium.com/@mttkay?source=rss-e8f399862cd4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*eetEiAgPCT6pcMjn.png</url>
            <title>Stories by Matthias on Medium</title>
            <link>https://medium.com/@mttkay?source=rss-e8f399862cd4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:24:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mttkay/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[Refactoring with Monoids and Sum Types — Part 2]]></title>
            <link>https://medium.com/@mttkay/refactoring-with-monoids-and-sum-types-part-2-b2a8e8b29d5f?source=rss-e8f399862cd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2a8e8b29d5f</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Matthias]]></dc:creator>
            <pubDate>Mon, 08 May 2017 18:26:09 GMT</pubDate>
            <atom:updated>2017-05-11T19:53:38.782Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@mttkay/refactoring-with-monoids-and-sum-types-part-1-bddc9ea61f5f">previous part</a> we introduced monoids and refactored a simple game inventory to understand item management as addition of inventory slots.</p><p>Our set based solution had some drawbacks, however, most of all an over-reliance on Set, which is a platform type. While Kotlin has <a href="https://kotlinlang.org/docs/reference/extensions.html">extension methods</a> to enrich types with functionality, it would be ill advised to let your domain model spill into external modules. Moreover, relying on a single type to represent all required cases means that our model isn’t represented fully in the type system, which means we cannot lean on the compiler to verify correctness or leverage useful properties of object-functional languages such as <a href="https://en.wikipedia.org/wiki/Subtyping">subtype polymorphism</a>. With this in mind, let’s see how we can pour our model into a custom type.</p><p>Let’s recap quickly what we want:</p><ul><li>Our item type should explicitly encode our model, which is to have three distinct cases: no item, one item, or a stack of items.</li><li>We would like it to maintain its monoidal properties, plus commutativity.</li></ul><p>We’ll look at the first problem first. Whenever you need “distinct cases”, chance are you want a <em>sum type</em>, given you’re fortunate enough to work with a programming language allowing you to express this. Sum types are <a href="https://en.wikipedia.org/wiki/Algebraic_data_type"><em>algebraic data types</em></a> that represent mutually exclusive cases. Hence the term sum: they represent the <a href="https://en.wikipedia.org/wiki/Disjoint_union"><em>disjoint union</em></a> of their value sets, which is sometimes denoted as + (not to be confused with the addition operator we introduced earlier!)</p><p>Here’s one way to declare our inventory element type:</p><pre><strong>sealed class</strong> Elem {<br>  <strong>abstract operator</strong> <strong>fun</strong> plus(el: Elem): Elem<br>}</pre><p>What we’re saying here is that there exist a set of objects that we can combine using the + operator. We furthermore indicate this to be a <a href="https://kotlinlang.org/docs/reference/sealed-classes.html">sealed hierarchy</a>, meaning all cases will be known to the compiler upfront. I’ll discuss the significance of this in a minute. Let’s define our cases now, starting with the simplest one (the empty element), working our way up to stacks. Here’s the empty case:</p><pre><strong>object</strong> Empty : Elem() {<br>  <strong>override fun</strong> plus(e: Elem): Elem = e<br>}</pre><p>Pretty straight forward. We’re applying the <a href="https://en.wikipedia.org/wiki/Null_Object_pattern">null-object pattern</a> here to represent our neutral element: a singleton object that leaves its input untouched. This makes it efficient and safe, without having to rely on nulls and the typically defensive code accompanying it.</p><p>Our single item case is a bit more interesting:</p><pre><strong>data class</strong> Item(<strong>val</strong> obj: GameObject) : Elem() {<br>  <strong>override fun</strong> plus(el: Elem): Elem =<br>      <strong>when</strong> (el) {<br>        <strong>is</strong> Empty -&gt; <strong>this</strong><br>        <strong>is</strong> Item -&gt; ItemStack(setOf(<strong>this</strong>, el))<br>        <strong>is</strong> ItemStack -&gt; ItemStack(el.items + <strong>this</strong>)<br>      }<br>}</pre><p>This is slightly more complicated, but still quite intuitive: adding nothing simply yields the item back, adding another item creates a new stack, and adding a stack grows the stack with the item. You can see Kotlin’s <a href="https://kotlinlang.org/docs/reference/typecasts.html#smart-casts">smart casts</a> at work here: matching a type via is allows us to refer to the object as that type in the lexical scope that follows.</p><p>Finally, adding stacks:</p><pre><strong>data class</strong> ItemStack(<strong>val</strong> items: Set&lt;Item&gt;) : Elem() {</pre><pre>  <strong>init</strong> {<br>    require(items.size &gt; 1) {<strong> </strong>&quot;Stacks must contain &gt; 1 items&quot; }<strong><br>  </strong>}</pre><pre>  <strong>override fun</strong> plus(e: Elem): Elem =<br>      <strong>when</strong> (el) {<br>        <strong>is</strong> Empty -&gt; <strong>this</strong><br>        <strong>is</strong> Item -&gt; ItemStack(<strong>this</strong>.items + el)<br>        <strong>is</strong> ItemStack -&gt; ItemStack(<strong>this</strong>.items + el.items)<br>      }<br>}</pre><p>We’re making generous use of the Set::plus operator here, which we can use to merge stacks, but note how this is merely an implementation detail. We also added a check ensuring that stacks must never contain fewer than two items. Since stacks can currently only grow larger, not shrink, this is sufficient to enforce the &gt; 1 items invariant.</p><p>We’re now ready to combine inventory items freely, without having to worry about whether they’re empty, single items, or stacks. We can furthermore exploit sub-type polymorphism to dynamically dispatch to the correct + implementation based on the case type. Here’s a few examples:</p><pre><strong>val</strong> item1 = Item(sword1)<br><strong>val</strong> item2 = Item(sword2)<br><strong>val</strong> stack = item1 + item2 // creates an ItemStack<br><strong>val</strong> stillItem1 = Empty + item1 // this compiles and works!<br>...</pre><p>Our move function remain almost unchanged (that’s a good sign!), except for a change in the element type:</p><pre><strong>fun</strong> move(inventory: Array&lt;Elem&gt;, from: <strong>Int</strong>, to: <strong>Int</strong>) {<br>  inventory[to]   = inventory[to] + inventory[from]<br>  inventory[from] = Empty<br>}</pre><p>Needless to say, we had to bring back some complexity that we had gotten rid of earlier when using just sets. This seems to be a small price to pay, however, considering that we now own the model implementation and can extend it as needed.</p><p>Before we move on, I promised I’d get back to the sealed keyword and its significance with respect to sum types. Since sum types represent disjoint unions of cases, we’re usually interested in whether a particular when clause handles <em>all</em> possible cases. If we accidentally forgot to handle a particular case when we need to return a value, the only possible option for the program would be to crash, because how would it know what to return?</p><p>This is where sealed comes in. Since a sealed hierarchy is impossible to extend with new cases outside its lexical scope, the compiler knows exactly when a particular when clause is exhaustive; if it’s not, we can fail compilation and thus prevent our program from crashing at runtime. This is something we wouldn’t be able to do with sets: because our cases were not explicitly encoded in the type system, but were just reflections of set contents (i.e. dynamic data), the compiler would never know if we were handling all cases properly.</p><p>Before wrapping up, let’s see what we got in terms of extra flexibility by defining a new type. After all, this was one of the primary reasons for not relying on sets. Considering that we’d want to render our inventory elements at some point, it would be useful to have a function yielding the first item in a slot, so that we can use its sprite to render the slot contents. This is convenient when dealing with stacks, since we can simply represent them by the first element they contain (we’re assuming they’re all of the same kind.)</p><p>Here’s how we could extend our Elem type to define yieldFirst as a higher-order function:</p><pre><strong>sealed class</strong> Elem {<br>  <strong>abstract operator fun</strong> plus(e: Elem): Elem<br><br>  <strong>inline fun</strong> yieldFirst(f: (Item) -&gt; Unit) =<br>      <strong>when</strong> (<strong>this</strong>) {<br>        <strong>is</strong> Empty -&gt; <strong>Unit</strong><br>        <strong>is</strong> Item -&gt; f(<strong>this</strong>)<br>        <strong>is</strong> ItemStack -&gt; f(<strong>this</strong>.items.first())<br>      }<br>}</pre><p>We could have also made the function abstract and have the sub-types implement it accordingly, but it was a bit more compact to do it in Elem itself. Again, the compiler forces us to deal with all possible cases, and it’s safe to even call it on empty slots, in which case it will be a no-op:</p><pre>Empty.yieldFirst(::renderItem) // does nothing<br>Item(obj1).yieldFirst(::renderItem) // renders a sword<br>(Item(obj1) + Item(obj2)).yieldFirst(::renderItem) // render stack</pre><p>Or we could simply do it as a batch operation:</p><pre><strong>fun</strong> renderAll() = inventory.forEach {<strong> it</strong>.yieldFirst(::renderItem) }</pre><p>Kotlin will desugar these calls to efficient loops when compiling this down to Java byte code.</p><p>I hope I could demonstrate how sometimes innocent looking problems can quickly lead to unwieldy, unsafe implementations. Applying even the simplest patterns such as a combination operator in a <em>principled</em> way can not only lead to a cleaner, more intuitive, and ultimately safer implementation, but might even make new functionality available for free that you had not initially thought about, be it generic algorithms like folds or simply getting better feedback from the compiler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2a8e8b29d5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring with Monoids and Sum Types — Part 1]]></title>
            <link>https://medium.com/@mttkay/refactoring-with-monoids-and-sum-types-part-1-bddc9ea61f5f?source=rss-e8f399862cd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/bddc9ea61f5f</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Matthias]]></dc:creator>
            <pubDate>Sun, 07 May 2017 12:22:28 GMT</pubDate>
            <atom:updated>2017-05-08T21:22:35.164Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article is loosely based on an internal tech talk I gave at SoundCloud in April 2016.</em></p><p>Much has been written about the virtues of <em>composition</em> in software development, but surprisingly little about the rules governing it. Composition can happen at practically any level of granularity (think systems/components/modules at the higher level, objects/values/functions at the lower level), but more often than not we deal with it at the <em>value</em> level. With this article I would like to help demystify the abstraction that governs the composition of values, and how one can apply it effectively to write better code.</p><p>Composing values is effectively <em>combining</em> them: take many, return one. Giving this concept a concrete shape can help you produce code that is both simpler and safer. The concept or abstraction I’m referring to is called a <a href="https://en.wikipedia.org/wiki/Monoid"><em>monoid</em></a>, and this is the story of how I discovered it through refactoring before I knew it had a name. I hope approaching it this way, from the bottom up and with a concrete problem to solve, will make the ideas (rooted in maths) easier to relate to.</p><p>What follows is a more or less accurate account of my thought process then, and the steps I went thought. I did strip it free of anything I thought would just get in the way of explaining things, and needless to say, the actual implementation is more complex than what is outlined here.</p><p>The problem I faced was building an inventory for a simple 2D game. The requirements were as follows:</p><ul><li>The inventory has a fixed number of slots</li><li>A slot can either be empty, contain a single item, or a stack of items</li><li>Items can be dragged from one slot onto another</li><li>Dropping an item onto an empty slot moves the item</li><li>Dropping an item onto an occupied slot creates a stack</li></ul><p>Here’s a screenshot of the inventory containing a pickaxe and two swords:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*AJiAM53a6-mBfleMwdvQQQ.png" /></figure><p>We can take the first sword and move it to the center slot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*vzUbZFGqDPGmGy7m-H_c8A.png" /></figure><p>If we take the same sword and drag it onto the other sword, we create a stack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*b-Fuef6B8o_E8l33U_MIqw.png" /></figure><p><em>DISCLAIMER: The following sections contain code samples in Kotlin. I think it should be easy enough to follow along, even if this is your first encounter with the language.</em></p><p>So, how can we model this inventory?</p><p>First, we need a data structure that represents an item. How about Item?</p><pre><strong>data class</strong> Item(<strong>val</strong> obj: GameObject)</pre><p>Neat.</p><p>We also need to hold our items in the inventory. For simplicity’s sake we’ll use an Array :</p><pre><strong>val</strong> inventory: Array&lt;Item&gt;(size = 9) { <strong>null</strong> }</pre><p>And just like that, we’re ready to add some items:</p><pre>inventory[0] = Item(pickaxe)<br>inventory[1] = Item(sword1)<br>inventory[2] = Item(sword2)</pre><p>This leaves us with the following structure in memory, where every row except for the first contains null:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*yL8sXb5s-rGykDRiYbiBRQ.png" /></figure><p>Looks like we’re ready to move some items.</p><p>Here’s a first stab at implementing a move function:</p><pre><strong>fun</strong> move(inventory: Array&lt;Item&gt;, from: <strong>Int</strong>, to: <strong>Int</strong>) {<br>  <strong>val</strong> item = inventory[from]<br>  inventory[from] = <strong>null<br></strong>  <strong>if</strong> (inventory[to] == <strong>null</strong>) {<br>    inventory[to] = item<br>  } <strong>else</strong> {<br>    TODO()<br>  }<br>}</pre><p>Not too bad I suppose. Those nulls are gross of course, but Kotlin is <a href="https://kotlinlang.org/docs/reference/null-safety.html">null-safe</a> right, so we’re cool. Of course this only handles one case so far (moving to an empty slot), hence the TODO(). (This is an actual function in Kotlin, if you’re unfamiliar, akin to Scala’s ???.)</p><p>What the else branch needs to handle are two cases:</p><ul><li>if the target slot contains a stack, grow the stack</li><li>if the target slot contains an item, create a new stack</li></ul><p>When we say stack, we don’t actually care about order. All we need is a set of items bundled together in a slot, so Set seems like a good choice. Let’s see where this takes us:</p><pre><strong>fun</strong> move(inventory: Array&lt;Item&gt;, from: <strong>Int</strong>, to: <strong>Int</strong>) {<br>  ...<br>  <strong>else</strong> {<br>    <strong>val</strong> other = inventory[to]<br>    <strong>if</strong> (other is Set) {<br>      // add item to stack<br>      inventory[to] = other + item<br>    } <strong>else</strong> { <br>      // create new stack<br>      inventory[to] = setOf(other, item) // NOPE!<br>    }<br>  }<br>}</pre><p>Nice try! Needless to say, this doesn’t type-check: our inventory contains Items, not Set&lt;Item&gt;s, so the last assignment fails. Of course we could make our inventory an Array&lt;Any&gt;, so that assignment to a slot always type-checks. We’re already on thin ice with all those null checks, however, so instead of throwing the remaining type safety out the window, we decide it’s time to refactor.</p><p>Before refactoring, it’s always good to take a step back, assess the situation and understand where we derailed our train. The main deficiency in our approach appears to be that slot contents can have incompatible values (null, Item, Set&lt;Item&gt;), so they <em>do not add up. </em>There is simply no way to “add” an Item to null, or a Set to an Item. But wait, you can certainly add an Item to a Set&lt;Item&gt;. Maybe we’re onto something here?</p><p>Our mistake was to think about the inventory as a structure in an imperative rather than functional way: move writes slots by inspecting their contents and swaps their content out accordingly, but it’s cumbersome because there is no clear model governing this operation. If we shift our perspective instead to understand slot assignment as <em>addition of values</em>, a lot of complexity suddenly disappears.</p><p>To accomplish that, we need a proper model for what a slot may contain. Before we dive back into code, let’s sketch out the idea first. It appears there are three distinct cases — values! — we need to represent:</p><ol><li>An empty element — let’s call it e<em> </em>for “empty”</li><li>A single item — let’s call it i<em> </em>for “item”</li><li>A stack of items — let’s call it s<em> </em>for “stack”</li></ol><p>Furthermore, we need an operation — +, perhaps — under which these values compose, i.e. composition derives naturally from the objects themselves rather than us having to prod the slots for their content in move. We want it to produce the following results given the respective inputs:</p><pre>e + e = e // two nothings combine to nothing<br>e + i = i // adding an item to nothing leaves us with the item<br>i + e = i // adding nothing to an item leaves us with the item<br>e + s = s // adding a stack to nothing leaves us with a stack<br>s + e = s // adding nothing to a stack leaves us with a stack<br>i + i = s // adding two items creates a new stack<br>s + s = s // adding two stacks creates a larger stack</pre><p>Our + operation should also follow some simple laws. For instance, whatever its arguments, it should always return e, i, or s as is evident from the table above. This precludes us from returning null or throwing exceptions. We say the operation is <em>closed</em> over the set {e, i, s}. This might sound obvious at first, but if you go back to our previous solution, you can convince yourself easily that it violates this law; for instance, null + i does not only <em>not</em> yield i, it doesn’t even compile!</p><p>We also do not want the <em>order of composition</em> to matter in terms of the result: given our two swords, dragging the first onto the second (creating a stack), then moving the stack to an empty slot should be equivalent to moving a sword to the empty slot first, then dropping the remaining sword onto it (again creating a stack.) Or in terms of our small <em>inventory algebra</em>:</p><pre> (i + i) + e = i + (i + e)</pre><p>This is called <em>associativity</em>, which simply means we can freely change the way we group our operands without changing the result. Another way to think of this is: parentheses don’t matter, so the order of evaluation doesn’t matter either. This doesn’t only make our model intuitive (as explained above), it can be an extremely beneficial property in distributed systems, where we might want to break up a series of combinations and run them in parallel.</p><p>As hinted at earlier, the algebraic structure we just described is called a <em>monoid</em>. Monoids consist of the following ingredients:</p><ol><li>A set of objects S</li><li>A neutral element e in S</li><li>A binary, associative function closed over S and commutative w.r.t e</li></ol><p>You might have noticed that our combination table contained mappings for all element permutations. That is, we effectively asked for + to commute regardless of the elements being combined. This might appear like an unnecessarily strong requirement at first (and in fact, a monoid does not demand it), since it covers cases we don’t care about: for instance, we cannot drag “nothing” (the empty slot) onto something else, but often you get commutativity “for free”, as we’ll see in a second, and it can help to drastically simplify reasoning about code.</p><p>If all this looks awfully familiar, there’s a reason. The natural numbers along with addition, for instance, form a monoid with 0 for the neutral element. Multiplication, likewise, forms a monoid with 1 for the neutral element. There are more interesting monoids, however. Sets form a monoid with union as the binary operation and the empty set as the neutral element. Hold on — sets? Maybe our intuition earlier that sets might be more useful than we initially gave them credit for is holding up. Here’s how we’d map our objects to sets:</p><ul><li>e — the empty set</li><li>i — a singleton set</li><li>s — a set with ≥ 2 elements</li></ul><p>Let’s rewrite our move method using Set&lt;Item&gt;:</p><pre><strong>val</strong> inventory = Array&lt;Set&lt;Item&gt;&gt;(size = 9) { emptySet() }</pre><pre><strong>fun</strong> move(inventory: Array&lt;Set&lt;Item&gt;&gt;, from: <strong>Int</strong>, to: <strong>Int</strong>) {<br>  inventory[to]   = inventory[to] + inventory[from]<br>  inventory[from] = emptySet()<br>}</pre><p>And that’s it — that’s all we need. We reduced all that clutter to a 2-liner, without having to rely on nulls or other shenanigans. Convince yourself quickly that this method actually works as expected. But wait, that’s not all! Not only did we simplify our code, we also <em>get new functionality for free</em>. Let’s say we want to add a “drop all items” feature which rolls up the inventory into a single collection, so that the player can drop them onto the stage. In our initial solution, you’d have to write code that iterates over all slots, and either skips items (null), adds one (Item), or adds all (Set&lt;Item&gt;). Instead, we can now say</p><pre>inventory.fold(emptySet()) {<strong> </strong>a: Set&lt;Item&gt;, b: Set&lt;Item&gt; <strong>-&gt; </strong>a + b }</pre><p>which returns a single Set&lt;Item&gt; containing all items. Folds go hand in hand with monoids, since they require an initial item (our neutral element) and a combine operation to perform the reduction. This makes them safer to use than functions like reduce, which would fail when called with an empty inventory, since there is no initial value to start the reduction from. (For the curious folks among you, reduce merely requires a <a href="https://en.wikipedia.org/wiki/Semigroup"><em>semigroup</em></a>, which is a slightly weaker structure than a monoid in that it does not demand a neutral element to exist.)</p><p>We started with what appeared to be the most obvious approach to something, implementing the simplest case first, then incrementally adding complexity as needed. There is nothing wrong with that, however, we need to continuously refactor to distill code to a <em>sound and meaningful model</em>. In the process, patterns emerge, and it’s important to identify them for what they are, giving related concepts related shapes. Usually such patterns are already well understood and can unlock additional functionality or flexibility in your code base.</p><p>There are caveats with our approach, however. By pouring all our cases into the same shape (they’re all sets), we lost something:</p><ul><li>We are using a type that we don’t own (Set) to implement a key aspect of our model. This can only backfire in the long run when we plan to add more functionality, and it wouldn’t be prudent to extend a platform type with domain specific logic.</li><li>We lowered the “resolution” of our model: e, i and s are conceptually different cases, but they’re all represented by the same type. This can lead to unwieldy und unsafe code when trying to invoke case specific behavior, since we need to inspect the set content (e.g. isEmpty) before acting on it.</li></ul><p>Wouldn’t it be great if we could carry over the monoidal aspects of sets to a custom type and reclaim the precision we lost at the same time? The <a href="https://medium.com/@mttkay/refactoring-with-monoids-and-sum-types-part-2-b2a8e8b29d5f">next (and final) part of this article</a> will therefore look at <em>sum types</em>, and how they can help to get our model back in shape.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bddc9ea61f5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Your Arrows]]></title>
            <link>https://medium.com/@mttkay/reverse-your-arrows-86173bd4aae0?source=rss-e8f399862cd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/86173bd4aae0</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Matthias]]></dc:creator>
            <pubDate>Sun, 11 Sep 2016 15:43:43 GMT</pubDate>
            <atom:updated>2016-09-12T07:32:42.775Z</atom:updated>
            <content:encoded><![CDATA[<p>I can now safely say that I have been programming for the better part of my life. If you’re like me, you might still be astounded by the amount of things you learn day in and day out, but the moments of real insight become rarer over time. I mean those insights that change your perspective on things in some profound and lasting fashion. Often those insights mark the difference between <a href="http://tumblr.austinkleon.com/post/759642471"><em>naming</em> things and <em>knowing</em> things</a>.</p><p>For instance, you might be able to name a few design patterns. For some of them you might have internalized how and when to apply them. But how often do you step back and ask yourself whether they are governed by some underlying principle, a meta-pattern, so to speak? One pattern to rule them all? That could mean <em>knowing</em> design patterns and their relationships.</p><p>The benefit of developing an understanding of how patterns are connected is that it becomes easier to judge whether a new problem can be fitted into a familiar problem space, or whether you can amend an existing solution for a related problem and apply it to the new problem instead. I believe that one such governing principle that is key to solving problems in their respective problem space is found in <em>understanding the problem spaces’s arrows, and manipulating their direction to your benefit</em>.</p><p>That sounds awfully abstract, so let me start by exploring why this sounds difficult to comprehend at first. Bear with me though, I promise that soon you’ll start seeing arrows everywhere.</p><h3>Enslaved by intuition</h3><p>We, as people, are fundamentally forward-oriented in our thinking and actions. It is ingrained in us by how we perceive the world: time flows forward, effect follows cause — <a href="https://en.wikipedia.org/wiki/Arrow_of_time">despite most physical processes being indifferent to it</a>. It’s common sense: a shattered glass dropped to the floor has not yet been observed replacing itself to its original state. People are actors in this world, so we naturally assume that this is transitive: to solve a problem, we start with ourselves and things created and put in motion by us, which in turn create other things and put yet more things in motion. In other words, an act of creation or derivation usually consists of <em>forward pointing arrows</em>.</p><p>In this article I will try to explain why going from forward-pointing to backward-pointing arrows, while often difficult, is the key to understanding many patterns in programming and software architecture. This seems to be at odds with our intuition, which leads us to tackle complexity in the most straight forward way first. After all, there is a reason it’s called straight<em>forward</em>, and not straight<em>backward</em>. Unfortunately, while straight forward often means simple, it doesn’t always mean good.</p><p>Reversing a familiar thought process often sounds absurd at first, but can suddenly lead to elegant solutions for difficult problems. When Ptolemy declared the Sun and stars to circle the Earth, he was victim to his own common sense. Today the idea of us being the center of the universe sounds ludicrous, but that’s purely thanks to someone with a strong sense of abstraction and rationality disconnecting themselves from intuition to consider a higher level view: that there are other points of reference than just Sun and Earth, and we’re not special after all. That someone was Copernicus and he rocked our world by <em>reversing Ptolemy’s arrows.</em></p><p>Where Ptolemy assumed that everything originates from Earth and everything else derives from it (<a href="https://en.wikipedia.org/wiki/Deferent_and_epicycle">leaving some inconvenient questions unanswered in the process</a>), Copernicus realized that the motions of the heavenly bodies made a lot more sense if the Sun was dominating Earth and the other planets instead. The <a href="https://en.wikipedia.org/wiki/No_Silver_Bullet">accidental complexity</a> of Ptolemy’s model (the infamous epicycles) suddenly disappeared. While it’s unlikely that we’ll arrive at similarly Earth shattering conclusions in our programming careers, we can still learn from this and apply it in the small.</p><p>In software development, you’ll find two kinds of arrows that are essentially universal: <em>control flow</em> and <em>information flow</em>. The examples of poorly written software rooted in forward-pointing control and information flow are countless: complex, unmaintainable, incomprehensible software where every cog in the system <em>acts</em> on other cogs instead of being <em>acted on</em>. Components taking control when instead they would better left <em>being controlled</em>, components talkin<em>g</em> when instead they should shut up and <em>listen</em>. The first arrow reversal I would like to explore is therefore <em>Inversion of Control (IoC)</em>, also known as the <em>Hollywood Principle</em> — “Don’t call us, we’ll call you!”</p><h3>Reversal in object hierarchies</h3><p>One of the earliest recollections I have of reversing arrows to solve a programming problem in some structured way is the <em>Template Method Pattern</em>. In class based Object-Oriented Programming, subclasses often specialize their superclasses by overriding their behavior. In my programming rookie days, I’ve been guilty of writing despicable code like the following:</p><pre>class A {<br>  void performSteps() { // do A specific things }<br>}</pre><pre>class B extends A {<br>  @Override void performSteps() {<br>    doFirstThing();<br>    super.performSteps();<br>    doLastThing();<br>  }</pre><pre>  private void doFirstThing() { ... }<br>  private void doLastThing() { ... }</pre><pre>}</pre><p>What’s happening here is that B is “decorating” A’s behavior by first unhinging the inherited method by overriding it and then wrapping extra steps around it. While this might look harmless at first, it quickly leads to code that is difficult to understand or even misbehaves, since it’s subject to subtle call ordering issues. Worse, imagine if we make the super call conditional and A’s behavior can suddenly “disappear” based on changes in program state. The crux of the matter is that B is trying to <em>take control</em> over A. We can instead arrive at more solid, more readable, more maintainable code by applying the template method pattern:</p><pre>abstract class A {<br>  final void performSteps() {<br>    onStart();<br>    // do A specific things<br>    ...<br>    onFinish();<br>  }</pre><pre>  protected abstract void onStart();<br>  protected abstract void onFinish();<br>}</pre><pre>class B extends A {<br>  @Override void onStart() { // do first thing }<br>  @Override void onFinish() { // do last thing }<br>}</pre><p>That is, we inverted the arrow by yielding control flow back to the superclass that defines the algorithm. The subclass instead becomes a <em>passive actor</em> — it’s not calling anymore, it’s <em>being called</em>. This is an example of control inversion.</p><h3>Reversal of Dependencies</h3><p>One of the most well known applications of IoC is the dependency inversion pattern, better known as <em>dependency injection (DI)</em>. I was first introduced to the idea as part of a practical course during my Software Engineering curriculum at university ca. 2004 in form of the Spring IoC container (anecdotal fact: dependencies were then wired via XML files, believe it or not.) Let me stress, however, that it is a common misunderstanding to equate DI with a particular framework or library. In fact, no tooling other than your programming language of choice is required to practice DI. All you need is to do is understand the arrow of this problem space: you don’t <em>create</em> objects, they are <em>provided to you.</em></p><p>Before the wide spread recognition of DI as a good practice, it was commonplace to “pull in” dependencies directly at the call site. In its mildest form this meant directly allocating a collaborating object, at its worst it meant reaching out to global state (that includes singleton objects, which are just global state in disguise.) In both cases we are coupling ourselves to the <em>execution context</em> in which we act. If our collaborator is an object that performs expensive side effects (such as network or disk I/O), we lose the ability to take the caller out of its “natural habitat” and into, say, a test or staging environment instead. Violating dependency inversion therefore erodes modularity and increases coupling across your entire system.</p><p>We can easily solve this problem by reversing the control arrow from <em>defining</em> dependencies to <em>declaring</em> them. When practiced rigorously, DI means that every single module in your system attempts to push the responsibility of provisioning collaborators to its owner, so long until there is no more owner, i.e. you’ve reached the root of your <em>object graph</em>. There are different ways of how this can be achieved, largely dependent on language idioms, but constructor injection, method injection, the cake pattern and function composition are some that come to mind.</p><h3>The Law of Demeter</h3><p>Staying in the object world a while longer, I cannot leave the Law of Demeter (LoD) unmentioned as an example of arrow reversal that has a profound effect on the readability and maintainability of code modules. The LoD is sometimes referred to as the “Tell, don’t ask” principle of object-oriented programming. In a nutshell, it attempts to minimize the distance information has to travel over a series of method calls. Consider the following code snippet:</p><pre>obj.a().b().c()</pre><p>Here, <em>obj</em> wants to invoke the behavior of a method <em>c</em>, by traversing the graph of collaborators <em>obj’</em> (defining <em>a</em>),<strong><em> </em></strong><em>obj’’</em> (defining <em>b</em>) and <em>obj’’’</em> (defining <em>c</em>). This is sometimes called “train wreck” code due to the shape of the invocation chain.</p><p>The problem here is that <em>obj</em> accidentally assumes knowledge of the entire span of methods exposed by its direct and indirect collaborators. In other words, the influence of <em>obj</em> increases rapidly with the distance of the behavior it summons. LoD therefore demands that behavior and data are to be co-located with the object that requires it, either by defining it on <em>obj</em> to begin with or by keeping it in a collaborator that is in direct reach.</p><p>Obeying the LoD is a form of arrow reversal. Instead of moving forward along a dependency graph, we reverse the arrow and move the required functionality closer to the place where it is required.</p><h3>Event driven programming</h3><p>So far we’ve been looking at control arrows. Let’s turn our attention to information arrows, specifically <em>event driven programming (EDP)</em>. In its simplest form, EDP can be practiced by applying the observer pattern, a prime example of the “Hollywood Principle”. Without events, any code module must ask for the data it requires, potentially blocking on a function call until that data becomes available. This model quickly falls apart when blocking is simply not an option, such as in user interface programming, where we must not stall the rendering thread.</p><p>We can solve this problem by <em>pushing</em> data as events instead of <em>pulling</em> it from the source. This is sometimes called the Publish/Subscribe model, or pub/sub for short. The arrow kind here is therefore one of <em>data flow direction</em>. Pub/sub completely decouples us from making decisions about when an event source is ready to send more data. This is of paramount importance in asynchronous or distributed systems, where this is difficult to control or predict.</p><p>There is another interesting relationship here that I wouldn’t want to leave unmentioned: the relationship between events and <em>application state</em>. With pub/sub, an event is typically sent as a result of mutating application state to inform observers of the change. You can turn this relation on its head by reversing the arrow and <em>derive application state from events</em> instead. This can be achieved by modeling every state transition in your system as a <em>persisted additive event</em>, thus obviating mutable storage of state. In case of state loss or when retrying failed events, this log of events <em>e’, e’’, … </em>can be replayed onto your application to partially or fully reconstruct a particular state <em>sk</em>:</p><pre>e&#39;  =&gt; s&#39;<br>e&#39;&#39; =&gt; s&#39;&#39;<br>...<br>ek  =&gt; sk // replaying [e&#39;...ek] yields sk<br>ek&#39; =&gt; sk&#39;<br>...</pre><p>This practice is called <em>event sourcing </em>and it’s one of the most ingenious arrow reversals I’ve seen. It leads to <a href="http://martinfowler.com/articles/lmax.html">highly predictable, reproducible, and fault-tolerant systems</a> and can be combined effectively with other architectural patterns such as <em>Command Query Responsibility Segregation (CQRS)</em> to obtain systems with high cohesion and low coupling.</p><h3>Reactive programming</h3><p>If one takes the idea of EDP to its ultimate conclusion, one arrives at the concept of <em>reactive programming, data flow programming, or stream programming</em>. In reactive systems the result of expressions is evaluated lazily so that state changes are never polled for, only pushed. This is in stark contrast to traditional imperative programming styles advertised by languages such as those of the C family, where you always have to ask for the value of something. RP is best explained with a very simple example:</p><pre>x = 1<br>y = x + 1<br>x = 2</pre><pre>return y</pre><p>What would you say is the value of <em>y</em> by the time we return? If you answered <em>2</em>, then unfortunately your intuition has been successfully undermined by years of programming in imperative languages, because every mathematician would tell you the answer is <em>3</em>. The trap into which you fell is that imperative languages make you think in <em>instructions</em>, not in <em>relationships</em>, because instructions are really all a computer understands. But when we think in relationships, then what this code really says is that <em>y is completely dependent on the value of x</em>, so when we look at <em>y</em>, it needs to either <em>lazily evaluate x</em> or have been updated accordingly by the time we changed <em>x. </em>That’s why in any reactive programming environment, <em>3</em> is returned.</p><p>This constitutes a reversal of arrows, since we completely changed the direction in which things evaluate. In imperative programming we only see change when we ask for it. In reactive programming we never ask: we <em>declare</em> functional relationships and let state changes trickle through the system, updating all dependent bindings in the process.</p><p>In the <a href="http://reactivex.io/">ReactiveX</a> family of libraries, this pattern is implemented in the <em>Observable </em>type, which is the conceptual dual to <a href="https://en.wikipedia.org/wiki/Iterator_pattern">iterators</a>. When I first learned about reactive programming in December 2012, I thought the idea so radical and appealing, our team and I immediately started to migrate the SoundCloud Android app to an Rx driven architecture. We haven’t looked back.</p><h3>Typeful programming</h3><p>I would like to conclude this post by shifting perspective just a bit. We’ve been talking about design and architectural patterns a lot, and how arrow reversal can help us solve problems in surprising and powerful ways. However, we were just enumerating examples and <em>naming things is not knowing things</em>.</p><p>That said, I think the best way to get to familiarize yourself with “arrow based thinking” is to practice <em>typeful programming</em>. Type systems are deeply connected to <a href="https://en.wikipedia.org/wiki/Category_theory">category theory</a>, the field of mathematics which attempts to discover and formalize relationships between structures in mathematics itself. Or simply put, it studies <em>arrows</em> and how they connect objects in some interesting way. This is extremely useful when reasoning about relationships between types, which is what compilers spend much of their time on.</p><p>In the recent years, more and more higher-level languages have started to make these “objects” and “arrows” available not just to the compiler, but to the programmer. If this sounds too abstract and you’re wondering why this is useful, consider this function in Scala:</p><pre>def parseInt(s: String): Option[Int] = { ... }</pre><p>Here we have a function that takes a <em>String</em> and knows how to convert it to an <em>Int</em>; however, the string might not actually be a number so this operation can fail. This is expressed in the return type <em>Option</em>, which is either <em>Some(x)</em> or <em>None.</em> The task is to produce from a list of strings a new value that is</p><p>a) <em>Some(list) </em>of all the numbers, if all strings are numbers, or<br>b) <em>None</em>, if at least one string is not a number.</p><p>This is<em> </em>not a contrived example; in fact, I had to write code like that just the other day in order to validate a list of HTTP request parameters. If you’re already thinking of how to traverse lists in loops and what not, let me stop you right there: category theory already solved it for you. Here’s how it’s done using <a href="http://typelevel.org/cats/index.html">typelevel’s cats</a> library (I borrowed the example <a href="http://typelevel.org/cats/api/#cats.Traverse">from the docs</a>):</p><pre>List(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;).traverse(parseInt)<br>res0: Option[List[Int]] = Some(List(1, 2, 3))</pre><pre>List(&quot;1&quot;, &quot;two&quot;, &quot;3&quot;).traverse(parseInt)<br>res1: Option[List[Int]] = None</pre><p>So what is this magical function <em>traverse</em>? You might think it has been written specifically for turning lists of strings to options of lists. Nothing of the kind. In fact, we can use it with any <em>applicative functor; </em>because that’s what <em>List </em>and <em>Option</em> are, and there are <em>well known arrows</em> that connect these structures. This is an example of how studying the relationships between things can ultimately safe you time.</p><h3>Conclusion</h3><p>I hope I could demonstrate how understanding arrows between things can be extremely useful and exploited to your benefit. While it’s not our default <em>modus operandi</em> to think backwards, it can be a powerful problem solving tool. There is a lot more to be said about the topic, since arrows are important not just in programming. Ever put yourself in someone else’s shoes? Arrow! But I’ll leave that for someone else to explore.</p><p>So next time you’re faced with a difficult problem: <em>reverse your arrows</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86173bd4aae0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blockchain: On availability]]></title>
            <link>https://medium.com/@mttkay/blockchain-on-availability-191e9d22582d?source=rss-e8f399862cd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/191e9d22582d</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Matthias]]></dc:creator>
            <pubDate>Sat, 18 Jun 2016 14:02:51 GMT</pubDate>
            <atom:updated>2016-06-18T14:02:51.191Z</atom:updated>
            <content:encoded><![CDATA[<p>I would like to draw attention to what seems to be a commonly misunderstood property of <em>distributed applications</em> running on a blockchain, or DApps for short. A claim I have repeatedly seen creeping up is a DApp’s alleged superior <em>availability</em> compared to a traditional centralized web application. One must take this with a grain of salt, as it depends largely on what is meant when one talks about a “DApp” and what this actually entails. I mean to write this as a heads-up for a non-technical audience, such as economists, investors, and other non-technical decision makers, as I’m sure developers or people with a technical background do see the problem in this argument straight away.</p><h3>Terminology</h3><p>Let’s clarify terminology and scope of argument briefly. I’m not aware of any precise definition of the term, but simply judging by what appears to be common appropriation (see for instance <a href="http://dapps.ethercasts.com/">the DApp browser</a>), a <em>DApp</em> is an application that partially or fully executes on a blockchain (such as Ethereum.) A <em>user facing DApp (UFDA)</em> is then a DApp that is made accessible to an <em>end user</em> through some form of <em>gateway technology</em> such as web browsers or desktop and mobile applications. Not all DApps are UFDAs; it is perfectly feasible and desirable to run DApps that purely execute on the blockchain as some form of mediator between other DApps. Examples include escrow services, oracles, and blockchain middleware. For most people, however, the most interesting DApps are naturally those that are user facing, so I would like to focus on these hereafter, and whenever I say DApp, I really mean a UFDA. Examples for UFDAs include gambling and betting applications, blockchain explorers, identity services and many more.</p><p>As for availability, when I say a DApp is (partially) <em>available</em>, I mean it must be ready to serve the end user by carrying out at least a portion of its defined functionality. It is <em>unavailable</em> if none of its features can be accessed by means of its gateway technology. That portion of a DApp which is used by an end user directly is called the <em>interface</em> from here on. We will see shortly why this distinction is important when talking about DApp availability.</p><h3>Why DApps can experience downtime</h3><p>Now to the core of my argument: most or all DApps will by their very nature be susceptible to down time, that is, to being unavailable for some fraction of their life-time. The reason why is that a typical DApp runs only a small portion of its code on the strong backbone that is the blockchain. To use an analogy, think of a car. A car has many moving parts: an engine, doors, wheels and so forth. Some parts are more important for the car to remain functional than others. For instance, I can remove a door, but the car will still run. If I remove the engine, it won’t run. What if I take off the wheels though?</p><p>Let’s carry this analogy to its conclusion: the blockchain is to DApps what the engine is to a car. Here’s the twist: If the engine runs with 99.99999% availability, but your tires go flat, <em>your car isn’t going anywhere</em>. It becomes <em>unavailable</em> from an end user’s perspective. The same is true for DApps. It is really only the core business logic and small amounts of state data that execute on the highly available blockchain. This is only the tip of the iceberg though; the user interface and more data heavy portions of a DApp will not actually execute on the blockchain, but most likely use standard web technology as found in any ordinary web app. Hence, they are just as susceptible to unavailability as any other web app out there.</p><p>This is exactly what happened during the DAO attack on June 17 2016: while Ethereum nodes were happily crunching away on transactions, major crypto exchanges and blockchain explorers suffered outages due to panicking traders flocking to those websites to rescue their investments from a rapidly decreasing Ether value. So if not even exchanges and key services such as those monitoring the blockchain are safe from downtime, what does this say about the general availability of DApps?</p><h3>Breaking down availability</h3><p>I would like to come back briefly to the point of what can and can not be made highly available. Again, one needs to understand the nature of DApps to understand which parts can remain available in cases of traffic spikes as those witnessed during the DAO attack and which ones might not. Let’s break it down.</p><h4>1 — Business rules</h4><p>Business logic and the associated persistent state transitions can — and probably should — execute on the blockchain. This will allow you to reap the availability and security benefits you gain from blockchain technology. This is great, but it’s simply only part of the picture.</p><h4>2 — Data storage</h4><p>For many DApps, like those that operate on large data files (such as music or photo attribution services), storing their data on general purpose blockchains like Ethereum is simply impractical. Being fully replicated (at least thus far —Ethereum is considering a sharding approach in the future, effectively splitting up the blockchain among nodes) blockchain size is quite literally one of its biggest growth pains. This is why DApp developers should not get incentivized to store large amounts of data directly on the blockchain. The Ethereum projects solves this problem by making it extraordinarily expensive to store data. In fact, at the time of this writing, a transaction storing 100KB worth of data on the Ethereum blockchain costs more than 17 US dollars (0.000000021 ETH/gas * 640000 gas/KB * 100KB * 12.85 USD/ETH). This makes it economically unfeasible to store things such as images directly on the blockchain. Instead, a DApp would most likely involve a traditional (centralized) storage solution and merely record the existence and ownership attribution of said data on the blockchain, but not the data itself. What this amounts to is obvious: the availability of said data is not bound to the availability of the blockchain.</p><h4>3 — User interface</h4><p>I mentioned before that user need to interface with a DApp. This will most likely happen through standard web technology such as HTTP, HTML and web browsers, where a user request is made through the web interface, the request gets routed through a traditional web app, and only then talks to the blockchain to execute business logic or query for account data. None of the code realizing these interactions, let alone the code responsible for an app’s presentational aspects, is stored on the blockchain. This, again, makes it susceptible to down time just as much or little as any other web app.</p><h3>Conclusion</h3><p>What does this all mean? It means that you shouldn’t read too much into the claims of blockchains being the silver bullet for app availability in the foreseeable future. It does mean, however, that crucial pieces of a DApp, namely state transitions, business rules and account data can still live on the blockchain and benefit from its distribution and availability aspects. So just keep in mind that a DApp is typically more than just some smart contract that runs on a blockchain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=191e9d22582d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>