<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Refactoring on MoskitoHero</title><link>/tags/refactoring/</link><description>Recent content in Refactoring on MoskitoHero</description><generator>Hugo</generator><language>en-us</language><lastBuildDate>Sun, 21 Nov 2021 07:44:36 +0000</lastBuildDate><atom:link href="/tags/refactoring/index.xml" rel="self" type="application/rss+xml"/><item><title>Writing code for your future self</title><link>/post/2021-11-21-writing-code-for-your-future-self/</link><pubDate>Sun, 21 Nov 2021 07:44:36 +0000</pubDate><guid>/post/2021-11-21-writing-code-for-your-future-self/</guid><description>A set of guidelines to write clean, readable code that you — and your future self — will thank you for.</description><content:encoded><![CDATA[<div class="paragraph">
<p>We all write bad code. Let’s face it. Even if we do our best at writing the most efficient and well-designed code, we all happen to write this dirty method we don’t feel so proud of and dread having to debug next month, or next year.</p>
</div>
<div class="paragraph">
<p>I’m not going to talk about that code, because it’s so easy to spot and there is no need to write blog posts about it. What I’m interested in is code which looks fine when you have finished typing, but will bite you in the back someday. It ends up being hard to maintain, extend or even understand. After years of coding, I have come up with a set of warnings that alert me whenever I am heading for a dead end.</p>
</div>
<div class="sect1">
<h2 id="meaning"><a class="anchor" href="#meaning"></a>Meaning</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Code is language. Even more so when you use a programming language such as Ruby, which is designed to be very expressive. But to me, code begins to smell when it becomes unclear what it really does.</p>
</div>
<div class="sect2">
<h3 id="names"><a class="anchor" href="#names"></a>Names</h3>
<div class="paragraph">
<p>Naming is essential. One of the thing that changes the most in my creation process is probably the name of the classes, methods and variables I design.</p>
</div>
<div class="paragraph">
<p>Humans name things they understand. And the higher the knowledge of an element, the sharper the naming. Renaming my classes in the development process is usually a good sign that I am getting a better idea of what they do or what concept they stand for.</p>
</div>
</div>
<div class="sect2">
<h3 id="method-length"><a class="anchor" href="#method-length"></a>Method length</h3>
<div class="paragraph">
<p>One of the most frequent design patterns we are taught as aspiring OOP developers is to keep methods shorter than a few lines. One caveat, however, is that code ends up scattered all over the place, and you can sometimes lose touch with the lifecycle of your data. This is especially true for classes that are used to build a data structure.</p>
</div>
<div class="paragraph">
<p>For instance, take this class that builds a <code>data</code> hash to be sent to FCM:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="k">module</span> <span class="nn">MobilePush</span>
  <span class="k">class</span> <span class="nc">FcmNotification</span> <span class="o">&lt;</span> <span class="no">BaseNotification</span>

    <span class="k">def</span> <span class="nf">launch</span>
      <span class="c1"># Bootstrap stuff...</span>
      <span class="n">push_service</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">project</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>
    <span class="k">end</span>
    <span class="kp">private</span>
      <span class="c1"># Lots of methods...</span>
      <span class="k">def</span> <span class="nf">data</span>
       <span class="p">{</span>
          <span class="ss">notification: </span><span class="n">json_notification</span><span class="p">,</span>
          <span class="ss">recipient: </span><span class="n">recipient_name</span><span class="p">,</span>
          <span class="ss">room: </span><span class="n">room_name</span>
        <span class="p">}</span>
      <span class="k">end</span>
      <span class="c1"># Lots of other methods...</span>
      <span class="k">def</span> <span class="nf">json_notification</span>
        <span class="vi">@notification</span><span class="p">.</span><span class="nf">to_json</span>
      <span class="k">end</span>
      <span class="k">def</span> <span class="nf">recipient_name</span>
        <span class="vi">@recipient</span><span class="p">.</span><span class="nf">name</span>
      <span class="k">end</span>

      <span class="c1"># Maybe a few other methods...</span>
      <span class="k">def</span> <span class="nf">room_name</span>
        <span class="vi">@room</span><span class="p">.</span><span class="nf">name</span>
      <span class="k">end</span>
      <span class="c1"># The rest of the methods...</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><em>Note: This example is a little over-simplified for brevity. But you get the idea.</em></p>
</div>
<div class="paragraph">
<p>I wrote this thinking <em>&#34;Hey that’s smart! Everything is nicely sorted. It really looks like clean code&#34;</em>.</p>
</div>
<div class="paragraph">
<p>Then I took a few day’s break with my family. While I was away, one of my co-workers had to deal with my new code and add a new feature. But he found it unnecessarily abstracted, hard to maintain and extend. And he was right. So I refactored it to:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="k">module</span> <span class="nn">MobilePush</span>
  <span class="k">class</span> <span class="nc">FcmNotification</span> <span class="o">&lt;</span> <span class="no">BaseNotification</span>

    <span class="k">def</span> <span class="nf">launch</span>
      <span class="c1"># Bootstrap stuff...</span>
      <span class="n">push_service</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">project</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>
    <span class="k">end</span>
    <span class="kp">private</span>
      <span class="c1"># Lots of methods...</span>
      <span class="k">def</span> <span class="nf">data</span>
       <span class="p">{</span>
          <span class="ss">notification: </span><span class="vi">@notification</span><span class="p">.</span><span class="nf">to_json</span><span class="p">,</span>
          <span class="ss">recipient: </span><span class="vi">@recipient</span><span class="p">.</span><span class="nf">name</span><span class="p">,</span>
          <span class="ss">room: </span><span class="vi">@room</span><span class="p">.</span><span class="nf">name</span>
        <span class="p">}</span>
      <span class="k">end</span>
      <span class="c1"># The rest of the methods...</span>
  <span class="k">end</span>
<span class="k">end</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>So OK, I had to swap out <code>room_name</code> for <code>@room.name</code> in two or three places in the class, because it was also used elsewhere. But I also made my code a little less abstracted. Now, my co-worker knows exactly what data is made of, at a glance.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="stories"><a class="anchor" href="#stories"></a>Stories</h2>
<div class="sectionbody">
<div class="paragraph">
<p>One thing to remember when writing code, is that it is not just meant to be effective and concise. Code is meant to be read by others. Your co-workers, your team leader, and even more crucially, by the person who will be in charge of your once-new, now-legacy codebase.</p>
</div>
<div class="sect2">
<h3 id="one-liners"><a class="anchor" href="#one-liners"></a>One-liners</h3>
<div class="paragraph">
<p>I love one-liners. They are fun, straight to the point, and they showcase the technical skills and the wit of their creators. They are to programming what punchlines, or newspaper headlines are to writing. But who wants to read a whole book written in this way?</p>
</div>
<div class="paragraph">
<p>Even though I sometimes use one-liners in my code, I only do so when I feel confident my successor - or my future self - will be able to make sense out of it easily.</p>
</div>
</div>
<div class="sect2">
<h3 id="be-explicit"><a class="anchor" href="#be-explicit"></a>Be explicit</h3>
<div class="paragraph">
<p>I believe that most code should be explicit and guide the reader with landmarks that will help him or her follow along.</p>
</div>
<div class="paragraph">
<p>For instance, instead of this kind of expression:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="no">Device</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="s1">&#39;last_seen &gt; ?&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">.</span><span class="nf">hour</span><span class="p">.</span><span class="nf">ago</span><span class="p">).</span><span class="nf">where</span><span class="p">(</span><span class="ss">logging: </span><span class="kp">true</span><span class="p">).</span><span class="nf">where</span><span class="p">(</span><span class="ss">notifications: </span><span class="kp">true</span><span class="p">).</span><span class="nf">last</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">topic</span><span class="p">,</span> <span class="n">payload</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>I would rather either use class methods, or scopes in the model, to end up with:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="n">device</span> <span class="o">=</span> <span class="no">Device</span><span class="p">.</span><span class="nf">active_last</span><span class="p">(</span><span class="mi">1</span><span class="p">.</span><span class="nf">hour</span><span class="p">).</span><span class="nf">logging</span><span class="p">.</span><span class="nf">notifying</span><span class="p">.</span><span class="nf">last</span>
<span class="n">device</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">topic</span><span class="p">,</span> <span class="n">payload</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>I’m not stupid. I can understand the first example. But when parsing hundreds of lines of code to find a bug, I can look at this code and instantly tell what it does. No need to make sure I got the &lt; and the &gt; right. This was done once, on the day it was typed, and I can rely on it with confidence because each of these methods is tested and does what it says.</p>
</div>
</div>
<div class="sect2">
<h3 id="be-methodic"><a class="anchor" href="#be-methodic"></a>Be methodic</h3>
<div class="paragraph">
<p>I like to separate intents in what I do with my class. When you tell a story, you first introduce your character with a clear description. Then only you give him an active role in your story. That’s what the code example above is doing. I could also have easily  written:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="no">Device</span><span class="p">.</span><span class="nf">active_last</span><span class="p">(</span><span class="mi">1</span><span class="p">.</span><span class="nf">hour</span><span class="p">).</span><span class="nf">logging</span><span class="p">.</span><span class="nf">notifying</span><span class="p">.</span><span class="nf">last</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">topic</span><span class="p">,</span> <span class="n">payload</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>But that’s mixing intents. This line is both querying the model and triggering an action, so you start reading the line thinking: <em>&#34;Oh, he is defining the Device&#34;</em> and finish it thinking <em>&#34;Ah. No, he is sending this device a message&#34;</em>. Your reader should never ever be misguided, even in short, simple assertions like these.</p>
</div>
<div class="paragraph">
<p>I try to separate queries from actions. They are two types of tasks and require two distinct steps in my code.</p>
</div>
<div class="paragraph">
<p>Consider these three sentences:</p>
</div>
<div class="quoteblock">
<blockquote>
<div class="paragraph">
<p>The man in the bar that is old and dirty is talking about yesterday’s soccer results. - messy</p>
</div>
</blockquote>
</div>
<div class="quoteblock">
<blockquote>
<div class="paragraph">
<p>There is a man who is talking in the dirty old bar about yesterday’s soccer results. - clearer</p>
</div>
</blockquote>
</div>
<div class="quoteblock">
<blockquote>
<div class="paragraph">
<p>In the dirty old bar, there is a man. He is talking about yesterday’s soccer results. - crystal clear</p>
</div>
</blockquote>
</div>
<div class="paragraph">
<p>I want my code to be crystal-clear. I want my code reviewer, my successor or my future very-tired-on-a-friday-afternoon self to perfectly get what I am doing with my code.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="tests"><a class="anchor" href="#tests"></a>Tests</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Writing tests helps me identify dependencies. Integration tests often require quite a lot of bootstrapping: a logged in user, a few related entities…​ that’s fine.</p>
</div>
<div class="paragraph">
<p>But I sometimes write tests that rely too much on other models. If you can’t test your <code>Comment</code> model without a <code>Post</code> model, then something may be too tightly coupled in the code, and the relationship between those entities needs to be inquired.</p>
</div>
<div class="paragraph">
<p>Assertions also guide me towards code clarity. I have found that when I have trouble defining an expectation in my test, it usually means that this particular method is not doing something clear enough. It either needs to be split into smaller methods or completely re-thought about.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="a-word-aboutcomments"><a class="anchor" href="#a-word-aboutcomments"></a>A word about comments</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Another sign that code needs to be refactored is comments. Comments mostly indicate that what the program does is unclear. So when I see comments in code, the first thing I do is delete them and figure out what is happening without reading them. And whenever that comes out messy, it’s a good sign that they can all be replaced by a single <code>TODO: refactor</code>.</p>
</div>
<div class="paragraph">
<p>Comments are also often a sign of an external dependency. Typically, you will get this kind of thing:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="ruby"><span class="c1"># Handle temperature &gt; 21</span>
<span class="c1"># Deal with legacy customer IDs</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The first one might depend on the device you’re dealing with, and that dependency might be addressed by the hardware team.</p>
</div>
<div class="paragraph">
<p>The second one could be deleted by resorting to an inherited class, like <code>LegacyCustomer</code>, which could handle that kind of special user cases and keep the <code>Customer</code> class clean with a predictable and simple interface.</p>
</div>
<div class="paragraph">
<p>The only comments I keep are top comments above class declarations, Yard documentation, a few refactor TODOs and silly, fun meta about the code.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="conclusion"><a class="anchor" href="#conclusion"></a>Conclusion</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I sometimes look at messy code and wonder <em>&#34;who wrote this piece of crap?&#34;</em></p>
</div>
<div class="paragraph">
<p>Let’s see…​ Git blame…​</p>
</div>
<div class="paragraph">
<p><em>Me.</em></p>
</div>
<div class="paragraph">
<p>I don’t like this feeling. I want to feel proud of my code. I want other developers, including my future self, to make sense out of it easily and instantly, and thank me for making the effort of crafting code that makes sense, is easy to debug and maintain.</p>
</div>
<div class="paragraph">
<p>Following this set of guidelines will hopefully help me down that path.</p>
</div>
</div>
</div>
]]></content:encoded></item></channel></rss>