<?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>Code Quality on MoskitoHero</title><link>/tags/code-quality/</link><description>Recent content in Code Quality on MoskitoHero</description><generator>Hugo</generator><language>en-us</language><lastBuildDate>Tue, 17 May 2022 07:44:36 +0000</lastBuildDate><atom:link href="/tags/code-quality/index.xml" rel="self" type="application/rss+xml"/><item><title>Love your error messages as thyself</title><link>/post/2022-05-17-learn-your-error-messages-as-thyself/</link><pubDate>Tue, 17 May 2022 07:44:36 +0000</pubDate><guid>/post/2022-05-17-learn-your-error-messages-as-thyself/</guid><description>Stop ignoring error messages and start reading them — it will make you a better developer and help you understand your language from the inside out.</description><content:encoded><![CDATA[<div class="paragraph">
<p>Learn to hate, then love error messages.</p>
</div>
<div class="sect1">
<h2 id="stack-overflowoverflow"><a class="anchor" href="#stack-overflowoverflow"></a>Stack Overflow overflow</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I have lost so much time on Stack Overflow.</p>
</div>
<div class="paragraph">
<p>I mean Stack Overflow is great, and software development knowledge would not be so advanced and so widespread without its great influence. What I mean is that I have often found myself repeating the endless pattern of <em>&#39;Hey, I have an error…​ Wow, so many words…​ Let’s google this. Stack Overflow has it! Let’s see what they say&#39;</em></p>
</div>
<div class="paragraph">
<p>I am not talking about the infamous Stack Overflow copy-paste syndrome, nor am I dismissing the great answers produced by the great developers out ther, but rather about the missing step in the example above: making sense of the error message myself before actually looking for a ready-made answer.</p>
</div>
<div class="paragraph">
<p>Our brain is so quick at taking shortcuts that it often makes us lazy and skip the seemingly unneeded steps our thinking needs to fully develop. Take the example of walking. Although I don’t exactly remember taking my first step in this world, I can imagine it was a movement that required so much concentration - not to say bravery - and coordination that it must have felt quite awkward at the beginning. Today, I don’t even think about it. My brain just orchestrates everything, allowing me to go for a walk and actually think about something else.</p>
</div>
<div class="paragraph">
<p>Think about the first day you typed your first computer program. Think about the way you were thinking at the time. Maybe you are currently learning computer science and many mechanisms experienced developers don’t even think about are steps you consciously take, one by one, in order to reach code quality - or even to write code that actually works.</p>
</div>
<div class="paragraph">
<p>And while learning, we all encountered bugs. The language we were coding in was talking to us with complicated words, and concepts we sometimes did not even know about. We all googled for solutions. And Stack Overflow is so well conceived and maintained that we most certainly found the answer there. And it happened again. Error messages were so hard to understand, so cryptic, sometimes. So we just kept copy-pasting the error messages, and it just kept throwing correct answers at you, which, with a little adaptation, just worked.</p>
</div>
<div class="paragraph">
<p><em>And then, your brain skipped the error-message-reading step.</em></p>
</div>
<div class="paragraph">
<p>But we don’t want to just be very, very, very talented googlers, do we?</p>
</div>
</div>
</div>
<h1 id="rtfem" class="sect0"><a class="anchor" href="#rtfem"></a>RTFEM!</h1>
<div class="paragraph">
<p>Read the f***ing error messages!</p>
</div>
<div class="paragraph">
<p>So I encourage all of you learners to actually take a long look at the error messages that are thrown right in your face just as you were expecting a successful compilation. Take the time to read them. Take the time to look at those weird symbols that show up here and there. And you know what? You may not get to the point quicker at first, but you will gain a deeper knowledge of how your language is actually built, how it works internally. You might look at your fellow programmers increase their skills faster on the surface, but your understanding of error messages will eventually turn you into a Code Jedi Master.</p>
</div>
<div class="paragraph">
<p>What made me really stop overlooking error messages was reading <em>Ruby Under A Microscope</em> by Pat Shaughnessy, a most excellent book about the way Ruby is actually written in C, the way the language parser works and the way it turns the words you write into machine-understandable concepts.</p>
</div>
<div class="paragraph">
<p>Somewhere in the first part of the book that introduces how the parser works, the author talks about language tokenisation, which is - very basically - how the parser takes words and understand how to match them with a feature. And here they were, in a code example, my long-seen-yet-so-little-known error message friends, namely <code>tSTRING</code>, <code>tCONSTANT</code> and <code>tINTEGER</code>.</p>
</div>
<div class="paragraph">
<p>If only I had known what these correspond to before, <a href="https://makandracards.com/makandra/15611-how-to-fix-unexpected-token-error-for-json-parse">error messages such as these</a> would never have had me google for an answer.</p>
</div>
<div class="paragraph">
<p>But how could I know? When you google for ruby tString, you get all sorts of results, mostly skipping the preceding t. In order to get to the real stuff, I should have taken the time to actually read the error messages and wonder:</p>
</div>
<div class="paragraph">
<p>What is the language trying to tell me?</p>
</div>
<div class="paragraph">
<p>And if that sounds awkward, just remember that your programming language is actually a computer program written by other humans, and ask yourself:</p>
</div>
<div class="paragraph">
<p>What is the author of the language telling me to look at?</p>
</div>
<div class="paragraph">
<p>Chances are he is trying to get you to look at features of the language that may not be plain to see, but a little hidden from sight. And if he is trying to have you look at these, you might just as well do it. And learn.</p>
</div>
<div class="sect1">
<h2 id="learn-to-love-your-errormessages"><a class="anchor" href="#learn-to-love-your-errormessages"></a>Learn to love your error messages</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Not only should you read error messages carefully, but you should also take the time to craft yours with love and care. Like I said in an earlier post, <a href="https://moskitohero.com/development/2021/11/21/writing-code-for-your-future-self.html">you should always try to write code with your future self in mind</a>. And I guess the same applies to error messages.</p>
</div>
<div class="paragraph">
<p>Don’t just raise <code>Error</code>, or <code>StandardError</code> in your lib. Actually write your own <code>OddError</code> class. Give it a message. Make it clear. Make it so your user - and that may be the future you - is eager to look at what you coded and understand how it is architectured.</p>
</div>
<div class="paragraph">
<p>An error message must be clear, so it requires your code to be clear, and therefore it requires your programming mind to be clear about what the code is actually doing. Error messages tell something about your self.</p>
</div>
<div class="paragraph">
<p>Error messages are the conversation between the author of a program and his users. As a programmer, you will be either one or the other, in turn, and often both at the same time.</p>
</div>
<div class="paragraph">
<p>Error messages will make you grow while <em>learning</em> software. They will make you grow while <em>using</em> software. They will make you grow while <em>writing</em> software. Do not just dismiss them and skip to the Stack Overflow step.</p>
</div>
</div>
</div>
]]></content:encoded></item><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>