<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Programming with Shahan - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Programming with Shahan - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 23 May 2026 19:40:23 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/codewithshahan/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ The Clean Code Handbook: How to Write Better Code for Agile Software Development ]]>
                </title>
                <description>
                    <![CDATA[ Building scalable software applications requires writing clean code that’s so simple that any dev can understand it. In this article, I’ll explain and demonstrate what clean code is. Then I’ll share my favorite clean code patterns for building modern... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-clean-code-handbook/</link>
                <guid isPermaLink="false">679a5fa86177eb24200d0f7f</guid>
                
                    <category>
                        <![CDATA[ clean code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ agile ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Programming with Shahan ]]>
                </dc:creator>
                <pubDate>Wed, 29 Jan 2025 17:04:40 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738170236859/edacf21e-7180-4f65-9e7e-f7cf95b4f9d8.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Building scalable software applications requires writing clean code that’s so simple that any dev can understand it.</p>
<p>In this article, I’ll explain and demonstrate what clean code is. Then I’ll share my favorite clean code patterns for building modern Agile applications.</p>
<p>I won’t use complex jargon. I’ll hit you with simple, clear JavaScript examples that focus on the core concepts. Straight to the point, no nonsense – that’s how I roll.</p>
<p>Let’s get started.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-the-cost-of-bad-code">The Cost of Bad Code</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-clean-coder-vs-messy-coder">Clean Coder vs. Messy Coder</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-ai-cant-save-you-if-your-code-is-a-mess">AI Can’t Save You If Your Code is a Mess 🗑️</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-12-clean-code-design-patterns-for-building-agile-applications">12 Clean Code Design Patterns for Building Agile Applications ⚖️</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-use-names-that-mean-something">🌿 Use Names That Mean Something</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-keep-functions-laser-focused-srp">🔨 Keep Functions Laser-Focused (SRP)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-comments-thoughtfully">🚪 Use Comments Thoughtfully</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-best-practices-for-writing-good-comments">⚡ Best Practices for Writing Good Comments</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-make-your-code-readable">🧩 Make Your Code Readable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-test-everything-you-write">🏌️ Test Everything You Write</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-dependency-injection">💉 Use Dependency Injection</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-clean-project-structures">📂 Clean Project Structures</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-be-consistent-with-formatting">🤹‍♂️ Be Consistent with Formatting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-stop-hardcoding-values">✋ Stop Hardcoding Values</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-keep-functions-short">🤏 Keep Functions Short</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-follow-the-boy-scout-rule">⛺ Follow the Boy Scout Rule</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-follow-the-openclosed-principle">🏟️ Follow the Open/Closed Principle</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-modern-best-practices-to-help-you-write-clean-code-a-summary">Modern Best Practices to Help You Write Clean Code: A Summary 🥷</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-automated-tools-for-maintaining-clean-code">Automated Tools for Maintaining Clean Code ⚓</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-static-analysis">1️⃣ Static Analysis</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-automated-code-formatting">2️⃣ Automated Code Formatting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-continuous-integration-ci-testing">3️⃣ Continuous Integration (CI) Testing</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-cicd-pipelines">4️⃣ CI/CD pipelines</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-the-role-of-documentation-in-agile-software-development">The Role of Documentation in Agile Software Development 🚣</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion 🏁</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-frequently-asked-questions-about-clean-code">Frequently Asked Questions About Clean Code 🧯</a></p>
</li>
</ol>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xh3j6ccn1hc3euc3lfyl.png" alt="Image of agile software development meme" width="3125" height="1250" loading="lazy"></p>
<p>In Agile, where change is the only constant, clean code is your armor. It makes you adaptable, swift, and, most importantly, in control.</p>
<p>Here’s the truth: writing clean code is not optional if you want to survive in the software development industry. Fortunately, we human beings are able to master clean code with some effort and practice.</p>
<h2 id="heading-the-cost-of-bad-code">The Cost of Bad Code</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wdai6npb55j71sguj6kl.png" alt="Image of cost of messy code vs clean code graph by shahan" class="image--center mx-auto" width="500" height="600" loading="lazy"></p>
<p>To explain this stack bar graph, in the initial development phase, bad code is <strong>slightly</strong> more costly to change than clean code.</p>
<p>But as we move into the maintenance and refactoring phases, the gap widens significantly, with bad code costing nearly twice as much as clean code.</p>
<p>By the legacy phase, bad code reaches 100% cost – now it’s extremely expensive to update, while clean code remains more manageable at 45%.</p>
<p>As of now, the most recent analysis on the cost of poor software quality in the U.S. is the 2022 report by the Consortium for Information and Software Quality (<a target="_blank" href="http://cisq.org">cisq.org</a>). This report estimates that poor software quality cost the U.S. economy at least $2.41 trillion in 2022, with technical debt accounting for about $1.52 trillion of this amount.</p>
<p>You can <a target="_blank" href="https://www.it-cisq.org/the-cost-of-poor-quality-software-in-the-us-a-2022-report/">read more about that here</a>.</p>
<p>Recent discussions continue to highlight the significant impact of technical debt on software quality and business performance.</p>
<p>For instance, <a target="_blank" href="https://vfunction.com/blog/how-to-manage-technical-debt">a 2024 survey</a> indicated that for more than 50% of companies, technical debt accounts for greater than a quarter of their total IT budget. And this can really hinder innovation if it’s not addressed.</p>
<p>As you can see, there’s no doubt that bad code is a costly problem in software development.</p>
<h2 id="heading-clean-coder-vs-messy-coder"><strong>Clean Coder vs. Messy Coder</strong></h2>
<p>Here’s a graph that shows the journey of <strong>two types</strong> of coders:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c6ubf77uwipf4gtucw8q.png" alt="Image of clean code vs bad code graph chart" class="image--center mx-auto" width="604" height="340" loading="lazy"></p>
<ul>
<li><p><strong>⚠️ The Messy Coder (Red line):</strong> Starts fast but crashes hard. The more lines they write, the more trouble they make.</p>
</li>
<li><p><strong>⚡ The Clean Coder (Blue line):</strong> Starts slow but stays consistent. Growth doesn’t stop — it accelerates.</p>
</li>
</ul>
<p>🫵 Now, you decide which line you want to follow.</p>
<h2 id="heading-ai-cant-save-you-if-your-code-is-a-mess">AI Can’t Save You If Your Code is a Mess 🗑️</h2>
<p>When you get stuck writing code, you might turn to AI. But let me tell you something: AI can’t save you if your code is a mess.</p>
<p>It’s like building a house on sand. Sure, it stands for a while, but one strong gust of wind or big wave, and it collapses.</p>
<p>Remember: AI is just a tool. If you don’t know how to write clean, scalable applications, you're setting yourself up for failure.</p>
<p>If you can’t maintain the code you write, you’re in trouble.</p>
<p>I’ve seen it over and over again: developers who know five programming languages. They can build apps, websites, software. They know algorithms and data structures like the back of their hand.</p>
<p>But when faced with a large project or someone else’s messy code, they crumble.</p>
<p>They’re like an aerospace engineer who designs and builds their own planes but doesn’t know how to fly them. They crash into their own code.</p>
<p>This was me...once upon a time. I’d write thousands of lines of code, only to realize I couldn’t even understand what I wrote last week. It was chaos for me.</p>
<p>But then it hit me — every developer struggles with this. It wasn't about how much I knew. It was about how I organized and structured what I knew. In other words, it was about knowing the art of programming itself.</p>
<p>I decided to escape this trap. After five months of intense work — four to five hours a day writing, designing, and researching — I created something I wish I had when I started programming. A book that’s a complete beginner’s guide: <strong>Clean Code Zero to One.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737731329839/c4c862d9-7fdc-460a-ae2e-18b19468b6ec.png" alt="cover image of clean code zero to one: from messy code to masterpiece" class="image--center mx-auto" width="1920" height="1080" loading="lazy"></p>
<p>If you want to learn more about the book, I give you all the details at the end of this tutorial. So read on to learn more about writing clean code.</p>
<h2 id="heading-12-clean-code-design-patterns-for-building-agile-applications">12 Clean Code Design Patterns for Building Agile Applications ⚖️</h2>
<p>If your code doesn’t follow these modern clean code design patterns, you could be creating a ticking time bomb. These patterns are your tools. Master them and enjoy the success of your projects. Let me show you one by one.</p>
<h3 id="heading-use-names-that-mean-something"><strong>🌿 Use Names That Mean Something</strong></h3>
<p>Naming your variables or functions b or x is not helpful. Call them what they are so they’re easier to understand. Here’s an example of both a bad and good variable name:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Weak and vague</span>
<span class="hljs-keyword">let</span> b = <span class="hljs-number">5</span>;

<span class="hljs-comment">// Strong and clear</span>
<span class="hljs-keyword">let</span> numberOfUsers = <span class="hljs-number">5</span>;
</code></pre>
<p>People who write unclear names don’t want to own their mistakes. Don’t be that person.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736165724746/37b2edc3-3c68-47a8-ab6f-f131a2239a01.png" alt="Comic showing a bad vs a good variable name, by Shahan" class="image--center mx-auto" width="2000" height="800" loading="lazy"></p>
<h3 id="heading-keep-functions-laser-focused-srp"><strong>🔨 Keep Functions Laser-Focused (SRP)</strong></h3>
<p>A function should do <strong>one thing</strong>—and do it perfectly. This is called the Single Responsibility Principle (<strong>SRP</strong>).</p>
<p>Good code is like a hammer. It hits one nail, not ten. For example, if you are hiring someone to do everything in your company — finance, sales, marketing, janitorial work, and so on — they’ll likely fail miserably because they can’t focus one one thing. The same goes for your classes in code.</p>
<p>🚧 When a class or function does more than one thing, it becomes a tangled mess. Debugging it feels like solving a puzzle upside down. If your class handles both user input and database operations, for example, it’s not multitasking — it’s madness. Break it up. One method, one job.</p>
<p><strong>🔥 My Rule:</strong> Your code works for you. Keep it sharp, focused, and controllable, or it’s going to control you. Here is how to make that happen:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Clean: One job, one focus</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotal</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logTotal</span>(<span class="hljs-params">user, total</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`User: <span class="hljs-subst">${user}</span>, Total: <span class="hljs-subst">${total}</span>`</span>);
}

<span class="hljs-comment">// Messy: Trying to do EVERYTHING</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateAndLogTotal</span>(<span class="hljs-params">a, b, user</span>) </span>{
    <span class="hljs-keyword">let</span> total = a + b;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`User: <span class="hljs-subst">${user}</span>, Total: <span class="hljs-subst">${total}</span>`</span>);
}
</code></pre>
<p>🪧 When you mix tasks, you mix in confusion. As simple as that.</p>
<h3 id="heading-use-comments-thoughtfully"><strong>🚪 Use Comments Thoughtfully</strong></h3>
<p>There is a great saying among professional developers:</p>
<blockquote>
<p>“ Code speaks for itself. ”</p>
</blockquote>
<p>You don’t explain what a door does every time someone walks into a room, do you? Your code should work the same way.</p>
<p>Comments aren’t bad, but if your code can’t stand on its own, then you may have a problem.</p>
<p>🪧 A good comment should tell “why” not “how or what”. If a developer doesn’t understand “how” something works, then they likely aren’t going to understand “why” either.</p>
<p>Here are some short examples of good comments vs bad comments. I’ll also show you a real-world project for writing clean comments.</p>
<p><strong>Example 1: Bad Comment 👎</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Multiply the price by the quantity to calculate the total</span>
<span class="hljs-keyword">const</span> total = price * quantity;
</code></pre>
<p>This is a <strong>bad comment</strong> because it simply repeats what the code already says. The code <code>price * quantity</code> is self-explanatory, so the comment doesn’t add anything useful.</p>
<p><strong>Good Comment: 👍</strong></p>
<p>If the code is clear and simple, <strong>you don’t need a comment.</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> total = price * quantity;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736165891398/6a942ad7-5b09-4990-9c7f-95358dafcbf3.png" alt="Image illustrating unnecessary comment vs &quot;silent comment&quot;, by Shahan" class="image--center mx-auto" width="2000" height="800" loading="lazy"></p>
<p><strong>Example 2: Bad Comment 👎</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Check if the user logged in</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isUserLoggedIn</span>(<span class="hljs-params">session</span>) </span>{
    <span class="hljs-keyword">return</span> !!session.user;
}
</code></pre>
<p>This comment is bad because it doesn’t explain why the <code>isUserLoggin()</code> exists. It just explains what happens. But we already know that this is an auth function. This comment is a waste of time.</p>
<p><strong>Good Example 👍</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// The user is authenticated before accessing protected resources</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isUserLoggedIn</span>(<span class="hljs-params">session</span>) </span>{
    <span class="hljs-keyword">return</span> !!session.user;
}
</code></pre>
<p>This is a <strong>good comment</strong> because it explains <strong>why</strong> the code exists. It tells us that the function checks if the user is authenticated before allowing access to sensitive parts of the app. It focuses on the bigger picture.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736166143011/b3ddae3d-41cf-4534-8f1a-af710579922c.png" alt="Before: &quot;Check if the user is logged in&quot;. After: &quot;The user is authenticated before accessing protected resources.&quot; By Shahan." class="image--center mx-auto" width="2000" height="800" loading="lazy"></p>
<h3 id="heading-best-practices-for-writing-good-comments"><strong>⚡ Best Practices for Writing Good Comments</strong></h3>
<ol>
<li><p><strong>Explain the “Why,” not the “What”:</strong><br> Write comments to explain the purpose or context of the code, not what the code is doing.</p>
</li>
<li><p><strong>Avoid obvious comments:</strong><br> Don’t write comments for things the code already makes clear.</p>
</li>
<li><p><strong>Keep them short and precise:</strong><br> Write concise comments that are easy to read and directly explain the purpose.</p>
</li>
<li><p><strong>Update comments regularly:</strong><br> Outdated comments can mislead developers, so always update them when the code changes.</p>
</li>
</ol>
<p><strong>Real-World Example (with Good Comments) 🛒</strong></p>
<p>Let’s implement these practices into a real-world project: a large e-commerce application. One function calculates shipping costs based on the order details. Here's the full code, I will explain each comment below:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Shipping rules:</span>
<span class="hljs-comment">// - Free shipping for orders over $100</span>
<span class="hljs-comment">// - Standard shipping ($10) for orders below $100</span>
<span class="hljs-comment">// - Additional $5 for international orders</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateShipping</span>(<span class="hljs-params">order</span>) </span>{
    <span class="hljs-keyword">let</span> shippingCost = <span class="hljs-number">0</span>;

    <span class="hljs-comment">// Check if the order qualifies for free shipping</span>
    <span class="hljs-keyword">if</span> (order.total &gt;= <span class="hljs-number">100</span>) {
        shippingCost = <span class="hljs-number">0</span>; <span class="hljs-comment">// Free shipping</span>
    } <span class="hljs-keyword">else</span> {
        shippingCost = <span class="hljs-number">10</span>; <span class="hljs-comment">// Standard shipping cost</span>
    }

    <span class="hljs-comment">// Add additional cost for international orders</span>
    <span class="hljs-keyword">if</span> (order.isInternational) {
        shippingCost += <span class="hljs-number">5</span>;
    }

    <span class="hljs-keyword">return</span> shippingCost;
}

<span class="hljs-comment">// Example usage</span>
<span class="hljs-keyword">const</span> order1 = { <span class="hljs-attr">total</span>: <span class="hljs-number">120</span>, <span class="hljs-attr">isInternational</span>: <span class="hljs-literal">false</span> };
<span class="hljs-keyword">const</span> order2 = { <span class="hljs-attr">total</span>: <span class="hljs-number">80</span>, <span class="hljs-attr">isInternational</span>: <span class="hljs-literal">true</span> };

<span class="hljs-built_in">console</span>.log(calculateShipping(order1)); <span class="hljs-comment">// Output: 0</span>
<span class="hljs-built_in">console</span>.log(calculateShipping(order2)); <span class="hljs-comment">// Output: 15</span>
</code></pre>
<p>At the start of the function, we include a comment explaining the rules for shipping costs. This gives the reader an overview of the logic without needing to read the full code.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Shipping rules:</span>
<span class="hljs-comment">// - Free shipping for orders over $100</span>
<span class="hljs-comment">// - Standard shipping ($10) for orders below $100</span>
<span class="hljs-comment">// - Additional $5 for international orders</span>
</code></pre>
<p>Then, the first condition checks if the order total is greater than or equal to $100. A comment here clarifies <strong>why</strong> free shipping is applied.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Check if the order qualifies for free shipping</span>
<span class="hljs-keyword">if</span> (order.total &gt;= <span class="hljs-number">100</span>) {
    shippingCost = <span class="hljs-number">0</span>; <span class="hljs-comment">// Free shipping</span>
}
</code></pre>
<p>The second condition applies an additional charge for international shipping. The comment explains <strong>why</strong> the extra cost is added.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Add additional cost for international orders</span>
<span class="hljs-keyword">if</span> (order.isInternational) {
    shippingCost += <span class="hljs-number">5</span>;
}
</code></pre>
<p><strong>Why are these comments good?</strong></p>
<p>Imagine you’re working in a team of 20 developers. Someone reads the <code>calculateShipping</code> function six months later. Without these comments, they might waste time guessing why international orders have an extra fee. Good comments clarify the why and save hours of frustration.</p>
<h3 id="heading-make-your-code-readable"><strong>🧩 Make Your Code Readable</strong></h3>
<p>If someone reading your code feels like they’re solving a riddle, you’ve already become a troublemaker. Here is the proof:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Clean: Reads like a story</span>
<span class="hljs-keyword">if</span> (isLoggedIn) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Welcome!"</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Please log in."</span>);
}

<span class="hljs-comment">// Messy: Feels like chaos</span>
<span class="hljs-keyword">if</span>(isLoggedIn){<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Welcome!"</span>);}<span class="hljs-keyword">else</span>{<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Please log in."</span>);}
</code></pre>
<p>If your code is messy and hard to read, it will confuse others—and even yourself later! Imagine coming back to your own code after six months and feeling like you’re reading a foreign language. Readable code saves time, reduces bugs, and makes everyone’s life easier.</p>
<p><strong>🍵 Why is Readability Important?</strong></p>
<ol>
<li><p><strong>For yourself:</strong> When you revisit your code after weeks or months, clean code helps you pick up where you left off without wasting time figuring out what you did.</p>
</li>
<li><p><strong>For your team:</strong> If someone else reads your code, they shouldn’t have to solve a puzzle. Clean code makes teamwork smoother and prevents miscommunication.</p>
</li>
<li><p><strong>Fewer bugs:</strong> Clear code is easier to debug because you can quickly spot mistakes.</p>
</li>
</ol>
<p><strong>🧙‍♂️ How to Write Readable Code</strong></p>
<p>Let’s build a simple program to manage books in a library. We’ll make it clean and readable and then I will break down this code below:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// A class to represent a book</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span> </span>{
    <span class="hljs-keyword">constructor</span>(title, author, isAvailable) {
        <span class="hljs-built_in">this</span>.title = title;
        <span class="hljs-built_in">this</span>.author = author;
        <span class="hljs-built_in">this</span>.isAvailable = isAvailable;
    }

    borrow() {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.isAvailable) {
            <span class="hljs-built_in">this</span>.isAvailable = <span class="hljs-literal">false</span>;
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`You borrowed "<span class="hljs-subst">${<span class="hljs-built_in">this</span>.title}</span>".`</span>);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Sorry, "<span class="hljs-subst">${<span class="hljs-built_in">this</span>.title}</span>" is not available.`</span>);
        }
    }

    returnBook() {
        <span class="hljs-built_in">this</span>.isAvailable = <span class="hljs-literal">true</span>;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`You returned "<span class="hljs-subst">${<span class="hljs-built_in">this</span>.title}</span>".`</span>);
    }
}

<span class="hljs-comment">// A function to display available books</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayAvailableBooks</span>(<span class="hljs-params">books</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Available books:"</span>);
    books.forEach(<span class="hljs-function">(<span class="hljs-params">book</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (book.isAvailable) {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`- <span class="hljs-subst">${book.title}</span> by <span class="hljs-subst">${book.author}</span>`</span>);
        }
    });
}

<span class="hljs-comment">// Example usage</span>
<span class="hljs-keyword">const</span> book1 = <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"The Clean Coder"</span>, <span class="hljs-string">"Robert Martin"</span>, <span class="hljs-literal">true</span>);
<span class="hljs-keyword">const</span> book2 = <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"You Don’t Know JS"</span>, <span class="hljs-string">"Kyle Simpson"</span>, <span class="hljs-literal">false</span>);
<span class="hljs-keyword">const</span> book3 = <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"Eloquent JavaScript"</span>, <span class="hljs-string">"Marijn Haverbeke"</span>, <span class="hljs-literal">true</span>);

<span class="hljs-keyword">const</span> library = [book1, book2, book3];

displayAvailableBooks(library); <span class="hljs-comment">// Show available books</span>
book1.borrow(); <span class="hljs-comment">// Borrow a book</span>
displayAvailableBooks(library); <span class="hljs-comment">// Show available books again</span>
book1.returnBook(); <span class="hljs-comment">// Return the book</span>
displayAvailableBooks(library); <span class="hljs-comment">// Final list</span>
</code></pre>
<p>We created a <code>Book</code> class to represent each book. It has properties like <code>title</code>, <code>author</code>, and <code>isAvailable</code> to track its status.</p>
<ul>
<li><p>The <code>borrow</code> method checks if the book is available. If yes, it marks it as unavailable and prints a message.</p>
</li>
<li><p>The <code>returnBook</code> method makes the book available again.</p>
</li>
<li><p>The <code>displayAvailableBooks</code> function loops through the library and prints only the books that are available.</p>
</li>
<li><p>We create three books (<code>book1</code>, <code>book2</code>, <code>book3</code>) and store them in a <code>library</code> array.</p>
</li>
<li><p>We borrow and return books, showing how the list of available books changes.</p>
</li>
</ul>
<p>As you can see, readable code is not just about style. It saves time, prevents bugs, and preserves your code as useful for years to come.</p>
<h3 id="heading-test-everything-you-write"><strong>🏌️ Test Everything You Write</strong></h3>
<p>If you don’t take the time to write tests, you shouldn’t be surprised if your code breaks. If you do want to write tests, follow this unit testing strategy to catch problems ahead.</p>
<p><strong>What Is Unit Testing?</strong></p>
<p>Concretely, unit testing checks individual parts of your code (like functions or classes) to ensure they work correctly. Just like checking each brick of your house for soundness before building the walls.</p>
<p>Let me give you an example of how unit testing works:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span> </span>{
    add(a, b) { <span class="hljs-keyword">return</span> a + b; }
    subtract(a, b) { <span class="hljs-keyword">return</span> a - b; }
}

<span class="hljs-comment">// Test it (Unit Test)</span>
<span class="hljs-keyword">const</span> calculator = <span class="hljs-keyword">new</span> Calculator();
<span class="hljs-built_in">console</span>.assert(calculator.add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) === <span class="hljs-number">5</span>, <span class="hljs-string">"Addition failed"</span>);
<span class="hljs-built_in">console</span>.assert(calculator.subtract(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>) === <span class="hljs-number">2</span>, <span class="hljs-string">"Subtraction failed"</span>);
</code></pre>
<p>Here’s what’s going on in this code:</p>
<p>First, we create the calculator class:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span> </span>{
    add(a, b) { <span class="hljs-keyword">return</span> a + b; }
    subtract(a, b) { <span class="hljs-keyword">return</span> a - b; }
}
</code></pre>
<p>The <code>Calculator</code> class has two methods: <code>add</code> and <code>subtract</code>.</p>
<ul>
<li><p><code>add(a, b)</code> takes two numbers and returns their sum.</p>
</li>
<li><p><code>subtract(a, b)</code> takes two numbers and returns their difference.</p>
</li>
</ul>
<p>Next, we set up the tests:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> calculator = <span class="hljs-keyword">new</span> Calculator();
</code></pre>
<p>Here, we’re creating an instance of the <code>Calculator</code> class to test its methods.</p>
<p>Then we write test cases:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.assert(calculator.add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) === <span class="hljs-number">5</span>, <span class="hljs-string">"Addition failed"</span>);
<span class="hljs-built_in">console</span>.assert(calculator.subtract(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>) === <span class="hljs-number">2</span>, <span class="hljs-string">"Subtraction failed"</span>);
</code></pre>
<p><code>console.assert(condition, message)</code> checks if the condition is <code>true</code>. If it’s <code>false</code>, the message ("Addition failed" or "Subtraction failed") is displayed in the console.</p>
<ul>
<li><p><strong>First test</strong>: <code>calculator.add(2, 3) === 5</code></p>
<ul>
<li><p>Calls the <code>add</code> method with <code>2</code> and <code>3</code>.</p>
</li>
<li><p>Checks if the result is <code>5</code>.</p>
</li>
</ul>
</li>
<li><p><strong>Second test</strong>: <code>calculator.subtract(5, 3) === 2</code></p>
<ul>
<li><p>Calls the <code>subtract</code> method with <code>5</code> and <code>3</code>.</p>
</li>
<li><p>Checks if the result is <code>2</code>.</p>
</li>
</ul>
</li>
</ul>
<p>So what happens if something breaks? It’s pretty simple to solve any issues that arise here. In this case, if the <code>add</code> or <code>subtract</code> method doesn’t work correctly, the test will fail. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.assert(calculator.add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) === <span class="hljs-number">6</span>, <span class="hljs-string">"Addition failed"</span>);
</code></pre>
<ul>
<li><p>The condition <code>calculator.add(2, 3) === 6</code> is <code>false</code>.</p>
</li>
<li><p>The console will display: <code>"Addition failed"</code>.</p>
</li>
</ul>
<p><strong>Real-World Example: Testing a Login System 👥</strong></p>
<p>Let’s test a simple login system to see how unit testing works in a real-world scenario.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Auth</span> </span>{
    login(username, password) {
        <span class="hljs-keyword">return</span> username === <span class="hljs-string">"admin"</span> &amp;&amp; password === <span class="hljs-string">"1234"</span>;
    }
}

<span class="hljs-comment">// Test the Auth class</span>
<span class="hljs-keyword">const</span> auth = <span class="hljs-keyword">new</span> Auth();
<span class="hljs-built_in">console</span>.assert(auth.login(<span class="hljs-string">"admin"</span>, <span class="hljs-string">"et5t45#@"</span>) === <span class="hljs-literal">true</span>, <span class="hljs-string">"Login failed for valid credentials"</span>);
<span class="hljs-built_in">console</span>.assert(auth.login(<span class="hljs-string">"user"</span>, <span class="hljs-string">"wrongpassword"</span>) === <span class="hljs-literal">false</span>, <span class="hljs-string">"Login succeeded for invalid credentials"</span>);
</code></pre>
<p>First, create the <code>Auth</code> class:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Auth</span> </span>{
    login(username, password) {
        <span class="hljs-keyword">return</span> username === <span class="hljs-string">"admin"</span> &amp;&amp; password === <span class="hljs-string">"1234"</span>;
    }
}
</code></pre>
<p>The <code>login</code> method checks if the username is <code>"admin"</code> and the password is <code>"1234"</code>. If both match, it returns <code>true</code> – otherwise, <code>false</code>.</p>
<p>Next, set up the tests:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> auth = <span class="hljs-keyword">new</span> Auth();
</code></pre>
<p>Create an instance of the <code>Auth</code> class. Then write the test cases:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.assert(auth.login(<span class="hljs-string">"admin"</span>, <span class="hljs-string">"1234"</span>) === <span class="hljs-literal">true</span>, <span class="hljs-string">"Login failed for valid credentials"</span>);
<span class="hljs-built_in">console</span>.assert(auth.login(<span class="hljs-string">"user"</span>, <span class="hljs-string">"wrongpassword"</span>) === <span class="hljs-literal">false</span>, <span class="hljs-string">"Login succeeded for invalid credentials"</span>);
</code></pre>
<ul>
<li><p><strong>First test</strong>: Checks if valid credentials (<code>"admin"</code>, <code>"1234"</code>) succeed. If not, <code>"Login failed for valid credentials"</code> is displayed.</p>
</li>
<li><p><strong>Second test</strong>: Checks if invalid credentials (<code>"user"</code>, <code>"wrongpassword"</code>) fail. If not, <code>"Login succeeded for invalid credentials"</code> is displayed.</p>
</li>
</ul>
<p><strong>🌱 Why testing results in clean code:</strong></p>
<ol>
<li><p>You naturally write smaller, more focused functions to make your code testable</p>
</li>
<li><p>Tests verify that your code behaves as expected under different conditions.</p>
</li>
<li><p>With tests in place, you can confidently update your code, knowing the tests will catch any mistakes.</p>
</li>
</ol>
<h3 id="heading-use-dependency-injection"><strong>💉 Use Dependency Injection</strong></h3>
<p>Hardcoding dependencies is like tattooing someone’s name on your forehead — it’s permanent, can be abrasive, and locks you in.</p>
<p>So, what does Dependency Injection do? It lets you manage your code's relationships by passing dependencies as arguments. It’s flexible, adaptable, and maintainable.</p>
<p>To demonstrate how it works, here I’m using the Nodemailer dependency for sending emails to users:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Dependency: Sending emails with Nodemailer</span>
<span class="hljs-keyword">const</span> nodemailer = <span class="hljs-built_in">require</span>(<span class="hljs-string">'nodemailer'</span>);
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendEmail</span>(<span class="hljs-params">to, subject, message</span>) </span>{
    <span class="hljs-keyword">const</span> transporter = nodemailer.createTransport({ <span class="hljs-comment">/* config */</span> });
    <span class="hljs-keyword">return</span> transporter.sendMail({ <span class="hljs-attr">from</span>: <span class="hljs-string">"programmingwithshahan@gmail.com"</span>, to, subject, <span class="hljs-attr">text</span>: message });
}
</code></pre>
<p>⚠️ To save yourself from risk, make sure to avoid <strong>hardcoding</strong> dependencies. Use abstraction or configuration files for secure maintenance.</p>
<p>This is just one example. As a developer, you may use hundreds of libraries or dependencies.</p>
<p>I’m not saying you shouldn’t rely on dependencies/libraries at all, as nowadays it is hard to avoid them. But you should be very careful before installing them in your coding projects.</p>
<p>You should check the security, performance, quality, or functionality of an organization's software systems. Because they sometimes contain risks that can ruin your entire project.</p>
<p>🚧 Always control your tools, don't let them control you.</p>
<h3 id="heading-clean-project-structures"><strong>📂 Clean Project Structures</strong></h3>
<p>A well-organized project is the difference between a <strong>trash heap</strong> and a high-end <strong>boutique</strong>.</p>
<p>Here is how each folder should be organized:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xwyg9iqqcybz21lsgxz.png" alt="Image of clean code project structure by shahan" width="1563" height="1250" loading="lazy"></p>
<p>If your codebase looks like a junk drawer, you’ve already caused trouble for your future self.</p>
<p>Let’s go through the clean project structure you can see above to better understand it:</p>
<p><strong>1.</strong> <code>myProjet/src</code></p>
<p>This is the main container for your entire application. Everything your app needs is stored inside this folder. It has subfolders to keep things tidy and managed in one place.</p>
<p><strong>2.</strong> <code>components</code></p>
<p>This is where you keep all the reusable pieces of your app. You can use these components in multiple places without building them again.</p>
<p><strong>3.</strong> <code>services</code></p>
<p>This is the "brain" of your app. It handles all the work behind the scenes for both the frontend and backend. <code>emailService.js</code>, <code>userService.js</code> and <code>productService.js</code> are some of the example files for your <code>services</code> folder.</p>
<p><strong>4.</strong> <code>utils</code></p>
<p>This contains all the small, handy tools you need to make your application run smoothly and make your life easier. For example, <code>formatedate.js</code>, <code>validateEmail.js</code> and <code>generateId.js</code> are some of the common utils files to make reusable pieces of components for your entire project.</p>
<h4 id="heading-5-tests"><strong>5.</strong> <code>tests</code></h4>
<p>Conventionally, test files are typically located <strong>outside</strong> the <code>src</code> folder, at the project root level. This keeps your production code (<code>src</code>) separate from your test code (<code>tests</code>), making it cleaner and easier to manage. Have a look:</p>
<pre><code class="lang-bash">myProject/
├── src/              <span class="hljs-comment"># Production code</span>
│   ├── components/
│   ├── services/
│   └── utils/
├── tests/            <span class="hljs-comment"># Test files</span>
│   ├── components/
│   ├── services/
│   └── utils/
├── package.json      <span class="hljs-comment"># Project configuration</span>
└── README.md         <span class="hljs-comment"># Documentation</span>
</code></pre>
<p>Some developers may prefer creating one testing file inside the <code>test</code> folder to test everything in one place. Unfortunately, it may feel clean at first, but as your project grows, you’ll have to find and search for specific code blocks. It’s ugly and can produce unexpected testing results. So breaking them into multiple testing files inside the <code>tests</code> folder is highly recommended.</p>
<p><strong>Real-world example 📧</strong></p>
<p>So let me create a clean, durable project structure for you to apply in any future projects you might work on. Needless to say, clean project structure is the foundation of building a maintainable project.</p>
<p>From our previous email sending application example, we will write a clean project structure for this app. We want to build an application that sends emails to users. Your clean project structure for this app should look like this:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6v6rlc5qiplgxz1h4dps.png" alt="Image of email app clean code project structure by shahan" width="1563" height="1250" loading="lazy"></p>
<p>As you can see, I packed every subfolder and file inside the <code>src</code> folder which is the main container of our application. Inside the <code>src</code> folder, we created <code>components</code>, <code>services</code>, <code>utiles</code>. Finally, we have a manageable <code>test</code> folder outside the <code>src</code> folder to test each component independently. This test folder has nothing to do with our production code that is located inside the <code>src</code> folder.</p>
<h3 id="heading-be-consistent-with-formatting"><strong>🤹‍♂️ Be Consistent with Formatting</strong></h3>
<p>Don’t write code like you’re 10 different people. Be consistent with your formatting.</p>
<p>Use tools like <a target="_blank" href="https://prettier.io/">Prettier</a> or <a target="_blank" href="https://eslint.org/">ESLint</a> to enforce a consistent style. If every file looks different, you’re creating chaos that no one wants to fix.</p>
<p>I would say that consistency in formatting is one of the most important aspects of writing clean code.</p>
<p>Have a look...</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/46zu4k5nnrkcdesgqrye.png" alt="Image of consistent formatting snippets from clean code zero to one book" width="1562" height="1875" loading="lazy"></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Always use 2 spaces for indentation</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateArea</span>(<span class="hljs-params">width, height</span>) </span>{
  <span class="hljs-keyword">if</span> (width &lt;= <span class="hljs-number">0</span> || height &lt;= <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Dimensions must be positive numbers."</span>);
  }
  <span class="hljs-keyword">return</span> width * height;
}

<span class="hljs-comment">// Add meaningful whitespace for readability</span>
<span class="hljs-keyword">const</span> rectangle = {
  <span class="hljs-attr">width</span>: <span class="hljs-number">10</span>,
  <span class="hljs-attr">height</span>: <span class="hljs-number">20</span>,
};

<span class="hljs-comment">// Clear separation of logic</span>
<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> area = calculateArea(rectangle.width, rectangle.height);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Area: <span class="hljs-subst">${area}</span>`</span>);
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-built_in">console</span>.error(error.message);
}
</code></pre>
<p>Let’s examine some of the aspects of this code that make it clean:</p>
<h4 id="heading-1-consistent-indentation">1️⃣ Consistent Indentation</h4>
<p>Why 2 or 4 spaces? It’s clean, minimal, and universally accepted in many JavaScript style guides. It doesn’t overwhelm the eyes, and the code structure stands out clearly. When you mix inconsistent indentation (2 spaces here, 4 spaces there), you confuse people—and confused people make mistakes.</p>
<h4 id="heading-2-meaningful-whitespace-giving-code-room-to-breathe">2️⃣ Meaningful Whitespace: Giving Code Room to Breathe</h4>
<p>That extra line break between the rectangle definition and the <code>try</code> block is like a pause in a sentence — it gives the reader time to process.</p>
<h4 id="heading-3-clear-separation-of-logic-modular-thinking">3️⃣ Clear Separation of Logic: Modular Thinking</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> area = calculateArea(rectangle.width, rectangle.height);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Area: <span class="hljs-subst">${area}</span>`</span>);
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-built_in">console</span>.error(error.message);
}
</code></pre>
<p>Look at how the logic is divided into clear sections:</p>
<ul>
<li><p>First, the calculation (<code>calculateArea</code> function).</p>
</li>
<li><p>Then, the output (<code>console.log</code>).</p>
</li>
<li><p>Finally, error handling (<code>catch</code> block).</p>
</li>
</ul>
<p>Each task has its own space and purpose.</p>
<h4 id="heading-4-readable-error-handling">4️⃣ Readable Error Handling</h4>
<p>When you throw errors or log messages, you format them cleanly. No vague or cryptic messages here. A developer seeing this will immediately know the problem.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Dimensions must be positive numbers."</span>);
</code></pre>
<p><strong>🐦‍⬛ General tips for consistent formatting:</strong></p>
<ul>
<li><p>Use 2 or 4 spaces for indentation consistently throughout your codebase. Avoid tabs to maintain uniformity across different editors.</p>
</li>
<li><p>Keep lines to a maximum of 100-120 characters to prevent horizontal scrolling and improve readability.</p>
</li>
<li><p>Group related logic together and separate blocks of code with blank lines to highlight their purpose.</p>
</li>
<li><p>Finally, avoid over-aligning code. Instead, let indentation naturally guide the flow of logic.</p>
</li>
</ul>
<h3 id="heading-stop-hardcoding-values"><strong>✋ Stop Hardcoding Values</strong></h3>
<p>Hardcoding values is a lazy way to code. Here is the proof:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Bad: Hardcoded and rigid</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createUser</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> maxUsers = <span class="hljs-number">100</span>;
    <span class="hljs-keyword">if</span> (currentUsers &gt;= maxUsers) <span class="hljs-keyword">throw</span> <span class="hljs-string">"Too many users!"</span>;
}

<span class="hljs-comment">// Clean: Dynamic and flexible</span>
<span class="hljs-keyword">const</span> MAX_USERS = <span class="hljs-number">100</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createUser</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">if</span> (currentUsers &gt;= MAX_USERS) <span class="hljs-keyword">throw</span> <span class="hljs-string">"Too many users!"</span>;
}
</code></pre>
<p>You see, changing this variable won’t surprise you in the future. You know exactly where to find it to change uncertain values.</p>
<p>Its best to store your fixed values in the global configuration (config) file.</p>
<p>🪧 So, avoid hardcoding values at all costs. Hardcoding is the shortcut that may drive your future self (or others) crazy.</p>
<h3 id="heading-keep-functions-short"><strong>🤏 Keep Functions Short</strong></h3>
<p>If your function is longer than 20 lines, it’s probably trying to do too much<em>.</em></p>
<p>Short functions are sharp functions. They hit their mark every time.</p>
<p>Long, bloated functions are messy and hard to read, but short functions are clear and focused. Here is how your large functions should break down:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateCart</span>(<span class="hljs-params">cart, item</span>) </span>{
    addItemToCart(cart, item);
    <span class="hljs-keyword">let</span> total = calculateTotal(cart);
    logTransaction(item, total);
    <span class="hljs-keyword">return</span> total;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addItemToCart</span>(<span class="hljs-params">cart, item</span>) </span>{
    cart.items.push(item);
}
</code></pre>
<p>Let me explain this code so you understand why breaking down large functions is a winning strategy.</p>
<ol>
<li><p><strong>The Main Function:</strong> <code>updateCart()</code> calls smaller helper functions to handle specific tasks like:</p>
<ul>
<li><p>Adds the item to the cart.</p>
</li>
<li><p>Calculates the total price.</p>
</li>
<li><p>Logs the details of the transaction.</p>
</li>
<li><p>Finally, it returns the total price.</p>
</li>
</ul>
</li>
</ol>
<p>Instead of one long block of code that tries to do everything, it delegates tasks to helper functions.</p>
<ol start="2">
<li><strong>Helper Function:</strong> <code>addItemToCart()</code> This function <strong>only</strong> handles adding the item to the cart. if you need to change how items are added (for example, checking for duplicates). You could just edit this small function instead of digging through a giant block of code in <code>updateCart</code>. That’s how you write clean code functions that’s a joy to read and easy to maintain.</li>
</ol>
<p><strong>What Happens If Functions Are Too Long? 💤</strong></p>
<p>Let’s say you didn’t break down the <code>updateCart</code> function. Here’s what it might look like:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateCart</span>(<span class="hljs-params">cart, item</span>) </span>{
    cart.items.push(item);
    <span class="hljs-keyword">let</span> total = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; cart.items.length; i++) {
        total += cart.items[i].price;
    }
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Added <span class="hljs-subst">${item.name}</span>. Total is now $<span class="hljs-subst">${total}</span>.`</span>);
    <span class="hljs-keyword">return</span> total;
}
</code></pre>
<p>What are the problems here?</p>
<ul>
<li><p>It’s trying to do everything.</p>
</li>
<li><p>It’s hard to read, especially if it grows bigger.</p>
</li>
<li><p>If something breaks, you’ll waste time figuring out which part is the problem.</p>
</li>
</ul>
<p>Now the choice is yours: stick with the messy all-in-one approach or practice the clean one function one job mindset.</p>
<h3 id="heading-follow-the-boy-scout-rule"><strong>⛺ Follow the Boy Scout Rule</strong></h3>
<blockquote>
<p>Always leave your campsite cleaner than you found it.</p>
</blockquote>
<p>Let me break it down for you. You don’t just use something and leave it worse than before. That’s inconsiderate behavior. Real professionals leave things better than they found them.</p>
<p>In coding terms, every time you touch the codebase, <strong>make it better.</strong> Clean it up, refactor messy parts, and improve readability. If you don’t, you’re just piling on garbage that will eventually collapse on your head.</p>
<p>Here is an example. Instead of improving it, we’re just adding more layers of complexity:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Original code: Hard to read, poorly named variables</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calc</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">let</span> x = a + b;
  <span class="hljs-keyword">let</span> y = x * <span class="hljs-number">0.2</span>;
  <span class="hljs-keyword">return</span> y;
}

<span class="hljs-comment">// We're adding to it but not cleaning it up</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calcDiscount</span>(<span class="hljs-params">a, b, discountRate</span>) </span>{
  <span class="hljs-keyword">let</span> total = calc(a, b);
  <span class="hljs-keyword">let</span> final = total - discountRate;
  <span class="hljs-keyword">return</span> final;
}
</code></pre>
<p>After: it gets better every time. Here’s how a disciplined coder works — they improve as they go:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Improved code: Clear names, refactored for clarity</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateSubtotal</span>(<span class="hljs-params">price, quantity</span>) </span>{
  <span class="hljs-keyword">return</span> price * quantity;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateDiscountedTotal</span>(<span class="hljs-params">price, quantity, discountRate</span>) </span>{
  <span class="hljs-keyword">const</span> subtotal = calculateSubtotal(price, quantity);
  <span class="hljs-keyword">const</span> discount = subtotal * discountRate;
  <span class="hljs-keyword">return</span> subtotal - discount;
}
</code></pre>
<p>Now, anyone can tell what’s happening at a glance. Because we’ve broken down the code into smaller, more focused functions. Thus, adding new features won’t break existing functionality. 🏕️</p>
<h3 id="heading-follow-the-openclosed-principle"><strong>🏟️ Follow the Open/Closed Principle</strong></h3>
<p>This design principle suggests your code should be designed to allow extensions without changing the existing foundation.</p>
<p>You want to add features <em>—</em> not rip it apart every time you upgrade<em>.</em> Modifying old code to fit new requirements is exactly like trying to rebuild your house every time you buy new furniture. It’s not sustainable.</p>
<p>Let’s see how you can build smarter, scalable code that lets you add features without breaking everything else.</p>
<h4 id="heading-before-violating-the-principle">Before: Violating the principle</h4>
<p>You’ve got a class to handle payments — simple enough. At first, it just handles credit cards.</p>
<p>But then your boss shows up and says, <em>“Hey, now we need PayPal support.”</em></p>
<p>And because you didn’t bother learning clean code, your code looks like a spaghetti monster straight out of a legacy enterprise system from 1995. Here’s the masterpiece you’ve crafted:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PaymentProcessor</span> </span>{
  processPayment(paymentType, amount) {
    <span class="hljs-keyword">if</span> (paymentType === <span class="hljs-string">"creditCard"</span>) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Processing credit card payment of $<span class="hljs-subst">${amount}</span>`</span>);
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (paymentType === <span class="hljs-string">"paypal"</span>) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Processing PayPal payment of $<span class="hljs-subst">${amount}</span>`</span>);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Unsupported payment type"</span>);
    }
  }
}

<span class="hljs-keyword">const</span> paymentProcessor = <span class="hljs-keyword">new</span> PaymentProcessor();
paymentProcessor.processPayment(<span class="hljs-string">"creditCard"</span>, <span class="hljs-number">100</span>);
paymentProcessor.processPayment(<span class="hljs-string">"paypal"</span>, <span class="hljs-number">200</span>);
</code></pre>
<p>Alas! Every new payment type (like Apple Pay, Google Pay, and so on) requires modifying the <code>processPayment</code> method. Needless to say, you risk breaking existing functionality while adding new features. If you had learned this principle, you might not be in this mess.</p>
<p>Don’t worry: I’ll help you to fix this. First, we need to refactor the code. Instead of modifying the existing class, we’ll extend its functionality using <a target="_blank" href="https://stackify.com/oop-concept-polymorphism/">polymorphism</a>:</p>
<pre><code class="lang-javascript">javascriptCopy code<span class="hljs-comment">// Base class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PaymentProcessor</span> </span>{
  processPayment(amount) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"processPayment() must be implemented"</span>);
  }
}

<span class="hljs-comment">// Credit card payment</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CreditCardPayment</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">PaymentProcessor</span> </span>{
  processPayment(amount) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Processing credit card payment of $<span class="hljs-subst">${amount}</span>`</span>);
  }
}

<span class="hljs-comment">// PayPal payment</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PayPalPayment</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">PaymentProcessor</span> </span>{
  processPayment(amount) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Processing PayPal payment of $<span class="hljs-subst">${amount}</span>`</span>);
  }
}

<span class="hljs-comment">// Adding a new payment type? Just extend the class!</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApplePayPayment</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">PaymentProcessor</span> </span>{
  processPayment(amount) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Processing Apple Pay payment of $<span class="hljs-subst">${amount}</span>`</span>);
  }
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> payments = [
  <span class="hljs-keyword">new</span> CreditCardPayment(),
  <span class="hljs-keyword">new</span> PayPalPayment(),
  <span class="hljs-keyword">new</span> ApplePayPayment(),
];

payments.forEach(<span class="hljs-function">(<span class="hljs-params">payment</span>) =&gt;</span> payment.processPayment(<span class="hljs-number">100</span>));
</code></pre>
<p>Now, adding new payment methods doesn’t require changing the existing <code>PaymentProcessor</code> class. You just created a new subclass. So the original code remains untouched, meaning there’s no risk of breaking existing features.</p>
<p>Each payment type has its own class, and adding PayPal payment support, for example, doesn’t break the code. Now you can reply to your boss: <em>“Of course, I will add this feature in 5 minutes.”</em> Your promotion is waiting for you to accept it.</p>
<p>I share even more tips in my book <a target="_blank" href="https://codewithshahan.gumroad.com/l/cleancode-zero-to-one">Clean Code Zero to One</a>.</p>
<h2 id="heading-modern-best-practices-to-help-you-write-clean-code-a-summary">Modern Best Practices to Help You Write Clean Code: A Summary 🥷</h2>
<p>Now let me show you the best practices and summarise our 12 Clean Code design principles to help you write clean code for agile application development.</p>
<h3 id="heading-common-code-smells-and-how-to-fix-them">🔎 Common Code Smells and How to Fix Them</h3>
<ul>
<li><p>💊 Duplication: If you're copying code, you’re creating more work for yourself. Extract it into a function, and do it right.</p>
</li>
<li><p>🛤️ Long methods: If your method needs a scroll bar, it's doing too much. Break it down, keep it focused.</p>
</li>
<li><p>👑 King objects: No class should be doing everything. Simplify responsibilities, or your codebase will become messy.</p>
</li>
</ul>
<h3 id="heading-effective-commenting-practices">💬 Effective Commenting Practices</h3>
<ul>
<li><p>💭 When to comment: Only comment if the code isn't clear. If it is, comments are just clutter.</p>
</li>
<li><p>🫗 Clarity: Comments should tell why, not what. If your code needs explaining, it might be too complex.</p>
</li>
<li><p>🌴 Avoid redundancy: Don't comment what's obvious. If your function is addNumbers, don't comment it does that.</p>
</li>
</ul>
<h3 id="heading-refactoring-techniques-for-clean-code">🧼 Refactoring Techniques for Clean Code</h3>
<ul>
<li><p>🏭 Extract methods: Big methods? Break them down. It's not just about cleanliness –– it's about control.</p>
</li>
<li><p>🫕Rename variables: If your variable names don’t shout their purpose, change and improve them. Precision in naming is precision in thought.</p>
</li>
<li><p>🍃 Simplify conditionals: If your conditionals look like algebra, simplify them. If a == true, just write if(a).</p>
</li>
</ul>
<h3 id="heading-testing-and-clean-code">🧪 Testing and Clean Code</h3>
<ul>
<li><p>🧙 Unit tests: Test every piece of code like you're interrogating a suspect. No stone unturned.</p>
</li>
<li><p>🏇TDD (Test Driven Development): Write tests first. It's not just about catching bugs, it's about knowing exactly what your code should do before you write it.</p>
</li>
<li><p>🧽 Clean tests: Your tests should be as clean as your code. If they're messy, they’re not going to be helpful.</p>
</li>
</ul>
<h3 id="heading-error-handling-and-clean-code">🐛 Error Handling and Clean Code</h3>
<ul>
<li><p>⁉️ Exceptions: Use them. They're not just for errors, they're also for keeping your code clean from error clutter.</p>
</li>
<li><p>🖍️ Fail fast: If something's wrong, stop right there. Don't let errors add up. Deal with them immediately.</p>
</li>
<li><p>🚨 Logging: Log like you're documenting a crime scene. Clear, precise, and only what's necessary.</p>
</li>
</ul>
<h3 id="heading-code-reviews-and-clean-code">🌱 Code Reviews and Clean Code</h3>
<ul>
<li><p>🚢 Process: Have a system. No cowboy coding. Review, critique, improve.</p>
</li>
<li><p>🔪 Tools: Use tools that make reviews easy. They're not just for catching mistakes, they're also for teaching discipline.</p>
</li>
<li><p>🧦 Culture: Cultivate a culture where feedback is gold. Help your team learn how to handle and receive critiques.</p>
</li>
</ul>
<h2 id="heading-automated-tools-for-maintaining-clean-code">Automated Tools for Maintaining Clean Code ⚓</h2>
<p>Tools and automation techniques can be really helpful in writing clean code. If you’re not using the right tools and automating things to save yourself time, you’re missing out.</p>
<p>You think you can "eyeball" your way through code quality? Guess again. Without automation, this is what happens:</p>
<ol>
<li><p>👎 You miss obvious mistakes because you're "too busy."</p>
</li>
<li><p>🤕 Your code looks different in every file, making collaboration a headache.</p>
</li>
<li><p>🪦 Deployment breaks because you skipped a critical test.</p>
</li>
</ol>
<p>Successful developers use the right tools to automate code and get things done. Here are four strategies for maintaining clean code using modern tools.</p>
<h3 id="heading-1-static-analysis"><strong>1️⃣ Static Analysis</strong></h3>
<p>Static analysis is actually a code inspector that reads through your code and points out potential issues early on. The best part? It works <strong>before</strong> runtime, catching errors that could otherwise lead to crashes, downtime, or embarrassing bugs.</p>
<h4 id="heading-how-does-it-work"><strong>How does it work?</strong></h4>
<ol>
<li><p><strong>Syntax checking</strong>: It looks at your code to analyze everything written in the correct syntax. If you misspell a variable or forget a closing bracket, it’ll call you out instantly.</p>
</li>
<li><p><strong>Code quality rules</strong>: Tools like ESLint enforce rules like consistent indentation, avoiding unused variables, and sticking to best practices.</p>
</li>
<li><p><strong>Error prevention</strong>: It identifies logic errors, such as using variables that haven’t been defined, or making comparisons that don’t make sense.</p>
</li>
</ol>
<p>Here’s how static analysis works in action:</p>
<h4 id="heading-before-static-analysis">🚨 Before static analysis:</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> sum = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> { <span class="hljs-keyword">return</span> a + b; }
<span class="hljs-built_in">console</span>.log(sume(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// Typo, unnoticed until runtime</span>
</code></pre>
<ul>
<li><strong>Problem</strong>: The typo in <code>sume</code> will only cause an error when the code runs, and that could lead to frustrating debugging sessions or worse — breaking the app in production.</li>
</ul>
<h4 id="heading-after-static-analysis-using-eslint">🚑 After static analysis (using ESLint):</h4>
<pre><code class="lang-javascript">codeError: <span class="hljs-string">'sume'</span> is not defined.
</code></pre>
<ul>
<li><strong>Solution</strong>: <a target="_blank" href="https://eslint.org/">ESLint</a> immediately flags the typo before you even run the code. The error is caught early, saving you time and headaches.</li>
</ul>
<h3 id="heading-2-automated-code-formatting"><strong>2️⃣ Automated Code Formatting</strong></h3>
<p>Before Formatting:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculate</span> (<span class="hljs-params"> x , y </span>)</span>{ <span class="hljs-keyword">return</span> x+ y;}
<span class="hljs-built_in">console</span>.log( calculate (<span class="hljs-number">2</span>,<span class="hljs-number">3</span> ) )
</code></pre>
<ul>
<li><strong>Problem</strong>: Inconsistent spacing and formatting make the code harder to read.</li>
</ul>
<h4 id="heading-after-using-prettier">After using Prettier:</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculate</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x + y;
}
<span class="hljs-built_in">console</span>.log(calculate(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>));
</code></pre>
<ul>
<li><strong>Solution</strong>: Clean, consistent, and professional formatting is applied automatically. No more nitpicking over spaces or alignment.</li>
</ul>
<p>Pretty basic stuff though. I covered this in case you write code in notepad or something where IDE is not provided (for example, a job interview).</p>
<h3 id="heading-3-continuous-integration-ci-testing"><strong>3️⃣ Continuous Integration (CI) Testing</strong></h3>
<p>CI testing make sure every new change to your code is verified automatically. It’s like a safety net that catches bugs introduced during development. CI tools run your tests every time you push code, so nothing breaks after deployment.</p>
<h4 id="heading-how-does-ci-testing-work"><strong>How Does CI Testing Work?</strong></h4>
<ol>
<li><p><strong>Triggers on change</strong>: Each time code is committed, the CI tool (like <a target="_blank" href="https://github.com/features/actions">GitHub Actions</a>, <a target="_blank" href="https://www.jenkins.io/">Jenkins</a>) runs automated tests.</p>
</li>
<li><p><strong>Feedback</strong>: It gives you instant feedback if something fails.</p>
</li>
<li><p><strong>Prevents broken code</strong>: Commits only clean, and the working code gets merged into the main branch.</p>
</li>
</ol>
<h3 id="heading-4-cicd-pipelines"><strong>4️⃣ CI/CD pipelines</strong></h3>
<p>We also use CI/CD pipelines as a continuous process that includes code building, testing, and deployment, while CI testing is a part of that process that focuses on automating the testing of code changes. </p>
<p><strong>Differece between CI/CD pipelines vs CI testing:</strong></p>
<ul>
<li><p><strong>CI/CD pipelines:</strong> A CI/CD pipeline combines code building, testing, and deployment into a single process. This process make sure that all changes to the main branch code are releasable to production. CI/CD pipelines can reduce deployment time, decrease costs, and improve team collaboration. </p>
</li>
<li><p><strong>CI testing:</strong> CI testing is the process of automatically testing code changes that are integrated into a central repository. CI testing focuses on making sure the codebase is stable and that integration issues are resolved. CI testing help developer build software that is stable, bug-free, and meets functional requirements</p>
</li>
</ul>
<p>🚧 This is what CI testing CI/CD pipelines concepts are really about. Not as complex as it seems. So let me elaborate more on CI testing with GitHub Actions, as we usually run tests through automated tools nowadays.</p>
<h3 id="heading-continuous-integration-ci-testing-with-github-actions"><strong>⚡ Continuous Integration (CI) Testing with GitHub Actions</strong></h3>
<p>As I said earlier, CI tools run automated tests every time you push code or open a pull request. This guarantees that only working, bug-free code gets merged into the main branch.</p>
<h4 id="heading-how-to-set-up-ci-testing-with-github-actions">How to Set Up CI Testing with GitHub Actions</h4>
<p><strong>Step 1: Create Your Repository</strong></p>
<p>Set up a GitHub repository for your project. Then, push your code to GitHub using the following commands:</p>
<pre><code class="lang-bash">git init
git add .
git commit -m <span class="hljs-string">"Initial commit for CI Testing"</span>
git branch -M main
git remote add origin https://github.com/codewithshahan/codewithshahan.git
git push -u origin main
</code></pre>
<p>Or you can create a new repo from your GitHub account without using the command. Just login to your GItHub account and visit dashboard. Here you will find a “New” button to create a brand new repo:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737618697327/dcef8be8-0d08-45d7-8000-34c4c65df425.png" alt="image of creating a new repo on github by Shahan" class="image--center mx-auto" width="1371" height="553" loading="lazy"></p>
<p><strong>Step 2: Add a GitHub Actions Workflow</strong></p>
<p>Navigate to your repository’s <strong>Actions</strong> tab. To do this, first, you have to visit your repo on Github (you will find the link after creating your repo). In this case, I created a new repo called “codewithshahan”. Here, look for the <strong>Actions</strong> tab on the right side of the navigation bar.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737618879398/7c5aa37a-72be-4701-a8f8-9ea9e05c0d5d.png" alt="Image of github actions navigation tab by shahan" class="image--center mx-auto" width="1885" height="724" loading="lazy"></p>
<p>After navigating the Actions tab, scroll down a little and you will find the <strong>continuous integration</strong> section:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737619002674/60003e57-f2b2-48f1-bef8-9bde39149faf.png" alt="Image of CI (Continuous Integration) testing on Github Actions Page by Shahan" class="image--center mx-auto" width="1496" height="508" loading="lazy"></p>
<p>Choose a setup workflow yourself. I will use Node.js for this project.</p>
<p>After clicking the configure button, a <code>node.js.yml</code> file will be created automatically, and you can adjust the code depending on your goals.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737619475568/74da6d46-c105-42c8-8662-fc72e9410bda.png" alt="Image of GitHub workflow snippet for automated testing by Shahan" class="image--center mx-auto" width="1879" height="854" loading="lazy"></p>
<p>I won’t go into detail about how should modify your <code>.yml</code> file. It depends on your project goals and personal preference. Also, it is a whole different broader topic and as this article has already become quite long, so I’ll explain it in a future article. For now, just stick with this foundational knowledge.</p>
<p>This CI Testing workflow is best for modern application development. Your app remains stable while incorporating key features including testing (e,g. Dark Mode), Building and deploying applications directly within your GitHub repository. This way, you can push your code confidently, knowing your code is always clean and ready for production.</p>
<h2 id="heading-the-role-of-documentation-in-agile-software-development">The Role of Documentation in Agile Software Development 🚣</h2>
<p>If you want your code to be top-notch, you need to understand how to write good documentation. If you think documentation is just about scribbling down how the code works, you’re wrong. It's about explaining <strong>why</strong> it works, not just how it works. That’s where most people miss the mark.</p>
<h3 id="heading-1-create-useful-docs-explain-why-not-just-how">1. 🚡 Create <strong>Useful Docs (Explain Why, Not Just How)</strong></h3>
<p>When you write documentation, you're not just throwing down some instructions for how to use the code. You're telling the next person (or even yourself in the future) why this piece of code exists in the first place. That’s the difference between good and bad documentation.</p>
<p>Bad docs leave people scratching their heads. They’re too vague, too simple, and they don’t answer the big questions. If your documentation is unclear, that likely means your thinking is unclear. You’re basically saying, <em>"I don’t care if you understand this, it works, just use it."</em> That’s not helpful.</p>
<p>Great documentation answers the tough questions:</p>
<ul>
<li><p>✅ Why did you choose this approach over another?</p>
</li>
<li><p>✅ Why does this function exist? What problem does it solve?</p>
</li>
<li><p>✅ Why did you write this code the way you did?</p>
</li>
</ul>
<p>If your docs are just regurgitating how to use the code, you’re not being as helpful as you can be. Start thinking deeper and explaining the reasoning behind everything.</p>
<h3 id="heading-2-keep-the-docs-updated-outdated-docs-are-worse-than-no-docs">2. ⏳ <strong>Keep the Docs Updated (Outdated Docs Are Worse Than No Docs)</strong></h3>
<p>Outdated documentation is the worst. In fact, it can be worse than having no docs at all. When you leave documentation that’s out of sync with the code, you’re doing your future self — or whoever has to deal with it next — a huge disservice.</p>
<p>Every time your code changes, your documentation needs to change too. It has to reflect the current state of things. Don’t mislead future developers (or yourself) by leaving outdated info that will only confuse them and waste their time. If something is no longer relevant, delete it. Outdated documentation is the equivalent of a cluttered mind — it holds you back.</p>
<p>Make it a habit to check and update your documentation regularly. The minute a line of code changes, so should your documentation. Period.</p>
<h3 id="heading-3-integrate-comments-good-comments-in-code-are-part-of-documentation">3. 🚆 <strong>Integrate Comments (Good Comments in Code Are Part of Documentation)</strong></h3>
<p>Here’s the deal — comments in your code should <strong>integrate</strong> with your documentation. Good comments aren’t just a crutch for developers who can’t explain their code elsewhere. They should improve your docs, not replace them.</p>
<p>Comments are supplements to your documentation. You write clean, understandable code that needs minimal explanation, but when something isn’t crystal clear, throw in a comment. Remember the rule for comments in your code: explain the <strong>why</strong>, not the <strong>how</strong>. It’s the same here. Don’t repeat yourself. Let your code do the talking. Comments should complement the bigger picture of your documentation, not act as a band-aid for sloppy code.</p>
<p>🪧 Great code should be self-explanatory. Fix the code, then add comments for clarification if necessary. Keep comments clean, short, and to the point.</p>
<p>If you want to write clean, efficient, and maintainable code, documentation is key. Stop thinking of docs as an afterthought or something you do to fill space. It’s an extension of your code — your way of communicating clearly and effectively. It’s your roadmap for future developers, and it’s a reflection of your thought process.</p>
<h2 id="heading-conclusion">Conclusion 🏁</h2>
<p>Clean code isn't a nice-to-have –– it's a must-have for those who aim to lead. It's about control, efficiency, and improvement over time in the long run. And ultimately, it’ll help you succeed in the game of agile software development.</p>
<p>🪧 If you want to truly master your craftsmanship, write clean code, and let the efficiency speak for itself.</p>
<h2 id="heading-frequently-asked-questions-about-clean-code">Frequently Asked Questions About Clean Code 🧯</h2>
<ol>
<li><p><strong>What is clean code?</strong> It's code that doesn't make you want to throw your laptop out the window.</p>
</li>
<li><p><strong>Why is clean code important in Agile?</strong> Because Agile is about speed and change, and you can't be quick with a mess.</p>
</li>
<li><p><strong>What are code smells?</strong> Signs that you're about to lose control of your codebase.</p>
</li>
<li><p><strong>How can I improve commenting?</strong> Only comment on what's necessary, and make sure each comment adds value, not noise.</p>
</li>
</ol>
<p>Thank you for being with me. You can visit my <a target="_blank" href="https://x.com/shahancd">Twitter account</a> or <a target="_blank" href="https://www.codewithshahan.com">my website</a> to read more posts about clean code and Agile application development. Until next time… keep improving your codebase.</p>
<p>If you’re serious about mastering clean code and taking your programming career to the next level, then my book is for you: <a target="_blank" href="https://codewithshahan.gumroad.com/l/cleancode-zero-to-one"><strong>Clean Code Zero to One</strong></a>. This book is your full guide from zero to one in clean code, from messy code to masterpiece. I am offering a 50% discount using the code "earlybird" — only for the first 50 copies. Plus, there’s a 30-day money-back guarantee — no risk, all reward.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Write Clean Code – Tips for Developers with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Imagine a messy room with clothes, books, and other items scattered everywhere. Finding something in that room would be tough, right? Now, think about writing messy code – it’s just as confusing, if not more! On the other hand, clean code is like an ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-write-clean-code-tips-for-developers/</link>
                <guid isPermaLink="false">672a51c02bb94277a075a484</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ clean code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming Blogs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Beginner Developers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Programming with Shahan ]]>
                </dc:creator>
                <pubDate>Tue, 05 Nov 2024 17:11:28 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730737606075/5cb4369b-9f2e-4f97-9765-ac00a62800c6.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Imagine a messy room with clothes, books, and other items scattered everywhere. Finding something in that room would be tough, right?</p>
<p>Now, think about writing messy code – it’s just as confusing, if not more!</p>
<p>On the other hand, clean code is like an organized room: you can easily find what you need, understand what’s happening, and get things done faster.</p>
<p>Let’s have a look at this graph. It shows two different ways of writing code and how they affect the time it takes to add more lines:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730728342241/3fa8f5a1-0af4-4ffd-aa3a-bb70001b026d.png" alt="3fa8f5a1-0af4-4ffd-aa3a-bb70001b026d" class="image--center mx-auto" width="604" height="340" loading="lazy"></p>
<ol>
<li><p>⚠️ <strong>Quick &amp; Dirty Code</strong> (Red line): This is when you write code quickly without planning or organizing it well. At first, it may seem faster, but as more lines are added, it becomes harder to understand and fix. So, over time, it takes longer and longer to add each new line.</p>
</li>
<li><p><strong>⚡ Thoughtful &amp; Clean Code</strong> (Blue line): This is when you write code carefully, making it easy to understand and change. At first, it might take a bit longer, but over time, it remains easy to work with. This way, adding new lines doesn't become more difficult.</p>
</li>
</ol>
<p>In simple terms, writing clean code might seem slower at the beginning, but in the long run, it saves a lot of time and makes work easier. It also leads to more reliable software and better products.</p>
<p>Writing clean code is a habit that professional developers cultivate, showing dedication to quality and a strong work ethic. And in this article, I’ll walk you through some best practices for keeping your code clean.</p>
<h3 id="heading-what-well-cover">What we’ll cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-1-use-meaningful-names">Use Meaningful Names</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-follow-the-single-responsibility-principle-srp">Follow the Single Responsibility Principle (SRP)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-avoid-unnecessary-comments">Avoid Unnecessary Comments</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-make-your-code-readable">Make Your Code Readable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-write-unit-tests">Write Unit Tests</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-6-be-careful-with-dependencies">Be Careful with Dependencies</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-7-organize-your-project">Organize Your Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-8-use-consistent-formatting">Use Consistent Formatting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-9-avoid-hardcoding-values">Avoid Hardcoding Values</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-10-limit-function-length">Limit Function Length</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-10-essential-tips-for-writing-clean-code">10 Essential Tips for Writing Clean Code</h2>
<p>To help you get started on your clean code journey, here are 10 practical tips to keep your code readable, organized, and efficient.</p>
<h3 id="heading-1-use-meaningful-names">1. Use Meaningful Names</h3>
<p>When naming variables, functions, and classes, pick names that clearly describe their purpose.</p>
<p>Instead of calling a variable <code>b</code>, try <code>numberOfUsers</code>. This way, anyone reading your code can easily understand its purpose without needing additional comments. A meaningful name eliminates guesswork and avoids confusion.</p>
<p><strong>Example</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Good</span>
<span class="hljs-keyword">let</span> numberOfUsers = <span class="hljs-number">5</span>; <span class="hljs-comment">// Clear and easy to understand</span>

<span class="hljs-comment">// Bad</span>
<span class="hljs-keyword">let</span> b = <span class="hljs-number">5</span>; <span class="hljs-comment">// Vague and unclear</span>
</code></pre>
<p><strong>💡 Naming Tips</strong></p>
<ul>
<li><p><strong>Variables</strong>: Use nouns that describe the data, like <code>userAge</code> or <code>totalAmount</code>.</p>
</li>
<li><p><strong>Functions</strong>: Use action words, like <code>calculateTotal()</code> or <code>fetchUserData()</code>.</p>
</li>
<li><p><strong>Classes</strong>: Use singular nouns, like <code>User</code> or <code>Order</code>, to represent what they are.</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// Variable: Describes the data it holds</span>
<span class="hljs-keyword">let</span> userAge = <span class="hljs-number">25</span>;

<span class="hljs-comment">// Function: Uses an action word to describe what it does</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotal</span>(<span class="hljs-params">price, quantity</span>) </span>{
    <span class="hljs-keyword">return</span> price * quantity;
}

<span class="hljs-comment">// Class: Singular noun representing a type of object</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    <span class="hljs-keyword">constructor</span>(name, age) {
        <span class="hljs-built_in">this</span>.name = name;
        <span class="hljs-built_in">this</span>.age = age;
    }
}
</code></pre>
<h3 id="heading-2-follow-the-single-responsibility-principle-srp">2. Follow the Single Responsibility Principle (SRP)</h3>
<p>The <strong>Single Responsibility Principle</strong> means that each function or method should have <strong>one specific job.</strong></p>
<p>This keeps your functions short and focused which makes them easier to read, test, and maintain.</p>
<p>Imagine a toolbox where each tool has a unique purpose—clean code functions should work the same way.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730728643183/77666f78-7ec9-4a5c-af4f-253e6de4acac.jpeg" alt="77666f78-7ec9-4a5c-af4f-253e6de4acac" class="image--center mx-auto" width="474" height="355" loading="lazy"></p>
<p>For instance, if you have a function called <code>calculateTotal</code>, it should only handle calculating the total. If you add extra tasks, it can lead to confusing code that’s hard to maintain.</p>
<p>Here's an example to show why it's important to keep functions focused:</p>
<p>Let’s say you want to calculate a total and return an object with extra information, like who calculated it and when. Instead of adding these directly into <code>calculateTotal</code>, we can use a second function.</p>
<ol>
<li><p><strong>Good Example (Separate Tasks)</strong></p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// This function only calculates the total</span>
 <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotal</span>(<span class="hljs-params">a, b</span>) </span>{
     <span class="hljs-keyword">return</span> a + b;
 }

 <span class="hljs-comment">// This function creates an object with extra details</span>
 <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createCalculationRecord</span>(<span class="hljs-params">a, b, user</span>) </span>{
     <span class="hljs-keyword">let</span> sum = calculateTotal(a, b); <span class="hljs-comment">// Calls the calculate function</span>
     <span class="hljs-keyword">return</span> {
         <span class="hljs-attr">user</span>: user,
         <span class="hljs-attr">total</span>: sum,
         <span class="hljs-attr">timestamp</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>()
     };
 }

 <span class="hljs-keyword">let</span> record = createCalculationRecord(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>, <span class="hljs-string">"Shahan"</span>);
 <span class="hljs-built_in">console</span>.log(record);
</code></pre>
<p> <strong>👍 Why this is good</strong>: Each function has a clear, focused task. <code>calculateTotal</code> only does the math, while <code>createCalculationRecord</code> adds the extra details. If you want to change how the total is calculated, you only update <code>calculateTotal</code>, and if you want to change the record format, you only update <code>createCalculationRecord</code>.</p>
</li>
<li><p><strong>Bad Example (Mixed Tasks in One Function)</strong></p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// This function calculates the total and creates an object in one step</span>
 <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotalAndReturnRecord</span>(<span class="hljs-params">a, b, user</span>) </span>{
     <span class="hljs-keyword">let</span> sum = a + b;
     <span class="hljs-keyword">return</span> {
         <span class="hljs-attr">user</span>: user,
         <span class="hljs-attr">total</span>: sum,
         <span class="hljs-attr">timestamp</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>()
     };
 }

 <span class="hljs-keyword">let</span> record = calculateTotalAndReturnRecord(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>, <span class="hljs-string">"Shahan"</span>);
 <span class="hljs-built_in">console</span>.log(record);
</code></pre>
<p> <strong>👎 Why this is bad</strong>: The function name <code>calculateTotalAndReturnRecord</code> shows that it’s trying to do multiple things. If you want to use just the calculation, you can’t reuse this function without the record part. It’s also harder to update and test each task separately.</p>
</li>
</ol>
<h3 id="heading-3-avoid-unnecessary-comments">3. Avoid Unnecessary Comments</h3>
<p>Good code should be self-explanatory without needing excessive comments. Focus on writing code that’s clear and understandable on its own.</p>
<p>Comments are helpful when explaining complex logic or a unique approach, but too many comments can clutter your code and make it hard to follow.</p>
<p><strong>💬 When to Use Comments</strong>:</p>
<ul>
<li><p>To clarify why something is done in a particular way.</p>
</li>
<li><p>When working with complex algorithms or calculations.</p>
</li>
<li><p>To add notes about potential limitations.</p>
</li>
</ul>
<p><strong>Example</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Clear name, no comment needed</span>
<span class="hljs-keyword">let</span> userAge = <span class="hljs-number">25</span>;

<span class="hljs-comment">// Unclear name, comment needed</span>
<span class="hljs-keyword">let</span> a; <span class="hljs-comment">// age of the user</span>
</code></pre>
<h3 id="heading-4-make-your-code-readable">4. Make Your Code Readable</h3>
<p>Readable code uses <strong>indentation</strong>, <strong>line breaks</strong>, and <strong>spaces</strong> to keep everything neat and organized.</p>
<p>Think of it like writing a story: paragraphs make reading easier by breaking up large chunks of text. In coding, line breaks serve the same purpose.</p>
<p><strong>Example</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Good Code</span>
<span class="hljs-keyword">if</span> (isLoggedIn) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Welcome!"</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Please log in."</span>);
}

<span class="hljs-comment">// Bad Code</span>
<span class="hljs-keyword">if</span>(isLoggedIn){<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Welcome!"</span>);}<span class="hljs-keyword">else</span>{<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Please log in."</span>);}
</code></pre>
<p>In VS Code, <strong>Prettier</strong> and <strong>Black</strong> are popular formatters that automatically apply clean code styling for multiple languages.</p>
<p><strong>PyCharm</strong> and <strong>IntelliJ</strong> have powerful built-in formatters with customizable rules, supporting PEP 8 for Python and other standard guides. These tools ensure consistent, readable code across projects with minimal manual effort.</p>
<h3 id="heading-5-write-unit-tests">5. Write Unit Tests</h3>
<p>Unit tests help make sure each part of your code works as expected.</p>
<p>By testing small, individual parts (like functions), you can catch bugs early and prevent them from spreading to other parts of the code.</p>
<p>Concretely, unit tests are actually mini quality checks for each part of your code to ensure they’re working as intended.</p>
<p><strong>🍎 Real-world Example:</strong></p>
<p>Let’s look at how to test a complex JavaScript object with multiple methods, using a <code>Calculator</code> class as an example.</p>
<p>This approach will help you see why it’s important to keep each method focused on one task and ensure each one works correctly through unit testing.</p>
<p>Here is the <code>Calculator</code> class that includes methods for basic arithmetic operations: addition, subtraction, multiplication, and division.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">this</span>.result = <span class="hljs-number">0</span>;
    }

    add(a, b) {
        <span class="hljs-keyword">return</span> a + b;
    }

    subtract(a, b) {
        <span class="hljs-keyword">return</span> a - b;
    }

    multiply(a, b) {
        <span class="hljs-keyword">return</span> a * b;
    }

    divide(a, b) {
        <span class="hljs-keyword">if</span> (b === <span class="hljs-number">0</span>) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Cannot divide by zero"</span>);
        <span class="hljs-keyword">return</span> a / b;
    }
}
</code></pre>
<p>As you can see, each method performs one specific operation. The <code>divide</code> method has additional logic to handle division by zero, which would otherwise cause an error.</p>
<p>Now, we’ll write unit tests to confirm that each method behaves as expected. 🔬</p>
<p><strong>🧪 Writing Unit Tests for Each Method</strong></p>
<p>To test our <code>Calculator</code> class, we can write unit tests that cover normal cases as well as edge cases. Here’s how we would set up tests for each method:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Initialize the Calculator instance</span>
<span class="hljs-keyword">const</span> calculator = <span class="hljs-keyword">new</span> Calculator();

<span class="hljs-comment">// Test add method</span>
<span class="hljs-built_in">console</span>.assert(calculator.add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) === <span class="hljs-number">5</span>, <span class="hljs-string">'Test failed: 2 + 3 should be 5'</span>);
<span class="hljs-built_in">console</span>.assert(calculator.add(<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>) === <span class="hljs-number">0</span>, <span class="hljs-string">'Test failed: -1 + 1 should be 0'</span>);

<span class="hljs-comment">// Test subtract method</span>
<span class="hljs-built_in">console</span>.assert(calculator.subtract(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>) === <span class="hljs-number">2</span>, <span class="hljs-string">'Test failed: 5 - 3 should be 2'</span>);
<span class="hljs-built_in">console</span>.assert(calculator.subtract(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>) === <span class="hljs-number">0</span>, <span class="hljs-string">'Test failed: 0 - 0 should be 0'</span>);

<span class="hljs-comment">// Test multiply method</span>
<span class="hljs-built_in">console</span>.assert(calculator.multiply(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) === <span class="hljs-number">6</span>, <span class="hljs-string">'Test failed: 2 * 3 should be 6'</span>);
<span class="hljs-built_in">console</span>.assert(calculator.multiply(<span class="hljs-number">-1</span>, <span class="hljs-number">2</span>) === <span class="hljs-number">-2</span>, <span class="hljs-string">'Test failed: -1 * 2 should be -2'</span>);

<span class="hljs-comment">// Test divide method</span>
<span class="hljs-built_in">console</span>.assert(calculator.divide(<span class="hljs-number">6</span>, <span class="hljs-number">3</span>) === <span class="hljs-number">2</span>, <span class="hljs-string">'Test failed: 6 / 3 should be 2'</span>);
<span class="hljs-keyword">try</span> {
    calculator.divide(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>);
    <span class="hljs-built_in">console</span>.assert(<span class="hljs-literal">false</span>, <span class="hljs-string">'Test failed: Division by zero should throw an error'</span>);
} <span class="hljs-keyword">catch</span> (e) {
    <span class="hljs-built_in">console</span>.assert(e.message === <span class="hljs-string">"Cannot divide by zero"</span>, <span class="hljs-string">'Test failed: Incorrect error message for division by zero'</span>);
}
</code></pre>
<p><strong>🫧 Explanation of the tests:</strong></p>
<ol>
<li><p><strong>Addition</strong> (<code>add</code> method): We test that <code>add(2, 3)</code> returns <code>5</code>, and <code>add(-1, 1)</code> returns <code>0</code>. If these tests pass, we know that the addition logic is working correctly.</p>
</li>
<li><p><strong>Subtraction</strong> (<code>subtract</code> method): We verify that <code>subtract(5, 3)</code> returns <code>2</code>, and <code>subtract(0, 0)</code> returns <code>0</code>. These checks confirm that subtraction is accurate.</p>
</li>
<li><p><strong>Multiplication</strong> (<code>multiply</code> method): We test the multiplication function with both positive and negative values, ensuring that <code>multiply(2, 3)</code> returns <code>6</code>, and <code>multiply(-1, 2)</code> returns <code>-2</code>.</p>
</li>
<li><p><strong>Division</strong> (<code>divide</code> method): We verify that dividing <code>6</code> by <code>3</code> returns <code>2</code>. For division by zero, we use a <code>try...catch</code> block to confirm that an error is thrown with the correct message. This test make sure the method handles errors properly.</p>
</li>
</ol>
<p>You can see that if any method fails, the test will produce a clear error message, allowing us to quickly identify and fix the issue. Testing methods individually helps us catch bugs early and maintain reliable, clean code as the project grows.</p>
<h3 id="heading-6-be-careful-with-dependencies">6. Be Careful with Dependencies</h3>
<p>Dependencies are pieces of software that your code relies on. 🔌</p>
<p>Imagine you’re building a web app that sends emails. Instead of writing the email-sending code yourself, you use an external library like <a target="_blank" href="https://nodemailer.com/"><strong>Nodemailer</strong></a>. Here, Nodemailer is a <strong>dependency</strong>—your app relies on it to handle the email-sending functionality.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> nodemailer = <span class="hljs-built_in">require</span>(<span class="hljs-string">'nodemailer'</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendEmail</span>(<span class="hljs-params">to, subject, message</span>) </span>{
    <span class="hljs-keyword">const</span> transporter = nodemailer.createTransport({
        <span class="hljs-attr">service</span>: <span class="hljs-string">'gmail'</span>,
        <span class="hljs-attr">auth</span>: {
            <span class="hljs-attr">user</span>: <span class="hljs-string">'your-email@gmail.com'</span>,
            <span class="hljs-attr">pass</span>: <span class="hljs-string">'your-email-password'</span>
        }
    });

    <span class="hljs-keyword">const</span> mailOptions = {
        <span class="hljs-attr">from</span>: <span class="hljs-string">'your-email@gmail.com'</span>,
        <span class="hljs-attr">to</span>: to,
        <span class="hljs-attr">subject</span>: subject,
        <span class="hljs-attr">text</span>: message
    };

    <span class="hljs-keyword">return</span> transporter.sendMail(mailOptions);
}
</code></pre>
<p>In this code, <code>nodemailer</code> is imported and used to create a transporter for sending emails. Without it, you’d need to build all the email functionality from scratch, which would be complex and time-consuming. By using Nodemailer as a dependency, your app can send emails easily.</p>
<p>Even though dependencies are useful, you should try to avoid over-dependence on external software or libraries. Use dependencies only when they simplify your work or add important functionality.</p>
<p>Managing dependencies effectively is key to writing clean code. Here are some tips:</p>
<ul>
<li><p><strong>Limit Dependencies</strong>: Only include libraries or modules that are essential for your project.</p>
</li>
<li><p><strong>Keep Versions Updated</strong>: Use updated versions of libraries to avoid security risks.</p>
</li>
<li><p><strong>Separate Logic</strong>: Write core functions yourself whenever possible. This way, if you ever need to remove a dependency, it won’t break your code.</p>
</li>
</ul>
<p>Let me give you an example with our previous Nodemailer code to implement the concept of separating logic in your code.</p>
<p>You can create a wrapper function that abstracts away the details of email sending. This way, you can change the underlying email service or remove the dependency on Nodemailer without affecting the rest of your code.</p>
<p>Here's how you can structure your code to accomplish this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> nodemailer = <span class="hljs-built_in">require</span>(<span class="hljs-string">'nodemailer'</span>);

<span class="hljs-comment">// Core function to send email</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendEmail</span>(<span class="hljs-params">to, subject, message</span>) </span>{
    <span class="hljs-keyword">const</span> transporter = createTransporter();
    <span class="hljs-keyword">const</span> mailOptions = createMailOptions(to, subject, message);
    <span class="hljs-keyword">return</span> transporter.sendMail(mailOptions);
}

<span class="hljs-comment">// Function to create the transporter</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createTransporter</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> nodemailer.createTransport({
        <span class="hljs-attr">service</span>: <span class="hljs-string">'gmail'</span>,
        <span class="hljs-attr">auth</span>: {
            <span class="hljs-attr">user</span>: <span class="hljs-string">'your-email@gmail.com'</span>,
            <span class="hljs-attr">pass</span>: <span class="hljs-string">'your-email-password'</span>
        }
    });
}

<span class="hljs-comment">// Function to create mail options</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createMailOptions</span>(<span class="hljs-params">to, subject, message</span>) </span>{
    <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">from</span>: <span class="hljs-string">'your-email@gmail.com'</span>,
        <span class="hljs-attr">to</span>: to,
        <span class="hljs-attr">subject</span>: subject,
        <span class="hljs-attr">text</span>: message
    };
}

<span class="hljs-comment">// Example usage</span>
sendEmail(<span class="hljs-string">'recipient@example.com'</span>, <span class="hljs-string">'Test Subject'</span>, <span class="hljs-string">'Hello, this is a test email.'</span>)
    .then(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Email sent successfully!'</span>);
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error sending email:'</span>, error);
    });
</code></pre>
<p><strong>🗝️ Key points:</strong></p>
<ol>
<li><p><strong>Core Functions</strong>: The <code>sendEmail</code>, <code>createTransporter</code>, and <code>createMailOptions</code> functions are separate, allowing you to modify one without affecting the others.</p>
</li>
<li><p><strong>Easy Modifications</strong>: If you want to switch to another email service in the future, you can simply modify the <code>createTransporter</code> function.</p>
</li>
<li><p><strong>Maintainability</strong>: This structure makes your code more maintainable and easier to understand.</p>
</li>
</ol>
<h3 id="heading-7-organize-your-project">7. Organize Your Project</h3>
<p>A well-organized project structure is as important as the code itself.</p>
<p>Think of this like organizing your workspace—you need designated places for everything so that you can find them easily. For coding projects, create folders for specific parts, like <code>components</code>, <code>utils</code>, and <code>services</code>.</p>
<p><strong>📂 How to Organize Your Project</strong></p>
<p>To set up a clean and organized project, you should categorize different parts of your code into designated folders. Here’s a simple example of what a well-organized project structure might look like:</p>
<pre><code class="lang-yaml"><span class="hljs-string">myProject</span>
<span class="hljs-string">├──</span> <span class="hljs-string">src</span>
<span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">components</span>
<span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">services</span>
<span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">utils</span>
<span class="hljs-string">└──</span> <span class="hljs-string">tests</span>
</code></pre>
<h4 id="heading-breakdown-of-the-project-structure">Breakdown of the project structure:</h4>
<ol>
<li><p><strong>myProject</strong>: This is the root folder of your project. It contains everything related to your application.</p>
</li>
<li><p><strong>src (Source)</strong>: This folder holds all the source code for your project. It’s where you’ll spend most of your time coding.</p>
</li>
<li><p><strong>components</strong>: This subfolder contains reusable UI components. For example, if you're building a web app, you might have individual files for buttons, headers, or forms here. Each component can be in its own file to keep things modular.</p>
<ul>
<li>Example structure within <code>components</code>:</li>
</ul>
</li>
</ol>
<pre><code class="lang-yaml">    <span class="hljs-string">components</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">Button.js</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">Header.js</span>
    <span class="hljs-string">└──</span> <span class="hljs-string">Form.js</span>
</code></pre>
<ol start="4">
<li><p><strong>services</strong>: This folder includes functions that perform specific tasks or handle business logic. For example, if you're sending emails, you could have a file here with all the email-related functions.</p>
<ul>
<li>Example structure within <code>services</code>:</li>
</ul>
</li>
</ol>
<pre><code class="lang-yaml">    <span class="hljs-string">services</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">emailService.js</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">userService.js</span>
    <span class="hljs-string">└──</span> <span class="hljs-string">productService.js</span>
</code></pre>
<ol start="5">
<li><p><strong>utils (Utilities)</strong>: Here, you place helper functions that can be used across your project. These might include functions for formatting dates, validating inputs, or any other common tasks that don't belong to specific components or services.</p>
<ul>
<li>Example structure within <code>utils</code>:</li>
</ul>
</li>
</ol>
<pre><code class="lang-yaml">    <span class="hljs-string">utils</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">formatDate.js</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">validateEmail.js</span>
    <span class="hljs-string">└──</span> <span class="hljs-string">generateId.js</span>
</code></pre>
<ol start="6">
<li><p><strong>tests</strong>: This folder is dedicated to your testing files. Keeping your tests organized helps ensure that as you build new features, you can easily test them without digging through your codebase.</p>
<ul>
<li>Example structure within <code>tests</code>:</li>
</ul>
</li>
</ol>
<pre><code class="lang-yaml">    <span class="hljs-string">tests</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">emailService.test.js</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">userService.test.js</span>
    <span class="hljs-string">└──</span> <span class="hljs-string">component.test.js</span>
</code></pre>
<p><strong>📨 Real-World Example: Working with Nodemailer</strong></p>
<p>Let's say you are building an application that sends emails to users. You might structure your project like this:</p>
<pre><code class="lang-yaml"><span class="hljs-string">myEmailApp</span>
<span class="hljs-string">├──</span> <span class="hljs-string">src</span>
<span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">components</span>
<span class="hljs-string">│</span>   <span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">EmailForm.js</span>
<span class="hljs-string">│</span>   <span class="hljs-string">│</span>   <span class="hljs-string">└──</span> <span class="hljs-string">SuccessMessage.js</span>
<span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">services</span>
<span class="hljs-string">│</span>   <span class="hljs-string">│</span>   <span class="hljs-string">└──</span> <span class="hljs-string">emailService.js</span>
<span class="hljs-string">│</span>   <span class="hljs-string">├──</span> <span class="hljs-string">utils</span>
<span class="hljs-string">│</span>   <span class="hljs-string">│</span>   <span class="hljs-string">└──</span> <span class="hljs-string">validateEmail.js</span>
<span class="hljs-string">└──</span> <span class="hljs-string">tests</span>
    <span class="hljs-string">├──</span> <span class="hljs-string">emailService.test.js</span>
    <span class="hljs-string">└──</span> <span class="hljs-string">EmailForm.test.js</span>
</code></pre>
<ul>
<li><p><strong>EmailForm.js</strong>: This component handles the user interface for sending an email, like the input fields for the recipient, subject, and message.</p>
</li>
<li><p><strong>SuccessMessage.js</strong>: This component displays a success message once the email has been sent.</p>
</li>
<li><p><strong>emailService.js</strong>: This service contains the logic for sending emails using Nodemailer, keeping your code modular and clean.</p>
</li>
<li><p><strong>validateEmail.js</strong>: A utility function that checks if an email address is formatted correctly.</p>
</li>
<li><p><strong>tests</strong>: Here, you would write tests to ensure your email service and components are functioning as expected.</p>
</li>
</ul>
<p><strong>🍱 Benefits of a Well-Organized Project</strong></p>
<ol>
<li><p><strong>Ease of Navigation</strong>: Anyone looking at your project can quickly understand where to find specific parts of the code.</p>
</li>
<li><p><strong>Better Collaboration</strong>: If you’re working with others, a clear structure helps everyone know where to contribute without stepping on each other’s toes.</p>
</li>
<li><p><strong>Scalability</strong>: As your project grows, maintaining a clear structure helps manage the complexity and keeps your codebase clean.</p>
</li>
<li><p><strong>Improved Maintenance</strong>: When you need to update or fix something, you can find the relevant files quickly, which saves time and reduces errors.</p>
</li>
</ol>
<h3 id="heading-8-use-consistent-formatting"><strong>8. Use Consistent Formatting</strong></h3>
<p>Consistency in formatting improves readability.</p>
<p>Establish a pattern for how you write your code, such as using two spaces for indentation or always including a line break before comments.</p>
<p>Following consistent formatting makes your code look clean and well-organized.</p>
<p><strong>🛠️ Tools for Formatting</strong></p>
<ul>
<li><p><a target="_blank" href="https://prettier.io/"><strong>Prettier</strong></a>: Automatically formats code based on a set of rules. <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-prettier-in-visual-studio-code/">Here’s a tutorial</a> that explains how to set up and use Prettier in VSCode.</p>
</li>
<li><p><a target="_blank" href="https://eslint.org/"><strong>ESLint</strong></a>: Helps enforce coding standards by highlighting issues. <a target="_blank" href="https://www.freecodecamp.org/news/how-to-set-up-eslint-prettier-stylelint-and-lint-staged-in-nextjs/#heading-set-up-eslint">Here’s a tutorial</a> that includes a helpful and in-depth section on setting up ESLint for your projects.</p>
</li>
</ul>
<h3 id="heading-9-avoid-hardcoding-values">9. Avoid Hardcoding Values</h3>
<p>Hardcoding is directly embedding data values in code, like setting a user ID as <code>123</code> instead of using a variable.</p>
<p>Avoiding hardcoded values allows you to reuse code without making constant changes. Store values in variables, constants, or configuration files instead.</p>
<p>Here’s a scenario where hardcoding can lead to issues:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Bad: Hardcoding user limit</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createUser</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-keyword">let</span> numberOfUsers = <span class="hljs-number">100</span>; <span class="hljs-comment">// Hardcoded value</span>
    <span class="hljs-keyword">if</span> (numberOfUsers &gt;= <span class="hljs-number">100</span>) {
        <span class="hljs-keyword">return</span> <span class="hljs-string">'User limit reached.'</span>;
    }
    <span class="hljs-comment">// Code to create the user</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">'User created.'</span>;
}
</code></pre>
<p>In this example, <code>numberOfUsers</code> is hardcoded to <code>100</code>. If you want to change the user limit, you have to find and modify this value in the code. If it appears in multiple places, this task becomes cumbersome and error-prone.</p>
<h4 id="heading-improved-example-using-constants"><strong>🏗️ Improved Example Using Constants</strong></h4>
<p>Now, let’s refactor this code to use a constant instead:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Good: Using a constant</span>
<span class="hljs-keyword">const</span> MAX_USERS = <span class="hljs-number">100</span>; <span class="hljs-comment">// Store the limit in a constant</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createUser</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-keyword">let</span> numberOfUsers = getCurrentUserCount(); <span class="hljs-comment">// Get the current count from a function or database</span>
    <span class="hljs-keyword">if</span> (numberOfUsers &gt;= MAX_USERS) {
        <span class="hljs-keyword">return</span> <span class="hljs-string">'User limit reached.'</span>;
    }
    <span class="hljs-comment">// Code to create the user</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">'User created.'</span>;
}

<span class="hljs-comment">// Example function to get current user count</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCurrentUserCount</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Simulate fetching the current count, e.g., from a database</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">90</span>; <span class="hljs-comment">// Example count</span>
}
</code></pre>
<p><strong>🥣 Breakdown of the improved example:</strong></p>
<ol>
<li><p><strong>Using Constants</strong>: The <code>MAX_USERS</code> constant is defined at the top. This way, if you ever need to change the maximum number of users, you only have to update it in one place.</p>
</li>
<li><p><strong>Dynamic Values</strong>: The <code>getCurrentUserCount()</code> function dynamically retrieves the current user count from a database or any other source. This approach prevents hardcoding the count and allows for easy changes.</p>
</li>
<li><p><strong>Maintainability</strong>: By storing values in constants, your code becomes more maintainable. If the business requirement changes and you need to increase the user limit to <code>150</code>, you can simply change <code>MAX_USERS</code> from <code>100</code> to <code>150</code>, and the change will reflect throughout your application.</p>
</li>
<li><p><strong>Clarity</strong>: Using descriptive names for your constants (like <code>MAX_USERS</code>) improves the readability of your code. Anyone looking at your code can quickly understand what this value represents.</p>
</li>
</ol>
<p><strong>🤐 When to Use Configuration Files</strong></p>
<p>In larger applications, you might also consider using configuration files (like JSON, YAML, or environment variables) to store values that may change between environments (development, staging, production).</p>
<p>For instance in your <strong>config.json</strong> file you can hardcode <code>maxUsers</code> as follows (keep in mind that in config.json, its recommended to use camelCase as it follows consistent formatting):</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"maxUsers"</span>: <span class="hljs-number">100</span>,
    <span class="hljs-attr">"emailService"</span>: {
        <span class="hljs-attr">"service"</span>: <span class="hljs-string">"gmail"</span>,
        <span class="hljs-attr">"user"</span>: <span class="hljs-string">"your-email@gmail.com"</span>,
        <span class="hljs-attr">"pass"</span>: <span class="hljs-string">"your-email-password"</span>
    }
}
</code></pre>
<p><strong>🪴 Using Configuration in Your Code:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> config = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./config.json'</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createUser</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-keyword">let</span> numberOfUsers = getCurrentUserCount(); 
    <span class="hljs-keyword">if</span> (numberOfUsers &gt;= config.maxUsers) {
        <span class="hljs-keyword">return</span> <span class="hljs-string">'User limit reached.'</span>;
    }
    <span class="hljs-comment">// Code to create the user</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">'User created.'</span>;
}
</code></pre>
<h3 id="heading-10-limit-function-length">10. Limit Function Length</h3>
<p>Long functions are harder to understand and maintain.</p>
<p>There’s no strict rule, but in general, functions should ideally be no more than 20-30 lines. If a function has multiple responsibilities or contains many steps, that’s a good indication it might be too long. Breaking down these functions into smaller "helper" functions can make them more manageable and understandable.</p>
<p>Here’s what a long, complex function might look like:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateCart</span>(<span class="hljs-params">cart, item, discountCode</span>) </span>{
    <span class="hljs-comment">// Add the item to the cart</span>
    cart.items.push(item);

    <span class="hljs-comment">// Calculate the new total</span>
    <span class="hljs-keyword">let</span> total = <span class="hljs-number">0</span>;
    cart.items.forEach(<span class="hljs-function"><span class="hljs-params">cartItem</span> =&gt;</span> {
        total += cartItem.price * cartItem.quantity;
    });

    <span class="hljs-comment">// Apply discount if available</span>
    <span class="hljs-keyword">if</span> (discountCode) {
        total = applyDiscount(total, discountCode);
    }

    <span class="hljs-comment">// Log the transaction</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Item added: <span class="hljs-subst">${item.name}</span>, New total: $<span class="hljs-subst">${total}</span>`</span>);

    <span class="hljs-keyword">return</span> total;
}
</code></pre>
<p>⚠️ <strong>This function does multiple things:</strong></p>
<ol>
<li><p>Adds an item to the cart.</p>
</li>
<li><p>Calculates the total price.</p>
</li>
<li><p>Applies a discount if there’s a code.</p>
</li>
<li><p>Logs the transaction.</p>
</li>
</ol>
<p>While this function might look manageable now, it can quickly grow if more tasks are added, making it harder to debug and maintain.</p>
<p>Let’s break this long function into smaller, single-purpose functions:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateCart</span>(<span class="hljs-params">cart, item, discountCode</span>) </span>{
    addItemToCart(cart, item);
    <span class="hljs-keyword">let</span> total = calculateTotal(cart);

    <span class="hljs-keyword">if</span> (discountCode) {
        total = applyDiscount(total, discountCode);
    }

    logTransaction(item, total);
    <span class="hljs-keyword">return</span> total;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addItemToCart</span>(<span class="hljs-params">cart, item</span>) </span>{
    cart.items.push(item);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotal</span>(<span class="hljs-params">cart</span>) </span>{
    <span class="hljs-keyword">return</span> cart.items.reduce(<span class="hljs-function">(<span class="hljs-params">total, cartItem</span>) =&gt;</span> total + cartItem.price * cartItem.quantity, <span class="hljs-number">0</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logTransaction</span>(<span class="hljs-params">item, total</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Item added: <span class="hljs-subst">${item.name}</span>, New total: $<span class="hljs-subst">${total}</span>`</span>);
}
</code></pre>
<h4 id="heading-let-me-explain">🧩 Let me explain:</h4>
<ol>
<li><p><code>addItemToCart</code>: This function is now responsible only for adding an item to the cart. It’s simple, with a clear purpose.</p>
</li>
<li><p><code>calculateTotal</code>: This function calculates the total price of all items in the cart. It’s easier to read and understand, and if you need to update the way totals are calculated, you only have to modify this function.</p>
</li>
<li><p><code>logTransaction</code>: Handles the responsibility of logging details. If you ever need to change what gets logged (for example, adding a timestamp), you can do so in this function without touching the rest of the code.</p>
</li>
<li><p><code>updateCart</code>: The main function now reads more like a summary of the actions being taken: add an item, calculate the total, apply discounts, and log the result. It’s easier to follow and understand at a glance.</p>
</li>
</ol>
<p><strong>📒 Let’s summarize limiting function length:</strong></p>
<ol>
<li><p><strong>🎯 Focus on One Task</strong>: Each function should ideally perform just one task. If a function seems to be doing multiple tasks, consider breaking it up.</p>
</li>
<li><p><strong>🩼 Use Helper Functions</strong>: Helper functions are small, focused functions that assist a main function by performing a specific task. In the example above, <code>addItemToCart</code>, <code>calculateTotal</code>, and <code>logTransaction</code> are helper functions.</p>
</li>
<li><p><strong>🪦 Descriptive Names</strong>: Name your functions based on their tasks (for example, <code>addItemToCart</code>), which helps make the code self-explanatory.</p>
</li>
</ol>
<h2 id="heading-best-practices-for-clean-code">Best Practices for Clean Code</h2>
<p>Now that we’ve covered some important tips, let’s look at some overarching principles that make up the philosophy behind clean code:</p>
<ol>
<li><p><strong>🎏 Simplicity</strong>: Always aim to make your code as simple as possible.</p>
</li>
<li><p><strong>🧂 Consistency</strong>: Keep your code uniform in style and structure.</p>
</li>
<li><p><strong>🌾 Clarity</strong>: Your code should clearly communicate what it does.</p>
</li>
<li><p><strong>⛽ Efficiency</strong>: Write code that’s optimized for performance without sacrificing readability.</p>
</li>
</ol>
<p>These principles make coding less about writing and more about designing solutions. Writing clean code is a skill that grows with practice, so keep learning and improving over time.</p>
<p><strong>🔌 A Note on Dependencies</strong></p>
<p>Instead of hardcoding dependencies directly into your code, use package managers like <a target="_blank" href="https://www.npmjs.com/"><strong>npm</strong></a> (for JavaScript) or <strong>pip</strong> (for Python) to manage them. This way, you can easily update or remove them when needed.</p>
<h2 id="heading-conclusion">Conclusion 🏁</h2>
<p>Writing clean code is like building a strong foundation for a house. It keeps everything in order, making it easy to add new features or fix issues as your project grows.</p>
<p>With these tips, you can start developing habits that will make your code more readable, maintainable, and enjoyable to work on.</p>
<h3 id="heading-recommended-next-steps">Recommended Next Steps 📘</h3>
<p>For a structured guide to becoming a backend developer in six months, you can check out my <a target="_blank" href="https://codewithshahan.gumroad.com/l/pcela">backend developer roadmap</a>. It’s designed to help beginners stay on track with weekly goals, covering the essential skills, tools, and technologies. This roadmap can keep you motivated and make learning more manageable.</p>
<p><strong>You can follow me on</strong> <a target="_blank" href="https://x.com/shahancd"><strong>𝕏</strong></a> <strong>for instant updates.</strong></p>
<p>Hope to see you next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Skills You Need to Become a Backend Developer – A Roadmap for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ In this guide, I'll discuss the basic skills you need and steps you can take to become a backend developer. I'll give you a simple roadmap that'll help you know where you are and where you should go next. Front End vs Back End Every website has two p... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/skills-you-need-to-become-a-backend-developer-roadmap/</link>
                <guid isPermaLink="false">66d71f6c2567a1ecb3ff38c6</guid>
                
                    <category>
                        <![CDATA[ backend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Programming with Shahan ]]>
                </dc:creator>
                <pubDate>Tue, 03 Sep 2024 14:38:36 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725110852270/9185d74e-4b0f-482f-8cc2-abbfc70a5849.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this guide, I'll discuss the basic skills you need and steps you can take to become a backend developer.</p>
<p>I'll give you a simple roadmap that'll help you know where you are and where you should go next.</p>
<h2 id="heading-front-end-vs-back-end">Front End vs Back End</h2>
<p>Every website has two parts: a <strong>front end</strong> and a <strong>back end</strong>.</p>
<p>The front end is the part that you see in the browser and interact with. Basically, it represents all the visual aspects of a website.</p>
<p>The back end is the part that powers the front end. It's <em>behind the scenes</em>, and it's mainly concerned with storing and accessing data using databases, APIs, and so on.</p>
<p>Because of this, web development jobs fall into three main categories:</p>
<ul>
<li><p>👨‍💻 Front-end development</p>
</li>
<li><p>🛟 Back-end development</p>
</li>
<li><p>🚢 Full-stack development (involves both front-end and back-end development)</p>
</li>
</ul>
<h2 id="heading-what-exactly-does-a-backend-developer-do">👷‍♂️What Exactly Does a Backend Developer Do?</h2>
<p>Backend developers are responsible for constructing the foundational systems that drive the functionality of applications that users engage with.</p>
<p>This includes various tasks such as designing the architecture, and then implementing and maintaining these critical systems.</p>
<p>Their responsibilities typically involve working with:</p>
<ul>
<li><p>💾 Databases, such as MySQL,</p>
</li>
<li><p>✂️ Frameworks, like Laravel or Ruby on Rails, and</p>
</li>
<li><p>🧨 APIs (Application Programming Interfaces).</p>
</li>
</ul>
<p>Backend devs ensure that the backend infrastructure operates seamlessly, enabling smooth interactions between the user interface and the underlying data and processes.</p>
<p>Here are some of the core responsibilities of a backend developer:</p>
<ul>
<li><p>Understanding the website's performance needs and goals</p>
</li>
<li><p>Developing and managing APIs for the website</p>
</li>
<li><p>Developing systems for secure data storage and processing (especially special use cases like payments)</p>
</li>
<li><p>Writing code, testing it, maintaining it, and developing solutions to bugs</p>
</li>
<li><p>Designing the site's architecture using established methodologies like Agile/Scrum and various frameworks</p>
</li>
<li><p>Organizing the system logic effectively</p>
</li>
<li><p>Providing solutions to address system-related issues and challenges</p>
</li>
</ul>
<h2 id="heading-what-you-need-to-know-to-become-a-backend-developer">🥷 What You Need to Know to Become a Backend Developer</h2>
<p>Becoming a proficient backend developer requires mastering various skills and technologies.</p>
<p>Below, I've outline a comprehensive roadmap to help you achieve this goal as quickly as possible.</p>
<p>Just keep in mind that everyone learns at a different pace, so it's hard to set a specific timeframe on how long this will take. Some might be able to get through it in six months or less, but others might take significantly more time.</p>
<h3 id="heading-step-1-foundations-of-backend-development"><strong>Step 1: Foundations of Backend Development 🏗️</strong></h3>
<ul>
<li><p>Understand the role and responsibilities of a back-end developer. Familiarize yourself with databases, frameworks, and APIs.</p>
</li>
<li><p>Join a <a target="_blank" href="https://www.freecodecamp.org/news/learn-sql-free-relational-database-courses-for-beginners/">comprehensive course on databases</a>. Learn about SQL and relational databases like <a target="_blank" href="https://www.freecodecamp.org/news/learn-mysql-beginners-course/">MySQL</a>. Practice creating and managing databases.</p>
</li>
<li><p>Learn about server-side programming languages. Start with <a target="_blank" href="https://www.freecodecamp.org/news/the-php-handbook/">PHP</a> or <a target="_blank" href="https://www.freecodecamp.org/news/python-back-end-development-the-beginners-guide/">Python</a>. Learn basic syntax, control structures, and data types.</p>
</li>
</ul>
<h3 id="heading-step-2-advanced-backend-concepts"><strong>Step 2: Advanced Backend Concepts 🔋</strong></h3>
<ul>
<li><p>Deepen your understanding of databases. Explore <a target="_blank" href="https://www.freecodecamp.org/news/learn-nosql-in-3-hours/">NoSQL databases</a> like <a target="_blank" href="https://www.freecodecamp.org/news/crud-api-with-node-js-express-mongodb/">MongoDB</a>. Learn about data modeling and optimization.</p>
</li>
<li><p>Master server-side programming languages. Dig deeper into PHP or Python. Learn about functions, classes, and <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-oop-in-python/">object-oriented programming</a>.</p>
</li>
<li><p>Get hands-on projects with frameworks. Choose a popular framework like <a target="_blank" href="https://www.freecodecamp.org/news/build-a-google-drive-clone-with-laravel-php-vuejs/">Laravel</a> for PHP or <a target="_blank" href="https://www.freecodecamp.org/news/django-for-everybody-learn-the-popular-python-framework-from-dr-chuck/">Django</a> for Python. Build simple applications to understand the <a target="_blank" href="https://www.freecodecamp.org/news/model-view-architecture/">model-view-controller (MVC) architecture</a>.</p>
</li>
</ul>
<h3 id="heading-step-3-api-development-and-integration"><strong>Step 3: API Development and Integration 🛠️</strong></h3>
<ul>
<li><p>Learn about APIs and their importance in backend development. Explore <a target="_blank" href="https://www.freecodecamp.org/news/rest-api-design-best-practices-build-a-rest-api/">RESTful API design principles</a>.</p>
</li>
<li><p>Start building your own APIs. Use tools like <code>Postman</code> to <a target="_blank" href="https://www.freecodecamp.org/news/master-api-testing-with-postman/">test and debug API endpoints</a>. Learn about different <a target="_blank" href="https://www.freecodecamp.org/news/php-jwt-authentication-implementation/">authentication</a> <a target="_blank" href="https://www.freecodecamp.org/news/set-up-github-oauth-on-django-for-user-authentication/">methods</a> as well as <a target="_blank" href="https://www.freecodecamp.org/news/how-to-build-a-secure-django-web-app/">security</a>.</p>
</li>
<li><p>Focus on API integration. Learn how to consume APIs in web and mobile applications. Practice integrating third-party APIs into your projects.</p>
</li>
</ul>
<h3 id="heading-step-4-troubleshooting-and-optimization"><strong>Step 4: Troubleshooting and Optimization 🔮</strong></h3>
<ul>
<li>Master troubleshooting techniques. Learn how to diagnose and <a target="_blank" href="https://www.freecodecamp.org/news/python-debugging-handbook/">debug</a> backend applications effectively.</li>
</ul>
<ul>
<li><p>Jump into performance optimization techniques. Learn about <a target="_blank" href="https://www.freecodecamp.org/news/next-js-performance-optimization/">lazy loading</a>, <a target="_blank" href="https://www.freecodecamp.org/news/caching-vs-content-delivery-network/">caching</a>, <a target="_blank" href="https://www.freecodecamp.org/news/auto-scaling-and-load-balancing/">load balancing</a>, and <a target="_blank" href="https://www.freecodecamp.org/news/postgresql-indexing-strategies/">database indexing</a>.</p>
</li>
<li><p>Learn <a target="_blank" href="https://www.freecodecamp.org/news/how-to-set-up-monitoring-for-nodejs-applications-using-elastic/">monitoring</a> and analytics tools. Use tools like <a target="_blank" href="https://newrelic.com/">New Relic</a> or <a target="_blank" href="https://www.datadoghq.com/">Datadog</a> to monitor application performance. Learn how to generate and <strong>analyze</strong> performance metrics.</p>
</li>
</ul>
<h3 id="heading-step-5-cloud-infrastructure-and-deployment"><strong>Step 5: Cloud Infrastructure and Deployment 🌥️</strong></h3>
<ul>
<li><p>Understand <a target="_blank" href="https://www.freecodecamp.org/news/what-is-cloud-computing/">cloud computing</a> concepts. Learn about popular cloud providers like <a target="_blank" href="https://www.freecodecamp.org/news/free-107-hour-aws-cloud-project-bootcamp/">AWS</a> or <a target="_blank" href="https://www.freecodecamp.org/news/master-the-azure-devops-engineer-expert-certification-az-400/">Azure</a>.</p>
</li>
<li><p>Take a course on cloud services for backend development. Learn about <a target="_blank" href="https://www.freecodecamp.org/news/serverless-architecture-patterns-and-best-practices/">serverless computing</a>, <a target="_blank" href="https://www.freecodecamp.org/news/how-docker-containers-work/">containerization</a>, and <a target="_blank" href="https://www.freecodecamp.org/news/microservices-and-software-system-design-course/">microservices</a>.</p>
</li>
<li><p>Practice <a target="_blank" href="https://www.freecodecamp.org/news/how-to-deploy-node-js-app-on-azure/">deploying applications to the cloud</a>. Learn about <a target="_blank" href="https://www.freecodecamp.org/news/what-is-ci-cd/">CI/CD pipelines</a> and automated deployment strategies.</p>
</li>
</ul>
<h3 id="heading-step-6-advanced-topics-and-projects"><strong>Step 6: Advanced Topics and Projects 🚀</strong></h3>
<ul>
<li><p>Now you're ready to learn more advanced backend topics. Choose topics like <a target="_blank" href="https://www.freecodecamp.org/news/how-to-implement-message-queues-in-your-backend-applications/">message queues</a>, <a target="_blank" href="https://www.freecodecamp.org/news/implement-event-driven-architecture-with-react-and-fastapi/">event-driven architecture</a>, and <a target="_blank" href="https://www.freecodecamp.org/news/laravel-reverb-realtime-chat-app/">real-time communication</a>.</p>
</li>
<li><p>Work on a <a target="_blank" href="https://www.freecodecamp.org/news/backend-web-development-three-projects/"><strong>capstone project</strong></a>. Choose a challenging project that integrates various backend technologies and concepts.</p>
</li>
<li><p>Finally, reflect on your learning journey. Review your projects and identify areas for improvement. Prepare for job interviews by practicing <a target="_blank" href="https://www.freecodecamp.org/news/the-most-popular-coding-challenge-websites/"><strong>coding challenges</strong></a>.</p>
</li>
</ul>
<h2 id="heading-back-end-development-tools-and-software">Back-end Development Tools and Software</h2>
<p>Here's a breakdown of the tools and software commonly used in back-end development:</p>
<h3 id="heading-1-database-frameworks"><strong>1. Database Frameworks:</strong></h3>
<ul>
<li><p><strong>MySQL:</strong> A relational database management system used for storing and retrieving data. It's widely used for web applications and offers scalability and reliability.</p>
</li>
<li><p><strong>MongoDB:</strong> A NoSQL database program that uses JSON-like documents with schema flexibility. It's suitable for applications with rapidly changing data models or unstructured data.</p>
</li>
</ul>
<h3 id="heading-2-web-servers"><strong>2. Web Servers:</strong></h3>
<ul>
<li><p><strong>Node.js</strong>: Node.js is a cross-platform (meaning it supports multiple operating systems) JavaScript Runtime Environment that uses an event-driven, non-blocking I/O model. That means it can handle a large number of users at the same time. If you already know JavaScript, Node.js will likely be your best choice for building real-time applications like chat apps, online gaming apps, and collaborative tools.</p>
</li>
<li><p><strong>Apache HTTP Server 2:</strong> An open-source web server software that delivers web content across the internet. It's known for its stability, security, and flexibility, making it a popular choice for hosting websites and web applications.</p>
<p>  If your team is used to using languages like PHP or Python, Apache might be easier for them to work with.</p>
</li>
<li><p><strong>LiteSpeed</strong>: LiteSpeed is another web server software that helps websites handle lots of visitors without slowing down or crashing. It’s great for businesses that expect a lot of traffic, like during busy times. LiteSpeed also works with many programming languages like Python, Ruby, PHP, and Java.</p>
</li>
</ul>
<p>Imagine you're a company with 20 servers that can each handle 500 websites. Together, that’s 10,000 websites. But if you switch to LiteSpeed, you might be able to handle 20,000 websites with the same number of servers. That’s a big improvement!</p>
<p>When choosing a web server, it depends on what kind of website or app you’re building. If you’re just starting out, try Node.js first. It’s simple because you only need to learn one language (JavaScript) to build both the front part and the back part of your website.</p>
<h3 id="heading-3-security-protocolshttpswwwtheknowledgeacademycomblogwhat-is-apache"><a target="_blank" href="https://www.theknowledgeacademy.com/blog/what-is-apache/"><strong>3. Security Protocols:</strong></a></h3>
<ul>
<li><a target="_blank" href="https://www.theknowledgeacademy.com/blog/what-is-apache/"><strong>SSL/TLS Certificates:</strong> These are cryptographic protocols that provide secure commun</a>ication over a computer network. SSL (Secure Sockets Layer) and its successor TLS (Transport Layer Security) encrypt data between the server and client, ensuring confidentiality and integrity in online connections.</li>
</ul>
<h3 id="heading-4-version-control-system"><strong>4. Version Control System:</strong></h3>
<p>Next on your journey is to become familiar with version control systems. These systems help track project history and enable collaborative work with others.</p>
<ul>
<li>🔌 <a target="_blank" href="https://www.freecodecamp.org/news/gitting-things-done-book/">Learn Git</a>: Git is the most widely used version control system, employed by over 70% of software development teams. It's a must-know tool, and allocating around two weeks for learning Git is advisable.</li>
</ul>
<p>Back-end developers usually utilize these tools and software to build robust, scalable, and secure web applications that handle data storage, server hosting, and encryption of online communications.</p>
<p>If you seek more knowledge regarding backend development, you can check out this <a target="_blank" href="https://roadmap.sh/backend">in-depth visual guide to backend development</a>.</p>
<h3 id="heading-printable-roadmap">✅ Printable Roadmap</h3>
<p>You can also use this printable Backend Developer Notion template to track your progress.</p>
<p>Beginner developers often struggle with choosing the right tech stack which leads them to waste their time and often lose motivation.</p>
<p>To help you out, I created this easy-to-follow <a target="_blank" href="https://codewithshahan.gumroad.com/l/pcela">6-month backend developer roadmap</a> in Notion so that you can track your progress and stick with your goals in real-time.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j23rj7fwvut4fphzqud5.png" alt="Image of backend developer roadmap" width="1080" height="1080" loading="lazy"></p>
<p>This roadmap:</p>
<ul>
<li><p>🛤️ Provides a clear path to avoid confusion.</p>
</li>
<li><p>🎯 Helps you stay motivated by outlining where to start and end.</p>
</li>
<li><p>📚 Follows a structured plan, similar to a school syllabus.</p>
</li>
<li><p>📅 Organizes your learning with weekly goals for tools and languages.</p>
</li>
<li><p>⏳ Helps you get through it in 6 months, covering everything you need.</p>
</li>
<li><p>👀 Features a beautiful design for easy navigation.</p>
</li>
</ul>
<h2 id="heading-conclusion">👏 Conclusion</h2>
<p>By following this roadmap and dedicating consistent effort to learning, you can acquire valuable backend development skills and be well-prepared to land a job in backend development.</p>
<p>If you're curious about becoming a front-end developer as well, you can read this article as well. 👉 <a target="_blank" href="https://dev.to/codewithshahan/must-have-frontend-development-skills-roadmap-2024-28jc">The Roadmap to Become a Frontend Developer in 6 Months</a></p>
<p>If you ever wonder about <a target="_blank" href="https://dev.to/codewithshahan/the-future-of-frontend-development-1amd">the future of frontend development</a>, you can also take a look at this article.</p>
<p>Stay tuned for more valuable content, and if you find it helpful, you may also like my <a target="_blank" href="https://www.youtube.com/programmingwithshahan">YouTube Channel</a>.</p>
<p>🤳My Social: <a target="_blank" href="https://twitter.com/shahancd">X</a></p>
<p>Thanks for taking the time to read this article.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build Reusable React Components ]]>
                </title>
                <description>
                    <![CDATA[ What are reusable React components? You can think of them as building blocks. They are independent pieces of code that can be reused throughout your website to save you time and effort. They can be anything from simple buttons to complex forms. Why U... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-reusable-react-components/</link>
                <guid isPermaLink="false">66bfa1c9a1fd8cc5bc645a0d</guid>
                
                    <category>
                        <![CDATA[ best practices ]]>
                    </category>
                
                    <category>
                        <![CDATA[ components ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Programming with Shahan ]]>
                </dc:creator>
                <pubDate>Wed, 28 Feb 2024 19:05:07 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Purple-Blue-Modern-Gradient-New-Blog-Post-Emoji-Twitter-Post--1--1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>What are reusable React components? You can think of them as building blocks. They are independent pieces of code that can be reused throughout your website to save you time and effort.</p>
<p>They can be anything from simple buttons to complex forms.</p>
<h2 id="heading-why-use-reusable-components">Why Use Reusable Components?</h2>
<p>As your website grows, you can easily add new features by combining existing components. This makes your code more scalable and adaptable.</p>
<p>You can use your reusable code in future projects without writing it again from scratch.</p>
<h2 id="heading-how-to-make-reusable-react-components">🏭 How to Make Reusable React Components</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Designer--10-_LE_auto_x2_colored.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration credit: <a target="_blank" href="https://www.youtube.com/programmingwithshahan">Shahan</a></em></p>
<p>Here are the two most important things to keep in mind when creating reusable React components:</p>
<h2 id="heading-1-avoid-side-effects">1. 🩼Avoid Side Effects</h2>
<p>Don't put logic that interacts with external data (like making API calls) directly inside a reusable component. Instead, pass this logic as <code>props</code> to the component.</p>
<p>For example, if a button does more than just looking pretty, like fetching data from the internet, it might not be reusable.</p>
<p>This is a reusable button component. But it lacks best practices. I will show you why in the example section.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// This is a reusable button component (bad practice!)</span>
<span class="hljs-keyword">const</span> Button = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span> Click Me <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-2-use-props">2. 🗃️ Use Props</h2>
<p>Props are arguments you pass to a component to customize its behavior and appearance. This allows you to use the same component for different purposes.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// This is a button component that can change its color</span>
<span class="hljs-keyword">const</span> Button = <span class="hljs-function">(<span class="hljs-params">{ color }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">backgroundColor:</span> <span class="hljs-attr">color</span> }}&gt;</span> Click Here <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  );
}
</code></pre>
<p>This is still a bad practice because you have a fixed label called "Click Here". If you want to change the text on your button to, let's say: "Sign Up", then you would have to go back to the button component and make that change.</p>
<p>That means every time you want to use a different text, we'd have to go back and edit the code. In other words, it's no longer reusable.</p>
<p><strong>💪 Challenge:</strong> So what's the solution?</p>
<p>You already have the answer. But if you don't, I am going to show you in the example section.</p>
<p><strong>🌴 Hint:</strong> Think about how you might want to use the component in different situations and design it to be flexible and adaptable.</p>
<h2 id="heading-examples-of-reusable-react-components">🍃Examples of Reusable React Components</h2>
<p>Here are some common examples of reusable React components, along with some code examples to get you started:</p>
<h3 id="heading-buttons">Buttons</h3>
<p>Basic buttons with different styles and functionalities.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// Button component</span>
<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> Button = <span class="hljs-function">(<span class="hljs-params">{ color, label, onClick }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>
      <span class="hljs-attr">className</span>=<span class="hljs-string">{</span>`<span class="hljs-attr">padding-2</span> <span class="hljs-attr">shadow-none</span> <span class="hljs-attr">hover:shadow</span> <span class="hljs-attr">background-light-</span>${<span class="hljs-attr">color</span>} <span class="hljs-attr">hover:background-dark-</span>${<span class="hljs-attr">color</span>}`}
      <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onClick}</span>
    &gt;</span>
      {label}
    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Button;

<span class="hljs-comment">// Using the Button component</span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">color</span>=<span class="hljs-string">"blue"</span> <span class="hljs-attr">label</span>=<span class="hljs-string">"Click Here"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> console.log("Button clicked!")} /&gt;</span>
</code></pre>
<p>As you can see, I did not write "Click Here" in the <code>button</code> component. I want to make my button reusable, and thus it doesn't know anything about custom styles or texts.</p>
<p>So, I passed them as props (i.e., color, label, and onClick) to change them in the future without touching the original button components. Hope that makes it clear.</p>
<p><strong>🪜Solution:</strong> You need to pass each functionality as <code>props</code> in the reusable component.</p>
<h3 id="heading-navbars">Navbars</h3>
<p>Navigation bars that provide consistent navigation across your website.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// Navbar component</span>
<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> Navbar = <span class="hljs-function">(<span class="hljs-params">{ isLoggedIn }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"navbar"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"navbar-container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"navbar-logo"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{logo}</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"logo"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"navbar-links"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/"</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/about"</span>&gt;</span>About<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/contact"</span>&gt;</span>Contact<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
          {isLoggedIn ? (
            <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/profile"</span>&gt;</span>Profile<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
          ) : (
            <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/login"</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
          )}
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Navbar;

<span class="hljs-comment">// Using the Navbar component</span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Navbar</span> <span class="hljs-attr">isLoggedIn</span>=<span class="hljs-string">{true}</span> /&gt;</span></span>
</code></pre>
<p>As you can see, I passed  <code>&lt;Navbar isLoggedIn={true} /&gt;</code></p>
<p>This line utilizes the <code>Navbar</code> component and passes the <code>isLoggedIn</code> prop with a value of <code>true</code>, indicating the user is logged in. This will display the "Profile" link and hide the "Login" link. </p>
<p>Similar to the button component, the <code>Navbar</code> component is reusable and accepts props to customize its behavior. Perfect!</p>
<h3 id="heading-why-api-calls-in-a-button-component-is-a-bad-practice">Why API Calls in a Button Component is a Bad Practice</h3>
<p>Now, you understand everything about reusable components in React.</p>
<p>Let's dig deeper by solving a complex problem.</p>
<p>Consider the scenario where you have a button that does an API call. The code for the button component can be the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>; 
<span class="hljs-keyword">import</span> doAPICall <span class="hljs-keyword">from</span> <span class="hljs-string">"../api"</span>

<span class="hljs-keyword">const</span> SaveButton  = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>
      <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> {
        doAPICall();
      }}
    &gt;
      Save
    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> SaveButton
</code></pre>
<p>It is quite clear that you can’t reuse the above button in multiple places as this button component contains a side-effect (<code>doAPICall()</code>) inside it.</p>
<p>You can make this component reusable. First, you'll have to extract out the side-effect and pass that as a prop to the button component like this:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span>  {
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doAPICall</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Does an API call to save the current state of the app.</span>
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">SaveButton</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{doAPICall}/</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>The button component should look like this:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> SaveButton  = <span class="hljs-function">(<span class="hljs-params">{
  onClick
}</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>
      <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onClick}</span>
    &gt;</span>
      Save
    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  );
}
</code></pre>
<p>As you can see, the above button can now be reused anywhere you want to save data with the click of a button. The button can now be used like this in multiple places:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span>  {
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saveUser</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Does an API call to save the user.</span>
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saveProject</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Does an API call to save the project.</span>
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">SaveButton</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{saveUser}/</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">SaveButton</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{saveProject}/</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>You can also make the button component more reusable by using a prop to control the label:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span>  {
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saveUser</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Does an API call to save the user.</span>
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saveProject</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Does an API call to save the project.</span>
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">SaveButton</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{saveUser}</span> <span class="hljs-attr">label</span>=<span class="hljs-string">"Save user"</span>  /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">SaveButton</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{saveProject}</span> <span class="hljs-attr">label</span>=<span class="hljs-string">"Save project"</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>The button component should look like this:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> SaveButton  = <span class="hljs-function">(<span class="hljs-params">{
  onClick,
  label
}</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>
      <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onClick}</span>
    &gt;</span>
      {label}
    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-conclusion">👏Conclusion</h2>
<p>Congratulations! You've successfully learned how to build reusable React components. </p>
<p>Remember, reusable components are the building blocks of robust React development. By practicing reusable components, you can build cleaner, more efficient, and more maintainable React applications. </p>
<p>The more you practice, the better you'll become at identifying opportunities to use them in your projects!</p>
<p><strong>Read More:</strong> <a target="_blank" href="https://dev.to/codewithshahan/the-future-of-frontend-development-1amd">The Future of Frontend Development</a></p>
<p>Thank you for taking the time to read this article. Until next time.. Keep learning and you can follow me on <strong><a target="_blank" href="https://twitter.com/shahancd">𝕏</a></strong>  for latest updates on programming and productivity. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Become a Better Web Developer ]]>
                </title>
                <description>
                    <![CDATA[ Web development is a highly in-demand and popular skill these days. So if you’re at a crossroads in your life and thinking about becoming a web developer – or just want to further improve your skills – read on. To be a great web developer, you must l... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-become-a-better-web-developer/</link>
                <guid isPermaLink="false">66bfa1c745d28503d749d458</guid>
                
                    <category>
                        <![CDATA[ self-improvement  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Programming with Shahan ]]>
                </dc:creator>
                <pubDate>Mon, 09 Jan 2023 23:05:20 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/pexels-pixabay-461593.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Web development is a highly in-demand and popular skill these days. So if you’re at a crossroads in your life and thinking about becoming a web developer – or just want to further improve your skills – read on.</p>
<p>To be a great web developer, you must learn many skills and techniques and hone your coding abilities. Every business is searching for an effective web developer, so if you have a few tricks up your sleeve, you will rarely be without work.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/ways-to-better-web-developer.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Become a better web developer (</em><a target="_blank" href="https://www.youtube.com/@ProgrammingwithShahan/featured"><em>shahan</em></a><em>)</em></p>
<p><strong>Web development is divided into three categories:</strong></p>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/front-end-developer-what-is-front-end-development-explained-in-plain-english/">Frontend developer</a>  —  you code the frontend of a website and have direct a connection to the user</p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/front-end-developer-vs-back-end-developer-definition-and-meaning-in-practice/">Backend developer</a>  — you work behind the scenes to make sure the technology that powers the frontend runs smoothly</p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/what-is-a-full-stack-developer-back-end-front-end-full-stack-engineer/">Full stack developer</a>  —  you know both frontend and backend development</p>
</li>
</ul>
<h2 id="heading-how-to-become-a-better-web-developer">🎏 How to Become a Better Web Developer</h2>
<h3 id="heading-determine-your-areas-of-interest"><strong>Determine your areas of interest</strong></h3>
<p>If you want to become an expert in both front-end and back-end programming, your goal could be to become a full-stack web developer. But if you are more into design and aesthetics, and want to work more directly with clients, the front end might be your niche.</p>
<p>There are a few different approaches you can take to determine your area of interest within web development:</p>
<ol>
<li><p><strong>Explore different technologies and frameworks:</strong> One way to get a sense of what you enjoy is to try out different tools and technologies. You can do this by working through tutorials or building small projects with different frameworks, languages, and libraries.</p>
</li>
<li><p><strong>Consider your personal interests:</strong> Think about what you enjoy doing in your free time. Are you interested in design? Do you like working with data? Your personal interests can be a great starting point for finding an area of web development that you'll enjoy.</p>
</li>
<li><p><strong>Find a project or problem that excites you:</strong> Another approach is to look for a project or problem that you find interesting and try to solve it using web development tools and techniques. This can help you discover what you enjoy working on and what you're good at.</p>
</li>
<li><p><strong>Talk to other web developers:</strong> Reach out to other web developers and ask them about their experiences and what they enjoy most about their work. This can give you insight into the different areas of web development and help you identify potential areas of interest.</p>
</li>
<li><p><strong>Take online courses or earn a degree:</strong> Finally, consider taking online courses (many are free!) or earning a degree in computer science (if you have the time and resources). This can give you a broad overview of the field and help you identify areas that you find particularly interesting or rewarding.</p>
</li>
</ol>
<h3 id="heading-cultivate-curiosity-and-an-open-mind"><strong>Cultivate Curiosity and an Open Mind</strong></h3>
<p>Without curiosity or the desire to learn, you won't be as successful of a web developer as you could otherwise be.</p>
<p>Web development is a challenging field, so it's vital to learn constantly. It's not easy to learn everything you need to know, but if you work hard you'll gradually build up your skills.</p>
<p>An essential trait for any web developer is curiosity, as well as an open mind. Always be open to learning new things and trying them out. The field of web development is constantly evolving, and it's important to stay up-to-date on new technologies and techniques.</p>
<p>In addition, always be willing to consider new ideas and approaches. There may be multiple ways to solve a problem, and being open to different solutions can lead to more creative and effective results. Being fearless about trying things out for yourself is one of the best ways to be open-minded.</p>
<h3 id="heading-dont-just-write-code-create-business-value"><strong>Don’t Just Write Code – Create Business Value</strong></h3>
<p>A web programmer must write functional lines of code, but that’s not all. In addition, they must go above and beyond the tasks that have been delegated to them. Instead of merely doing what you are told, focus on what your organization requires.</p>
<p>Writing code is an important aspect of web development, but it's not the only aspect. As a web developer, your ultimate goal should be to create business value through the use of technology. This means designing and building websites and applications that solve problems, meet the needs of users, and provide value to the business or organization.</p>
<p>Here are a few ways you can create business value as a web developer:</p>
<ol>
<li><p>Understand the needs of the business or organization you are working for and design solutions that meet those needs.</p>
</li>
<li><p>Consider the user experience and make sure the websites and applications you build are easy to use and provide value to the user.</p>
</li>
<li><p>Build websites and applications that are scalable and able to adapt to changing business needs.</p>
</li>
<li><p>Utilize data and analytics to make informed decisions about the development of websites and applications.</p>
</li>
<li><p>Work with cross-functional teams to ensure that the technology you develop aligns with the overall goals and objectives of the business or organization.</p>
</li>
</ol>
<p>By focusing on creating business value, you can ensure that the work you do as a web developer is meaningful and impactful.</p>
<h3 id="heading-be-willing-to-invest-in-yourself"><strong>Be Willing to Invest in Yourself</strong></h3>
<p>A good web developer should be well-read. Listen to web development seminars and podcasts, test new plugins and frameworks, use social media responsibly, and be prepared to practice, practice, practice! Hours of diligent practice are required to become an expert and master the craft.</p>
<p>You should also take free courses, read tutorials, and build projects to constantly learn about new trend and ideas. Aside from taking courses, you can attend conferences and meetups and read industry blogs and articles.</p>
<p>Building a strong portfolio is also important for any budding web developer. A strong portfolio of work is essential for showcasing your skills and abilities to potential employers. Make sure to include a variety of projects that demonstrate your capabilities and expertise.</p>
<p>Finally, building relationships with other professionals in the industry can help you learn from others, stay informed about new developments, and potentially open up new job opportunities.</p>
<h3 id="heading-develop-discipline-and-dedication-to-your-work"><strong>Develop Discipline and Dedication to Your Work</strong></h3>
<p>A web developer should be productive, which requires dedication and discipline. Embrace a work culture that makes others want to emulate it. But keep in mind that even though you'll need to work hard, don’t let it interfere too much with your personal and social life. You don't want to get burned out.</p>
<p>On the other side, you must organize your time so that you can be as productive as possible while also having fun. Having a clear understanding of what you want to achieve and how you will go about achieving it can help you stay focused and motivated.</p>
<p>Also, it's important to take breaks and rest to avoid burnout. Consider using the Pomodoro technique, which involves working for a set amount of time, taking a break, and then repeating the process. Having a regular schedule can help you stay on track and ensure that you have dedicated time for web development work.</p>
<p>Finally, seek out opportunities to learn and grow. Dedication to your craft means constantly seeking out opportunities to learn and improve. Attend conferences, workshops, and other events, and make sure to keep up with new technologies and techniques.</p>
<h3 id="heading-help-out-with-open-source-projects"><strong>Help Out with Open Source Projects</strong></h3>
<p>If you're a good web programmer, people will notice and want you to work on their projects. So do your best to build your credibility by contributing to open-source communities like GitHub, Automatic, Angular, Go, and <a target="_blank" href="https://www.freecodecamp.org/">freeCodeCamp</a>.</p>
<h3 id="heading-finally-keep-your-body-and-mind-active"><strong>Finally, Keep your Body and Mind Active</strong></h3>
<p>It is natural for a programmer to spend a significant amount of time in front of a computer. If you want to recharge your batteries and be more effective at work, you should spend time outside doing your favorite athletic activity.</p>
<p>Here are a few ways you can keep your body and mind active as a web developer:</p>
<ol>
<li><p><strong>Take breaks and get up and move around:</strong> Sitting for long periods of time can be detrimental to both your physical and mental health. Make sure to take breaks to stretch, walk around, or do some light exercises.</p>
</li>
<li><p><strong>Exercise regularly:</strong> Exercise has numerous benefits for both your physical and mental health. Consider incorporating activities such as running, yoga, or strength training into your weekly routine.</p>
</li>
<li><p><strong>Get enough sleep:</strong> Adequate sleep is essential for both physical and mental health. Make sure to get at least 7-9 hours of sleep per night to ensure you are well rested and able to perform at your best.</p>
</li>
<li><p><strong>Eat a healthy diet:</strong> A healthy diet can help improve your physical and mental well-being. Make sure to incorporate plenty of fruits, vegetables, and other nutritious foods into your meals.</p>
</li>
<li><p><strong>Stay hydrated:</strong> Dehydration can lead to physical and mental fatigue. Make sure to drink plenty of water throughout the day to stay hydrated and energized.</p>
</li>
</ol>
<p>By taking care of your physical and mental health, you can ensure that you have the energy and focus needed to be productive and successful as a web developer.</p>
<h2 id="heading-conclusion">🏁 Conclusion</h2>
<p>A web developer created each and every website and piece of software you use today. The web development field is fascinating, and new innovations emerge from it every day.</p>
<p>If you think web development is for you, hopefully these tips help you develop strategies that lead to success. It’s a good idea to get in headfirst if you’re considering changing jobs and becoming a web developer right away.</p>
<p>You can always buy me a coffee <a target="_blank" href="https://www.buymeacoffee.com/codewithshahan">here</a>.</p>
<p>Additionally, you can subscribe to my <a target="_blank" href="https://www.youtube.com/@ProgrammingwithShahan/featured">YouTube</a> channel to sharpen your programming skills.</p>
<p>Thank you for your time and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Game Development – How to Make a Turtle Racing Game with PyCharm ]]>
                </title>
                <description>
                    <![CDATA[ In this article, you'll learn how to build a racing game in Python using the Turtle library in just 39 lines of code.  Here's what we're going to create: Turtle Racing Game Project Overview 🧵 Prerequisites Very basic knowledge of Python programming... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-make-racing-game-using-python/</link>
                <guid isPermaLink="false">66bfa1ccc342783fb4349d68</guid>
                
                    <category>
                        <![CDATA[ Game Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Programming with Shahan ]]>
                </dc:creator>
                <pubDate>Tue, 01 Feb 2022 15:49:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/python-game.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, you'll learn how to build a racing game in Python using the Turtle library in just 39 lines of code. </p>
<p>Here's what we're going to create:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/turtle-overview.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Turtle Racing Game Project Overview</em></p>
<h2 id="heading-prerequisites">🧵 Prerequisites</h2>
<p>Very basic knowledge of Python programming will be enough to go through this tutorial. Also, I assume that you don't know anything about this <a target="_blank" href="https://docs.python.org/3/library/turtle.html">turtle</a> library. I will teach you everything from scratch.</p>
<h2 id="heading-tools-well-use">🛠 Tools we'll use</h2>
<p>First, if you don't have Python installed on your machine, go to <a target="_blank" href="https://www.python.org/">python.org</a> to download latest version of Python and then install it right away. </p>
<p>For writing the program, we will be using <a target="_blank" href="https://www.jetbrains.com/pycharm/">PyCharm</a> which is the most popular integrated development environment (IDE) for Python. After installing <a target="_blank" href="https://www.jetbrains.com/pycharm/">PyCharm</a> on your machine, you are ready to build this amazing game from scratch. </p>
<h2 id="heading-project-goals">⛳ Project Goals</h2>
<p>Concretely, we'll write a program that moves a turtle object horizontally until it reaches our calculated finish line. Then we will create seven unique replicas of this turtle object using a <code>for</code> loop along with different colors and random moving speeds.</p>
<p>We'll also add a background image (roads with lanes for the turtles to race in) to create something like a real racing environment. </p>
<p>Then we'll compute different values along the vertical or Y-axis to define their starting locations. </p>
<p>Finally, we will prompt the user to enter their bet (turtle color) so that if a user's bet color matches our winner turtle's color, we will display <strong>Winner!</strong> on the screen. Otherwise, we'll display <strong>You Lost!</strong> on the screen. </p>
<p>Note: for screen readers or anyone who is interested in getting the full source code of this project, you can access it in my <a target="_blank" href="https://github.com/codewithshahan/python-racing-game">GitHub Repository here</a>. </p>
<p>So are you exited to build this game? I'm too. Let's begin!</p>
<h2 id="heading-how-to-set-up-the-project">👩‍💻 How to Set Up the Project</h2>
<p>Open your PyCharm IDE. Then click New Project.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/Screenshot-2022-01-25-185042.png" alt="Image" width="600" height="400" loading="lazy">
<em>creating a new project</em></p>
<p> Let's call it <strong>racing-game</strong> and click <strong>create.</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/2-5.png" alt="Image" width="600" height="400" loading="lazy">
<em>Project name</em></p>
<p>Then, add a new Python file called <code>main.py</code>. </p>
<h2 id="heading-how-to-use-the-turtle-library">📂 How to Use the Turtle Library</h2>
<p>Now, let's go to <a target="_blank" href="https://docs.python.org/3/library/turtle.html">turtle-graphics python documentation</a>. Here you will find the full details about this library. </p>
<p>Let's scroll down and go to the Turtle methods section. You will see different types of methods that we can use for many different purposes. We will use a few of them in our current project. </p>
<p>I recommend reading this documentation at least once before jumping into the code. But don't worry, I will simplify it for you while we're writing the program. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/3-5.png" alt="Image" width="600" height="400" loading="lazy">
<em>turtle docs</em></p>
<h3 id="heading-import-the-library">Import the Library</h3>
<p>So let's import <strong>Turtle</strong> and <strong>Screen</strong> from the turtle module. Call this Screen in a new variable called <strong>screen</strong>. Then, call the <code>screen.exitonclick()</code> function to stop the program when we click on the screen. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/4-3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-define-the-game-canvas">🔳 How to Define the Game Canvas</h2>
<p>Now, let's work with the screen object to define our game canvas. So, let's set the <strong>width</strong> to 800 pixels and <strong>height</strong> to 600 pixels.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/5-4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p> Here is the result: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/6-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-add-background-graphics">How to Add Background Graphics</h3>
<p>It's time to load our background image for our canvas. So let's drag our <strong>road.gif</strong> file into our racing-game project. <a target="_blank" href="https://drive.google.com/file/d/14n2LlzMELtUazYYdEfusx_uVpyRU_n9t/view?usp=sharing">Click this link to download the graphics.</a> </p>
<p>Let's add this image using <strong><code>screen.bgpic</code>('road.gif'</strong>).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/7-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p> Here is the result:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/8-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-work-with-turtle-objects">🐢 How to Work with Turtle Objects</h2>
<p>Now, let's create a turtle instance using the <code>Turtle()</code> method with the shape called <strong>turtle</strong>.</p>
<p>But it will seem really small. So we need define <code>shapesize(2)</code>. </p>
<h3 id="heading-how-to-position-the-turtles">How to position the turtles</h3>
<p>Now we need to change our turtle's location to the left bottom corner using <code>goto(x=-350, y=-260)</code>.</p>
<p>So here we set <code>x</code> for moving the turtle horizontally and <code>y</code> for vertically along with the computed values with respect to our canvas. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/9-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/10-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here you can see that the turtle has moved to our desired location. So, we can take the <code>y</code> position in a global variable and add different types of values for positioning our turtles on their respective roads.  </p>
<h3 id="heading-how-to-create-the-turtle-replicas">How to create the turtle replicas</h3>
<p>Now, we have to create seven different types of turtle objects. For this reason, we will use a <code>for loop</code>. </p>
<p>So <code>for</code> index in <code>range(0, 7)</code> and then move our existing turtle instance in this loop. And of course, we have to change <code>y</code> to our global <code>y</code> positions variable and get their <strong>indexes</strong> in order.  </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/11-4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here is the result:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/12-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-define-the-turtle-colors">How to define the turtle colors</h3>
<p>So as you can see, we have seven turtle instances created equally with different <code>y</code> locations. Let's add some random colors by using a global colors variable as we did for the <code>y</code> positions. Then use the <code>color(colors[index])</code> method with their indexes. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/13-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here is the result – beautiful! </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/14-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-remove-the-ugly-lines">How to remove the ugly lines</h3>
<p>You may see that there are some ugly lines that point towards the middle, and the move direction is very slow. So we can use the <code>speed('fastest')</code> and <code>penup()</code> methods to solve these problems. Have a look! </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/15-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-move-the-turtles-forward">How to move the turtles forward</h3>
<p>Now, what else do we need? Yeah, you got it! We need to define a random pace for every turtle. But before doing that, how can we move a single turtle forward? </p>
<p>Well, you can use the <code>forward()</code> method to do this. Let's say we need to move our turtles forward 30 pixels. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/17.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here is the result:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/18.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>But they are not moving continuously. What else can we do here? Think about it and come back to see my solutions.</p>
<p>So, to solve this problem, we take a variable called <strong>is_on</strong> and set it to <code>True</code>. Now we will continuously execute our program until we break it using a <code>while</code> loop.</p>
<p>Now, we have the opportunity to move our turtle forward continuously with 30 pixels in every step. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/7-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here is the result:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/9-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>It's moving like a plane because we set <code>forward</code> to 30.</p>
<h3 id="heading-how-to-run-multiple-turtles-in-sync">How to run multiple turtles in sync</h3>
<p>Now we need to target all the turtle objects, not just a single one. But how can we do it? Think about it and come back to see my solution.</p>
<p>So, we can take a global variable called <strong>all_turtle</strong> and set it to an empty list. Now, in the for loop, after creating seven new turtle instances, we can <code>append</code> our new born turtle to this global <strong>all_turtle</strong> list. This way we can access them in other code blocks.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/19.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now we have all our turtles. So, while our <code>is_on</code> variable in true, we can say <code>all_turtle.forward(10)</code>. Also, here we need to use a for loop again to get each turtle from this <strong>all_turle</strong> global variable and then move them <code>forward</code> by 10 pixels. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/20-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let's see the result up until now:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/21.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-set-random-moving-speed">How to set random moving speed</h3>
<p>So, we solved our turtle moving problem. But they're running infinitely – there is no ending point. Also all turtles are moving at the same speed. Think about this problem, and try to solve it on your own. </p>
<p>So let's take a new variable <strong>random_pace</strong> and set it to <code>random.randint(0, 7)</code>. It will return value between zero to seven randomly. You have to import random at the top. Finally pass this <strong>random_pace</strong> variable to the <code>forward()</code> method like <code>forward(random_pace)</code>. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/22.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here is the result:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/23.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-set-the-finish-line">🏁 How to Set the Finish Line</h2>
<p>Now, we need to define our finish line in this canvas. To solve this problem, we check <code>if</code> <code>turtle.xcor()</code> &gt; 330, set <strong>is_on</strong> = <code>False</code>, else we need to continue executing our program. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/24.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-prompt-the-user-to-enter-their-bet">👥 How to Prompt the User to Enter Their Bet</h2>
<p>We are done with the UI. Now, we need to define some logic to let the user enter their bet and compare their bet with our programmed result. </p>
<p>To let the user enter their bet, we can write <code>screen.textinput</code> and with a placeholder <strong>'Enter your bet'</strong>. We'll also <strong><code>prompt</code></strong> the user <strong>"which turtle color"</strong> and store it in a global variable <strong>user_bet</strong>. </p>
<p>Then we take a variable <strong>winner</strong>. We check if <code>winner == user_bet</code> which will come from the user's input color. We print <strong>You Won</strong>, Otherwise, <strong>You lost</strong> with the turtle winner's color. That's why we have to use an f-string to pass the variable in the print method.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/25.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-show-the-results-on-the-screen">🎐 How to Show the Results on the Screen</h2>
<p>Now, I want you to show this print text in the canvas with their responsive turtle color after touching the finish line. How can you implement this? You will see my solution next.</p>
<p>S0, here in the top. We take two global variables <strong><code>ALIGN = "right"</code></strong> and <strong><code>FONT = ("Courier", 28, "bold")</code></strong>. We will write to align the text on the right, and also make the font family courier and font size 28, bold. </p>
<p>Now, we'll use them when we want to show the user the racing results. So when the winner turtle color is equal to the user_bet color, we have to show the text in the canvas instead of printing it in the terminal. </p>
<p>To do this, we write <code>turtle.write()</code> and past the print statement along with font=<strong>FONT</strong> and align=<strong>ALIGN</strong>. Else, we need to show the text "You lost" with the same variable <strong>FONT</strong> and <strong>ALIGN</strong>. See, this is the benefit of using global variables.  </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/26.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Finally, let's run this code one more time. Let's say that the red turtle will be the winner. But, as you can see below – Oops, the yellow turtle is the winner. So, you can see the bold yellow font displayed next to this turtle. This is why we used align = "right" and set the turtle color using the <code>turtle.pencolor()</code> method. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/turtle-overview.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Turtle Racing Game Project</em></p>
<p>And there you have it - we've built our turtle racing game. If you want to watch this tutorial in video form, here's a full video tutorial for you:</p>
<h2 id="heading-full-video-tutorial">📹 Full Video Tutorial</h2>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/_XmPt7iZtho" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-conclusion">👏 Conclusion</h2>
<p>So, we are at the end of this racing game project. If you liked this article, feel free to subscribe to my <a target="_blank" href="https://www.youtube.com/c/programmingwithshahan">YouTube Channel</a> or send me a <a target="_blank" href="https://www.twitter.com/codewithshahan">tweet</a>. </p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
