<?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 Jason Deng on Medium]]></title>
        <description><![CDATA[Stories by Jason Deng on Medium]]></description>
        <link>https://medium.com/@jason.deng?source=rss-bb10dc433ffc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mh68tEBMHxv3e3Gdqtp_Xw.jpeg</url>
            <title>Stories by Jason Deng on Medium</title>
            <link>https://medium.com/@jason.deng?source=rss-bb10dc433ffc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:07:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jason.deng/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[ASTs & Codemods: Effective and Automated Codebase Refactoring]]></title>
            <link>https://medium.com/bluecore-engineering/asts-codemods-effective-and-automated-codebase-refactoring-3ef93ff975a1?source=rss-bb10dc433ffc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ef93ff975a1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[bluecore]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jason Deng]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 12:04:01 GMT</pubDate>
            <atom:updated>2020-10-01T13:59:38.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6UtD4gUUrcWTbsFq71o3A.jpeg" /><figcaption>Credit: <a href="https://acodez.in/">https://acodez.in/</a></figcaption></figure><p>Code refactoring is an important part of the process of evolving any software application, but large scale refactoring can be very time-consuming. Commonly used techniques such as find and replace or fancy regex have their own limits and restrictions depending on the complexity of the refactor. That’s where “codemods” come in. <a href="https://github.com/facebook/codemod">Codemods</a> are scripts that modify code by manipulating the source code’s <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">abstract syntax tree (AST)</a>. This blog discusses what ASTs are, how they’re used in everyday tools such as compilers, formatters and linters. We’ll also detail the process of writing a codemod that manipulates an AST and how we used ASTs and codemods at Bluecore to automate the long, tedious, and error-prone process of code refactoring with confidence.</p><p><strong>What problem were we trying to solve?</strong></p><p>Over the last five years, hundreds of thousands of lines of JavaScript have been committed to our main repo. With the evolution of the frontend web development landscape, new features in the ECMAScript specification every year, it can be difficult to keep up a codebase to modern standards while also adding new features and fixing bugs. As we dug more and more into the codebase, we discovered more chunks of legacy code that needed attention.</p><p>It’s easy to adhere to new best practices with the team and ensure that the new code is consistent with our style guide or code standards. But at a certain point, legacy code can get out of control and be difficult to maintain. Fixing and cleaning up this old code manually is tedious and isn’t work that most engineers like to do. It became apparent to us that we needed to fix this soon in order to reduce bugs, speed up development, and accelerate the ramp-up of new engineers. Thankfully, we discovered Facebook’s <a href="https://github.com/facebook/jscodeshift">jscodeshift</a>, which uses ASTs and codemods to help solve this problem.</p><p><strong>What is an Abstract Syntax Tree (AST)?</strong></p><p>If you are writing code, chances are that you are probably leveraging ASTs in one or more ways. An AST or Abstract Syntax Tree is a <a href="https://en.wikipedia.org/wiki/Tree_(data_structure)">tree</a> representation of code. ASTs are a formation of tokens generated from statements and expressions in a programming language. The source code that engineers write is typically piped through a parser and transformed into an AST. A compiler or interpreter can then use the AST to generate the corresponding lower-level machine code and evaluate instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*IB6WBE2lapUmEtNz" /><figcaption>The typical flow of how an AST is created and used. — Diagram made with <a href="http://draw.io/">draw.io</a></figcaption></figure><p>When source code is converted to its AST representation, only the structure and content of the source code are kept; any other additional attributes such as punctuation and delimiters (braces, semicolons, parentheses, etc.) are thrown away. Information that’s preserved, which is needed for an AST, are:</p><ul><li>Variable types and location of each variable declaration</li><li>The order of executable statements in which they defined and represented</li><li>Left and right operands of operations</li><li>Identifiers and their assigned values</li></ul><p>So given these requirements, what does an AST look like?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*m-fBCxxlfUrN9uJe" /><figcaption>An abstract representation an AST — Diagram made with <a href="http://draw.io/">draw.io</a></figcaption></figure><p>The above tree is an abstract representation of what a JavaScript AST would look like.</p><ol><li>From the top level, we first start off with a variable declaration.</li><li>This variable declaration has a property node of vartype. (as opposed to let or const</li><li>This variable declaration also consists of an “identifier” and its corresponding assignment, in this case, a binary expression.</li><li>The binary expression is formed with a “left” and “right” literal and an operator.</li></ol><p>This naming of each “node” is defined in accordance with the specification of the parser, but the idea of the AST is consistent throughout all parsers/programming languages.</p><p>A more human consumable format for the tree is typically in JSON format.</p><figure><img alt="AST JSON Representation of var example = 5 * 9;" src="https://cdn-images-1.medium.com/max/379/1*ZRtNLgf6RaNIzJOeUyhkvg.png" /><figcaption>AST JSON Representation of var example = 5 * 9; — Image made with <a href="https://carbon.now.sh/">https://carbon.now.sh/</a></figcaption></figure><p>That’s a lot of JSON just for one line of code!</p><p><strong>How are abstract syntax trees used in everyday tools like formatters and linters?</strong></p><p>Now that the theory is covered, let’s examine how ASTs are used in our everyday tools. Since ASTs can be represented in JSON format, we can traverse it like any other normal JSON object. Having the ability to traverse an AST and visit nodes of the tree without actually executing it allows us to gain insights or perform operations on it. We can write code that parses, modifies, and outputs it back to a different tree which in turn will change the source code.</p><p><a href="https://eslint.org/">ESLint</a>, a commonly used JavaScript linter, statically analyzes code by converting it to an AST and identifying and reporting on patterns by simply traversing the JSON. If needed, ESLint can be configured to modify the JSON to fix or change the pattern.</p><p><a href="https://babeljs.io/">Babel</a>, a JavaScript compiler, performs code modifications on ASTs that will convert ECMAScript 2015 and onwards code into a backward-compatible version of JavaScript for older browsers or runtime environments. This can mean turning React JSX into function calls or stripping out TypeScript or Flow type annotations before source code is bundled and reaches the browser.</p><p><a href="https://prettier.io/">Prettier</a>, a popular JavaScript formatter restructures code lexically according to configurations without changing the content/meaning of the code. This is possible by converting the code into an AST which is formatting agnostic and then rewriting it based on certain rules.</p><p><strong>What is a codemod?</strong></p><p>Now that we understand how ASTs are used in the background of our development environments so frequently, how else can it be leveraged?</p><p><a href="https://github.com/facebook/codemod">Codemod</a> and <a href="https://github.com/facebook/jscodeshift">jscodeshift</a> are tools created by Facebook to assist in these large scale codebase refactors. Codemods are one-time scripts that leverage ASTs to allow developers to write code to transform code. jscodeshift is a toolkit for running codemods on large codebases and provides us with a unified API to easily find, modify, and replace the underlying AST nodes. Using these two together, we are able to do large scale refactors reliably and easily.</p><p><strong>How does one write a codemod that manipulates an abstract syntax tree?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*1Kr4rKlwXHqlpgJykL6rXQ.png" /><figcaption>Image made with <a href="https://carbon.now.sh/">https://carbon.now.sh/</a></figcaption></figure><p>Let&#39;s have a simple import.js file that imports a few modules. There’s a new requirement to sort all imports in every single file in the codebase.</p><p>If done manually, this can easily turn into a nightmare if the codebase is large.</p><p>Automating this by writing a codemod to modify the underlying AST will make it much simpler.</p><p>We should first initialize the setup code for the transform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*PqeYK_GEHangphI8LQ2zBA.png" /><figcaption>Image made with <a href="https://carbon.now.sh/">https://carbon.now.sh/</a></figcaption></figure><p>This code imports the file, converts it to an AST, and then converts it back to source code.</p><p>We can add this script command to a package.json as well as the jscodeshift dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*qOMNpHiySLlit838IGS80w.png" /><figcaption>package.json — Image made with <a href="https://carbon.now.sh/">https://carbon.now.sh/</a></figcaption></figure><p>Before doing anything, we should look at our AST to see what we are dealing with, we can do this by logging the parsed source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*AoxYMzTyfVVGoyP7a-_6pQ.png" /><figcaption>Image made with <a href="https://carbon.now.sh/">https://carbon.now.sh/</a></figcaption></figure><p>By examining the <a href="https://gist.github.com/jasondeng/e1638eae697f868f1018c5e4d272e53a">generated AST</a>, we can see that there is a body node that contains an array for 4 elements; each of which areObjects of type ImportDeclaration. Since this is a regular JavaScript object now, all we would need to do is sort this array by the import name.</p><p>jscodeshift provides us with an API to help us to do AST traversals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*xzXBp5jYrsAz6TUiJZGSeA.png" /><figcaption>Find all imports in a file — Image made with <a href="https://carbon.now.sh/">https://carbon.now.sh/</a></figcaption></figure><p>Now that we have all the import declarations we can sort them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*hRnaF3yeEdSC7niKGt_G7w.png" /><figcaption>Sort import declarations — Image made with <a href="https://carbon.now.sh/">https://carbon.now.sh/</a></figcaption></figure><p>After sorting, remove the old declarations so that they can be replaced with the new ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*XYNn9ouHmvWVQhJrH1qr4A.png" /><figcaption>Replace old imports with new ones — Image made with <a href="https://carbon.now.sh/">https://carbon.now.sh/</a></figcaption></figure><p>And that’s it! We’ve now written a simple codemod that will sort imports in any files. We can run the npm script to see our results!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUJQsMRs8idF8-akrS0-TA.gif" /><figcaption>Gif made with <a href="https://asciinema.org/">https://asciinema.org/</a></figcaption></figure><p>Please note, this is by no means a production-ready codemod. This codemod only sorts default imports and doesn’t handle named imports or imports that have both named or default imports but we can see how transforming code into a tree structure such as an AST can be very powerful and allows us to write code to change code very effectively.</p><p><strong>How did we leverage ASTs at Bluecore?</strong></p><p>We were able to use both open source and internally developed codemods to help us clean up our codebase.</p><p>Some of which included</p><ul><li>We created our own funnel description language and parse that to an AST which we wrote scripts to auto-generate SQL — <a href="https://medium.com/bluecore-engineering/the-funnel-a-fundamental-abstraction-in-designing-autonomous-commerce-marketing-systems-f45bef4b533f">Blog Post</a></li><li><a href="https://github.com/Hacker0x01/coffee-to-es2015-codemod">coffee-to-es2015-codemod</a>:a codemod that helped finish our conversion from CoffeeScript to ES6</li><li><a href="https://github.com/billyvg/codemod-proptypes-to-flow">codemod-proptypes-to-flow</a>:a codemod that converts runtime prototypes into statically typed Flow types</li><li><a href="https://github.com/Khan/flow-to-ts">flow-to-ts</a>: a codemod that converts a codebase from Flow to TypeScript</li><li><a href="https://github.com/reduxjs/reselect">reselect</a> (internal) — an internal codemod that automates TypeScript typings for reselect.</li><li><a href="https://github.com/redux-utilities/redux-actions">redux-actions</a> to <a href="https://github.com/piotrwitek/typesafe-actions">typesafe-actions</a> (internal): an internal codemod that migrates all uses of redux-actions to the typesafe-actions API.</li></ul><p>These are just a few of the refactors that were made possible with codemods. Looking for codemods and spending a little bit of time upfront to develop new ones <strong>saved our team hundreds of hours of valuable engineering time</strong> that we can spend writing new features or fixing bugs.</p><p><strong>Some learnings and tips to conclude</strong></p><ul><li>Before writing your own codemod, make sure that it hasn’t been created. <a href="https://github.com/reactjs/react-codemod">react-codemod</a> and <a href="https://github.com/cpojer/js-codemod">js-codemod</a> are both fantastic resources for writing your own codemod. Better yet, <strong>open-source your codemod</strong> if you can’t find it online!</li><li><strong>Use the </strong><a href="https://astexplorer.net/"><strong>AST Explorer</strong></a>. This is an amazing open-source tool that helps speed up development for codemods. It comes built-in with different parsers for different programming languages and a paste and drop editor that shows the AST and before/after code in one simple view. Writing codemods would be almost impossible without some way of visualizing code as an AST.</li><li>Refer to <a href="https://github.com/benjamn/ast-types">ast-types</a> to see what types of nodes are used to create nodes. It serves as good documentation to make sure that the arguments that you are passing in are of the correct node type.</li><li>When first writing a codemod, have both the pre-transformed and transformed code and their respective ASTs opened at the same time, this way it is easier to compare the ASTs between the two to see what modifications are necessary, especially if the code is complex and long.</li><li><strong>Do dry runs</strong>: due to the experimental nature of a codemod, it is important to get a quick feedback loop for tests, jscodeshift comes with a dry run feature that will print the transformed code into the console, allowing you to iterate more quickly.</li><li><strong>Manual Intervention</strong>: especially when running codemods on production code, it’s imperative that you and a few other people on the team scan all files that were modified. Because we are writing code to change code, it’s easy to forget an edge case, which can cause bugs and undesirable effects.</li></ul><p>In conclusion, codebase wide changes can be made simpler and less scary to approach. Using open-source codemods and a few ones we wrote internally, we were able to vastly improve the state of our codebase with minimal effort and low risk. Being able to write code that changes code is an amazing technique for any team to have in their toolkit!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ef93ff975a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bluecore-engineering/asts-codemods-effective-and-automated-codebase-refactoring-3ef93ff975a1">ASTs &amp; Codemods: Effective and Automated Codebase Refactoring</a> was originally published in <a href="https://medium.com/bluecore-engineering">Bluecore Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring a Legacy Flow Codebase]]></title>
            <link>https://medium.com/bluecore-engineering/refactoring-a-legacy-flow-codebase-190e623eac1d?source=rss-bb10dc433ffc------2</link>
            <guid isPermaLink="false">https://medium.com/p/190e623eac1d</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[bluecore]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Jason Deng]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 20:22:50 GMT</pubDate>
            <atom:updated>2020-06-11T21:00:27.060Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/facebook/flow">Flow</a> and <a href="https://www.typescriptlang.org/">TypeScript</a> are both type systems that help developers ship scalable JavaScript applications, make changes with confidence, and prevent bugs. At Bluecore, it took us a while to distill best practices with Flow, some of which include how to properly propagate or “flow” our types down through the codebase and auto-generating typed bindings from APIs. This blog post shares best practices and techniques that we’ve learned to optimize our usage of Flow.</p><p><em>This post assumes a basic understanding of Flow, </em><a href="https://flow.org/en/docs/getting-started/"><em>this getting started guide</em></a><em> should provide enough context for this blog.</em></p><h3>A Brief History</h3><p>In 2015, Bluecore’s user interface (UI) started out using basic web forms in Jinja, a Python-based templating language. At first, the UI was mostly used by our Forward Deployed Engineers, but as we added more features to the product and increased our client base, more and more of our customers started to self-serve. Eventually, we split out the UI from the backend into its own application. During this time, React was the new hot thing and CoffeeScript was a popular language that had many features JavaScript didn’t have. Bluecore’s first customer-facing platform was built using React, CoffeeScript, <a href="https://github.com/reflux/refluxjs">Reflux</a>, and <a href="https://reactjs.org/docs/typechecking-with-proptypes.html">PropTypes</a> (React’s default type checking library).</p><figure><img alt="Bluecores UI tech stack over the years." src="https://cdn-images-1.medium.com/max/768/0*JXdKvYu_7AM1vzxl" /><figcaption>Bluecores UI tech stack over time.</figcaption></figure><p>Fast forward a year — Bluecore doubled its engineering team size, resulting in a larger and more complex codebase. Our developers needed a better way to maintain the codebase, as PropTypes was outclassed by popular compile-time type checking alternatives like Flow and TypeScript. At the time, the frontend team decided to adopt Flow because it integrated well with React, whereas TypeScript was less mature and had much less support than it does now. However, due to a lack of proper usage and standardization at Bluecore, our Flow codebase became even harder to maintain and more difficult for new engineers to approach.</p><p>Some common problems we encountered:</p><ol><li>No API payload contracts, leading to a gap in frontend and backend expectations.</li><li>No typed libraries and <a href="https://reactjs.org/docs/higher-order-components.html">HOCs</a>, causing types to be dropped midway through data flows.</li><li>Excessive usage of weak types (<a href="https://flow.org/en/docs/types/any/">any</a>, <a href="https://flow.org/en/docs/types/objects/#toc-object-type">Object</a>, <a href="https://flow.org/en/docs/types/functions/#toc-function-type">Function</a>); which essentially opts-out of the type checker in many places in the code.</li></ol><h3>Zero Libdefs</h3><p>When I joined Bluecore in late 2018, the frontend codebase had mostly migrated from PropTypes to Flow with a little bit of CoffeeScript remaining. One of the first things I noticed about our codebase was the lack of library definitions. <a href="https://flow.org/en/docs/libdefs/">Library Definitions (libdefs)</a> are special files that tell Flow the type signature of third-party libraries.</p><h4>Why does it matter?</h4><p>Without any libdefs, Flow will assume that all library imports default to an <a href="https://flow.org/en/docs/types/any/">any</a> type. Using the any type causes Flow to opt-out of type checking. A library without its libdef will result in dropped types between where the type is defined and where it’s used. This means if a breaking change was made to the type and there was no libdef, <strong>Flow would not report it as an error</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b521c42b19183535a009594485f0b92b/href">https://medium.com/media/b521c42b19183535a009594485f0b92b/href</a></iframe><p>This is especially important in a Redux application, where the data flow between the different areas of the application is piped through the use of many libraries. In our React + Redux app, we make use of common libraries such as <a href="https://react-redux.js.org/">react-redux,</a> <a href="https://redux-actions.js.org/">redux-actions</a>, <a href="https://github.com/reduxjs/reselect">reselect</a>, and <a href="https://github.com/reduxjs/redux-thunk">redux-thunk</a>. These libraries are all part of the Redux data flow chain and need to be typed in order to achieve full end-to-end type coverage. If any libdef is missed, we lose proper type checking within the data flow, weakening the initial purpose of using Flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*DljUj5mK5MRM0RWF" /><figcaption>A typical React + Redux data flow and the libraries we used, the red represents external libraries of which we need libdefs.</figcaption></figure><h4>How did we solve this?</h4><p>The fix <em>seemed</em> simple and easy, we just needed to add the missing libdefs. A npm package, <a href="https://github.com/flow-typed/flow-typed">flow-typed</a>, allows us to run a command that will add existing public libdefs for libraries in our repository. It should only take the team a few days to debug errors that appear from running the command, and all of our problems will (or should) be solved, right? Unfortunately, it didn’t work this way. While this approach will work for smaller packages, it isn’t so straightforward for libraries with more complex typings.</p><p>We use 50+ libraries thousands of times across thousands of files. After running flow-typed on our codebase, it surfaced thousands of errors. Most of the errors were false positives but still required individual attention to address. It was easy to fix the libraries outputting a small number of errors, but what about the ones that caused hundreds, if not thousands, of errors? How can we fix all these errors in a reliable, measurable, and safe way?</p><p>We had several options to tackle this:</p><ol><li><strong>Code freeze</strong>: We debated having a code freeze for a few sprints and everyone would grind out fixing Flow errors during this time. However, this would mean that all bug fixes, feature work, and releases would have to be put on hold. This is difficult because of the fast-paced nature of startups since we need to constantly ship features and products to keep our customers happy. As engineers, technical maintenance to keep a codebase healthy is important, but as employees of a business, we can’t risk losing customer confidence. Therefore, a code freeze was not a viable option.</li><li><strong>Maintaining a separate branch</strong>: The next idea was to have a separate dev branch where we can start incrementally fixing the Flow errors and rebasing with the master branch to keep it up-to-date. We quickly ruled this out as a solution though, as we didn’t like the idea of having to maintain a separate branch that would be so different from the master branch.</li><li><strong>Incrementally fixing errors through untyped versions of the libraries: </strong>We defined an “untyped” version of a library as a renamed file that exports all the functions of the actual library and reference that in our code. Since the file name of the “untyped” file is no longer the same as the libdef, Flow will not associate the libdef with the new file. The functionality of the library still works and doesn’t break anything. This is the approach we decided to use.</li></ol><p>We followed several simple steps:</p><ol><li>Create an untyped version of a library.<br> export * from &#39;react-redux&#39;; // untyped-react-redux.js</li><li>Replace all usages of the library with the untyped one and merge the code.</li><li>Work on swapping out the untyped versions with the typed versions, and fix any errors that appear as a result.</li><li>Move on to the next library and repeat.</li><li>Profit 💲💲💲.</li></ol><p>While this approach is slow, it guarantees us the flexibility and reliability that we need. We can create tickets based on code ownership, bundle priority, or any other measure. We can also work on features and bugs on the side while ensuring that any new code will use typed libraries and not increase technical debt. As a bonus, we can track our progress over-time since all we needed to count was the number of files that had untyped usages in our codebase.<br>Using this approach, we were able to type and fix <strong>~20k lines of code</strong> over six months. In the end, we removed the untyped library files we created and harnessed the zen of having our libraries be fully typed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6Eeyo697h1E7Z40s" /><figcaption>Progress of our untyped usages over the end of last year.</figcaption></figure><h3>Staying in sync between the client and server</h3><p>Ensuring that the data flow within the frontend application is typed is only part of the solution. Having consistent and well-defined types that the UI receives from the server was just as important. Establishing a clearly defined API contract between the client and the server is crucial in understanding the business requirements. We started getting bugs when a breaking change was introduced into an API, but no corresponding frontend changes were made to accommodate the change. We wanted a way for the UI to stay in sync with what API data our servers expected and returned.</p><p>API versioning is a common technique for handling these issues. Another technique is to have the server generate schemas for the frontend to use. This is incredibly useful because it ensures that all parties will know when a breaking change in the API happens. <a href="https://graphql.org/">GraphQL</a> + <a href="https://www.apollographql.com/">Apollo</a> + <a href="https://www.typescriptlang.org/">TypeScript</a> is a popular example of this paradigm.</p><p>Following this pattern, we decided to implement our own version of schema generation leveraging Marshmallow Schemas + APISpec + Flow.</p><ol><li>We started requiring all new APIs to be created with <a href="https://marshmallow.readthedocs.io/en/stable/index.html">Marshmallow Schemas</a>. This had the added benefit of adding serialization and validation to our APIs.</li><li>Afterwards, we converted these schemas to Swagger YAML using <a href="https://github.com/marshmallow-code/apispec">APISpec</a>.</li><li>In the same workflow, we started a node process that would convert the generated Swagger YAML to Flow Types using <a href="https://github.com/yayoc/swagger-to-flowtype">swagger-to-flowtype</a> into a directory that the frontend would use.</li><li>After this workflow finished, we would run Flow on our frontend codebase to ensure that no errors would surface an API change. If an error occurred, we discussed whether this change was intentional or not.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/0*QLGnc0jXCjID5arQ" /><figcaption>Our process for auto-generating Flow typings from APIs.</figcaption></figure><p><strong>We require these workflows to run on all PRs which gives us the needed confidence for keeping our UI in sync with the server. </strong>Using this workflow, we can guarantee that if any breaking API changes would be caught before code got shipped to production.</p><h3>Object types are “inexact” by default</h3><p>Let’s say we declare an object type such as this one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62e2df05bed4d646bfc77ed21bbd34aa/href">https://medium.com/media/62e2df05bed4d646bfc77ed21bbd34aa/href</a></iframe><p>It is possible to create instances of this type such as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f949e12dfe3f91a1f911770bfba2c95/href">https://medium.com/media/8f949e12dfe3f91a1f911770bfba2c95/href</a></iframe><p>This is valid and Flow will not raise any errors. However, It will if we make Employee exact.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/521bbe6c59f3702f70ba9b4d2d52ffca/href">https://medium.com/media/521bbe6c59f3702f70ba9b4d2d52ffca/href</a></iframe><p>Flow types should be annotated as exactly as possible. If something is inexact, it must have been done for a special reason. Objects being inexact by default is probably one of the biggest flaws of Flow. To combat this, we decided that require-exact-type is one of the few ESLint rules for Flow that should be enabled by default. <strong>Furthermore, we are slowly converting inexact types to be exact to ensure type reliability and safety in the future.</strong></p><h3>Use linting to your advantage</h3><p>In addition to basic syntax checking, linting can also be used to help refactor a codebase and keep it up-to-date. We enabled several rules with Flow using ESLint strategically to help us maintain our codebase.</p><p>Some rules that we thought were helpful to enable:</p><ol><li><a href="https://github.com/gajus/eslint-plugin-flowtype/blob/master/.README/rules/no-weak-types.md">eslint-plugin-flowtype/no-weak-types</a>: Enforcing this rule will forbid any uses of any, Object, and Function. It is much better to always be explicit with typing than not. The occasional time where it is not feasible to type something, we can opt-out of the rule with eslint-disable-next-line flowtype/no-weak-types<em>.</em></li><li><a href="https://github.com/gajus/eslint-plugin-flowtype/blob/master/.README/rules/require-return-type.md">eslint-plugin-flowtype/require-return-type</a>: We had a discussion internally whether we wanted to enable this rule globally. Although it can be useful for new engineers to see the return types, it can be verbose and repetitive since Flow is adept at inferring return types already. We decided to enable this rule for a subset of files only. We have a naming convention that files that interact with an API are inside an api directory. Using this convention, we can have the ESLint rule enabled only for these directories.</li></ol><p>Using ESLint’s override functionality, we required certain rules to be enabled for new files and certain rules to be disabled for older files. It entirely depends on the rule and circumstances that are set in place. This technique was a major help when refactoring old code and ensuring that new code wouldn’t cause more issues.</p><p><strong>Want to enable a rule but can’t fix old files immediately? </strong>Add a regex to the overrides array that catches new directories or files.</p><p><strong>Want to enable a rule for only files that match a certain naming convention? </strong>Add a regex to the overrides array that catches the naming convention.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c7d85df863bfda940f64c78c5fa8319/href">https://medium.com/media/8c7d85df863bfda940f64c78c5fa8319/href</a></iframe><h3>Conclusion</h3><p>Being able to fully type a JavaScript application is a difficult but fulfilling experience. This post outlined just a few of the many ways to break out of a legacy codebase. Using <strong>simple workarounds</strong>,<strong> linting</strong>,<strong> and enforcing processes through CI/CD reduces a codebase’s technical debt</strong>; making it a better experience for engineers and users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=190e623eac1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bluecore-engineering/refactoring-a-legacy-flow-codebase-190e623eac1d">Refactoring a Legacy Flow Codebase</a> was originally published in <a href="https://medium.com/bluecore-engineering">Bluecore Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>