<?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 Christian de Botton on Medium]]></title>
        <description><![CDATA[Stories by Christian de Botton on Medium]]></description>
        <link>https://medium.com/@cdebotton?source=rss-7b3316a53577------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FcXNqG_bR0YanPj9p5O_Ig.jpeg</url>
            <title>Stories by Christian de Botton on Medium</title>
            <link>https://medium.com/@cdebotton?source=rss-7b3316a53577------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 01:58:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cdebotton/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[Statically Typing Complexity with TypeScript]]></title>
            <link>https://medium.com/@cdebotton/statically-typing-complexity-with-typescript-8a0bdb5f135f?source=rss-7b3316a53577------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a0bdb5f135f</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Christian de Botton]]></dc:creator>
            <pubDate>Mon, 14 Jan 2019 02:09:00 GMT</pubDate>
            <atom:updated>2019-01-14T15:16:57.520Z</atom:updated>
            <content:encoded><![CDATA[<h3>What we’re building</h3><p>There’s going to be a brief (I promise) wall of text before we get into some code, so entice you into continuing, here’s a video of what we’re building. A type safe implementation at a key access level for several methods that get, set, and update values in deeply nested, complex objects and arrays.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F311138371%3Fapp_id%3D122963&amp;dntp=1&amp;url=https%3A%2F%2Fvimeo.com%2F311138371%2F1519bf23c9&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F751884897_1280.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1440" height="2088" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa6cdb8f973fdf66a190509d38b4cdd2/href">https://medium.com/media/fa6cdb8f973fdf66a190509d38b4cdd2/href</a></iframe><p>In this article I would like to discuss how to statically type and write a set of complex functions that provide an API with absolute type safety. Through this exercise, my goal is to highlight the strengths and weaknesses of TypeScript as a type system. I may have been in the minority leading up to this point, but I’ve been eagerly looking forward to statically typed JavaScript for a very long time. My first real experience with types and programming behind high school Java and C classes was pretty late. I spent a year writing Swift while building a native iPad application. It definitely changed how I thought about programming and shifted my mental model from scrambling to get things to work toward designing well thought out systems which worked because of a guarantee from the compiler.</p><p>I was very interested in, invested a lot of time into, and previously wrote about <a href="https://medium.com/@cdebotton/redux-and-flowtype-69ff1dd09036">Facebook’s flow</a>. However, to my disappointment, flow was not Swift. About 2 years ago I then moved over to TypeScript, which was also, unfortunately, not Swift. I also spent some time with OCaml and Rust. What I had previously perceived as shortcomings of Flow and TypeScript, I then came to realize that the ways in which these type systems were designed were meant to compliment the languages they were in service of. That isn’t to stay that they’re perfect. TypeScript (as well as Flow) have weak points. Whereas languages like Rust have limitations in the type system (which are currently being addressed) that prevent typings on async code, TypeScript and Flow have limitations that actually allow unsafe data to be passed through your code rather than preventing the code from being written. This was, I believe, a conscious decision on the part of Facebook and Microsoft to make adoption seem easier upfront. Unfortunately these lax rules leave it up to the developer to manage the effectiveness and safety that usage of types can guarantee.</p><h3>Typescript’s strength is flexibility.</h3><p>There are two broad categories of type systems, as described by Javiar Chávarri in <a href="https://twitter.com/javierwchavarri/status/1082597155628568577?s=12">this thread of Tweets</a>. The first is Hindley-Milner, which describes the systems of Rust and OCaml, and then there are systems which are based on implicit subtyping. The former requires that every function only return one type. The tl;dr of this approach is that it effectively makes it harder for the engineer in the onset as the type system is harder to appease, but there is a stronger guarantee that there will be no runtime errors, and the toolchain can make better inferences about what the engineer intends to do.</p><p>Typescript allows for functions to return many different types, and also allows for an <strong>any</strong> type which acts as a wildcard but loses any guarantee of safety at the scope of that code. This puts the impetus of creating a sound type system more so in the engineers hands and also allows for a slight margin of error. This might be written off as a weakness, but could also be considered a strength. Let’s take a look at how we can use this flexibility to our advantage.</p><p>The three methods I would like to discuss writing are <strong>setIn</strong>, <strong>getIn</strong>, and <strong>updateIn</strong>. These three are excellent candidates to exemplify the strengths of Typescript because they model a complexity that other languages like OCaml and Rust would often struggle with. We need to accomplish the following:</p><p>1. Maintain that the keys over which we’re traversing into the object exist.</p><p>2. We need to ensure that the type returned from <strong>getIn</strong> properly references the value of the key we are pointing to.</p><p>3. In <strong>setIn</strong> and <strong>updateIn</strong>, we need to make sure that the value we are setting is the write type for the key we are referencing.</p><p>So let’s look at what these function signatures might look like, starting with the most simple: <strong>getIn</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48gGu98RJOI9BM_0UZZeGw.png" /></figure><p>First, what parts of the toolchain do we need? What are these types going to look like. Well, what’s the first thing in our function that we need to type? <strong>obj</strong>. We don’t know what the shape of that type will be, it can really be anything, so this is an excellent use case for a <strong>generic</strong>. Generic’s are a language feature of many modern type safe languages like Swift and Rust where we can use a placeholder to represent a type that we know nothing or very little about. What does that look like?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*xMaLqBbe8psL3yhAYLW87g.png" /></figure><p>We’re declaring some type that is represented by the letter `T` and then saying that <strong>obj</strong> is that type. Some people prefer to use descriptive names for generics, some prefer using single letters, which is more mathematical. I will probably write another post about my thoughts on that later, but I figured I’d call it out now.</p><p>So wait, what about <strong>arrayOfNestedKeys</strong>? We have a problem, the signature for an array is <strong>SomeType[]</strong> (or <strong>Array&lt;SomeType&gt;</strong>), which represents a set of types that all conform to the same value. The best we can do with an array type is say the keys can be any of a set of values that conform to a type, in any order, which doesn’t give us any of the type safety (or IDE benefits) of explicit expectations around the keys.</p><p>We can, however, use a <strong>tuple</strong> type. In Typescript, a tuple sort of looks like an array, it describes a sequence of values that must occur in a specific order. This sounds exactly like what we want. Let’s update our signature to allow for the first key to be passed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h6zCyBTgAu4K3LJw_MqOlA.png" /></figure><p>A lot happened here. The first thing we did was describe a second generic and put a constraint on it using the <strong>extends</strong> keyword, stating that it must be a key of the the first parameter using the <strong>keyof</strong> language feature. We then set the return type to the accessed value’s type. In Typescript we can access the type of a property of a known object using standard object access notation. At this point, if we had the following implementation, our types would provide the following feedback:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iswhy3TwCmSOMsqxONNBog.png" /></figure><p>You’ll also notice, if you’re using an IDE like VSCode, as you begin typing the second parameter, it would actually suggest the keys available to you. Pretty cool, right?</p><p>Ok, so this only gets us access one level deep, which isn’t very useful. But what next? We’ll need to define several definitions for the <strong>arrayOfNestedKeys</strong> variable, and several definitions for the return type. Your first instinct might be to use a union type, ` | `. The problem with this approach is that we won’t be associating the correct return types with the correct path types. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGQXD7nTOqNPqSt5meOSXQ.png" /><figcaption>In this example, the return type can be any matching result at any matching index of our array of keys.</figcaption></figure><p>We need to describe a set of signatures that map out expected results for provided parameters. There’s a feature of Typescript and many other languages called <strong>overloading</strong> that we can take advantage of for this exact situation. Let’s build out our example a bit more and see what this will look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uznduk4C_iirpmkLExekPA.png" /></figure><p>What did we just do? Typescript allows you to define multiple signatures for a function with types, omitting the function body. Notice in the actual implementation, we used any types, because the overloads stated beforehand are used rather than the <strong>any</strong> types. It is important that the function overloads are defined next to the actual function implementation, otherwise Typescript will not attach the type requirements to the function as desired. Looking at our previous implementation example, we will now have proper type traversal. Also, since the object’s shape is a generic, and we’re looking up keys of that object, we can traverse arrays for free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-T6G1yewcdTmQSXVLgsmzg.png" /></figure><p>This code will give us coverage of nested keys up to 5 levels deep. If we were creating an API for use by others, we might continue down this path for more iterations.</p><p>We can easily extrapolate these types for a <strong>setIn</strong> function, which would have the following parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YvNHWY-kT-cTImEczpkd2Q.png" /></figure><p>If you’ve followed through the previous examples, this will hopefully make some sense. We don’t know about the type of the first parameter, so we assign a generic. Since the second parameter needs to be a tuple of keys, since we care about the orders and types of, we need to define a generic that represents each key. We have one new, third, parameter in this function, which is the value we want to set. We want to make sure that the type of the value we’re setting matches the type of the value at the key we’re traversing into, and luckily, we’ve done all of the work to figure that out. This is the same type as the value returned from our <strong>getIn</strong> implementation.</p><p>Finally, since we’re writing a set of immutable functions, the method should return the new object with changes made immutably. Here’s an abbreviated implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mcqPajs75tU7CYk7LdjIg.png" /></figure><p>Lastly, let’s take a look at how we might use this same approach to write an <strong>updateIn</strong> method. With this, we want to similarly work with an object, traverse a set of keys, but we now want to be able to pass a function to the third parameter which provides access to the previously set value, allowing you to return a new updated value. We’ll skip deriving the types and just look at an abbreviated bit of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QBTv7GFI_XeIj5T2Bl7Tw.png" /></figure><p>You’ll notice that in our implementations for all of these functions we are typing out the parameters and return types as <strong>any</strong>. Under any other circumstance, this would be a bad thing to do. We lose type safety in our implementations. The benefit is that we gain type safety at a key access level in the API that we create. I haven’t tried, but I suppose you could create a type safe implementation, possibly, using another set of language features, <strong>conditional types</strong> and <strong>type inferences</strong>, but that would become unwieldy really quickly. Maybe we can save that one for another article?</p><p>Hopefully this gives you an idea of the power of the flexibility of in Typescript. That power does come at the cost of an increased responsibility as the implementing engineer, but gives you the tools to create flexible, safe tools for others to use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a0bdb5f135f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Case for Immutability]]></title>
            <link>https://medium.com/@cdebotton/the-case-for-immutability-fb8a330c342c?source=rss-7b3316a53577------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb8a330c342c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Christian de Botton]]></dc:creator>
            <pubDate>Wed, 02 Mar 2016 03:22:14 GMT</pubDate>
            <atom:updated>2016-03-02T03:22:14.153Z</atom:updated>
            <content:encoded><![CDATA[<p>Immutability is the notion that something cannot be changed. It has become a buzzword lately because of its pervasiveness throughout modern languages like <em>ClosureScript</em> and <em>Elm</em>. Why would you want data that can never change, when data is constantly changing in modern applications? One of the harder problems to solve for is how to detect when data has been updated. When we know that, we can update all of the pieces that need to respond.</p><p>Let’s look at a common case in JavaScript where we want to check if a value has changed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93283ce6c0227706c6aca9df6ea1a2b8/href">https://medium.com/media/93283ce6c0227706c6aca9df6ea1a2b8/href</a></iframe><p>There’s no trick to this example. We’re taking a variable named <em>data</em>, and creating a <em>newData</em> variable that is equal to the original. When we check if the two variables are equal, as expected it’s true. When we change the value of <em>newData</em> and check the equality again, as expected, we see that they are unequal, thus the <em>newData</em> has changed.</p><p>This works because when we declare the <em>data</em> variable, it is immediately given a value. Then we do the same with <em>newData</em> and set its value to the value of data. When we set the value of <em>newData</em> to something else, as expected, it is not equal to the value stored in the <em>data</em> variable.</p><p>So far, there’s no problem, right? With primitives in JavaScript, when we declare a variable, that variable effectively is a placeholder for its value. When we change the value, the variable changes. Taking that a step further, change its value changes the variable itself.</p><p>This isn’t true for non-primitives in JavaScript. Let’s see how this breaks down with objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c06c14e05814730f6e437215aa07b2c/href">https://medium.com/media/6c06c14e05814730f6e437215aa07b2c/href</a></iframe><p>Even though we changed the value of data2, JavaScript still evaluated the objects to be true. In fact, if you were to inspect data, you’d find that its value had changed as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72310cb77bc0b380e7af319cafba5824/href">https://medium.com/media/72310cb77bc0b380e7af319cafba5824/href</a></iframe><p>When a variable is set to a non-primitive in JavaScript, we aren’t creating a variable and setting its value, we’re actually creating a reference to the original object. Complex structures in JavaScript are allocated in memory, and variables simply become references to those memory allocations. Because of this, using our approach, we will never be able to check if data has changed.</p><p>So how do we solve for this? It’s actually easy, we just make a copy of the original object when we create our second variable, using the <em>Object.assign</em> method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e00a2aca3e31fe10334ca1dff8004bf/href">https://medium.com/media/0e00a2aca3e31fe10334ca1dff8004bf/href</a></iframe><p><em>Object.assign</em> copies subsequent objects’ properties into the original object that is passed to it. What we’re doing in the code above is creating a brand new object, then copying the properties from data into it, and then copying any new properties, giving a brand new object. Another positive from embracing immutable data is that our data becomes way more understandable. We now know that data is different from data2, and how it is different. Alternatively, if you just wanted to create an exact copy of an object, you could also use the Object.create method.</p><p>Likewise, when dealing with arrays, you’ll find the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/604415c8eaf91a1f528ac5bb0f8b34c5/href">https://medium.com/media/604415c8eaf91a1f528ac5bb0f8b34c5/href</a></iframe><p>You might worry that it’s inefficient to create copies of objects every time you want to change a property, but in reality, this is only an issue with particularly large data structures. When using this approach, it is best to keep your data structures relatively small. The JavaScript engine will destroy objects from memory when there are no longer references made to them, so by replacing and old object with a new copy, you are creating an <em>immutable</em> object reference. We can now compare when changes happen, making it easier to write incredibly performant code.</p><p>Using React as an example, you can tell your component to only update when the data it is watching changes. Using immutability, this becomes very simple, and it is now easy to write highly optimized components.</p><p>There are more ways to deal with immutability, however. Next let’s look at using modern JavaScript, or ES6, with its spread operator. The spread operator, or a preceding <strong>…</strong>, tells JavaScript to merge in the properties of another similarly-typed non-primitive object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/885bc93f692f275dae804076c9e05bce/href">https://medium.com/media/885bc93f692f275dae804076c9e05bce/href</a></iframe><p>This works just the same as before, the syntax is way more natural than using <em>Object.assign</em> or <em>[].concat</em>, but it becomes obtuse when working with more complex data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa70db0229bd0a53154f5ef6c328d863/href">https://medium.com/media/fa70db0229bd0a53154f5ef6c328d863/href</a></iframe><p>We find that we are constantly spreading in different layers of data. For me, this feels a little too verbose, especially when dealing with something as simple as updating one property on a nested record. We also have the problem that whenever we attempt to update a record, even if the data doesn’t change, we are returned a new object. We are effectively now able to test if an attempt to change data was made, but not if the data was actually changed.</p><p>Luckily, there’s a library named <em>Immutable.js</em>, written by Facebook, that provides a very robust suite of Immutability helpers. Not only is the syntax much cleaner using the Immutability library, but manages your state as a set of smaller objects, internally. Here’s how we’d solve the same problem with <em>Immutable.js</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/028433d6f0e23955ce9de912a5787d80/href">https://medium.com/media/028433d6f0e23955ce9de912a5787d80/href</a></iframe><p>This approach, to me, is vastly more readable. The immutable object has several methods, <em>set</em>, <em>setIn</em>, <em>update</em>, <em>updateIn</em>, <em>merge</em>, <em>deepMerge</em>, that will return a new object as well as update any parameters that you pass to it. There are also many functions that help you iterate over this complex object types just like you would iterate over natural JavaScript objects and arrays. <em>Immutable.js</em> also supports a great deal more than the natively provided primitives, including <em>Map</em>, <em>OrderedMap</em>, <em>List</em>, <em>Record</em>, <em>Seq</em>, <em>Collection</em>, and more. It is likely to be overkill in a lot of projects as it is extraordinarily comprehensive, however when you need to update and compare large, complex data sets, it has invaluable.</p><p>Let’s look at a real world example. Let’s say we’re building a friend list, and we only want it to re-render when the data it cares about is changed. Let’s say the friends list relies on a total user count, whereas individual user items need to update when any map of properties changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d798f2b42b4b286aaf24e141e2bdc36f/href">https://medium.com/media/d798f2b42b4b286aaf24e141e2bdc36f/href</a></iframe><p>We can see the list component will only update when the user information changes and likewise, the list item component will only change when the information that it’s concerned with is updated. When using <em>Immutable.js</em>, we don’t have to worry about new memory allocations being created for objects unless the data actually changes, which means that we can be sure that the user interface only updates when data actually changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb8a330c342c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux and Flowtype]]></title>
            <link>https://medium.com/@cdebotton/redux-and-flowtype-69ff1dd09036?source=rss-7b3316a53577------2</link>
            <guid isPermaLink="false">https://medium.com/p/69ff1dd09036</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Christian de Botton]]></dc:creator>
            <pubDate>Thu, 05 Nov 2015 16:20:59 GMT</pubDate>
            <atom:updated>2017-06-21T13:07:53.897Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical introductory walkthrough for static typing</h4><p>First, I want to begin by stating that this is not an article about how to use <a href="https://github.com/rackt/redux">Redux</a>, there’s a ton of <a href="http://redux.js.org/">fantastic</a> <a href="https://github.com/gaearon/redux-devtools/tree/master/examples">documentation</a> out there already, I want to discuss how you apply the concepts of static typing to Redux. <a href="http://flowtype.org/">Flow</a> is a static type checker for JavaScript, created by the engineering team at <a href="http://facebook.github.io/">Facebook</a>. Static typing adds a lot of value to your code, but it’s a strange topic for people who don’t come from programming in statically typed languages like C or Java. Let’s jump in by writing some <strong>non-typed</strong> <em>redux</em> code. We’re going to build a set of controls for an audio player. I’m assuming you’re familiar with all of this so I won’t do much explaining.</p><p>First, let’s define our <strong>constants</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03d02ca13c1a37e7278cbb3581e34c47/href">https://medium.com/media/03d02ca13c1a37e7278cbb3581e34c47/href</a></iframe><p>This is going to be a crazy easy file to statically type as we’re just declaring a bunch of string constants. Flow also infers the types of a variable based on the value that it’s instantiated with, so we technically don’t need to do anything here other than add the appropriate banner to our file that instructs flow to parse it. If we want to we can declare the types explicitly, which I’ll do here just to set us up for more complicated declarations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb9a8f9aaf9cf2b6145b0e86021dcbc9/href">https://medium.com/media/eb9a8f9aaf9cf2b6145b0e86021dcbc9/href</a></iframe><p>Flow allows you declare types as several primitives: <em>string</em>, <em>number</em>, <em>boolean</em>, <em>Function</em>, <em>Array</em>, <em>Object</em>, <em>any</em>, <em>mixed</em>, and <em>void</em>. If you’re instantiating without a value, or a variable can potentially be `null`, you precede your type declaration with a <strong>?</strong>, eg: <em>?string</em>, <em>?number</em>, <em>?boolean</em>.</p><p>Now that that’s out of the way, let’s look at something slightly more intricate, and dive into actions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52a083fd6bdf17ea30c799bf0de0ea27/href">https://medium.com/media/52a083fd6bdf17ea30c799bf0de0ea27/href</a></iframe><p>We’re dealing with functions now, so need to dictate the types of variables that pass into functions as well as the return values. For this example, we’re going to define a custom action <strong>type</strong> that is returned from each method, like a boolean, string, or number declaration, but a more fine-tuned declaration of an object type with it’s properties. Here’ what our action type is going to look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8efa013697c8b9a450f921756832575a/href">https://medium.com/media/8efa013697c8b9a450f921756832575a/href</a></iframe><p>You’ll notice we’re exporting our types, like any other JavaScript module, this will allow us to import and export types from our JavaScript modules, so the data can be shared. The track type is going to reference another type declaration, that describes what an audio track is. This will look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6bb2e0397c7209dd30fceedc9daa83b/href">https://medium.com/media/b6bb2e0397c7209dd30fceedc9daa83b/href</a></iframe><p>Ultimately, the track type will not live in our <em>actions/playerActions.js</em> file, it should live with our reducer as that in a way describes our client model data. Let’s assume this is going in <em>reducers/player</em>, and import it from there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/329246607a7f946848ef6a0fd34494aa/href">https://medium.com/media/329246607a7f946848ef6a0fd34494aa/href</a></iframe><p>Slightly more complicated than our super-simple constant declarations, we’re just labeling all variables and return values with types. In this case, most of our types are custom definitions. Each action returns a PlayerAction type, which defines all possible types that can be sent to our reducers. We’re also importing our track from our reducer file, which almost acts like a type definition for model data.</p><p>So now that that’s all out of the way, let’s take a look at our reducer, which is easily the most interesting module. Hopefully you’re a little more comfortable with how typings are declared because we’re going to skip the non-statically typed version.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/271aee7631533434903420871bad72c0/href">https://medium.com/media/271aee7631533434903420871bad72c0/href</a></iframe><p>And that’s it. We have our statically typed redux tools. If any part of our application tries to pass data into our state that doesn’t strictly conform to our declared typings, we will get an error before we ever go into a browser, which is invaluable in saving debugging time. As an added bonus, if you use <a href="http://nuclide.io/">nuclide</a> as your IDE, you will get type hinting throughout your code. This type hinting will make it extraordinarily easy for other developers to start working in your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69ff1dd09036" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write Applications that Scale, or Writing Your Code as a Service, Part I.]]></title>
            <link>https://medium.com/@cdebotton/how-to-write-applications-that-scale-or-writing-your-code-as-a-service-part-i-3763937cf927?source=rss-7b3316a53577------2</link>
            <guid isPermaLink="false">https://medium.com/p/3763937cf927</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Christian de Botton]]></dc:creator>
            <pubDate>Thu, 05 Nov 2015 00:48:29 GMT</pubDate>
            <atom:updated>2015-11-05T00:48:29.391Z</atom:updated>
            <content:encoded><![CDATA[<p>Scalability is one of the hardest problems you’ll have to solve as a developer. It’s difficult to maintain a product when it has a long or indeterminate lifespan and you have to account for growth in users, code base, the development team, and the systematic outdating of tools and frameworks that is commonplace in web development now. The solution to the problem can be conveyed in one succinct sentence, <em>“Write good code.”</em> That’s a gross oversimplification, so I should explain. The goal is to be able to write software that can be maintained by ever changing sets of eyes, deployed on changing platforms, and so on, so the only thing you can do is write code that people understand. Whether the people who need to understand it is a new set of developers, or you 3 weeks in the future, it is imperative to write code that people can understand without any question, any additional thought. this is how you maintain productivity, alone or on a team.</p><p>Style is obviously a subjective matter, but there are plenty of rules that can be implemented; the key to making something widely and easily understandable is to enforce simple rules uniformly. I’m going to discuss four categories that are particularly difficult to map together, largely because of the wide variety of options to choose from.</p><ol><li>Uniform editor configuration.</li><li>Programmatic safety nets, like linting and static typing.</li><li>Build processes that can scale with technology.</li><li>An architecture that is based on the idea of services and modules, where pieces can be swapped out without breaking everything else.</li></ol><p>The first two points I’ve mentioned are processes you run in the background and don’t require building out any tooling for the project. Today, I’m going to discuss these two items, and will write individual articles about build processes and service based architecture as they are lengthy topics that warrant their own discussions.</p><h4>Editor configuration</h4><p>The simplest point to discuss is <em>editor configuration</em>, so we’ll start there. You’ve probably never really thought about your editor settings before; how many spaces is the size of your tab, or is your tab writing actual tabs, or spaces, and how is a linefeed written? This is one of the more basic and immediate problems of working on a team, and is particularly important at a time when open source and community built projects are so prevalent, thanks to <a href="http://www.github.com/">Github</a>. It may not sound like much, but when you have one file where four or five people have made changes, and they all use different width tabs, represented by either tabs <em>or</em> spaces, you’ll quickly find that the resulting code looks pretty rough. The solution couldn’t be more simple; thankfully, there’s a dotfile for it.” If you drop an <a href="http://editorconfig.org/"><em>.editorconfig</em></a><em> </em>file in the root of your project or any child folder, it will define how the editor writes characters to that file, overriding their original settings. All modern browsers respect these configurations, including Sublime Text, Atom, Vim, and so on. Let’s take a look at an example:</p><pre>[*]<br>root = true<br>indent_style = space<br>indent_size = 2<br>tab_width = 2<br>end_of_line = lf<br>charset = utf-8<br>trim_trailing_whitespace = true</pre><p>That’s the editor config that I drop in every project, the rules that I find to be the most comfortable to work with. Yours might be different, and that’s fine. All that matters is that the rules are <strong>always</strong> the same amongst the team members of any given project. You can configure the group of rules — everything that follows the bracketed asterisk <em>[*] —</em> to target globs. Taken from the <a href="http://editorconfig.org/">editorconfig site</a>, all of the following glob types work:</p><pre><em># Target JavaScript &amp; Python files </em><strong><br>[*.{js,py}]</strong></pre><pre><em># Target just Python files<br></em><strong>[*.py]</strong></pre><pre><em># Only the Makefile</em><br><strong>[Makefile]</strong></pre><pre><em># All of the JavaScript files in the lib folder</em><strong><br>[lib/**.js]</strong></pre><pre><em># Either package.json or travis.yml</em><strong><br>[{package.json,.travis.yml}]</strong></pre><p>While all of these are possible, I find it best to just maintain the same settings across all filetypes for the sake of consistency.</p><h4>Lint and type: programs that help you program your programs</h4><p>This is a tough sell for some, as it takes extra time to write code that polices your other code. And the honest truth is, you probably don’t have to do all of these on every project you work on. Timelines, budgets, and other resources often get in the way of linting, testing, and statically typing your code on every project, but I will argue that at the very least, you should be linting your code. Since I’m so adamant about that one, we’ll start there.</p><p>Linting is incredibly easy, and also really confusing. It’s easy because, in reality, it’s as simple as picking some rules and installing a tool that tells you when you break those rules. This is hard because there are seemingly infinite rules, infinite tools, and infinite ways of rendering those tools into a readable, digestable format. As a developer who works largely in JavaScript (namely with React and Babel), I find the best tool to be <a href="http://eslint.org/">ESLint</a>. ESLint works like any other JavaScript linter, but the set of rules it comes with are fairly minimal, and it’s all about adding packages that flesh out its feature set. My favorite combination of ESLint plugins is:</p><ul><li><a href="https://github.com/eslint/eslint">eslint</a></li><li><a href="https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb">eslint-config-airbnb</a></li><li><a href="https://github.com/babel/eslint-plugin-babel">eslint-plugin-babel</a></li></ul><p>The best way to set up ESLint is to install it through <a href="http://npmjs.com/">NPM</a>. I like to install all of my packages locally to avoid maintaining multiple global versions, which ensures that everyone who clones your repository receives the same version of the tools you used to originally write the application. When it comes to writing applications that can be maintained across a wide set of platforms and developers, this is a pretty obvious precaution to take. Let’s install these tools in a project through the command line now.</p><pre>npm install --save-development eslint eslint-config-airbnb eslint-plugin-babel</pre><p>And quickly, my .eslintrc file looks like this:</p><pre>{<br>  “extends”: “airbnb”,<br>  “env”: {<br>    “browser”: true,<br>    “node”: true,<br>    “mocha”: true<br>  },<br>  “rules”: {<br>    “spaced-comment”: 0,<br>    “new-cap”: 0,<br>    “babel/generator-star-spacing”: [2, “after”],<br>    “babel/new-cap”: 2,<br>    “babel/object-curly-spacing”: [3, “always”],<br>    “babel/object-shorthand”: 2,<br>    “babel/arrow-parens”: [2, “as-needed”],<br>    “max-len”: [2, 80, 2, {<br>      &quot;ignoreComments&quot;: true,<br>      &quot;ignoreUrls&quot;: true,<br>    }],<br>  },<br>  “plugins”: [<br>    “babel”<br>  ]<br>}</pre><p>I want to extend the Airbnb config file, as their developers have come up with what I believe to be the most sane and least abrasive set of rules for modern JavaScript including ES6 functionality and React standards. If you’re interested, you should check out their Github <a href="https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb">repo</a>, because there isn’t much value in me spoon-feeding you those rules right now. Additionally, I add all of the Babel ESLint plugin settings, which add strict rules around new ES7+ functionality found in Babel.</p><p>You can use any of these plugins or not, I don’t very much care, and no one else will either… unless you write lists of variables, beginning each line with a comma, you people make me sick, bunch of animals. The important thing is that you enforce linting rules, and anyone that contributes to the project has to live by these rules. To protect software as it scales, we need to make sure that things break in a very bad and severe ways when the rules aren’t followed. When we discuss the build process at a later point, I’ll explain how to force ESlint to fail your build and refuse to compile until all linting, testing, and so on all pass successfully.</p><h4>Oh, and about static typing…</h4><p>Statically typing variables is kind of a new concept in the world of JavaScript. Microsoft originally made this widely popular with its superset of JavaScript, called TypeScript. The goal of static typing is to apply rules around your methods and variables that dictate what types of data are acceptable. Somewhat unrelated, but one nice side effect of this is that it starts to enable intelligent code hinting if you have the tooling to support it —<a href="https://code.visualstudio.com/"> Visual Studio Code</a> for TypeScript developers, or <a href="http://nuclide.io/">Nuclide</a> for Babel / Flow developers. If I’m going to be honest, I fall into the latter camp, because I love Babel and Flow.</p><p>As I have already bought into a static typing language, I’m going to describe how to work with those tools. These are what I recommend, but obviously, if you choose to go with TypeScript, then you’ll see similar benefits, and if you choose neither, then whatever, I just can’t even. To install Flow, just turn to Homebrew:</p><pre># Update homebrew, you should always do this before installing<br>brew update</pre><pre># Install flow<br>brew install flow</pre><pre># Upgrade flow periodically, and as always, update homebrew first<br>brew update<br>brew upgrade flow</pre><p>Like every other tool, flow starts with a <em>dotfile.</em> In the root of your project, type “flow init” to create an empty flowtype config file. Here’s a quick look at mine.</p><pre>[ignore]<br>.*/node_modules/invariant/.*<br>.*/node_modules/koa/.*<br>.*/node_modules/koa-static/.*<br>.*/node_modules/express/.*<br>.*/node_modules/fbjs/.*<br>.*/node_modules/babylon/.*<br>.*/node_modules/babel-.*<br>.*/node_modules/babel-core/.*</pre><pre>[include]<br>./app/<br>./config/</pre><pre>[libs]<br>./interfaces/</pre><pre>[options]<br>esproposal.class_instance_fields=ignore<br>esproposal.class_static_fields=ignore<br>esproposal.decorators=ignore<br>module.system=haste<br>munge_underscores=true<br>strip_root=true<br>suppress_type=$FlowIssue<br>suppress_type=$FlowFixMe<br>suppress_type=$FixMe<br>suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(&gt;=0\\.\\(1[0–6]\\|[0–9]\\).[0–9]\\)? *\\(site=[a-z,_]*www[a-z,_]*\\)?)\\)<br>suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(&gt;=0\\.\\(1[0–6]\\|[0–9]\\).[0–9]\\)? *\\(site=[a-z,_]*www[a-z,_]*\\)?)\\)? #[0–9]+<br>suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy</pre><pre>[version]<br>0.18.1</pre><p>What does all of that mean? There are a few important things to note:</p><ol><li>I’m explicitly including the folders that I won’t flow to scan through. Flow will look at files in these folders that open with the <strong><em>/* @flow */ </em></strong>comment block.</li><li>Flow is in its infancy, and there are certain things (like duplicate module definitions and code that contain new ES2015+ proposal features that it doesn’t understand) that cause it to more or less freak out.. I’m telling it to not bother looking at those packages.</li><li>I’m telling flow that I need exactly version 0.18.1.</li><li>The [options] block is particular to how I work. You’ll notice that I’m telling flow to ignore some esproposal features it doesn’t understand (this only works for <strong>some</strong> features), and I’m also declaring a comment regex pattern that will instruct flow to ignore the following lines. This was largely <a href="https://github.com/facebook/relay/blob/master/src/.flowconfig#L16">stolen from code at Facebook</a>.</li></ol><p>So what does that give us? We can now run <em>flow check</em> in the root of our project and it will walk through our code and ensure there’s nothing weird going on with data passing through. I’ll show you some examples of how the flow checker might fail:</p><pre>const age: number = &#39;Thirty&#39;; // Fails</pre><pre>function getStringLength(str: string): number {<br>  return str.length;<br>}</pre><pre>debug(getStringLength(true)); // Fails</pre><pre>type PluginConfig = {<br>  name: string;<br>  value: any;<br>  author: string;<br>  company?: string;<br>  private?: boolean;<br>  listeners?: {[key: string]: Function};<br>};</pre><pre>function Plugin(config: PluginConfig): void {<br>  const { name, ...rest } = config;<br>  this.name = name;<br>  debug(rest);<br>}</pre><pre>new Plugin({<br>  Name: &#39;My Plugin&#39;, // fails, missing required prop `name`,<br>  value: 2,<br>  author: &#39;Christian de Botton&#39;,<br>  company: &#39;Brooklyn United&#39;,<br>  private: 1, // fails, expecting `boolean`<br>  listeners: &#39;yes please&#39;, // Fails, needs obj of key/function pairs<br>});</pre><p>You strictly define what datatypes the values can be. It’s a pretty simple concept, and if any code changes in such a way that you could potentially pass the wrong value types on through, resulting in a situation where data won’t <em>flow </em>correctly (Get it? Puns are fun), you’re immediately notified. Ever see the cryptic error <em>‘Undefined is not a function’</em>? Probably all the time, well, this will prevent that from happening again. And, as a pretty cool bonus, if you use <a href="http://nuclide.io/">Nuclide</a> as an IDE, you get this for free:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TILGg13sOSzUWmt-kl5Z2w.gif" /><figcaption>Hover to see type hinting definitions. Image property of Facebook, <a href="http://nuclide.io/docs/flow/">http://nuclide.io/docs/flow/</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*Dyyt94jgbDjAaUs_fAwraQ.gif" /><figcaption>Cmd/Ctrl + Click to jump to code definitions. Image property of Facebook, <a href="http://nuclide.io/docs/flow/">http://nuclide.io/docs/flow/</a></figcaption></figure><h4>That’s all for today</h4><p>The pattern we’re working toward should be pretty apparent at this point. We want to make it as difficult as possible to break our code, and when that does happen, we want to make it very apparent to everyone, immediately. As applications scale they become more frail, where one small change can have a ripple effect and break many other things. These tools that enforce very strict rules on us as developers reduce this fragility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3763937cf927" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>