<?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 Vinh Bachsy on Medium]]></title>
        <description><![CDATA[Stories by Vinh Bachsy on Medium]]></description>
        <link>https://medium.com/@vinhbachsy?source=rss-9cfa9c7afb4a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9JwN6kWlT9KrGL7giQR1gQ.png</url>
            <title>Stories by Vinh Bachsy on Medium</title>
            <link>https://medium.com/@vinhbachsy?source=rss-9cfa9c7afb4a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:09:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vinhbachsy/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[Refactor legacy code 101]]></title>
            <link>https://medium.com/devblogcamp/refactor-legacy-code-101-b582d3a361ff?source=rss-9cfa9c7afb4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b582d3a361ff</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vinh Bachsy]]></dc:creator>
            <pubDate>Sun, 21 May 2017 16:12:53 GMT</pubDate>
            <atom:updated>2017-05-27T16:59:35.988Z</atom:updated>
            <content:encoded><![CDATA[<p>Working with legacy code is not the most fascinating thing to do for developers. It’s often viewed as a time-consuming, energy-drained and unmotivated task. The reason is that very often legacy code is hard to understand, hard to debug, but quite easy to break even with a seemed-to-be trivial change.</p><p>However, the fact that our code is aging very fast, what we write today would easily become something legacy within a few months, working with legacy code is something can not be avoided for developers. Furthermore, legacy code accumulated a lot of decisions and practices from many people over the years, no better place we can analyze the pros and cons of a technical decision for a specific use case than in legacy code, which ultimately helps us making better decisions in the future.</p><blockquote>“Those who cannot learn from history are doomed to repeat it”</blockquote><blockquote>- George Santayana</blockquote><p>Understanding the inevitable and importance of legacy code, this article aims to provide some practices that I found very useful from my previous experience. I believe they would help working with legacy code base become more efficient, more comfortable and less scary.</p><p>In short, working with legacy code could be broken into 3 steps:</p><ul><li>Understanding</li><li>Testing</li><li>Refactoring</li></ul><p>Let’s start checking out my approach for each step.</p><h3><strong>Understanding the legacy code by refactoring it</strong></h3><p>The first fundamental step when working with legacy code is to understand what it does. We might think about reading the requirements, checking the API docs or consulting people who worked with them before. But more often than not, we are rarely able to do those things, mostly because:</p><ul><li>The people who wrote the original code are no longer there or don’t remember anything about that code.</li><li>The documentation doesn’t exist or is completely outdated.</li><li>Automation test suites don’t exist or no one has touched them for the last 5 years.</li></ul><p>In those cases, our last resort has to be reading the code line by line to understand the logic. The problem is that following a big bunch of code line by line is very hard, and we might encounter a lot of methods with few-hundred lines of code with all kinds of nested and obscure naming along the way.</p><p>So how we can tackle that? One approach I found very useful is integrating a bit refactoring along with reading the code. I will show you one approach to do that right below.</p><p>First, we branch out the trunk as the starting point, then start refactoring as we follow the code by using simple techniques such as extracting method and meaningful naming. The ultimate goal is to keep track of our understanding of the code as we go through them. Some people might suggest to use comments for this, but in general I’m against this advice, first comments tend make the code messier instead of cleaner, and secondly jumping your eyes around comments put between messy code in a very long method is not efficient. Considering reading this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ac7a334775c95b3a90cd934078feea6/href">https://medium.com/media/1ac7a334775c95b3a90cd934078feea6/href</a></iframe><p>Compare to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26201cd233b46ec671b79d0c3cb6a1fb/href">https://medium.com/media/26201cd233b46ec671b79d0c3cb6a1fb/href</a></iframe><p>Comments should be only reserved for cases where logic is so complex that makes them impossible to be explained by the code itself.</p><p>During the process, we might observed weird behaviors of code, it’s usually a good chance to identify dead code and bugs. Trying to reproduce the output of those behaviors, then checking them with the client of the module will give us the reasons behind those behaviors. If they are really bugs or dead code, we could logged them as issues and address them in the later steps. If they’re not, the behaviors of those should be explained as documentation, and using comments might be acceptable in this case.</p><h3>Writing tests as a safety net</h3><p>By following the approach described above, we would gain substantial understanding while also achieving a cleaner and easier to follow version of the code. Based on our new understanding, we can temporarily put this branch on hold and go back to the trunk to start writing test for the legacy code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-ntoi8_ZjIq3BybS0iP_cw.jpeg" /><figcaption>Source: <a href="http://www.commitstrip.com/en/2013/10/11/mieux-et-moins-cher-que-les-tests-unitaires/">http://www.commitstrip.com/en/2013/10/11/mieux-et-moins-cher-que-les-tests-unitaires/</a></figcaption></figure><p>One of the biggest obstacles to write test for legacy code is the tight coupling between components in the code. Without significant refactoring, it’s almost impossible to just pick up some component and start writing isolated unit tests for it. This is why a preferred approach for testing legacy code is to start with functional or integration test first.</p><p>A good place to start is verifying the boundary of the module and writing contract tests for it. It would ensure that we won’t introduce any breaking changes for the current client of the module. Let’s say an API, for example, we could write some tests to make sure it returns the correct response structure for both happy and failure paths. If you’re using json, then JSONSchema is a good candidate to do sort of things.</p><p>The next steps is organizing our understanding of the code into specific flows and writing tests to verify each flow one by one. Noted that a bit pragmatic should be applied when working on this, we should focus more for the flows that bring users the most value or could significantly decrease the experience if it’s gone wrong and try to cover as much as we can for them.</p><h3>Connecting the dots</h3><p>Now with the functional test suite and draft version of the refactored code in place, we could merge them and run the test on our refactored code to verify it’s still working correctly.</p><p>Then, we could address the issues we logged from the first step. We start by writing test cases to verify they’re failing in the expected way then making changes in our refactored code to fix them.</p><p>What to do after this point will depend on situations, we might perform further refactor to make the code more DRY, or we might just move on to another module as we need to understand other parts in the system before recognizing the patterns for refactoring, or maybe we can start extracting the module into a self-contained service because it looks isolated enough and there is significant benefit by doing this (in term of testing, maintainability, performance, and so on). Whatever actions we chose, however, the important point is that now we have a good safety net and a great deal of confidence to make the call.</p><h3>Important tips</h3><ul><li>Pair programming is invaluable while refactoring legacy code, as it’s always better to have more than 1 pair of eyes look for weird behaviors in the messy code. Also, your assumption for the behavior of the code can be double checked and verified right away with your pair.</li><li>Ensuring the test failed for a right reason before committing it. While writing test for a specific behavior, we could try to comment out or make a small change to the code which we think it will change the behavior. After that, run the test and expect it failed, then undo the change and see it passed. Even outside of TDD context, I often found that the Red — Green — Refactor cycle give me a good insurance that the test I wrote is valid instead of a cosmetic one.</li><li>Making good test report is also important, i.e. avoiding showing too generic or nonsense message when the test failed such as Expect [object Object] is equal to [object Object]. Showing more details about the reason of the failing test is super important when we need to debug the failing test while refactoring. For example, a better report for the above test case would be:</li></ul><pre>Expect Object { foo: 2, … } to be equal to Object { bar: 3, … }<br>Diff:<br>  ---<br>  foo: 2<br>  ---<br>  bar: 3</pre><ul><li>Defining a scope of code to refactor is also important, avoiding refactoring module that is the dependency of many other modules (e.g. that five-thousand line of User model) from the beginning, as it has a lot of moving parts and unexpected things might happen even though we’re super careful. Instead, we could start with some module that is the downstream of this, so we can gain the idea how the interaction happens and what requirements of the upstream module are. It also gives us a chance to build a comprehensive contract for the upstream module.</li></ul><h3>Wrap up</h3><p>This is the basic strategy to start working with the legacy code, the aim is to regain the knowledge of the code as well as to have a good test coverage as a safety net and living documentation.</p><p>To further understanding the practice of working with legacy code, I’d recommend those 2 following books:</p><ul><li><a href="https://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052">Working Effectively with Legacy Code</a>, <em>by</em> <strong>Micheal Feathers</strong></li><li><a href="https://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672">Refactoring: Improving the Design of Existing Code</a>, <em>by</em> <strong>Martin Fowler</strong></li></ul><p>Hopefully, they will help you feel confident and comfortable whenever someone ask you to help refactoring their legacy code base.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b582d3a361ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devblogcamp/refactor-legacy-code-101-b582d3a361ff">Refactor legacy code 101</a> was originally published in <a href="https://medium.com/devblogcamp">DevBlogCamp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>