<?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 Jacob on Software on Medium]]></title>
        <description><![CDATA[Stories by Jacob on Software on Medium]]></description>
        <link>https://medium.com/@marthaller-jr?source=rss-2a093fe993db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QuwbeKOsQ4gG3CXNVT8BOA.jpeg</url>
            <title>Stories by Jacob on Software on Medium</title>
            <link>https://medium.com/@marthaller-jr?source=rss-2a093fe993db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:53:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marthaller-jr/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[I’m back!]]></title>
            <link>https://marthaller-jr.medium.com/im-back-7ab6349e8976?source=rss-2a093fe993db------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ab6349e8976</guid>
            <dc:creator><![CDATA[Jacob on Software]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 18:17:26 GMT</pubDate>
            <atom:updated>2025-01-19T18:17:26.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*UNzb69ZB3mk-1xoZ1aw9Ug.png" /></figure><p>As the title says… I’m back! I’ve learned a ton in the last couple years of my software engineering career, and am excited to write about how I’ve built my own skills up.</p><p>I’m also really excited about AI. Ultimately, I think AI will revolutionize all aspects of work, especially in how we build software. I’m spending the majority of my extracurricular time reading about and building AI projects, and will use this space to write about what I’m learning.</p><p>I’ll also be cross-posting everything I write to my <a href="https://jacobmarthaller.dev/">personal webpage</a>. If you want to read my writing over there, or keep up with me on social media, feel free to pay me a visit.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ab6349e8976" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Emergent Design with Clean Code]]></title>
            <link>https://medium.com/codex/emergent-design-with-clean-code-2116cec8edf1?source=rss-2a093fe993db------2</link>
            <guid isPermaLink="false">https://medium.com/p/2116cec8edf1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Jacob on Software]]></dc:creator>
            <pubDate>Fri, 20 Aug 2021 19:15:58 GMT</pubDate>
            <atom:updated>2021-08-21T11:51:51.404Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the great things about <em>Clean Code</em> is that as you progress through the book, the concepts you cover become more abstract. To my mind, this practice mirrors how one gets better at the art of programming itself. When you begin reading <em>Clean Code</em>, you cover concepts like good names for variables or functions and the optimal number of lines for a class. As you read on, however, Uncle Bob &amp; Co. elaborate on how you can step back from your code and ensure that it is well-designed, that one of your colleagues could drop into your program on any given day and easily understand what you intend it to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*sSa07nkG0yT2MSmWCHljIw.png" /></figure><p>In the same way, once you grok the syntax and basic features of a language or framework, you’re able to go <a href="https://tomassetti.me/raising-the-level-of-abstraction-what-if-we-tried-to-do-that-bottom-up/">up a layer of abstraction</a> with your code, focusing on the overall design and maintainability of your programs. I’m referring here to <a href="https://en.wikipedia.org/wiki/Emergent_Design#Emergent_design_in_agile_software_development">emergent design</a>, a concept in Agile software development that urges developers to focus on building the functionality of an application and letting the overall design of that system emerge with time. In this blog, I’ll review <em>Clean Code</em>’s general rules (in order of importance) for facilitating emergent design, and how you can build robust programs that are more readable and maintainable.</p><h4>Rule 1: Run All the Tests</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*B17-DCi0JxCrQ3TC.jpg" /></figure><p>While we’ve <a href="https://medium.com/geekculture/reading-clean-code-week-5-unit-tests-ccbfe31b6460?source=your_stories_page-------------------------------------">talked about testing before</a>, it bears repeating. To keep this lesson simple, I’ll repeat the most oft-quoted phrase my mentors in the software development space say to me: <a href="https://maurits.vanrees.org/weblog/archive/2007/10/untested-code-is-broken-code">Untested code is broken code</a>. As <em>Clean Code </em>puts it, an untested program is an unverifiable program; that is, you cannot check to see if your code consistently does what you intended it to do. And if you cannot check what a system does, you may as well not deploy it.</p><p>While I may sound a broken record, prioritizing tests essentially <em>forces us</em> to write cleaner code. For instance, if all of your logic for a program exists in a single file, it will be immensely difficult to test. To write tests for that logic, you’ll need to break your functions into separate files, adhering more closely to <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">SRP</a> by default and ultimately making your programs smaller. In addition, this practice lends itself well to loose coupling and high cohesion. So if you glean nothing else from this blog post, glean this: WRITE YOUR TESTS.</p><h4>Rule 2: Refactoring</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/0*LOLd1N8XWqFxBJEI.gif" /></figure><p>We’ve touched on <a href="https://levelup.gitconnected.com/reading-c%CC%B6l%CC%B6e%CC%B6a%CC%B6n%CC%B6-c%CC%B6o%CC%B6d%CC%B6e%CC%B6-refactoring-week-4-a7abe6539eb3?source=your_stories_page-------------------------------------">refactoring before as well</a>, but like testing, it’s such an important subject that we should discuss it in more depth. Simply put, refactoring our code is essential to good design. In point of fact, the rule about refactoring comes after the rule about tests for a very good reason: if we have good tests, we can be confident our program does what we intend it to do, <em>even if we change it</em>. As Jeff Langr writes in <em>Clean Code</em>:</p><blockquote>The fact that we have these tests eliminates the fear that cleaning up the code will break it!</blockquote><p>Although it can be a daunting proposition, it’s incredibly important to incrementally refactor our code. In giving our logic another look, we give ourselves a chance to employ programming best practices, choosing better names, modularizing our logic, etc. With testing and refactoring at the forefront of emergent design, we can fine-tune our code with the final three rules.</p><h4>Rule 3: No Duplication</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fr4aMmDLj9gu65oV.jpg" /></figure><p>At this point you can probably see that I’m summarizing a lot of my <a href="https://levelup.gitconnected.com/reading-clean-code-week-3-d-r-y-178da32e6220?source=your_stories_page-------------------------------------">earlier blog posts</a> with this article. But while there are more chapters to read and forthcoming blog posts from me on <em>Clean Code</em>, this chapter serves as a good encapsulation of the book, summarizing many of the most important points as you look to write a cohesive piece of software.</p><p>Duplicative code introduces unnecessary complexity to your system, and along with that complexity, more opportunity for your programs to fail. By eliminating that duplication, your code becomes more reusable. While there are many methods for keeping your code D.R.Y., <em>Clean Code </em>specifically mentions the <a href="https://refactoring.guru/design-patterns/template-method">Template Method</a> from the incredibly influential <a href="https://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612/ref=sr_1_1?dchild=1&amp;keywords=design+patterns&amp;qid=1629484668&amp;sr=8-1"><em>Design Patterns</em></a> as a way to reduce that complexity.</p><h4>Rule 4: Expressiveness</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*bUBHOGxh3eyyiAfu.jpg" /></figure><p>We’ve all been there, trying to decipher unclear code, painstakingly poring over every line looking for a pattern to emerge. Oftentimes we’re the programmer that wrote that unintelligible code in the first place, which makes the sting of confusion that much worse. As <em>Clean Code</em> tells us, the “the majority of costs of a software project is in the long-term maintenance.” As such, it’s critical that we write software everyone on our team will be able to understand.</p><p>There are <a href="https://medium.com/@daniel.oliver.king/writing-expressive-code-b69ef7a5a2fa">many ways to express ourselves well</a> in the medium of code. Good names help us write expressive code, as do small functions and separating concerns. In addition, unit tests act as another way to make our code expressive. When we run our tests we get a better sense of what our code intends to do.</p><h4>Rule 5: Minimize Classes and Methods</h4><p>While Rules 3 &amp;&amp; 4 are important to follow, we wouldn’t want to take it too far and create thousands of classes and/or files to accomplish our task. In keeping classes and methods small, we may make too many of them, which will ultimately increase our code’s complexity and slow us down. In truth, writing clean code is a balancing act; in trying to achieve your goal, you’ll constantly be asking yourself is this method too large? Do I have too many classes? Are these tests brittle?</p><p>Frankly, this uncertainty is the nature of programming. There is no hard and fast “right answer” to most coding problems. Programming is a creative exercise, one that is never perfected, but in attempting to be perfect we get a little bit better everyday. As your skills improve, the idea that there is no “perfect code” goes from utterly terrifying to ultimately freeing. In attempting to write clean code, you will improve as a programmer, you will push your colleagues to improve, and you will create amazing things. What work could be better than that?</p><p>At the end of this chapter, Langr mentions that while these rules are important to follow, no guidelines can trump the expertise gained with experience. Still, by looking to these principles, programmers of all levels increase their likelihood of writing clean code, and in doing so, creating elegant software.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2116cec8edf1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/emergent-design-with-clean-code-2116cec8edf1">Emergent Design with Clean Code</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Clean Code to Pass Your System Design Interview]]></title>
            <link>https://medium.com/codex/use-clean-code-to-pass-your-system-design-interview-65c57b9bdc94?source=rss-2a093fe993db------2</link>
            <guid isPermaLink="false">https://medium.com/p/65c57b9bdc94</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Jacob on Software]]></dc:creator>
            <pubDate>Tue, 10 Aug 2021 20:56:36 GMT</pubDate>
            <atom:updated>2021-08-11T14:00:08.105Z</atom:updated>
            <content:encoded><![CDATA[<p>For this week’s blog on <em>Clean Code</em>, I’m going to do something a little different. While up to this point we’ve discussed ways to keep code in our programs clean, we ought to spend some time thinking about how to expand our programs to be scalable systems. Just like our programs, our systems need to follow a set of standards to facilitate our ability to write software quickly and efficiently. While the questions we ask and solutions we uncover are slightly different at this higher level of <a href="https://www.springboottutorial.com/software-design-what-is-abstraction">abstraction</a>, we can abide by a set of guidelines to incrementally build more complex software artifacts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*auq0dhhbehGno2Su.jpg" /></figure><p>Although this <em>Clean Code </em>chapter is chock full of helpful information on designing clean systems, for the purposes of this blog I won’t go into too much detail on the following subjects: Separation of Main (a subset of <a href="https://softwareengineering.stackexchange.com/questions/32581/how-do-you-explain-separation-of-concerns-to-others">Separation of Concerns</a>), <a href="https://www.oodesign.com/factory-pattern.html">Factories</a>, <a href="https://www.freecodecamp.org/news/a-quick-intro-to-dependency-injection-what-it-is-and-when-to-use-it-7578c84fa88f/">Dependency Injection</a>, <a href="https://martinfowler.com/books/dsl.html">Domain-Specific Languages</a>, and the incredible work of <a href="http://www.patternlanguage.com/ca/ca.html">Christopher Alexander</a> (Sincerely, if you’re serious about system design, I would highly recommend you read Alexander’s <a href="https://www.amazon.com/Oregon-Experiment-Center-Environmental-Structure/dp/0195018249/ref=sr_1_1?dchild=1&amp;keywords=the+oregon+experiment&amp;qid=1628608371&amp;sr=8-1"><em>The Oregon Experiment</em></a>. It’s simply one of the best books I’ve ever read on how to design and build a cohesive system). Still, you should take some time to learn more about these topics. They’re great to know for both a system design interview as well as for general knowledge of keeping your code clean.</p><p>For this blog, I’ll be drawing heavily on Alex Xu’s practical — and aptly titled — book, <a href="https://www.amazon.com/System-Design-Interview-insiders-Second/dp/B08CMF2CQF/ref=sr_1_1?dchild=1&amp;keywords=system+design+interview&amp;qid=1628608787&amp;sr=8-1"><em>System Design Interview</em></a>. In it, Xu covers both a general approach to solving system design questions as well as common system design interview questions. While the <em>Clean Code</em> chapter on systems invites us to design a city, for the purposes of this blog post we’ll design a URL shortener like <a href="https://bitly.com/">Bitly</a> or <a href="https://tinyurl.com/app">tinyurl</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/0*TvMex_HTWv_8kR92.jpg" /></figure><p>Whenever we design a system, we want to follow a general guideline to keep our answer focused <em>and</em> flexible. It’s important to remember, there is no <em>right answer</em> for a system design interview. Interviewers aren’t interested in knowing if you’ve memorized the textbook answer for how to design Google’s software architecture. Rather, they want to see you reason through the needs of your system, ask intelligent questions, handle ambiguity, etc. It’s also important to collaborate with the interviewer, listening to their prompts for what the system should be able to control and taking their advice when offered. Think of it like a miniature pair programming exercise. These general steps for system design should help nudge us down the right path:</p><ol><li>Understand the problem and establish design scope</li><li>Propose high-level design</li><li>Design deep dive</li><li>Wrap up</li></ol><p>Now that we know the flow of the system design interview, let’s get started!</p><h4>Understand the problem and establish design scope</h4><p>There are many different ways to design a URL shortener. By asking relevant, opinionated questions, we scope out how we want our system to behave, which as the interviewee is ultimately up to you. For a URL shortener, some good opening questions might be something like the following:</p><ul><li>What is the traffic volume of the service?</li><li>How long is the shortened URL?</li><li>What characters can be included in the shortened URL?</li><li>Can shortened URLs be deleted or updated?</li></ul><p>For the purposes of this exercise, let’s assume that our URL shortener service takes a long URL and creates a much shorter alias which redirects the user to the long URL address. Let’s also assume that 100 million URLs are created every day, that they contain only alphanumeric characters (0–9, a-z, and A-Z), and that the generated URLs can neither be updated nor deleted. Given these considerations, we want this system to accommodate high availability, scalability, and fault tolerance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/0*FaW9GqCd-5oYDo09.png" /><figcaption>Sample back-of-the-envelope calculations</figcaption></figure><p>Once you have a basic understanding of the desired parameters, you can do some quick <a href="https://en.wikipedia.org/wiki/Back-of-the-envelope_calculation">back-of-the-envelope calculations</a> to get a better sense of how the system <em>should behave</em>. Remember, the interviewer isn’t grading you on correctness here. Rather, she or he is examining your thought process. By making some assumptions about what to expect you show that you understand what the system needs to function well. While it might seem daunting, it isn’t too difficult to assume that you’ll need your write operations to handle 1160 URLs/second (at 100m URLs/day), your read operations will need to handle 11,600 URLs/second (assuming a read to write ratio of 10:1), and that you’ll need to manage storage for 36.5 billion shortened URLs if you want to maintain them for a period of ten years (see below for Xu’s sample calculations for this question). While these are only assumptions, you now have a detailed template on which to build your URL shortener.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZOUh1Dl2COdOqO8Dt6WcQ.png" /></figure><h4>Propose high-level design</h4><p>To be sure, any URL shortener would need to address issues like <strong>API endpoints</strong>, <strong>URL redirecting</strong>, and <strong>URL shortening</strong>, and this is your chance in the interview to flesh out those details. More importantly than the specifics of your high-level design, however, is to avoid the temptation to do a <a href="https://www.freecodecamp.org/news/the-pros-and-cons-of-big-design-up-front-and-what-i-do-instead-375f00542dec/"><strong>Big Design Up Front</strong></a> (<strong>BDUF</strong>). As Dr. Kevin Wampler writes in <em>Clean Code</em>, doing a BDUF “inhibits adapting to change.” Unlike physical buildings, software’s ephemeral nature allows us to make radical changes to our design depending on our needs. With a “naively simple” (but still detailed) design, we’re able to build out our software but remain nimble enough to change depending on our evolving circumstances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/0*tfo18MM1ZzPpsq6D.png" /><figcaption>h/t xkcd.com</figcaption></figure><h4>Design deep dive</h4><p>A key component of any URL shortener is how you’ll implement a <a href="https://dev.to/antemarin_53/yet-another-url-shortener-4fe3"><strong>hash function</strong></a>. There are a number of different techniques for doing this, but people most commonly use <a href="http://www.cs.cmu.edu/~ab/15-121N11/lectures/lecture16.pdf">hash + collision resolution</a> and <a href="https://dev.to/antemarin_53/yet-another-url-shortener-4fe3">Base 62 conversion</a>. While the details of these two strategies are outside the scope of this blog, Xu gives a very helpful breakdown of the differences between the two procedures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*weLK_Jqx4mTAexPYuaYhcw.png" /></figure><p>Other strategies for a design deep dive might include methods for storing a shortURL in the database with a unique ID, as well as caching the hashed values for enhanced speed (given that your system is designed to handle read operations more quickly than write operations).</p><p>More importantly than these specific tactics, however, we would be more successful if we keep in mind what <em>Clean Code</em> reiterates again and again: “Growth (in software) is not without pain.” It’s not possible to get a system right the first time, and there will be many little hiccups along the way as you build increasingly intricate, more heavily-trafficked systems. Your interviewer is well aware of this, and rather than trying to account for every possible bug in the system, we would do better to write clean code, test and refactor that code, and slowly, diligently expand our system’s horizons.</p><p>Or, as Wampler tells us much more elegantly:</p><blockquote><em>“Software systems are unique compared to physical systems. Their architectures can grow incrementally,</em><strong><em> if</em></strong><em> we maintain the proper separation of concerns”</em></blockquote><p>Diagrammed out, our completed URL shortener might look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8d9gQIHIbZHpzpz5ZfkQ-g.png" /><figcaption>h/t kuczma.dev</figcaption></figure><h4>Wrap Up</h4><p>If there’s time left in your interview, you can go above and beyond by discussing more advanced aspects of a URL shortener. Delving into topics like <a href="https://cloud.google.com/architecture/rate-limiting-strategies-techniques">Rate Limiters</a>, <a href="https://aws.amazon.com/blogs/architecture/scale-your-web-application-one-step-at-a-time/">Web Server Scaling</a>, <a href="https://www.freecodecamp.org/news/understanding-database-scaling-patterns/">Database Scaling</a>, and how you could acquire <a href="https://geniuslink.com/blog/url-shortener-analytics/">Analytics</a> based on your shortened URLs show that you have a thorough understanding of the problem at hand. Congratulations! You nailed your system design interview!</p><p>As Wampler<em> </em>tells us in <em>Clean Code</em>, “systems must be clean too.” When you gain more skills and experience as a software engineer, you’ll steadily be relied upon to build up your system’s architecture. While this gives you a chance to dive into new and interesting topics, lessons learned from <em>Clean Code</em> can support you as you build up more robust software ecosystems.</p><p>If there is a main takeaway from <em>Clean Code</em> and Xu, I’d say that it’s important to remember that systems are built step by step. Something as vast and complex as Amazon or Google went through hundreds and thousands of iterations to be able to handle the traffic that they do today. Even a single physical building will go through tweaks and revisions from the design stage to when the final lightbulb is screwed in. In the same way, your systems will take time to build, and you would do well to remember that trial and error are features of the system rather than bugs. I loved the parting words of Wampler’s chapter in <em>Clean Code</em> so much I think it’s a good way to end this post:</p><blockquote><em>“Whether you are designing systems or individual modules, never forget to</em> use the simplest thing that can possibly work<em>.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65c57b9bdc94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/use-clean-code-to-pass-your-system-design-interview-65c57b9bdc94">Use Clean Code to Pass Your System Design Interview</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading Clean Code Week 6: Classes]]></title>
            <link>https://medium.com/codex/reading-clean-code-week-6-classes-162839d9361d?source=rss-2a093fe993db------2</link>
            <guid isPermaLink="false">https://medium.com/p/162839d9361d</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[uncle-bob]]></category>
            <category><![CDATA[single-responsibility]]></category>
            <dc:creator><![CDATA[Jacob on Software]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 20:06:35 GMT</pubDate>
            <atom:updated>2021-08-05T01:51:13.006Z</atom:updated>
            <content:encoded><![CDATA[<p>In this week’s blog on <em>Clean Code</em>, I’ll be talking a bit about classes. While object-oriented programming (OOP) is an extremely <a href="https://www.educative.io/blog/object-oriented-programming">vast topic</a> unto itself that I can’t delve into too deeply here, suffice to say for now that objects are bits of code that allow us to store data and operate on that data. By utilizing OOP, we keep the details of our programs hidden, which makes our code more flexible, modular, and abstract. OOP is very useful when writing large programs, especially in the case of working on a team building a robust application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d1KI9XmlLoGFH9km" /></figure><p>As with any code we write, we have a better chance of success when we keep our code clean, and Uncle Bob has some useful recommendations for helping us do that for classes. To drive home some of these points on writing clean classes, we’ll design a parking lot in JavaScript. Once we’re finished, we’ll have a better sense of the functionality classes give us, as well as how to keep them clean. I want to note that there are some OOP concepts that are simply outside the scope of this blog post, particularly <a href="https://medium.com/javascript-scene/encapsulation-in-javascript-26be60e325b4"><strong>Encapsulation</strong></a>, the <a href="https://medium.com/@_ericelliott/clarifying-my-use-of-the-open-closed-principle-de54f77342c3"><strong>Open-Closed Principle</strong></a> (OCP), and the <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle"><strong>Dependency-Inversion Principle</strong> </a>(DIP). Although we won’t discuss these in depth here, the linked articles will give you a broader understanding of classes.</p><h4>Design a Parking Lot</h4><p>Let’s be honest: You’ve probably never designed a parking lot before. Don’t let this <a href="https://www.youtube.com/watch?v=DSGsa0pu8-k">relatively common interview question</a> deter you. Let’s start by clarifying some assumptions about said parking lot. Good questions to ask about designing this system might include:</p><ul><li>What kind of vehicles are allowed to park in the lot?</li><li>Does the lot have multiple levels?</li><li>Can a small vehicle fit in a space designated for a larger vehicle?</li><li>Can more than one vehicle enter the lot at a time?</li></ul><p>By clarifying assumptions about the lot, we get a better idea of how this system is<em> supposed to work</em>, which will allow us to build a more efficient parking lot overall. To save ourselves a lot of discussion about how to design a parking lot in code, we’ll borrow an example from this excellent <a href="https://codereview.stackexchange.com/questions/254822/javascript-parking-lot-simplified-ood">StackExchange</a> post:</p><p>The Spot class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*HpXMW7kMRC99egnT6suZIg.png" /></figure><p>The ParkingLotManager class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YZyA5mYZ0oKzE8IKNdiTw.png" /></figure><p>The Vehicle, Motorcycle, Car, and Truck classes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*pOipJUSwKD_YRKSEWszOrQ.png" /></figure><p>Now that we have the following classes built, we can create new instances of them and perform operations on them. For example, if we create the following objects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*W9OVMTX4fVl3bNIyWolypg.png" /></figure><p>Our program gives us the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*PIPcyNWof1-n4b8ScoXPlw.png" /></figure><p>Again for the purposes of this blog, I won’t go into too much detail about the usefulness of OOP. For now I’lll just say that OOP enables us to modularize our programs, breaking them down into ever smaller pieces, reducing complexity and making it easier to solve bugs. As this is such an important concept in becoming a competent software engineer, it’s important that we’re able to keep our classes clean. Let’s see what recommendations Uncle Bob has for us.</p><h4>Classes Should Be Small</h4><p>As Martin writes, “ The first rule of classes is that they should be <strong>Small</strong>. The second rule of classes is that they should be <strong>Smaller</strong> than that.” If it sounds like Martin and his co-author is repeating their guidelines on function size, they are. Like functions, classes should be bite-sized and highly modularized. However, rather than measuring class size by the number of lines they take up— like we would with functions — we measure class size by the number of responsibilities it has. Let’s take a look at one of our classes from above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*NHrar4edU5_ehxp8zNqIZA.png" /></figure><p>As we can see, the Motorcycle class is small both in the number of lines it occupies as well as the number of responsibilities it holds. We know that Motorcycle inherits the id property from the Vehicle class, and it has an attribute specifying its size. As with functions, we introduce more opportunities for bugs to fester the more complex the class becomes. Conversely, we make classes cleaner by paring them down.</p><p>One way we might be able to keep our class sizes small is by giving them descriptive names. If you’ll recall from our review of the <em>Clean Code </em>chapter on <strong>Names</strong>, we should take care to give our objects designations that are clear and meaningful. You shouldn’t need myriad comments to describe a class’ responsibilities. To take a concrete example from our Parking Lot class system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*Yn3OejorDA6-aBZI-p991A.png" /></figure><p>the Truck class clearly indicates what we would expect of this class. Just by glancing at the names we can see that a truck is a type of vehicle, and that its size is one of its defining characteristics. While I know that some of the above code snippets violate this rule, in general the Motorcycle, Car, and Truck classes demonstrate how small classes ought to be.</p><h4>Single Responsibility Principle</h4><p>One of the most concepts in OOP and in software design generally, the <strong>Single Responsibility Principle</strong> (SRP) states that a class or module should have one, single, solitary reason to change. If a class has too many responsibilities, you might refactor part of your code and forget some method still operates on another piece of logic in your codebase. With vast, all-encompassing classes, it is difficult to keep your code organized. For example, let’s look back at our ParkingLotManager class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YZyA5mYZ0oKzE8IKNdiTw.png" /></figure><p>Ok, ParkingLotManager is obviously a bit bloated. For one, at 40 lines it simply occupies a sizable amount of space in our program. More importantly, though, it seems to me that we’re relying too much on ParkingLotManager to efficiently run our system. Currently ParkingLotManager has to keep track of space size <em>and</em> determine whether to add <em>or</em> remove a vehicle. A better system design might extrapolate the _getSizeIndex method from ParkingLotManager class, separating those concerns out and making our program easier to understand.</p><p>You might be thinking that creating too many classes has its drawbacks. Will I really save myself any time, you ask, if I have to scroll up and down my computer screen, scanning dozens of bite-size classes to be able to grok the whole of the program? Yet, Martin tells us, several small classes can have as many moving parts as a few large classes, and we would probably accomplish our goals more efficiently if we organized our tools into a clean, organized toolbox with ample labels for those tools. If SRP isn’t clicking for you, <a href="https://dev.to/skill_pathway/single-responsibility-principle-for-dummies-59gb">this blog post</a> gave a good explain like I’m 5 explanation on the topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*2X88BFWkD7hLBJt3" /></figure><p>There’s a great aside in <em>Clean Code</em>’s chapter on classes where Martin discusses why clean code is so rare. “Too many of us,” Martin claims, “think that we are done (writing code) once the program works.” As <em>Clean Code</em> makes a point of saying time and time again, writing code that a computer can understand is only part of the battle. The real challenge of programming comes in writing programs that humans can understand.</p><p>Like systems in the real world, computer programs change. New frameworks and/or logic is written into our systems, with tech debt accumulating in the process. As designers of our systems, every change we introduce subjects us to the risk that the system is no longer fully functional. In writing clean code, however, we reduce the risk of those programs — and our team — failing. I hope you found this blog helpful for understanding OO design and the way you can write clean classes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=162839d9361d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/reading-clean-code-week-6-classes-162839d9361d">Reading Clean Code Week 6: Classes</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading Clean Code Week 5: Unit Tests]]></title>
            <link>https://medium.com/geekculture/reading-clean-code-week-5-unit-tests-ccbfe31b6460?source=rss-2a093fe993db------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccbfe31b6460</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[uncle-bob-martin]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Jacob on Software]]></dc:creator>
            <pubDate>Wed, 28 Jul 2021 01:53:53 GMT</pubDate>
            <atom:updated>2021-07-28T15:26:11.840Z</atom:updated>
            <content:encoded><![CDATA[<p>If you ask any professional developer what the most import part of a software developer’s job is, I’d bet more than half of them would say testing your code. To be sure, Test Driven Development (TDD) is the way of the world in software development, and <em>Clean Code </em>dedicates an entire chapter to the topic. Even though it’s a relatively short chapter, the subject of unit testing is so important to the developer community at large it feels warranted to dedicate this week’s entire blog to it. In this post, I’ll discuss the <em>Clean Code</em> philosophy on testing and give some general guidelines on how an engineer can write good unit tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3_mSV25HRVvfZ5rL" /></figure><p>Martin begins this chapter by saying that when he writes tests, he slowly, meticulously steps through his code, isolating every nook and cranny of his program to ensure it behaves as expected every time. However, Martin says, although engineers have latched onto some of the <a href="https://www.softwaretestinghelp.com/software-testing-trends/">most popular aspects of testing</a> — such as writing test code before writing production code and automating tests — they sometimes fail to grasp the subtle, underlying thought processes behind testing. Delving more deeply into these principles, Martin lays out his three overarching rules of testing:</p><ol><li>You may not write production code until you have written a failing unit test</li><li>You may not write more of a unit test than is sufficient to fail (your code not compiling is failing, by the way)</li><li>You may not write more production code than is sufficient to pass the currently failing test</li></ol><p>Martin writes that the lifecycle of these three rules is roughly 30 seconds. If you’re reading these rules and thinking “It seems like I’m going to have to write a lot of tests,” then you’re right. While it may seem daunting to write this many tests, writing clean tests ultimately frees you up to write virtually any production code you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sjT7L_UnTInQwA-9.png" /></figure><p>In general Martin says our tests should follow these five rules, assigning them to an acronym called <strong>F.I.R.S.T.</strong>:</p><ul><li><strong>Fast</strong>: Tests should be fast. But tests don’t have to be lightning quick. Martin calls this the <strong>Dual Standard</strong>. Ultimately, you want your tests to be fast enough so that you actually run them, but they need not be as fast as your production code. After all, your users will never see your tests, so they don’t need to be as speedy as rendering your React code to the client.</li><li><strong>Independent</strong>: As this <a href="https://testguild.com/atomic-tests/">brilliant blog post</a> says, tests should be atomic. That is, they should test single, self-contained bits of logic in your code. This is related to Uncle Bob’s idea that each test should target only a <strong>Single Concept</strong>.</li><li><strong>Repeatable</strong>: Your tests have to work regardless of which machine they run on. If your tests perform differently in different environments, you can’t rely on them to, well, test.</li><li><strong>Self-Validating</strong>: As Martin says, unit tests should have a crystal-clear boolean output. You should be able to easily grok the outcome of your test, not have to scour the log files trying to intuit what your tests mean.</li><li><strong>Timely</strong>: Maybe most importantly, tests should be written in a timely fashion. Remember, the whole point of testing is to test your production code. By writing your tests <em>just before</em> you write production code, you ensure that you write tests and design your production code to be testable.</li></ul><p>To really drive home some of these points on testing, let’s look at a simple program and how to test it. For this example, I’m going to use one of <a href="https://exercism.io/my/tracks">Exercism</a>’s coding challenges. Exercism is an online, free coding platform that offers code practice and mentorship in 50 different programming languages, and they use an extremely popular testing framework called <a href="https://jestjs.io/">Jest</a>. More specifically, we’ll look at Exercism’s challenge on reversing a string. Below you can see both my code as well as the terminal output for the program:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*HcqKa3zWApKfG-Vwb0yaDQ.png" /><figcaption>reverse-string.js</figcaption></figure><p>Although we can visually see that this code works, it isn’t a very efficient way to test. For one, we’re breaking the <strong>Self-Validating</strong> rule of <strong>F.I.R.S.T.</strong> by verifying this code’s output in the console. We would be much more efficient (and cover a lot more of our code) by writing a comprehensive test suite, as the team from Exercism has done here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*djXgkPQUCpKHh_pvHqXauw.png" /><figcaption>reverse-string.spec.js</figcaption></figure><p>I’m going to avoid getting into the syntax of these tests for a very simple reason: these unit tests are intuitive! Any developer worth their salt could come into this file and see the six cases this suite is testing for, how we’re accounting for palindromes as well as capitalized words, among other things. As you can see, these tests also adhere to the <strong>Single Concept </strong>principle, each unit clearly isolating one potential input for our code to pass. While we could test a couple of edge cases — inputs that occur only at an extreme (maximum or minimum) frequencies — here, these units tests will catch a broad swath of errors. Let’s actually run our tests and see what we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*n8BiwlZ_7B5B5mObAw7fPw.png" /><figcaption>output for reverse-string.spec.js</figcaption></figure><p>As we can clearly see, our test suite is extremely fast, and our code passed our tests (as an aside, I don’t think there’s anything so satisfying to a developer as green checkmarks next to your tests). Jest’s tests are excellent because they give a clear description of what was tested in the output as well as how long it took to test our code. With these tests, we’ve clearly and quickly demonstrated that our code is working order, letting us move onto our next task with confidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*98FljKfbWmy_YXJ5.jpg" /></figure><p>While testing might seem cumbersome and restrictive, Martin makes the point again and again that good tests free you up to write any code you want. Rather than plodding around in the dark wondering what your logic is doing, TDD keeps our code flexible, maintainable, and reusable. With clean, readable tests, we can change our code as we please, knowing that our logic is still sound because we’re still passing our tests.</p><p>As you might imagine, we’ve barely scratched the surface of testing in this blog. And as with almost anything in software development, there are tons of resources to learn testing in more depth, from <a href="https://www.udemy.com/courses/development/software-testing/">Udemy</a> courses to <a href="https://www.oreilly.com/search/?query=testing&amp;extended_publisher_data=true&amp;highlight=true&amp;include_assessments=false&amp;include_case_studies=true&amp;include_courses=true&amp;include_playlists=true&amp;include_collections=true&amp;include_notebooks=true&amp;include_sandboxes=true&amp;include_scenarios=true&amp;is_academic_institution_account=false&amp;source=user&amp;sort=relevance&amp;facet_json=true&amp;json_facets=true&amp;page=0&amp;include_facets=true&amp;include_practice_exams=true">books</a> to helpful <a href="https://blog.feedspot.com/software_testing_blogs/">blogs</a>. In following Uncle Bob’s rules on writing clean tests, you’ll free yourself up to write any code you want… so long as it passes your tests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccbfe31b6460" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/reading-clean-code-week-5-unit-tests-ccbfe31b6460">Reading Clean Code Week 5: Unit Tests</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading Clean Code Week 5: Boundaries]]></title>
            <link>https://medium.com/codex/reading-clean-code-week-5-boundaries-aba7fbefb861?source=rss-2a093fe993db------2</link>
            <guid isPermaLink="false">https://medium.com/p/aba7fbefb861</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[boundaries]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[typegraphql]]></category>
            <dc:creator><![CDATA[Jacob on Software]]></dc:creator>
            <pubDate>Tue, 20 Jul 2021 16:00:08 GMT</pubDate>
            <atom:updated>2021-07-20T16:02:01.106Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m back to reviewing <em>Clean Code</em> this week after last week’s blog on <a href="https://levelup.gitconnected.com/reading-c%CC%B6l%CC%B6e%CC%B6a%CC%B6n%CC%B6-c%CC%B6o%CC%B6d%CC%B6e%CC%B6-refactoring-week-4-a7abe6539eb3"><em>Refactoring</em></a><em>. </em>And while the chapter I’m reviewing this week is short, the concept is incredibly important. This week I’m talking about <a href="https://www.cs.uct.ac.za/mit_notes/software/htmls/ch01s04.html">boundaries</a>, the way we incorporate code that we did not actually write into our systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*F8-r0j1Me9_AJKk7.jpg" /></figure><p>At a mere eight pages, <em>Clean Code</em>’s chapter on boundaries is one of the shortest in the book. But while the advice is relatively concise, in my opinion your ability to cleanly integrate third-party code into your applications will make or break your success as a developer.</p><p>Every software engineer, almost regardless of their experience, has been there, painstakingly staring at a computer screen trying to find a bug. Your program isn’t working as expected, and you can’t for the life of you figure out why. Worse yet, sometimes your program <em>does work as expected</em>, even though you <em>know</em> the code is broken. This nightmare scenario happens to the best of coders, but clearly something is wrong here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*NqUi22OuWlz8bxhl.jpg" /></figure><p>Although we’ve all written bugs into our programs, sometimes integrating third-party software introduces bugs that we didn’t write! Imagine spending hours staring at your computer screen, your eyes getting bleary, your frustration mounting, and this bug isn’t even your fault!</p><p>Well, it’s not <em>all</em> your fault. You may not have written the bug in the culprit code, but failure to exercise good boundaries in your programs is no one’s fault but your own. Luckily, <em>Clean Code</em>’s (and chapter author <a href="https://wingman-sw.com/about">James Grenning’s</a>) recommendations on boundaries can help protect your code from potentially buggy and broken software. By designing our programs in a way that protects from outside error, you keep your code more maintainable and can avoid some of those agonizing debugging sessions.</p><p>In truth, boundaries present something of a double-edged sword for web developers. On the one hand, building software in a team and being able to rely on others to help you write code can significantly improve your engineering experience. I’ve written about this a bit in my <a href="https://medium.com/swlh/working-with-obscure-ish-ruby-gems-3601bf60105a">earlier web developer days</a>, but using external packages saves you the time of writing that code. In addition, working with third party code allows you to rely on potentially more experienced and more talented developers to meet some of you software needs. For instance, you may need to hit an external API to acquire data for your application, or maybe there’s a Ruby gem for complex math that’s perfect for your use case. After all, there’s a reason open source software has been so useful for engineers.</p><p>On the other hand, as <em>Clean Code</em> says, “There is a natural tension between the provider of an interface and the user of an interface.” While users have specific needs of what they want their code to do, providers of third-party packages strive for broad applicability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*2Y8NAf3GWUBvL63z.jpg" /><figcaption>h/t cleancodejava.com</figcaption></figure><p>So what can you do to establish good boundaries for your program? The first thing you should do — and I promise this is not satisfying for a software engineer passionate about web development — is <strong>read</strong>. Instead of clacking away at your computer, read documentation about the external API or library you’re using. Slow down, take your time with it, and acquire deep understanding of the tool you want to use. Maybe even write a couple of internal tests (what <em>Clean Code </em>calls “Learning tests”) to check if the software works as desired. Only after learning and exploring this outside code should you feel comfortable exposing your system to it.</p><p>Another method for handling the boundaries of your programs is introducing <a href="https://en.wikipedia.org/wiki/Adapter_pattern"><strong>wrappers/adapters</strong></a> for external code. By introducing adapters into our code, we limit our dependencies. By limiting your program’s references to that third-party code, you limit the likelihood that your programs will break. I really liked the following podcast for its overall discussion of boundaries, but I thought it was especially insightful for information on how to “push the weird stuff to the edges of our code.” Frankly, the hosts do a better job than I can of explaining why boundaries are so important for writing clean code. I highly recommend you listen.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FP8nws-nkEPU&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DP8nws-nkEPU&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FP8nws-nkEPU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a67f35fd51ec542f79c6a441d48e42a/href">https://medium.com/media/4a67f35fd51ec542f79c6a441d48e42a/href</a></iframe><p>Finally, and I don’t mean this to sound trite, but exercise common sense when managing third-party boundaries. By common sense I mean maybe skip the library that hasn’t been updated in several years or that API with the skimpy, confusing documentation. Let’s look at the following code from a project I’ve been coding to get a better sense of what I mean here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*6luFevjZrJ4OKXWn3br3oQ.png" /></figure><p>While I’m working with lots of external code in this project, I’m fairly certain I’ve not overexposed my code here. One way I can be sure of that is I’m primarily using popular, well-documented projects like <a href="https://redis.io/">Redis</a> and <a href="https://typegraphql.com/">TypeGraphQL</a>. These projects have many contributors as well as thorough documentation, so if I run into an unexpected bug I won’t be grasping in the dark trying to figure it out.</p><p>One other thing I’ve done here is physically grouped my third-party software imports together, away from code I’m importing from within my own application. While not strictly a principle of maintaining clean boundaries, it follows the <em>Clean Code </em>rule of <strong>Conceptual Affinity</strong>, the notion that certain parts of code should be more closely grouped to things they resemble. Using a package manager like <a href="https://yarnpkg.com/">yarn</a> also helps maintain my external code.</p><p>Remember, <em>Clean Code </em>is not just about writing code that a computer can read, but what a human can read. As such, your code has to communicate your ideas clearly, and nothing muddles what you’re trying to say quite like someone else saying it for you. Rather than letting third-party libraries interject for your code, limit what these programs can say, and protect the overall cleanliness of your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aba7fbefb861" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/reading-clean-code-week-5-boundaries-aba7fbefb861">Reading Clean Code Week 5: Boundaries</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading C̶l̶e̶a̶n̶ C̶o̶d̶e̶ Refactoring Week 4]]></title>
            <link>https://levelup.gitconnected.com/reading-c%CC%B6l%CC%B6e%CC%B6a%CC%B6n%CC%B6-c%CC%B6o%CC%B6d%CC%B6e%CC%B6-refactoring-week-4-a7abe6539eb3?source=rss-2a093fe993db------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7abe6539eb3</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[martin-fowler]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jacob on Software]]></dc:creator>
            <pubDate>Tue, 13 Jul 2021 19:39:46 GMT</pubDate>
            <atom:updated>2021-07-14T02:48:54.850Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been loving reading through <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/B08X8ZXT15/ref=sr_1_1?dchild=1&amp;keywords=clean+code&amp;qid=1626195338&amp;sr=8-1"><em>Clean Code</em></a>, but am taking a bit of a break this week to discuss the first chapter of <a href="https://martinfowler.com/">Martin Fowler</a>’s <em>Refactoring. </em>Like <em>Clean Code</em>, <em>Refactoring</em> is fairly famous amongst professional programmers for its clear and concise advice on how to write clean, readable, and highly effective code. Now in its <a href="https://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Signature/dp/0134757599/ref=sr_1_1?dchild=1&amp;keywords=refactoring&amp;qid=1626195319&amp;sr=8-1">second edition</a> and containing incredible insights from Fowler, <em>Refactoring</em> is frequently included in lists of the <a href="https://www.geeksforgeeks.org/top-10-books-that-every-programmer-must-read-once/">best</a> <a href="https://hackr.io/blog/best-programming-books">programming</a> <a href="https://learntocodewith.me/posts/programming-books/">books</a> <a href="https://simpleprogrammer.com/best-programming-books-2019/">available</a> (Seriously, I just googled “Best Programming Books” and it is listed in each of the top four results). With that, let’s dive straight into some of the lessons Fowler presents in chapter one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*CA--iOiwOar_C4tV.jpg" /></figure><p>One of the first lines in <em>Refactoring</em> emphasizes that learning about code requires examples, lest you nod off trying to understand an abstract computer science subject. In that same vein, I’m going to use <em>Refactoring </em>to edit my previous code for <a href="https://putridpotatoes.netlify.app/">Putrid Potatoes</a>, a social media application that allows you to review the movies you watch and interact with other users on the site. While I always aim to write clear, professional code, in making this capstone project for the Flatiron School I’ll admit some of the code that I wrote could be improved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FarAD87bMSEK6tKtyuZdxA.png" /><figcaption>Putrid Potatoes homepage</figcaption></figure><p>More specifically, I’ll be refactoring a single React component from this application, the UserProfile component. This component is fairly straightforward, serving as a user’s personal profile page, containing a list of their followers as well as their personal movie reviews. The code for this component can be found <a href="https://github.com/jmarthaller/movie-chat-app-frontend/blob/main/src/components/UserProfile.js">here</a>, and here’s an example of what it looks like in the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqujbCVR0to6kBpttLjFPg.png" /><figcaption>Profile page for Putrid Potatoes</figcaption></figure><p>While the code for this component works perfectly well, it isn’t the most readable to other developers. As I’ve mentioned in previous blog posts, your compiler doesn’t really care if your code is readable to other people; if you <em>really</em> wanted to write your programs in as few lines as possible your IDE would probably accommodate you. But code readability is incredibly important to the other developers on your team. For Fowler, readability first becomes crucial in thinking about structure. Or, as Fowler says much more eloquently:</p><p><em>“When you have to add a feature to a program but the code is not structure in a convenient way, first refactor the program to make it easy to add the feature, then add the feature.”</em></p><p>Although it might seem obvious, I think what Fowler is saying here is a version of the “measure twice, cut one” philosophy that is more or less a staple of good engineering practice. Rather than hacking away at a program building out new and exciting features, experienced software engineers succeed when they lay a good foundation for their program, one that will be able to support features built today as well as in six months or a year. If you want to build applications all by your lonesome you should be fine maintaining any structure you want for your programs. However, as soon as you build things with even one other person, you’ll need to write readable code. To offer a simple example, let’s look at just some of the code forthe UserProfile component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLfSt3CNWsNDWa2w4kAlaw.png" /></figure><p>Again, this code works perfectly fine, but there are some pretty glaring problems with regard to its formatting. For one, these state management functions are awkwardly spaced out, and I can see there’s an unused variable of setReviews in my list of props for UserProfile.Worst of all, the props in allUserFriends is running off the page of my text editor! Thankfully, tools like <a href="https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode">Prettier</a> make it incredibly easy to refactor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*HCr58apAgzHZI1DtgvNt3g.png" /></figure><p>I think you’ll agree that this code is much easier to understand than the previous example (or is at the very least more pleasant to look at), and while it’s only a small code snippet in a relatively small portion of the entire application, giving your programs structure is the first thing Fowler does when looking to refactor previously written code. Even though this edited code takes up <em>more</em> lines than the previous snippet, it remains much easier to understand and build up over time.</p><p>Next we’ll look at the handleUpdateReview()function, which (maybe obviously) allows a user to update a previously submitted review for either its content or star rating. Here’s what that function looks like in my codebase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fmww37-JbfvNTuGnzz0Hzw.png" /></figure><p>Although this function is working well, the .then syntax for my Promise is a bit dated, and I’ve gotten feedback from my fellow software engineers that it would be better to use the more modern async-await syntax. Without getting into the specifics of that decision now, needing to make this change is a perfect example of why good refactoring is so important. As Fowler writes, “The true test of good code is how easy it is to change it.” The technologies we use will always need to be updated, and codebases will always require quality refactoring. Therefore, making our code modularized and flexible is the key to keeping our software efficient. After reformatting handleUpdateReview() with Prettier I have a pretty nice little piece of logic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*vq9460AUDljRWKLeezSU7A.png" /></figure><p>To be sure, this is a minor change to my program, encompassing only a couple of keystrokes. But though it seems like an insignificant change, it’s a good opportunity for me to save my program, test the altered feature to ensure it’s still working in the browser, and <em>only then</em> committing those changes with a version control system. This speaks to my favorite part of <em>Refactoring’</em>s first chapter.</p><p>Throughout the first chapter, Fowler reminds his reader that he is constantly, painstakingly checking his edits to ensure he has not broken his overall program. Indeed, Fowler’s phrase “compile-test-commit” appears on almost every page of the first chapter, serving as a coding mantra that he performs after every change to make sure he has not made a mistake. There are a few passages in the first chapter where Fowler even reminds the reader that even though he’s not explicitly writing “compile-test-commit” in the pages of <em>Refactoring</em>, it’s a regular part of his coding practice.</p><p>By running Putrid Potatoes locally I’m able to do something similar, testing changes in the browser before committing those changes and ultimately pushing them up to my hosting service at <a href="https://www.netlify.com/">Netlify</a>. Getting this kind of tight feedback loop will save you hours wasted if you were to just edit your programs blindly and save your changes to GitHub. To my mind, this practice gives a programmer a sense of the rhythm of refactoring, how editing your programs should always be accompanied with care and regular tests. It’s a reminder that after you’ve measured twice and cut once you should still double check that everything else still fits together. With modern tools like git, squashing your commits is easy to do, so making lots of commits in this broad refactoring phase won’t build up a lot of cruft when you do eventually push up your changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bB-cBACE3hUGputW.jpg" /><figcaption>Martin Fowler lecturing</figcaption></figure><p>Before I started reading <em>Refactoring</em> and <em>Clean Code</em>, I had my reservations about reading these types of books. While it seemed like a good idea to learn more about the process of writing quality code, wouldn’t it be a better idea to actually be writing that code? To be honest, I still think interested readers need to strike a balance between learning coding best practices and writing that code. It’s important to note, though, that while you’re reading books like <em>Refactoring</em>, you’re likely to catch yourself thinking of its lessons when programming. In my experience, if you take the time to sit with these books and internalize their lessons, they’ll seep deeply into your developer brain, ensuring you write more readable and maintainable code. Next week I’ll return to <em>Clean Code</em> once again. I hope you’ll come back to read about my progress.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7abe6539eb3" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/reading-c%CC%B6l%CC%B6e%CC%B6a%CC%B6n%CC%B6-c%CC%B6o%CC%B6d%CC%B6e%CC%B6-refactoring-week-4-a7abe6539eb3">Reading C̶l̶e̶a̶n̶ C̶o̶d̶e̶ Refactoring Week 4</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading Clean Code Week 3: D.R.Y]]></title>
            <link>https://levelup.gitconnected.com/reading-clean-code-week-3-d-r-y-178da32e6220?source=rss-2a093fe993db------2</link>
            <guid isPermaLink="false">https://medium.com/p/178da32e6220</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[dont-repeat-yourself]]></category>
            <category><![CDATA[uncle-bob-martin]]></category>
            <dc:creator><![CDATA[Jacob on Software]]></dc:creator>
            <pubDate>Tue, 06 Jul 2021 21:00:30 GMT</pubDate>
            <atom:updated>2021-07-06T23:51:58.837Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m continuing my <a href="https://levelup.gitconnected.com/reading-clean-code-week-1-a4df2c392e66">series</a> on <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?dchild=1&amp;keywords=clean+code&amp;qid=1622646055&amp;sr=8-1"><em>Clean Code</em></a><em> </em>this week, but I wanted to do something different with this blog post. When I first started reading Bob Martin’s classic handbook for writing better code, the advice given to me was to read it very, very slowly. If you have a physical copy, someone told me, it should look like a cherished family heirloom: dog-eared, flipped through back and forth, and clearly used. In fact, <em>Clean Code </em>offers the same advice. As Uncle Bob writes in the introduction, this is not a “feel good book that you can read on an airplane and finish before you land.” Rather, Martin and his co-authors urge readers to spend ample time on each concept in the text, wrestling with code snippets and case studies to deeply internalize why their advice is so important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q7aGAdOS7UBEYe2H9erpoA.png" /></figure><p>For that reason, I’m going to focus on just one guideline in <em>Clean Code</em> this week, peeling back the layers to get a better sense of how it can improve my code. More specifically, I’m going to focus on keeping my code D.R.Y., or Don’t Repeat Yourself. After a brief overview of how you can keep your code D.R.Y, I’ll apply those principles in refactoring one of my portfolio projects, a <a href="https://github.com/jmarthaller/quiz-app">simple quiz app written in TypeScript</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*IVIRjl_YL3bXKmDx" /></figure><p>To be fair, Bob Martin and <em>Clean Code </em>can’t take sole credit for Don’t Repeat Yourself. Originally conceived by Dave Thomas and Andy Hunt in their own classic programming text <a href="https://www.amazon.com/Pragmatic-Programmer-Anniversary-Journey-Mastery/dp/B0833FBNHV/ref=sr_1_1?dchild=1&amp;keywords=The+Pragmatic+Programmer&amp;qid=1625587763&amp;sr=8-1"><em>The Pragmatic Programmer</em></a>, the principle of writing D.R.Y. code has been a staple of good software development for decades. Still, the brief discussion of D.R.Y code in <em>Clean Code</em> underscores how important it is for any professional software engineer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/0*oj__D8B8f4B26ua8.jpg" /><figcaption>Another classic in the field</figcaption></figure><p>At the most basic level, Don’t Repeat Yourself states that every line of code you write should have a single, unambiguous representation in your program. An analogy might help explain this further. I sometimes jot down down notes on a notepad to organize my work week. Sometimes when I look back at my notes for the week, I’ll notice that I wrote some notes more than once. Maybe I didn’t email a colleague on Tuesday and rewrote it on my list for Wednesday. Maybe I simply forgot I wrote one note down at all and duplicated it. Regardless, copied notes in my note pad aren’t a big deal for my human brain because I can easily skip over them or throw the pad out at the end of the week and forget about it.</p><p>But computer brains don’t work like our brains. Any time my program runs, it will compile <em>all</em> the code in the files, original or not. If I make edits to that file and there are multiple instances of a particular piece of logic, I have to edit all instances of that logic or my program will break. As Martin says back in <em>Clean Code</em>, duplication is “the root of all evil in software.” “Wet” code bloats our programs, making any modifications to those programs n times larger. As wet code is harder read and maintain for us and (especially) our fellow developers, we should avoid it at all costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*PWEmM03O0dd1yTdK.jpg" /></figure><p>With that, I’m looking back at my TypeScript quiz app to see what could be refactored to make my code a bit more D.R.Y. In looking to clean up my codebase, the first piece of logic I noticed was the function I use to fetch and shuffle my quiz questions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLMUgz-oKpzGTop9I6FnjA.png" /><figcaption>in App.tsx</figcaption></figure><p>When initially building this project, I wanted my code to fetch the quiz questions whenever someone started up the application, so I included fetchQuizQuestions() in my top-level component, App.tsx. After reading more about D.R.Y. code, however, I have a better sense of the problems this design strategy presents.</p><p>By including this code directly inside my component, it’s not reusable. If myself and other programmers were to build this application out further, we might decide to add the ability to fetch quiz questions in different parts of the application. If we did this, we’d have to write fetchQuizQuestions() multiple times. Worse yet, if we had to refactor fetchQuizQuestions() based on new specifications, we’d have to find every instance of the function in the project and edit them all. This is not only tedious but dangerous, as we’re opening ourselves up to breaking our code base by missing duplicated code.</p><p>Instead we should <strong>Abstract</strong> our code out to more easily reuse it throughout the application. By pulling functionality out of the App component into its own file, which we’ll call API.ts, we’ll make this project more maintainable overall. We can see an example of what I mean here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PrpFWfAFdsDOdCOQrFoPQg.png" /><figcaption>In API.ts</figcaption></figure><p>By pulling this logic out into its own file, we separate the logic of fetching our quiz questions, modularizing them into bite-size chunks that any programmer could easily understand and contribute to. Now, back in App.tsx, we merely have to import the functions, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*S2ayh6ppS7SdjpXiU4RNvw.png" /><figcaption>importing fetchQuizQuestions() back in App.tsx</figcaption></figure><p>and then call fetchQuizQuestions() as we start up the entire application and set state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArLyni8oOxOcU55MJ-WuSQ.png" /></figure><p>Refactoring in this way also has the added bonus of shortening App.tsx, making it easier for other developers to understand. But wait, you might have noticed that we could clean up API.ts even further, pulling the shuffleArray() function into its own module for added readability. We’ll do that like so, in a file called utils.ts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-H75sKzkWK1W4vMAPKdeA.png" /><figcaption>utils.ts</figcaption></figure><p>We then import shuffleArray() into API.ts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*W4IDT02NEz8PBpkI29m2Xg.png" /><figcaption>API.ts</figcaption></figure><p>While it might feel like we’re making our code more complex by creating many files in which we store our logic, we’re actually making development much easier for our future selves. Remember, the computer’s brain has no problem keeping track of where we’ve placed which files. By breaking things out into smaller and smaller pieces, we can easily track these functions down if they ever need to change, command-clicking through the app to find the <em>exact</em> piece of logic in need of editing. With these changes our TypeScript quiz app still works as well as it did before, and is now much more maintainable.</p><p>As with nearly everything in software development, opinions about D.R.Y. code are numerous. <a href="https://dev.to/wuz/stop-trying-to-be-so-dry-instead-write-everything-twice-wet-5g33">Some argue</a> that keeping code D.R.Y. is too strict a guideline, even recommending that W.E.T. (Write Everything Twice) makes for a quicker development workflow. Others say that D.R.Y. practitioners are overzealous and that developers should <a href="https://kentcdodds.com/blog/aha-programming">Avoid Hasty Abstractions</a> (or A.H.A.). However, while there’s undoubtedly merit to these alternative frameworks for writing software, for the time being I want to follow <em>Clean Code</em>’s advice for improving the overall readability of my code. While there are many, many additional aspects of keeping your code D.R.Y. — including Rule of Three and Separation of Concerns, among others — this high-level overview should give you a general sense of how to get started with the concept.</p><p>I hope you’ve been enjoying this series on <em>Clean Code</em> as much as I have. Many times as software engineers, we measure our success by how much chatter we get out of our keyboard. However, as experienced developers will tell you, sitting down with a dense book and slowly digging into the lessons it has to offer can be infinitely more valuable to your long-term growth as a professional engineer. I love how Clean Code is helping me think not just of the ways I refactor my existing code, but also how I write fresh code. Check back next week to see my progress!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=178da32e6220" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/reading-clean-code-week-3-d-r-y-178da32e6220">Reading Clean Code Week 3: D.R.Y</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading Clean Code: Week 2]]></title>
            <link>https://medium.com/codex/reading-clean-code-week-2-643641e4dc28?source=rss-2a093fe993db------2</link>
            <guid isPermaLink="false">https://medium.com/p/643641e4dc28</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[uncle-bob-martin]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jacob on Software]]></dc:creator>
            <pubDate>Tue, 29 Jun 2021 15:06:34 GMT</pubDate>
            <atom:updated>2021-07-03T18:34:39.692Z</atom:updated>
            <content:encoded><![CDATA[<p>As followers of this blog know, I’m currently <a href="https://levelup.gitconnected.com/reading-clean-code-week-1-a4df2c392e66">reading</a> through <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?dchild=1&amp;keywords=clean+code&amp;qid=1622646055&amp;sr=8-1"><em>Clean Code</em></a>, a classic in how to write readable, professional code. Written primarily by “Uncle Bob” Martin, with appearances from a number of leading thinkers in the field of AGILE software development, <em>Clean Code</em> isn’t exactly a step-by-step coding manual. While I covet another animal-adorned O’Reilly book as much as the next code junkie, <em>Clean Code </em>won’t teach you a particular language or framework. Rather, <em>Clean Code</em>’s subtitle — “A Handbook of Software Craftsmanship” — explains the broader purpose of this book.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*7nVzoRBWCo3BBuRhVPBDRg.png" /><figcaption>Uncle Bob wants you to write clean code</figcaption></figure><p>For Bob Martin and his co-authors, <em>Clean Code </em>provides a way to <a href="https://www.youtube.com/watch?v=7EmboKQH8lM">take care with your code</a>. Just like a carpenter guides her or his lathe across a slab of wood with laser precision (nowadays literally with laser precision), so too should software engineers write their code with the utmost attention to detail. To illustrate more specifically what this fantastic book has to offer, I’m going to continue where I left off last week, providing more detail as to what elements of a computer program might require cleaning.</p><p>For this post, I’m going to look at code for a different project than last week, refactoring my own work using entirely different lessons from <em>Clean Code</em>. Fans of the book (and <a href="https://www.pullrequest.com/blog/3-clean-code-books/">similar texts</a>) might notice that I’m not writing sequentially by chapter. From my experience, <em>Clean Code</em> is one of those books that is best digested by flipping around to a chapter that immediately grabs you. Let’s start restructuring our project to make it a bit cleaner.</p><p>The project I’ll be refactoring for this post is in fact my capstone project for Flatiron School’s software engineering bootcamp, <a href="https://putridpotatoes.netlify.app/">Putrid Potatoes</a> (please excuse the corny name, I truly can’t help it). A clone of the movie review website <a href="https://letterboxd.com/">Letterboxd</a>, Putrid Potatoes allows you to log the films you’ve watched, write reviews of those films, and follow other reviewers on the site. As a fan of Letterboxd and cinema generally, I had so much fun building this website, and once it was complete I truly felt like a full-fledged software engineer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l21WyFeKRRT_84lKxytPfA.png" /><figcaption>Putrid Potatoes homepage</figcaption></figure><p>That said, as anyone who’s attended a coding bootcamp can tell you, learning to make a full stack web application in just three weeks can be immensely stressful. I’m not proud of it, but I’m sure that in that time I wrote some not so clean code, and I’m excited take lessons from Uncle Bob and co. to tidy some of my work up. As a reminder, the reason it’s so important to write clean code is that the time spent <a href="https://www.ybrikman.com/writing/2018/08/12/the-10-to-1-rule-of-writing-and-programming/">reading code as opposed to writing code is 10:1</a>. This is especially important because I’m still building out features for Putrid Potatoes, and anyone with a GitHub account can contribute to <a href="https://github.com/jmarthaller/putrid-potatoes-demo">my code</a> just like any piece of open-source software. If my code was unclear it would slow down their development process and possibly the evolution of the site. Worse yet, if Putrid Potatoes gained a significant amount of users and something broke it’d be infinitely harder to fix than if I had just written clean code! With that, let’s look at what we can clean up in this codebase.</p><h4>Functions</h4><p>Even if you don’t follow the functional programming paradigm, functions are, as <em>Clean Code</em> says, “the first line of organization in any program.” Functions allow us to pass data through our program, manipulating it to our heart’s desire and unlocking the real power of software. As we rely on functions so often in our code, it’s important to make sure we follow some best practices. Let’s look at the following function from Putrid Potatoes, which follows another user on the app when the correct button is clicked and sends that user an email notifying them of their new follower (utilizing the fantastic <a href="https://www.emailjs.com/">EmailJS</a> library):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vct5Jdg7D7J5q_SjELjplA.png" /></figure><p>While the naming conventions used here are relatively straightforward, there’s one major problem with this piece of code. As <em>Clean Code </em>says, functions should be <strong>Small!</strong> To be more specific, Martin tells us these are the first two rules of functions:</p><ol><li>Functions should be small.</li><li>Functions should be smaller than that.</li></ol><p>Although handleFollowOtherUser could be a lot longer — I’ve seen functions in the 1,000-line range (gulp!) — functions should be bite-size chunks we can easily grok. If writing code is like any other kind of writing, then we want our functions to serve as sentences, incrementally giving details on what a program is supposed to do as though it were a novel. Rather than have this 30-line behemoth like the one above, our code would be significantly more readable if it was broken up into multiple smaller functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPm5hif4K3auSzqoogZD8w.png" /></figure><p>In my opinion, even just halving this function into two chunks makes it much more readable. If another programmer were to come along, they would have a much easier time following the chain of functions here.</p><p>Refactoring my code in this way allows us to discuss another of Bob Martin’s recommendations for our functions: functions should <strong>Do One Thing</strong>. Before, handleFollowOtherUser was performing quite a few operations for us, taking in the event, collecting the proper information to create a new follower-followee relationship, <em>and then</em> posting that data to our database.This function is a no-brainer to edit. While we could abstract postNewFollowerRelationshipToBackend out into smaller and smaller chunks, I think it’s preferable in this case to keep all of our fetch logic in one place.</p><p>While I won’t go into them in full detail here, <em>Clean Code</em>’s recommendations on <strong>Function Arguments</strong>, <strong>Using Descriptive Names</strong>,<strong> </strong>and keeping your code <strong>D.R.Y. (Don’t Repeat Yourself) </strong>are well worth a Google, and will likely be a subject of future blog posts here. No doubt they will make your functions smaller and more easily digestible for your development team.</p><h4>Formatting</h4><p>One of the great joys of writing code today is the flexibility we can give to the layout of the words we write. Just imagine if we had to write code that looked anything like this minified JavaScript file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmpWyan9hN4fyS9QU44IAQ.png" /><figcaption>The nightmare fuel of code</figcaption></figure><p>Thankfully, our IDEs give us the ability to format our code in virtually anyway we want. So long as it’s still valid in the language we’re writing in, the compiler should be able to bundle our code and do what we tell it to. But just because we can write our code in an extremely loose format doesn’t mean we shouldn’t take care with how we present our code on the page. To be sure, <em>Clean Code</em>’s chapter on formatting has one of best sentences I’ve ever read on writing code, and I think it sums up the point of the entire book well:</p><p><em>“Code formatting is about communication, and communication is the professional developer’s first order of business.”</em></p><p>We have to remember as software engineers, code is just words. As convoluted as fetches and try-catches and switch statements get, we’re still just writing words, linking them together to make a cohesive whole of a program. For this reason, we want to pay close attention to detail. Let’s look at the following code to get a sense of formatting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7EShNAnYTZuA3JjP0AcQ6A.png" /></figure><p>As you can see, GenreFilter() takes up only 25 lines of code (it also clearly does one thing and has descriptive names, in case you were keeping score). But why is <strong>Vertical Formatting</strong> important for our programs? Let’s take a look at the following diagram from <em>Clean Code</em>, which shows the average file length of a number of large-scale production applications:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWZ67tRLUZQkEgSc5sg5Cg.png" /></figure><p>As <em>Clean Code</em> tells us, “small files are easier to understand than large files.” Rather than scrolling up and down our screen to understand what our code should do, we can write small files and break our logic out into other files if it gets too long. What’s more, it’s clearly possible to create useful applications writing ~100 lines of code/file. To help drive this point home, Martin tells us to use <strong>The Newspaper Metaphor</strong>. We read the newspaper vertically, looking first to an informative headline, then to the synopsis of the story in the first paragraph, and gleaning more details as we read further below. In the same way, our source files should have simple, explanatory names, with more details about the file revealing themselves as we read downwards. Let’s look at another aspect of formatting we should pay close attention to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzbiDJ8W-nQyMTvTrkqfzw.png" /></figure><p>While the functionality of allReviews is clear enough, there’s obviously a big problem here: the width of the line starting with canLeaveReview exceeds the length of the screen! Just like with vertical formatting, as programmers we also need to pay attention to <strong>Horizontal Formatting</strong>. To get a better sense of what I mean here, let’s look at another diagram from <em>Clean Code</em> showing the average line width:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__LE1jSPUzSZWwJ-Nh7-Ew.png" /></figure><p>As the diagram shows us, programmers clearly prefer short lines. Even if we’re working with large monitors, we should be cognizant that other programmers will likely not want to scan the entire length of their screen to see what the relevant code is supposed to do. Refactoring this code makes it much more readable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SO1PGLTyZzwF9nFbeZx7Hw.png" /></figure><p>While the edited code is still fairly wide, the longest line is now only 160 characters long, roughly half of what it was before. There are many more lessons to be learned about formatting that I won’t delve into here, including <strong>Indentation</strong>, <strong>Horizontal Alignment</strong>, and <strong>Conceptual Affinity</strong>. Although it might seem like with formatting you’re merely making your code look presentable, there is serious power in writing code that others can easily read.</p><p>As I mentioned in the beginning of this blog post, <em>Clean Code</em> is one of those books that you can flip around until something piques your interest. As an aside, the book has a number of funny cartoons at the start of every chapter, and you might do well to start reading wherever your interest takes you.</p><p>Over the next few weeks I’ll continue reading and writing my way through <em>Clean Code</em>, veering off into different blog topics when I need to learn more about writing good tests or general code design. My hope in this blog series is that you’re inspired to write good, clean code, so we can all collectively build software that does something important. So go ahead, flip around, find something that looks interesting to you, and go write some clean code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=643641e4dc28" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/reading-clean-code-week-2-643641e4dc28">Reading Clean Code: Week 2</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading Clean Code: Week 1]]></title>
            <link>https://levelup.gitconnected.com/reading-clean-code-week-1-a4df2c392e66?source=rss-2a093fe993db------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4df2c392e66</guid>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[uncle-bob-martin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Jacob on Software]]></dc:creator>
            <pubDate>Thu, 24 Jun 2021 21:13:38 GMT</pubDate>
            <atom:updated>2021-06-27T00:00:25.469Z</atom:updated>
            <content:encoded><![CDATA[<p>As followers of this blog may have noticed, I’ve been referencing <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?dchild=1&amp;keywords=clean+code&amp;qid=1622646055&amp;sr=8-1"><em>Clean Code</em></a> quite a bit the last several weeks. I started reading the book on the advice of a friend and fellow software engineer, who extolled the values of this classic programming text. I’ve been going through it very slowly, reading just one chapter a week to make sure I plant these lessons deep in my head. Still, I can see how <em>Clean Code</em> is having a significant effect on how I think about the code I write as well as the code I’ll write in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Q8FNYnGNY7oyOJBI.jpg" /><figcaption>The classic</figcaption></figure><p>Written by <a href="http://cleancoder.com/products">Bob Martin</a> — or “Uncle Bob” to those who know of him — <em>Clean Code</em> was first released in 2009, and follows some of the best insights programmers have discovered over the last several decades. You’ve probably heard of it before, and it’s almost certainly on the shelves of nearly every company in the tech space. As computation is all about making machines that can do particular tasks more efficiently than humans, we would do well to listen to some of the most insightful minds of the trade.</p><p>For this blog post, I’m going to look back at code I wrote for a previous project, refactoring it to reflect on the lessons I’ve been learning from <em>Clean Code</em>. As I’ve only read the first couple of chapters, I’ll be very specific with my insights, focusing only on meaningful names and comments. I hope it inspires you to always, whatever you do, write clean code.</p><p>More specifically, I’ll be refactoring a simple quiz app I built to teach myself TypeScript. Feel free to check out the GitHub repo <a href="https://github.com/jmarthaller/quiz-app">here</a> or read my Medium <a href="https://levelup.gitconnected.com/typescript-javascripts-more-responsible-cousin-58d1f045a7b2">article</a> on learning TypeScript. Run the app locally and you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8uO7m6dtU2lmpmdrx9drw.png" /></figure><p>I had a lot of fun learning TypeScript, and I definitely understand why programmers would want all the functionality of JavaScript with stricter typing. While I loved building this small app, I suspect I might not have written the cleanest code possible. And although this was a solo project where I was the only developer, someone else could easily come along and decide to build on top of what I made. Collaboration is part of the beauty of the internet, and tools like GitHub are what make programming so powerful. However, If another programmer came along, my lack of clean code would undoubtedly slow them down. As Uncle Bob tells us time and time again, the amount of time reading code as opposed to writing code is easily 10:1. Let’s dive into the code and see what we can refactor.</p><h4>Names</h4><p>One of the first chapters of <em>Clean Code</em> is all about names. The first sentence in the chapter reads “Names are everywhere in software.” We’re constantly naming functions, variables, and arguments, among other things. Because naming elements of our programs occurs so often, we should do it well, giving designations that are clear and meaningful. Let’s take the following function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CyuM99wDYykcLXdRMuA6CA.png" /></figure><p>The above function is fairly simple. It takes in the value of the click event (whichever answer the user picked) and checks to see if that answer is correct. While I’m fairly happy with some of the naming conventions I used here, I think we can do a bit better. Firstly, I think checkAnswer() could be a bit more specific. If this were a larger project, with different kinds of quiz questions, just telling your fellow programmer “Ya, this function checks the answer or whatever” might not be good enough. Does it check the user’s answer? In what context does it check the answer? Is there some background process “answer” that it’s checking? As <em>Clean Code</em> tells us, as programmers we want to use <strong>Intention-Revealing Names</strong>. That is, we want to show the reader why this function exists and what it does. Let’s try to clean it up now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lq7CLB8hzFYOwqCxB0n-pQ.png" /></figure><p>To my mind, this small update significantly improves our program. Now, when other coders come across checkUserAnswerForCorrectness(), they’ll clearly see that it takes in a MouseEvent from the user and checks to see if that answer matches the data in our database. This small change might save our team members valuable time.</p><p>Astute readers may have noticed that I also replaced the prev variables with previous. Although most people would have gathered what prev was short for, I made this refactor for a very important <em>Clean Code</em> reason: <strong>Avoid Disinformation</strong>. Being clear means being specific, and we wouldn’t want our fellow programmers coming across prev and thinking it could stand for anything other than previous. While programmers will likely always use an i for iteration or an x to hold a particularly obvious bit of data, writing out full words should help you in the long run.</p><p>Although being verbose in your naming conventions is important, writing clean code requires balance. You can’t just go naming your function something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*omfh-AOBkoUQHcZh4OOYjw.png" /></figure><p>While this is technically a more specific name for this function, it’s obviously worse than checkUserAnswerForCorrectness . We can’t even see the whole name of the function, let alone any arguments it takes in! Our programs are stories, and as storytellers we would do well to build up our descriptive skills. While there are many more lessons in this chapter of <em>Clean Code</em>, this is a good primer on using effective names.</p><h4>Comments</h4><p>Simply put, programmers cannot rely on comments to save their messy code. As Uncle Bob says, nothing can be “quite so helpful” as a well-placed comment, but it can also clutter up your programs the more you use them. While it might be useful to provide your reader copyright information or explanation of intent in the form of a comment, on the whole comments are unnecessary and distract the eye away from the code, the ultimate source of truth in your program.</p><p>I’ll admit, I’m actually pretty good about avoiding comments. The programmers that taught me consistently instructed me to express myself in code, and that comments are mostly frivolous. More than likely they taught that because they read <em>Clean Code </em>before I did. To stay true to this blog post I’ll insert some comments into the app and share some of the important lessons from <em>Clean Code</em>. We’ll first take a look at the following bad comment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dNmedz4FV7hdS2We8KbxA.png" /></figure><p>The above comment is a good example of what <em>Clean Code </em>calls a <strong>Redundant Comment</strong>. Does the comment even do anything for the reader here? Wouldn’t your program be clearer if you refactored the function name to be more descriptive, perhaps naming it something like provideNextQuestionToUser() ? Ultimately, you don’t want a comment — which is supposed to impart understanding — to take longer to grok than the function itself, so this is an easy comment to avoid in the future. Let’s look at another kind of bad comment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TI59QcHjNgeg4AtdgqEp2w.png" /></figure><p>The above comments represent what dear Uncle Bob calls <strong>Noise Comments</strong>. They pepper poorly-written functions, bloating your code until you can hardly follow it. While a programmer may want to include one comment at the top of a function to guide the reader, using good naming conventions can save several lines of comment fluff. Just see how much cleaner the code is when we cut it down a bit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RoOvvzf4aCCsswEb0WZbSg.png" /></figure><p>I think we can agree this is significantly easier to read, and your fellow programmers will likely appreciate the top comment describing what the function will do. Remember, before you write a comment, see if you can refactor your code to make it clearer. Let’s look at the last bad comment we’re going to examine here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-LCdatFMIWRKuNx02Oasbg.png" /></figure><p>Hopefully this is somewhat obvious, but <strong>Commented-Out Code</strong> has virtually zero usefulness to other people reading your programs. Maybe the above code was for an earlier iteration of the app, maybe it’s just cruft that an inattentive programmer forgot to delete. Regardless, it probably shouldn’t exist in the program, and because it carries so little information, it’s likely to persist. As <em>Clean Code</em> tells us, other people likely won’t have the courage to delete this comment because they don’t know if it’s important. As the initial writers of our programs we should pay close attention to what can be excised from our programs to make them clearer. Comments can be useful, but only when done well.</p><p>Over the next couple of weeks I will be reading more of <em>Clean Code</em> and sharing what insights it has for budding programmers. By reading this book very slowly (roughly one chapter/week), I want to really absorb as much information as I can, ultimately making me a significantly better programmer overall. Check back here weekly to see my progress!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4df2c392e66" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/reading-clean-code-week-1-a4df2c392e66">Reading Clean Code: Week 1</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>