<?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[ software design patterns - 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[ software design patterns - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 26 Aug 2026 20:17:51 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/software-design-patterns/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Design Patterns – Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article I'll explain what design patterns are and why they're useful. We'll also go through some of the most popular design patterns out there and give examples for each of them. Let's go! Table of Contents What Are Design Patte... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-design-patterns-explained/</link>
                <guid isPermaLink="false">66d45f0d9208fb118cc6cfa9</guid>
                
                    <category>
                        <![CDATA[ design patterns ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software design patterns ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Wed, 22 Jun 2022 17:06:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/pexels-pixabay-161043.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article I'll explain what design patterns are and why they're useful.</p>
<p>We'll also go through some of the most popular design patterns out there and give examples for each of them. Let's go!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-design-patterns">What Are Design Patterns?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-creational-design-patterns">Creational Design Patterns</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-singleton-pattern">Singleton Pattern</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-factory-method-pattern">Factory Method Pattern</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-abstract-factory-pattern">Abstract Factory Pattern</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-builder-pattern">Builder Pattern</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-prototype-pattern">Prototype Pattern</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-structural-design-patterns">Structural Design Patterns</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-adapter-pattern">Adapter Pattern</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-decorator-pattern">Decorator Pattern</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-facade-pattern">Facade Pattern</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-proxy-pattern">Proxy Pattern</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-behavioral-design-patterns">Behavioral Design Patterns</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-chain-of-responsibility-pattern">Chain of Responsibility Pattern</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-iterator-pattern">Iterator Pattern</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-observer-pattern">Observer Pattern</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-roundup">Roundup</a></p>
</li>
</ul>
<h1 id="heading-what-are-design-patterns">What Are Design Patterns?</h1>
<p>Design patterns were popularized by <a target="_blank" href="https://en.wikipedia.org/wiki/Design_Patterns">the book "Design Patterns: Elements of Reusable Object-Oriented Software"</a>, published in 1994 by a group of four C++ engineers.</p>
<p>The book explores the capabilities and pitfalls of object-oriented programming, and describes 23 useful patterns that you can implement to solve common programming problems.</p>
<p>These patterns are <strong>not algorithms or specific implementations</strong>. They are more like <strong>ideas, opinions, and abstractions</strong> that can be useful in certain situations to solve a particular kind of problem.</p>
<p>The specific implementation of the patterns may vary depending on many different factors. But what's important is the concepts behind them, and how they might help us achieve a better solution for our problem.</p>
<p>This being said, keep in mind these patterns were thought up with OOP C++ programming in mind. When it comes to more modern languages like JavaScript or other programming paradigms, these patterns might not be equally useful and might even add unnecessary boilerplate to our code.</p>
<p>Nevertheless, I think it's good to know about them as general programming knowledge.</p>
<p>Side comment: If you're not familiar with <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-programming-paradigms/">programming paradigms</a> or <a target="_blank" href="https://www.freecodecamp.org/news/object-oriented-javascript-for-beginners/">OOP</a>, I recently wrote two articles about those topics. 😉</p>
<p>Anyway... Now that we've gotten the introduction out of the way, design patterns are classified into three main categories: <strong>creational, structural, and behavioral patterns</strong>. Let's briefly explore each of them. 🧐</p>
<h1 id="heading-creational-design-patterns">Creational Design Patterns</h1>
<p>Creational patterns consist of different mechanisms used to create objects.</p>
<h2 id="heading-singleton-pattern">Singleton Pattern</h2>
<p><strong>Singleton</strong> is a design pattern that ensures that a class has only one immutable instance. Said simply, the singleton pattern consists of an object that can't be copied or modified. It's often useful when we want to have some immutable single <em>point of truth</em> for our application.</p>
<p>Let's say for example we want to have all of our app's configuration in a single object. And we want to disallow any duplication or modification of that object.</p>
<p>Two ways of implementing this pattern are using object literals and classes:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> Config = {
  <span class="hljs-attr">start</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'App has started'</span>),
  <span class="hljs-attr">update</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'App has updated'</span>),
}

<span class="hljs-comment">// We freeze the object to prevent new properties being added and existing properties being modified or removed</span>
<span class="hljs-built_in">Object</span>.freeze(Config)

Config.start() <span class="hljs-comment">// "App has started"</span>
Config.update() <span class="hljs-comment">// "App has updated"</span>

Config.name = <span class="hljs-string">"Robert"</span> <span class="hljs-comment">// We try to add a new key</span>
<span class="hljs-built_in">console</span>.log(Config) <span class="hljs-comment">// And verify it doesn't work: { start: [Function: start], update: [Function: update] }</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Config</span> </span>{
    <span class="hljs-keyword">constructor</span>() {}
    start(){ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'App has started'</span>) }  
    update(){ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'App has updated'</span>) }
}

<span class="hljs-keyword">const</span> instance = <span class="hljs-keyword">new</span> Config()
<span class="hljs-built_in">Object</span>.freeze(instance)
</code></pre>
<h2 id="heading-factory-method-pattern">Factory Method Pattern</h2>
<p>The <strong>Factory method</strong> pattern provides an interface for creating objects that can be modified after creation. The cool thing about this is that the logic for creating our objects is centralized in a single place, simplifying and better organizing our code.</p>
<p>This pattern is used a lot and can also be implemented in two different ways, via classes or factory functions (functions that return an object).</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Alien</span> </span>{
    <span class="hljs-keyword">constructor</span> (name, phrase) {
        <span class="hljs-built_in">this</span>.name = name
        <span class="hljs-built_in">this</span>.phrase = phrase
        <span class="hljs-built_in">this</span>.species = <span class="hljs-string">"alien"</span>
    }
    fly = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Zzzzzziiiiiinnnnnggggg!!"</span>)
    sayPhrase = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.phrase)
}

<span class="hljs-keyword">const</span> alien1 = <span class="hljs-keyword">new</span> Alien(<span class="hljs-string">"Ali"</span>, <span class="hljs-string">"I'm Ali the alien!"</span>)
<span class="hljs-built_in">console</span>.log(alien1.name) <span class="hljs-comment">// output: "Ali"</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Alien</span>(<span class="hljs-params">name, phrase</span>) </span>{
    <span class="hljs-built_in">this</span>.name = name
    <span class="hljs-built_in">this</span>.phrase = phrase
    <span class="hljs-built_in">this</span>.species = <span class="hljs-string">"alien"</span>
}

Alien.prototype.fly = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Zzzzzziiiiiinnnnnggggg!!"</span>)
Alien.prototype.sayPhrase = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.phrase)

<span class="hljs-keyword">const</span> alien1 = <span class="hljs-keyword">new</span> Alien(<span class="hljs-string">"Ali"</span>, <span class="hljs-string">"I'm Ali the alien!"</span>)

<span class="hljs-built_in">console</span>.log(alien1.name) <span class="hljs-comment">// output "Ali"</span>
<span class="hljs-built_in">console</span>.log(alien1.phrase) <span class="hljs-comment">// output "I'm Ali the alien!"</span>
alien1.fly() <span class="hljs-comment">// output "Zzzzzziiiiiinnnnnggggg"</span>
</code></pre>
<h2 id="heading-abstract-factory-pattern">Abstract Factory Pattern</h2>
<p>The <strong>Abstract Factory</strong> pattern allows us to produce families of related objects without specifying concrete classes. It's useful in situations where we need to create objects that share only some properties and methods.</p>
<p>The way it works is by presenting an abstract factory the client interacts with. That <strong>abstract factory</strong> calls the corresponding <strong>concrete factory</strong> given the corresponding logic. And that concrete factory is the one that returns the end object.</p>
<p>Basically it just adds an abstraction layer over the factory method pattern, so that we can create many different types of objects, but still interact with a single factory function or class.</p>
<p>So let's see this with an example. Let's say we're modeling a system for a car company, which builds cars of course, but also motorcycles and trucks.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// We have a class or "concrete factory" for each vehicle type</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> </span>{
    <span class="hljs-keyword">constructor</span> () {
        <span class="hljs-built_in">this</span>.name = <span class="hljs-string">"Car"</span>
        <span class="hljs-built_in">this</span>.wheels = <span class="hljs-number">4</span>
    }
    turnOn = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Chacabúm!!"</span>)
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Truck</span> </span>{
    <span class="hljs-keyword">constructor</span> () {
        <span class="hljs-built_in">this</span>.name = <span class="hljs-string">"Truck"</span>
        <span class="hljs-built_in">this</span>.wheels = <span class="hljs-number">8</span>
    }
    turnOn = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"RRRRRRRRUUUUUUUUUMMMMMMMMMM!!"</span>)
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Motorcycle</span> </span>{
    <span class="hljs-keyword">constructor</span> () {
        <span class="hljs-built_in">this</span>.name = <span class="hljs-string">"Motorcycle"</span>
        <span class="hljs-built_in">this</span>.wheels = <span class="hljs-number">2</span>
    }
    turnOn = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"sssssssssssssssssssssssssssssshhhhhhhhhhham!!"</span>)
}

<span class="hljs-comment">// And and abstract factory that works as a single point of interaction for our clients</span>
<span class="hljs-comment">// Given the type parameter it receives, it will call the corresponding concrete factory</span>
<span class="hljs-keyword">const</span> vehicleFactory = {
    <span class="hljs-attr">createVehicle</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">type</span>) </span>{
        <span class="hljs-keyword">switch</span> (type) {
            <span class="hljs-keyword">case</span> <span class="hljs-string">"car"</span>:
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Car()
            <span class="hljs-keyword">case</span> <span class="hljs-string">"truck"</span>:
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Truck()
            <span class="hljs-keyword">case</span> <span class="hljs-string">"motorcycle"</span>:
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Motorcycle()
            <span class="hljs-attr">default</span>:
                <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>
        }
    }
}

<span class="hljs-keyword">const</span> car = vehicleFactory.createVehicle(<span class="hljs-string">"car"</span>) <span class="hljs-comment">// Car { turnOn: [Function: turnOn], name: 'Car', wheels: 4 }</span>
<span class="hljs-keyword">const</span> truck = vehicleFactory.createVehicle(<span class="hljs-string">"truck"</span>) <span class="hljs-comment">// Truck { turnOn: [Function: turnOn], name: 'Truck', wheels: 8 }</span>
<span class="hljs-keyword">const</span> motorcycle = vehicleFactory.createVehicle(<span class="hljs-string">"motorcycle"</span>) <span class="hljs-comment">// Motorcycle { turnOn: [Function: turnOn], name: 'Motorcycle', wheels: 2 }</span>
</code></pre>
<h2 id="heading-builder-pattern">Builder Pattern</h2>
<p>The <strong>Builder</strong> pattern is used to create objects in "steps". Normally we will have functions or methods that add certain properties or methods to our object.</p>
<p>The cool thing about this pattern is that we separate the creation of properties and methods into different entities.</p>
<p>If we had a class or a factory function, the object we instantiate will always have all the properties and methods declared in that class/factory. But using the builder pattern, we can create an object and apply to it only the "steps" we need, which is a more flexible approach.</p>
<p>This is related to <a target="_blank" href="https://www.youtube.com/watch?v=wfMtDGfHWpA&amp;t=3s">object composition</a>, a topic I've talked about <a target="_blank" href="https://www.freecodecamp.org/news/object-oriented-javascript-for-beginners/#object-composition">here</a>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// We declare our objects</span>
<span class="hljs-keyword">const</span> bug1 = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Buggy McFly"</span>,
    <span class="hljs-attr">phrase</span>: <span class="hljs-string">"Your debugger doesn't work with me!"</span>
}

<span class="hljs-keyword">const</span> bug2 = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Martiniano Buggland"</span>,
    <span class="hljs-attr">phrase</span>: <span class="hljs-string">"Can't touch this! Na na na na..."</span>
}

<span class="hljs-comment">// These functions take an object as parameter and add a method to them</span>
<span class="hljs-keyword">const</span> addFlyingAbility = <span class="hljs-function"><span class="hljs-params">obj</span> =&gt;</span> {
    obj.fly = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Now <span class="hljs-subst">${obj.name}</span> can fly!`</span>)
}

<span class="hljs-keyword">const</span> addSpeechAbility = <span class="hljs-function"><span class="hljs-params">obj</span> =&gt;</span> {
    obj.saySmthg = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${obj.name}</span> walks the walk and talks the talk!`</span>)
}

<span class="hljs-comment">// Finally we call the builder functions passing the objects as parameters</span>
addFlyingAbility(bug1)
bug1.fly() <span class="hljs-comment">// output: "Now Buggy McFly can fly!"</span>

addSpeechAbility(bug2)
bug2.saySmthg() <span class="hljs-comment">// output: "Martiniano Buggland walks the walk and talks the talk!"</span>
</code></pre>
<h2 id="heading-prototype-pattern">Prototype Pattern</h2>
<p>The <strong>Prototype</strong> pattern allows you to create an object using another object as a blueprint, inheriting its properties and methods.</p>
<p>If you've been around JavaScript for a while, you're probably familiar with <a target="_blank" href="https://www.freecodecamp.org/news/prototypes-and-inheritance-in-javascript/">prototypal inheritance</a> and how JavaScript works around it.</p>
<p>The end result is very similar to what we get by using classes, but with a little more flexibility since properties and methods can be shared between objects without depending on the same class.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// We declare our prototype object with two methods</span>
<span class="hljs-keyword">const</span> enemy = {
    <span class="hljs-attr">attack</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Pim Pam Pum!"</span>),
    <span class="hljs-attr">flyAway</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Flyyyy like an eagle!"</span>)
}

<span class="hljs-comment">// We declare another object that will inherit from our prototype</span>
<span class="hljs-keyword">const</span> bug1 = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Buggy McFly"</span>,
    <span class="hljs-attr">phrase</span>: <span class="hljs-string">"Your debugger doesn't work with me!"</span>
}

<span class="hljs-comment">// With setPrototypeOf we set the prototype of our object</span>
<span class="hljs-built_in">Object</span>.setPrototypeOf(bug1, enemy)

<span class="hljs-comment">// With getPrototypeOf we read the prototype and confirm the previous has worked</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(bug1)) <span class="hljs-comment">// { attack: [Function: attack], flyAway: [Function: flyAway] }</span>

<span class="hljs-built_in">console</span>.log(bug1.phrase) <span class="hljs-comment">// Your debugger doesn't work with me!</span>
<span class="hljs-built_in">console</span>.log(bug1.attack()) <span class="hljs-comment">// Pim Pam Pum!</span>
<span class="hljs-built_in">console</span>.log(bug1.flyAway()) <span class="hljs-comment">// Flyyyy like an eagle!</span>
</code></pre>
<h1 id="heading-structural-design-patterns">Structural Design Patterns</h1>
<p>Structural patterns refer to how to assemble objects and classes into larger structures.</p>
<h2 id="heading-adapter-pattern">Adapter Pattern</h2>
<p>The Adapter allows two objects with incompatible interfaces to interact with each other.</p>
<p>Let's say, for example, that your application consults an API that returns <a target="_blank" href="https://www.freecodecamp.org/news/what-is-an-xml-file-how-to-open-xml-files-and-the-best-xml-viewers/">XML</a> and sends that information to another API to process that information. But the processing API expects <a target="_blank" href="https://www.freecodecamp.org/news/what-is-json-a-json-file-example/">JSON</a>. You can't send the information as it's received since both interfaces are incompatible. You need to <em>adapt it</em> first. 😉</p>
<p>We can visualize the same concept with an even simpler example. Say we have an array of cities and a function that returns the greatest number of habitants any of those cities have. The number of habitants in our array is in millions, but we have a new city to add that has its habitants without the million conversion:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Our array of cities</span>
<span class="hljs-keyword">const</span> citiesHabitantsInMillions = [
    { <span class="hljs-attr">city</span>: <span class="hljs-string">"London"</span>, <span class="hljs-attr">habitants</span>: <span class="hljs-number">8.9</span> },
    { <span class="hljs-attr">city</span>: <span class="hljs-string">"Rome"</span>, <span class="hljs-attr">habitants</span>: <span class="hljs-number">2.8</span> },
    { <span class="hljs-attr">city</span>: <span class="hljs-string">"New york"</span>, <span class="hljs-attr">habitants</span>: <span class="hljs-number">8.8</span> },
    { <span class="hljs-attr">city</span>: <span class="hljs-string">"Paris"</span>, <span class="hljs-attr">habitants</span>: <span class="hljs-number">2.1</span> },
] 

<span class="hljs-comment">// The new city we want to add</span>
<span class="hljs-keyword">const</span> BuenosAires = {
    <span class="hljs-attr">city</span>: <span class="hljs-string">"Buenos Aires"</span>,
    <span class="hljs-attr">habitants</span>: <span class="hljs-number">3100000</span>
}

<span class="hljs-comment">// Our adapter function takes our city and converts the habitants property to the same format all the other cities have</span>
<span class="hljs-keyword">const</span> toMillionsAdapter = <span class="hljs-function"><span class="hljs-params">city</span> =&gt;</span> { city.habitants = <span class="hljs-built_in">parseFloat</span>((city.habitants/<span class="hljs-number">1000000</span>).toFixed(<span class="hljs-number">1</span>)) }

toMillionsAdapter(BuenosAires)

<span class="hljs-comment">// We add the new city to the array</span>
citiesHabitantsInMillions.push(BuenosAires)

<span class="hljs-comment">// And this function returns the largest habitants number</span>
<span class="hljs-keyword">const</span> MostHabitantsInMillions = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.max(...citiesHabitantsInMillions.map(<span class="hljs-function"><span class="hljs-params">city</span> =&gt;</span> city.habitants))
}

<span class="hljs-built_in">console</span>.log(MostHabitantsInMillions()) <span class="hljs-comment">// 8.9</span>
</code></pre>
<h2 id="heading-decorator-pattern">Decorator Pattern</h2>
<p>The <strong>Decorator</strong> pattern lets you attach new behaviors to objects by placing them inside wrapper objects that contain the behaviors. If you're somewhat familiar with React and higher order components (HOC) this kind of approach probably rings a bell for you.</p>
<p>Technically, components in React functions, not objects. But if we think about how React Context or <a target="_blank" href="https://www.freecodecamp.org/news/memoization-in-javascript-and-react/">Memo</a> we can see that we're passing a component as a child to this HOC, and thanks to that this child component is able to access certain features.</p>
<p>In this example we can see that the ContextProvider component is receiving children as props:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> Context <span class="hljs-keyword">from</span> <span class="hljs-string">'./Context'</span>

<span class="hljs-keyword">const</span> ContextProvider: React.FC = <span class="hljs-function">(<span class="hljs-params">{children}</span>) =&gt;</span> {

    <span class="hljs-keyword">const</span> [darkModeOn, setDarkModeOn] = useState(<span class="hljs-literal">true</span>)
    <span class="hljs-keyword">const</span> [englishLanguage, setEnglishLanguage] = useState(<span class="hljs-literal">true</span>)

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Context.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span>
            <span class="hljs-attr">darkModeOn</span>,
            <span class="hljs-attr">setDarkModeOn</span>,
            <span class="hljs-attr">englishLanguage</span>,
            <span class="hljs-attr">setEnglishLanguage</span>
        }} &gt;</span>
            {children}
        <span class="hljs-tag">&lt;/<span class="hljs-name">Context.Provider</span>&gt;</span></span>
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ContextProvider
</code></pre>
<p>Then we wrap the whole application around it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ContextProvider</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Router</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">ErrorBoundary</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;
            <span class="hljs-tag">&lt;<span class="hljs-name">Header</span> /&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>

          <span class="hljs-tag">&lt;<span class="hljs-name">Routes</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;<span class="hljs-tag">&lt;<span class="hljs-name">AboutPage</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>}/&gt;

              <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/projects'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;<span class="hljs-tag">&lt;<span class="hljs-name">ProjectsPage</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>}/&gt;

              <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/projects/helpr'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;<span class="hljs-tag">&lt;<span class="hljs-name">HelprProject</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>}/&gt;</span>

              <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/projects/myWebsite'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;<span class="hljs-tag">&lt;<span class="hljs-name">MyWebsiteProject</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span></span>}/&gt;

              <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/projects/mixr'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;<span class="hljs-tag">&lt;<span class="hljs-name">MixrProject</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span></span>}/&gt;

              <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/projects/shortr'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;<span class="hljs-tag">&lt;<span class="hljs-name">ShortrProject</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span></span>}/&gt;

              <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/curriculum'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;<span class="hljs-tag">&lt;<span class="hljs-name">CurriculumPage</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span></span>}/&gt;

              <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/blog'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;<span class="hljs-tag">&lt;<span class="hljs-name">BlogPage</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span></span>}/&gt;

              <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/contact'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;<span class="hljs-tag">&lt;<span class="hljs-name">ContactPage</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span></span>}/&gt;
          &lt;/Routes&gt;
        &lt;/ErrorBoundary&gt;

      &lt;/Router&gt;
    &lt;/ContextProvider&gt;
  )
}
</code></pre>
<p>And later on, using the <code>useContext</code> hook I can access the state defined in the Context from any of the components in my app.</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> AboutPage: React.FC = <span class="hljs-function">() =&gt;</span> {

    <span class="hljs-keyword">const</span> { darkModeOn, englishLanguage } = useContext(Context)

    <span class="hljs-keyword">return</span> (...)
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> AboutPage
</code></pre>
<p>Again, this might not be the exact implementation the book authors had in mind when they wrote about this pattern, but I believe the idea is the same. Place an object within another so it can access certain features. ;)</p>
<h2 id="heading-facade-pattern">Facade Pattern</h2>
<p>The <strong>Facade</strong> pattern provides a simplified interface to a library, a framework, or any other complex set of classes.</p>
<p>Well...we can probably come out with lots of examples for this, right? I mean, React itself or any of the gazillion libraries out there used for pretty much anything related to software development. Specially when we think about <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-programming-paradigms/#declarative-programming">declarative programming</a>, it's all about providing abstractions that hide away complexity from the eyes of the developer.</p>
<p>A simple example could be JavaScript's <code>map</code>, <code>sort</code>, <code>reduce</code> and <code>filter</code> functions, which all work like good 'ol <code>for</code> loops beneath the hood.</p>
<p>Another example could be any of the libraries used for UI development nowadays, like <a target="_blank" href="https://mui.com/">MUI</a>. As we can see in the following example, these libraries offer us components that bring built-in features and functionalities that help us build code faster and easier.</p>
<p>But all this when compiled turns into simple HTML elements, which are the only thing browsers understand. These components are only abstractions that are here to make our lives easier.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/thewolfofwallstreet-fairydust.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A facade...</em></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> Table <span class="hljs-keyword">from</span> <span class="hljs-string">'@mui/material/Table'</span>;
<span class="hljs-keyword">import</span> TableBody <span class="hljs-keyword">from</span> <span class="hljs-string">'@mui/material/TableBody'</span>;
<span class="hljs-keyword">import</span> TableCell <span class="hljs-keyword">from</span> <span class="hljs-string">'@mui/material/TableCell'</span>;
<span class="hljs-keyword">import</span> TableContainer <span class="hljs-keyword">from</span> <span class="hljs-string">'@mui/material/TableContainer'</span>;
<span class="hljs-keyword">import</span> TableHead <span class="hljs-keyword">from</span> <span class="hljs-string">'@mui/material/TableHead'</span>;
<span class="hljs-keyword">import</span> TableRow <span class="hljs-keyword">from</span> <span class="hljs-string">'@mui/material/TableRow'</span>;
<span class="hljs-keyword">import</span> Paper <span class="hljs-keyword">from</span> <span class="hljs-string">'@mui/material/Paper'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createData</span>(<span class="hljs-params">
  name: string,
  calories: number,
  fat: number,
  carbs: number,
  protein: number,
</span>) </span>{
  <span class="hljs-keyword">return</span> { name, calories, fat, carbs, protein };
}

<span class="hljs-keyword">const</span> rows = [
  createData(<span class="hljs-string">'Frozen yoghurt'</span>, <span class="hljs-number">159</span>, <span class="hljs-number">6.0</span>, <span class="hljs-number">24</span>, <span class="hljs-number">4.0</span>),
  createData(<span class="hljs-string">'Ice cream sandwich'</span>, <span class="hljs-number">237</span>, <span class="hljs-number">9.0</span>, <span class="hljs-number">37</span>, <span class="hljs-number">4.3</span>),
  createData(<span class="hljs-string">'Eclair'</span>, <span class="hljs-number">262</span>, <span class="hljs-number">16.0</span>, <span class="hljs-number">24</span>, <span class="hljs-number">6.0</span>),
  createData(<span class="hljs-string">'Cupcake'</span>, <span class="hljs-number">305</span>, <span class="hljs-number">3.7</span>, <span class="hljs-number">67</span>, <span class="hljs-number">4.3</span>),
  createData(<span class="hljs-string">'Gingerbread'</span>, <span class="hljs-number">356</span>, <span class="hljs-number">16.0</span>, <span class="hljs-number">49</span>, <span class="hljs-number">3.9</span>),
];

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BasicTable</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">TableContainer</span> <span class="hljs-attr">component</span>=<span class="hljs-string">{Paper}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Table</span> <span class="hljs-attr">sx</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">minWidth:</span> <span class="hljs-attr">650</span> }} <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"simple table"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">TableHead</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">TableRow</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">TableCell</span>&gt;</span>Dessert (100g serving)<span class="hljs-tag">&lt;/<span class="hljs-name">TableCell</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">TableCell</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"right"</span>&gt;</span>Calories<span class="hljs-tag">&lt;/<span class="hljs-name">TableCell</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">TableCell</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"right"</span>&gt;</span>Fat<span class="hljs-symbol">&amp;nbsp;</span>(g)<span class="hljs-tag">&lt;/<span class="hljs-name">TableCell</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">TableCell</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"right"</span>&gt;</span>Carbs<span class="hljs-symbol">&amp;nbsp;</span>(g)<span class="hljs-tag">&lt;/<span class="hljs-name">TableCell</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">TableCell</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"right"</span>&gt;</span>Protein<span class="hljs-symbol">&amp;nbsp;</span>(g)<span class="hljs-tag">&lt;/<span class="hljs-name">TableCell</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">TableRow</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">TableHead</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">TableBody</span>&gt;</span>
          {rows.map((row) =&gt; (
            <span class="hljs-tag">&lt;<span class="hljs-name">TableRow</span>
              <span class="hljs-attr">key</span>=<span class="hljs-string">{row.name}</span>
              <span class="hljs-attr">sx</span>=<span class="hljs-string">{{</span> '&amp;<span class="hljs-attr">:last-child</span> <span class="hljs-attr">td</span>, &amp;<span class="hljs-attr">:last-child</span> <span class="hljs-attr">th</span>'<span class="hljs-attr">:</span> { <span class="hljs-attr">border:</span> <span class="hljs-attr">0</span> } }}
            &gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">TableCell</span> <span class="hljs-attr">component</span>=<span class="hljs-string">"th"</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"row"</span>&gt;</span>
                {row.name}
              <span class="hljs-tag">&lt;/<span class="hljs-name">TableCell</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">TableCell</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"right"</span>&gt;</span>{row.calories}<span class="hljs-tag">&lt;/<span class="hljs-name">TableCell</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">TableCell</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"right"</span>&gt;</span>{row.fat}<span class="hljs-tag">&lt;/<span class="hljs-name">TableCell</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">TableCell</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"right"</span>&gt;</span>{row.carbs}<span class="hljs-tag">&lt;/<span class="hljs-name">TableCell</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">TableCell</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"right"</span>&gt;</span>{row.protein}<span class="hljs-tag">&lt;/<span class="hljs-name">TableCell</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">TableRow</span>&gt;</span>
          ))}
        <span class="hljs-tag">&lt;/<span class="hljs-name">TableBody</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Table</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">TableContainer</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-proxy-pattern">Proxy Pattern</h2>
<p>The <strong>Proxy</strong> pattern provides a substitute or placeholder for another object. The idea is to control access to the original object, performing some kind of action before or after the request gets to the actual original object.</p>
<p>Again, if you're familiar with <a target="_blank" href="https://expressjs.com/">ExpressJS</a> this probably rings a bell for you. Express is a framework used to develop NodeJS APIs, and one of the features it has is the use of Middlewares. Middlewares are nothing more than pieces of code we can make execute before, in the middle, or after any request reaches our endpoints.</p>
<p>Let's see this in an example. Here I have a function that validates an authentication token. Don't pay much attention to how it does that. Just know that it receives the token as parameter, and once it's done it calls the <code>next()</code> function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> jwt = <span class="hljs-built_in">require</span>(<span class="hljs-string">'jsonwebtoken'</span>)

<span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">authenticateToken</span>(<span class="hljs-params">req, res, next</span>) </span>{
    <span class="hljs-keyword">const</span> authHeader = req.headers[<span class="hljs-string">'authorization'</span>]
    <span class="hljs-keyword">const</span> token = authHeader &amp;&amp; authHeader.split(<span class="hljs-string">' '</span>)[<span class="hljs-number">1</span>]

    <span class="hljs-keyword">if</span> (token === <span class="hljs-literal">null</span>) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).send(<span class="hljs-built_in">JSON</span>.stringify(<span class="hljs-string">'No access token provided'</span>))

    jwt.verify(token, process.env.TOKEN_SECRET, <span class="hljs-function">(<span class="hljs-params">err, user</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">403</span>).send(<span class="hljs-built_in">JSON</span>.stringify(<span class="hljs-string">'Wrong token provided'</span>))
      req.user = user
      next()
    })
}
</code></pre>
<p>This function is a middleware, and we can use it in any endpoint of our API in the following way. We just place the middleware after the endpoint address and before declaration of the endpoint function:</p>
<pre><code class="lang-javascript">router.get(<span class="hljs-string">'/:jobRecordId'</span>, authenticateToken, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> job = <span class="hljs-keyword">await</span> JobRecord.findOne({<span class="hljs-attr">_id</span>: req.params.jobRecordId})
    res.status(<span class="hljs-number">200</span>).send(job)

  } <span class="hljs-keyword">catch</span> (err) {
    res.status(<span class="hljs-number">500</span>).json(err)
  }
})
</code></pre>
<p>In this way, if no token or a wrong token is provided, the middleware will return the corresponding error response. If a valid token is provided, the middleware will call the <code>next()</code> function and the endpoint function will get executed next.</p>
<p>We could've just written the same code within the endpoint itself and validated the token in there, without worrying about middlewares or anything. But the thing is now we have an abstraction we can reuse in many different endpoints. 😉</p>
<p>Again, this might not have been the precise idea the authors had in mind, but I believe it's a valid example. We're controlling an object's access so we can perform actions at a particular moment.</p>
<h1 id="heading-behavioral-design-patterns">Behavioral Design Patterns</h1>
<p>Behavioral patterns control communication and the assignment of responsibilities between different objects.</p>
<h2 id="heading-chain-of-responsibility-pattern">Chain of Responsibility Pattern</h2>
<p>The <strong>Chain of Responsibility</strong> passes requests along a chain of handlers. Each handler decides either to process the request or to pass it to the next handler in the chain.</p>
<p>For this pattern we could use the same exact example as before, as middlewares in Express are somehow handlers that either process a request or pass it to the next handler.</p>
<p>If you'd like another example, think about any system in which you have certain information to process along many steps. At each step a different entity is in charge of performing an action, and the information only gets passed to another entity if a certain condition is met.</p>
<p>A typical front-end app that consumes an API could work as an example:</p>
<ul>
<li><p>We have a function responsible for rendering a UI component.</p>
</li>
<li><p>Once rendered, a another function makes a request to an API endpoint.</p>
</li>
<li><p>If the endpoint response is as expected, the information is passed to another function that sorts the data in a given way and stores it in a variable.</p>
</li>
<li><p>Once that variable stores the needed information, another function is responsible of rendering it in the UI.</p>
</li>
</ul>
<p>We can see how here we have many different entities that collaborate to execute a certain task. Each of them is responsible for a single "step" of that task, which helps with code modularity and separation of concerns.👌👌</p>
<h2 id="heading-iterator-pattern">Iterator Pattern</h2>
<p>The <strong>iterator</strong> is used to traverse elements of a collection. This might sound trivial in programming languages used nowadays, but this wasn't always the case.</p>
<p>Anyway, any of the JavaScript built in functions we have at our disposal to iterate over data structures (<code>for</code>, <code>forEach</code>, <code>for...of</code>, <code>for...in</code>, <code>map</code>, <code>reduce</code>, <code>filter</code>, and so on) are examples of the iterator pattern.</p>
<p>Same as any <a target="_blank" href="https://www.freecodecamp.org/news/introduction-to-algorithms-with-javascript-examples/#traversing-algorithms">traversing algorithm</a> we code to iterate through more complex <a target="_blank" href="https://www.freecodecamp.org/news/data-structures-in-javascript-with-examples/">data structures like trees or graphs</a>.</p>
<h2 id="heading-observer-pattern">Observer Pattern</h2>
<p>The <strong>observer</strong> pattern lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing. Basically, it's like having an event listener on a given object, and when that object performs the action we're listening for, we do something.</p>
<p>React's useEffect hook might be a good example here. What useEffect does is execute a given function at the moment we declare.</p>
<p>The hook is divided in two main parts, the executable function and an array of dependencies. If the array is empty, like in the following example, the function gets executed each time the component is rendered.</p>
<pre><code class="lang-javascript">  useEffect(<span class="hljs-function">() =&gt;</span> { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The component has rendered'</span>) }, [])
</code></pre>
<p>If we declare any variables within the dependency array, the function will execute only when those variables change.</p>
<pre><code class="lang-javascript">  useEffect(<span class="hljs-function">() =&gt;</span> { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'var1 has changed'</span>) }, [var1])
</code></pre>
<p>Even plain old JavaScript event listeners can be thought of as observers. Also, reactive programming and libraries like <a target="_blank" href="https://rxjs.dev/">RxJS</a>, which are used to handle asynchronous information and events along systems, are good examples of this pattern.</p>
<h1 id="heading-roundup"><strong>Roundup</strong></h1>
<p>If you'd like to know more about this topic, I recommend this g<a target="_blank" href="https://www.youtube.com/watch?v=tv-_1er1mWI">reat Fireship video</a> and <a target="_blank" href="https://refactoring.guru/">this awesome website</a> where you can find very detailed explanations with illustrations to help you understand each pattern.</p>
<p>As always, I hope you enjoyed the article and learned something new. If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>.</p>
<p>Cheers and see you in the next one! ✌️</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/See-ya-GIF.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Open-Closed Principle – The Software Development Concept Explained in Plain English ]]>
                </title>
                <description>
                    <![CDATA[ There are many articles about the Open-Closed Principle, but I can never find one that explains it in a way that really works for me.  So here, hopefully, is a good one – with a non trivial and real life example, what changes to support, and a descri... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/open-closed-principle/</link>
                <guid isPermaLink="false">66bb926e0eaca026d8cfa5f4</guid>
                
                    <category>
                        <![CDATA[ software design ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software design patterns ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Cedd Burge ]]>
                </dc:creator>
                <pubDate>Mon, 27 Sep 2021 19:43:06 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/09/IMG_8905.JPG" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There are many articles about the Open-Closed Principle, but I can never find one that explains it in a way that really works for me. </p>
<p>So here, hopefully, is a good one – with a non trivial and real life example, what changes to support, and a description of the trade offs.</p>
<p>The Open-Closed principle states that code should be "Open for extension" and "Closed for modification". </p>
<p>There is <a target="_blank" href="https://codeblog.jonskeet.uk/2013/03/15/the-open-closed-principle-in-review/">quite a lot of confusion about the term</a>, but essentially it means that if you want to implement a <em>supported</em> change, you should be able to do it without changing the code in a large number of places. Ideally, you can implement the new feature just by adding new code, and changing little or no old code, which makes the code easier to develop and maintain. </p>
<p>Open is the 'O' in the <a target="_blank" href="https://www.freecodecamp.org/news/solid-principles-explained-in-plain-english/">SOLID design principles</a>, which are probably the most famous guides for writing high quality code.</p>
<p>No useful code can ever be completely open to all possible changes, so we have to decide which changes we are going to <em>support</em>. When writing our code we can think about what the potential changes might be, decide which ones to <em>support</em>, and then make the code 'open' to these. </p>
<p>We can create a list of these potential changes by:</p>
<ul>
<li>Analysing the code</li>
<li>Looking at previous changes to the code</li>
<li>Using our experience of commonly requested changes</li>
<li>Using any knowledge of upcoming feature requests</li>
</ul>
<p>Take a minute to look at the code below (<a target="_blank" href="https://github.com/ceddlyburge/open-closed-principle/blob/master/OpenClosedPrinciple/Original/GrossToNetCalculator.cs">and on GitHub</a>) and think about what changes we might expect. You don't have access to the commit history, or any knowledge of upcoming feature requests, but you can still probably come up with some likely candidates.</p>
<pre><code class="lang-csharp=">public class GrossToNetCalculator
{
    public GrossToNetCalculator(
        IGrossEnergyYield grossYield,
        double grossEnergy,
        double hysteresisLoss,
        double curtailmentLossGrid,
        double turbineLossTurbulence,
        double electricalLoss,
        double turbineLossShear,
        double turbinePerformanceExperience,
        double operationalExperienceLoss)
    {
        double dependentLoss = 
            CombinePercentages(
                grossYield.TurbineAvailability,
                grossYield.BalanceAvailability,
                grossYield.AccessibilityAvailability,
                hysteresisLoss,
                electricalLoss,
                grossYield.EnvironmentalShutdownWeather,
                grossYield.EnvironmentalSiteAccess,
                grossYield.EnvironmentTreeGrowth);

        double independentLoss = 
            CombinePercentages(
                grossYield.GridAvailability,
                turbinePerformanceExperience,
                turbineLossTurbulence,
                grossYield.EnvironmentalPerformanceDegradationIcing,
                grossYield.CurtailmentPowerPurchase,
                grossYield.SubOptimalPerformance,
                turbineLossShear,
                operationalExperienceLoss);

        GrossToNet = 
            1 - 
            (1 - (dependentLoss + curtailmentLossGrid))
            * (1 - independentLoss);
    }

    double CombinePercentages(params double[] percentages)
    {
        double combination = 1;
        foreach (var percentage in percentages)
            combination *= 1 - percentage;
        return 1 - combination;
    }

    public double GrossToNet { get; private set; }
}
</code></pre>
<p>This code is relatively simple, and when I look at it these are the potential changes that I see:</p>
<ul>
<li>Items could be added or removed from the <code>dependentLoss</code> and <code>independentLoss</code> calculations. Items could be also be moved between <code>dependentLoss</code> and <code>independentLoss</code>, but this is essentially the same thing</li>
<li>The calculation of <code>GrossToNet</code> could change</li>
<li>The <code>CombinePercentages</code> calculation could change</li>
</ul>
<p>As with most things in computer programming, there is a tension when applying the Open-Closed Principle. </p>
<p>On the one hand, making the code more easily extensible is good. On the other hand, doing this often breaks encapsulation, adds complication, and adds unnecessary levels of abstraction. </p>
<p>So again, we need to make a decision about which of these changes we want to support and make the code 'open to'<em>.</em> We can then avoid adding unnecessary complication to the code for unsuitable changes. </p>
<p>It is worth remembering that the work can always be done later, when it will be easier, as we will know exactly what is required.</p>
<p>To make a decision about what changes we should support and make the code 'open to',  we need to estimate how likely the change is to occur, think about design solutions, and then think about the trade offs.</p>
<h2 id="heading-we-could-add-or-remove-items-from-the-dependentloss-and-independentloss-calculations">We Could Add or Remove Items from the dependentLoss and independentLoss Calculations</h2>
<h3 id="heading-ia"> </h3>
<p>Very likely to change</p>
<p>The calculation of <code>dependentLoss</code> and <code>independentLoss</code> (for example <code>double dependentLoss = CombinePercentages(...)</code>) each use 8 parameters (<code>electricalLoss</code>, <code>TurbineAvailability</code> and so on).</p>
<p>These 16 make up the majority of the 17 total inputs to the entire calculation. So, from a purely statistical point of view, a change to one of these has a 16/17 (94%) chance of affecting these calculations.</p>
<p>It's also easy to imagine that we might want to add another "Loss" or "Availability" or similar in the future, or that a current one is no longer relevant, or that different combinations will be required in different circumstances.</p>
<h3 id="heading-possible-solution">Possible solution</h3>
<p>Take a list of dependent and independent losses in the constructor, instead of taking each loss individually. So the existing constructor:</p>
<pre><code class="lang-csharp=">public GrossToNetCalculator(
    ...
    double hysteresisLoss,
    double curtailmentLossGrid,
    ...)
</code></pre>
<p>is replaced with this:</p>
<pre><code class="lang-csharp=">public GrossToNetCalculator(
    IReadOnlyList&lt;double&gt; dependentLosses
    IReadOnlyList&lt;double&gt; independentLosses)
</code></pre>
<p>This means that if the change is requested, we can implement it without changing the class (and instead just changing the parameters we pass to the constructor). </p>
<p>For example, if another 'dependentLoss' is requested, we can just add this to the <code>dependentLosses</code> list.</p>
<p>(You can see the <a target="_blank" href="https://github.com/ceddlyburge/open-closed-principle/tree/master/OpenClosedPrinciple/ListParameters">code on GitHub here</a>)</p>
<h3 id="heading-trade-offs">Trade offs</h3>
<p>A small amount of encapsulation is lost, and the calling code would now be in charge of deciding which losses to pass in.</p>
<p>The code adheres much better to the Open-Closed Principle and becomes much more easily extendable and reusable. If you need to make a change, you won't need to modify the tests, which is useful as they are complicated. </p>
<p>Tests for the calling code would have to modified, but only to verify that they pass the correct parameters, which is much simpler. </p>
<p>It is possible that the constructor parameters are passed around in the code base, and now there are only two parameters, as opposed to the previous nine.</p>
<h3 id="heading-decision">Decision</h3>
<p>We should implement this solution to support this change and make the code 'open' to it. </p>
<h2 id="heading-the-grosstonet-calculation-could-change">The GrossToNet Calculation Could Change</h2>
<h3 id="heading-ia-1"> </h3>
<p>Unlikely to change</p>
<p>The GrossToNet calculation is <code>GrossToNet = 1 - (1 - (dependentLoss + curtailmentLossGrid)) * (1 - independentLoss);</code></p>
<p>Only the <code>curtailmentLossGrid</code> parameter is used, aside from the <code>dependentLoss</code> and <code>independentLoss</code> which are covered earlier.</p>
<p>This 1 parameter is a small minority of the 17 total inputs to the entire calculation. So, from a purely statistical point of view, a change to one of these has a 1/17 (6%) chance of affecting this calculation.</p>
<h3 id="heading-possible-solutions">Possible solutions</h3>
<ol>
<li>Take a lambda parameter in the constructor to calculate <code>GrossToNet</code> and pass it <code>dependentLoss</code> and <code>independentLoss</code>, so that the calculation becomes <code>GrossToNet = grossToNetCalculatorLambda(dependentLoss, independentLoss)</code>(<a target="_blank" href="https://github.com/ceddlyburge/open-closed-principle/tree/master/OpenClosedPrinciple/GrossToNetLambda">code on GitHub</a>)</li>
<li>Remove <code>curtailmentLossGrid</code> from the calculation, which then becomes completely generic and can be renamed to <code>PercentageCombiner</code>. Require that the calling code applies this adjustment (this adjustment is too complicated for useful example code)</li>
<li>Remove <code>curtailmentLossGrid</code> from the calculation as above, then recreate the original <code>GrossToNetCalculator</code>, using the <code>PercentageCombiner</code> and adding <code>curtailmentLossGrid</code> to the calculation<br>(<a target="_blank" href="https://github.com/ceddlyburge/open-closed-principle/tree/master/OpenClosedPrinciple/PercentageCombiner">code on GitHub</a>)</li>
</ol>
<h3 id="heading-trade-offs-1">Trade Offs</h3>
<p>A large amount of encapsulation is lost for options 1 and 2. Option 3 is a reasonable amount of work, and adds a layer of abstraction.</p>
<h3 id="heading-decision-1">Decision</h3>
<p>This change isn't likely to happen, so it probably isn't worth the effort involved to support it and make the code 'open' to it. But if we had another use for the new <code>PercentageCombiner</code> then it would definitely be worthwhile.</p>
<h2 id="heading-the-combinepercentages-calculation-could-change">The CombinePercentages Calculation Could Change</h2>
<h3 id="heading-ia-2"> </h3>
<p>Very unlikely to change</p>
<pre><code class="lang-csharp=">CombinePercentages(params double[] percentages)
{
    double combination = 1;
    foreach (var percentage in percentages)
    combination *= 1 - percentage;
    return 1 - combination;
}
</code></pre>
<p>The CombinePercentages calculation implements some standard laws of math / statistics, which do not change.</p>
<h3 id="heading-possible-solutions-1">Possible solutions</h3>
<ol>
<li>Take a lambda parameter in the constructor to combine the percentages, and use this instead of the CombinePercentages function. So instead of having <code>double dependentLoss = CombinePercentages(...)</code>, you would have  <code>double dependentLoss = combinePercentagesLambda(...)</code>.<br>(<a target="_blank" href="https://github.com/ceddlyburge/open-closed-principle/tree/master/OpenClosedPrinciple/CombinePercentagesLambda">code on GitHub</a>)</li>
<li>Create a <code>PercentageCombiner</code> abstraction, take this in the constructor to combine the percentages, and use this instead of the CombinePercentages function. So instead of having <code>double dependentLoss = CombinePercentages(...)</code>, you would have <code>double dependentLoss = percentageCombiner.CombinePercentages(...)</code>.<br>(<a target="_blank" href="https://github.com/ceddlyburge/open-closed-principle/tree/master/OpenClosedPrinciple/PercentageCombinerAbstraction">code on GitHub</a>)</li>
</ol>
<h3 id="heading-trade-offs-2">Trade offs</h3>
<p>Combining percentages is at the heart of what this code does, so removing this logic makes the code mostly useless. </p>
<p>Option 1 passes all the responsibility for this on to the caller, whereas option 2 at least allows for predefined implementations of the abstraction.</p>
<h3 id="heading-decision-2">Decision</h3>
<p>This change is very unlikely, and the only reasonable solution (option 2) requires a lot of work and adds complexity and abstraction. </p>
<p>This means that it would only make sense to do it when the change is actually required, and even then only if multiple algorithms are required. Note that if a change is required to the algorithm, it will make more sense to simply change the implementation of the CombinePercentages function.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Deciding whether code adheres to the Open-Closed Principle is almost always a judgement call, and there are usually trade offs involved with encapsulation, complexity and abstraction. </p>
<p>It is worth thinking about likely changes and extensions, and using these to guide your decisions.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Model View Controller Pattern – MVC Architecture and Frameworks Explained ]]>
                </title>
                <description>
                    <![CDATA[ The MVC architecture pattern turns complex application development into a much more manageable process. It allows several developers to simultaneously work on the application. When I first learned about MVC patterns, I was intimidated by all the jarg... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-model-view-controller-pattern-mvc-architecture-and-frameworks-explained/</link>
                <guid isPermaLink="false">66bae5f5fea3aa95c7620fad</guid>
                
                    <category>
                        <![CDATA[ design patterns ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software design ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software design patterns ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Rafael D. Hernandez ]]>
                </dc:creator>
                <pubDate>Mon, 19 Apr 2021 14:13:49 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/04/BG.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The MVC architecture pattern turns complex application development into a much more manageable process. It allows several developers to simultaneously work on the application.</p>
<p>When I first learned about MVC patterns, I was intimidated by all the jargon. And even more so when I started applying these concepts to an actual application.</p>
<p>By taking a step back to focus on what MVC is and what it can accomplish, it's much easier to understand and apply the pattern to any web application.</p>
<h2 id="heading-what-is-mvc">What is MVC?</h2>
<p>MVC stands for model-view-controller. Here's what each of those components mean:</p>
<ul>
<li><strong>Model</strong>: The backend that contains all the data logic</li>
<li><strong>View</strong>: The frontend or graphical user interface (GUI)</li>
<li><strong>Controller</strong>: The brains of the application that controls how data is displayed</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/MVC3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The concept of MVCs was first introduced by Trygve Reenskaug, who proposed it as a way to develop desktop application GUIs.</p>
<p>Today the MVC pattern is used for modern web applications because it allows the application to be scalable, maintainable, and easy to expand.</p>
<h2 id="heading-why-should-you-use-mvc">Why Should You Use MVC?</h2>
<p>Three words: <strong>separation of concerns</strong>, or SoC for short.</p>
<p>The MVC pattern helps you break up the frontend and backend code into separate components. This way, it's much easier to manage and make changes to either side without them interfering with each other. </p>
<p>But this is easier said than done, especially when several developers need to update, modify, or debug a full-blown application simultaneously.</p>
<h2 id="heading-how-to-use-mvc">How to Use MVC</h2>
<p>To better illustrate the MVC pattern, I've included a web application that shows how these concepts all work.</p>
<p>My Car Clicker application is a variation of a well-known Cat Clicker app.</p>
<p>Here are some of the major differences in my app:</p>
<ol>
<li>No cats, <strong>only</strong> muscle cars images (sorry cat lovers!)</li>
<li>Multiple car models are listed</li>
<li>There are multiple click counters</li>
<li>It only displays the selected car</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/Screen-Recording-2021-04-11-at-11.31.27.07-PM.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now let's dive into these three components that make up the MVC architecture pattern.</p>
<h3 id="heading-model-data">Model (data)</h3>
<p>The model's job is to simply manage the data. Whether the data is from a database, API, or a JSON object, the model is responsible for managing it.</p>
<p>In the Car Clicker application, the model object contains an array of car objects with all the information (data) needed for the app.</p>
<p>It also manages the current car being displayed with a variable that's initially set to <code>null</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> model = {
    <span class="hljs-attr">currentCar</span>: <span class="hljs-literal">null</span>,
    <span class="hljs-attr">cars</span>: [
        {
            <span class="hljs-attr">clickCount</span>: <span class="hljs-number">0</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Coupe Maserati'</span>,
            <span class="hljs-attr">imgSrc</span>: <span class="hljs-string">'img/black-convertible-coupe.jpg'</span>,
        },
        {
            <span class="hljs-attr">clickCount</span>: <span class="hljs-number">0</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Camaro SS 1LE'</span>,
            <span class="hljs-attr">imgSrc</span>: <span class="hljs-string">'img/chevrolet-camaro.jpg'</span>,
        },
        {
            <span class="hljs-attr">clickCount</span>: <span class="hljs-number">0</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Dodger Charger 1970'</span>,
            <span class="hljs-attr">imgSrc</span>: <span class="hljs-string">'img/dodge-charger.jpg'</span>,
        },
        {
            <span class="hljs-attr">clickCount</span>: <span class="hljs-number">0</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Ford Mustang 1966'</span>,
            <span class="hljs-attr">imgSrc</span>: <span class="hljs-string">'img/ford-mustang.jpg'</span>,
        },
        {
            <span class="hljs-attr">clickCount</span>: <span class="hljs-number">0</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'190 SL Roadster 1962'</span>,
            <span class="hljs-attr">imgSrc</span>: <span class="hljs-string">'img/mercedes-benz.jpg'</span>,
        },
    ],
};
</code></pre>
<h3 id="heading-views-ui">Views (UI)</h3>
<p>The view's job is to decide what the user will see on their screen, and how.</p>
<p>The Car Clicker app has two views: <code>carListView</code> and <code>CarView</code>.</p>
<p>Both views have two critical functions that define what each view wants to initialize and render.</p>
<p>These functions are where the app decides what the user will see and how.</p>
<h4 id="heading-carlistview">carListView</h4>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> carListView = {
    init() {
        <span class="hljs-comment">// store the DOM element for easy access later</span>
        <span class="hljs-built_in">this</span>.carListElem = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'car-list'</span>);

        <span class="hljs-comment">// render this view (update the DOM elements with the right values)</span>
        <span class="hljs-built_in">this</span>.render();
    },

    render() {
        <span class="hljs-keyword">let</span> car;
        <span class="hljs-keyword">let</span> elem;
        <span class="hljs-keyword">let</span> i;
        <span class="hljs-comment">// get the cars to be render from the controller</span>
        <span class="hljs-keyword">const</span> cars = controller.getCars();

        <span class="hljs-comment">// to make sure the list is empty before rendering</span>
        <span class="hljs-built_in">this</span>.carListElem.innerHTML = <span class="hljs-string">''</span>;

        <span class="hljs-comment">// loop over the cars array</span>
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; cars.length; i++) {
            <span class="hljs-comment">// this is the car we've currently looping over</span>
            car = cars[i];

            <span class="hljs-comment">// make a new car list item and set its text</span>
            elem = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'li'</span>);
            elem.className = <span class="hljs-string">'list-group-item d-flex justify-content-between lh-condensed'</span>;
            elem.style.cursor = <span class="hljs-string">'pointer'</span>;
            elem.textContent = car.name;
            elem.addEventListener(
                <span class="hljs-string">'click'</span>,
                (<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">carCopy</span>) </span>{
                    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
                        controller.setCurrentCar(carCopy);
                        carView.render();
                    };
                })(car)
            );
            <span class="hljs-comment">// finally, add the element to the list</span>
            <span class="hljs-built_in">this</span>.carListElem.appendChild(elem);
        }
    },
};
</code></pre>
<h4 id="heading-carview">CarView</h4>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> carView = {
    init() {
        <span class="hljs-comment">// store pointers to the DOM elements for easy access later</span>
        <span class="hljs-built_in">this</span>.carElem = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'car'</span>);
        <span class="hljs-built_in">this</span>.carNameElem = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'car-name'</span>);
        <span class="hljs-built_in">this</span>.carImageElem = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'car-img'</span>);
        <span class="hljs-built_in">this</span>.countElem = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'car-count'</span>);
        <span class="hljs-built_in">this</span>.elCount = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'elCount'</span>);


        <span class="hljs-comment">// on click, increment the current car's counter</span>
        <span class="hljs-built_in">this</span>.carImageElem.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-built_in">this</span>.handleClick);

        <span class="hljs-comment">// render this view (update the DOM elements with the right values)</span>
        <span class="hljs-built_in">this</span>.render();
    },

    handleClick() {
        <span class="hljs-keyword">return</span> controller.incrementCounter();
    },

    render() {
        <span class="hljs-comment">// update the DOM elements with values from the current car</span>
        <span class="hljs-keyword">const</span> currentCar = controller.getCurrentCar();
        <span class="hljs-built_in">this</span>.countElem.textContent = currentCar.clickCount;
        <span class="hljs-built_in">this</span>.carNameElem.textContent = currentCar.name;
        <span class="hljs-built_in">this</span>.carImageElem.src = currentCar.imgSrc;
        <span class="hljs-built_in">this</span>.carImageElem.style.cursor = <span class="hljs-string">'pointer'</span>;
    },
};
</code></pre>
<h3 id="heading-controller-brain">Controller (Brain)</h3>
<p>The controller's responsibility is to pull, modify, and provide data to the user. Essentially, the controller is the link between the view and model.</p>
<p>Through getter and setter functions, the controller pulls data from the model and initializes the views.</p>
<p>If there are any updates from the views, it modifies the data with a setter function.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> controller = {
    init() {
        <span class="hljs-comment">// set the current car to the first one in the list</span>
        model.currentCar = model.cars[<span class="hljs-number">0</span>];

        <span class="hljs-comment">// tell the views to initialize</span>
        carListView.init();
        carView.init();
    },

    getCurrentCar() {
        <span class="hljs-keyword">return</span> model.currentCar;
    },

    getCars() {
        <span class="hljs-keyword">return</span> model.cars;
    },

    <span class="hljs-comment">// set the currently selected car to the object that's passed in</span>
    setCurrentCar(car) {
        model.currentCar = car;
    },

    <span class="hljs-comment">// increment the counter for the currently-selected car</span>
    incrementCounter() {
        model.currentCar.clickCount++;
        carView.render();
    },
};

<span class="hljs-comment">// Let's goooo!</span>
controller.init();
</code></pre>
<h2 id="heading-mvc-frameworks">MVC Frameworks</h2>
<p>JavaScript has grown in popularity, and it's taken over the backend in recent years. More and more full-blown JavaScript applications have opted for the MVC architecture pattern in one way or another.</p>
<p>Frameworks come and go, but what has been constant are the concepts borrowed from the MVC architecture pattern.</p>
<p>Some of the early frameworks that applied these concepts were <strong>KnockoutJS</strong>, <strong>Django</strong>, and <strong>Ruby on Rails.</strong></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The most attractive concept of the MVC pattern is separation of concerns.</p>
<p>Modern web applications are very complex, and making a change can sometimes be a big headache.</p>
<p>Managing the frontend and backend in smaller, separate components allows for the application to be scalable, maintainable, and easy to expand.</p>
<p><em><strong>If you want to take a look at the Car Clicker app, the code is available on <a target="_blank" href="https://github.com/RafaelDavisH/car-clicker/blob/main/README.md">GitHub</a> or checkout the live version <a target="_blank" href="https://rafaeldavish.github.io/car-clicker/">here</a>.</strong></em> </p>
<p>🌟Thank you for reading this far!🌟</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to write easily describable code ]]>
                </title>
                <description>
                    <![CDATA[ When code is not describable using words, most people have to do some mental mapping to turn it in to words. This wastes mental energy, and you run the risk of getting the mapping wrong. Different people will map to different words, which leads to co... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/writing-describable-code/</link>
                <guid isPermaLink="false">66bb9273a5fd14123a8b4a3c</guid>
                
                    <category>
                        <![CDATA[ Code Quality ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software design ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software design patterns ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Cedd Burge ]]>
                </dc:creator>
                <pubDate>Wed, 02 Oct 2019 20:34:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/10/writing-describable-code.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When code is not describable using words, most people have to do some mental mapping to turn it in to words. This wastes mental energy, and you run the risk of getting the mapping wrong. Different people will map to different words, which leads to confusion when discussing the code. </p>
<p>This is usually a fertile breeding ground for bugs born out of miscommunication / misunderstanding, and fixing these bugs often introduces new ones, for the same reasons. In the end it becomes code that no one really understands or wants to touch.</p>
<h2 id="heading-example-of-undescribable-code">Example of undescribable code</h2>
<p>It is easy to think that code is already a written language. If it looks simple, it should be easy to read, speak and listen to. However, this is not always the case.</p>
<p>Below is a common solution to deciding whether a year is a leap year.</p>
<pre><code class="lang-python">(divisibleBy(<span class="hljs-number">4</span>) <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> divisibleBy(<span class="hljs-number">100</span>)) <span class="hljs-keyword">or</span> divisibleBy(<span class="hljs-number">400</span>)
</code></pre>
<p>This is not overly complicated code. It calls a functions 3 times, has 3 operators (and, or, not), and has two levels of nesting.</p>
<p>However, if you take a second to try and describe the algorithm in words I think you will find it to be a struggle.</p>
<p>Maybe “A year is leap year if it is divisible by 4 and not divisible by 100, or divisible by 400”?</p>
<p>The trouble with this is that the code has brackets, but the words do not. So they cannot adequately describe the condition, and whether “or divisible by 400” applies to “divisible by 4” or “not divisible by 400”. You could try some hand waving and gesturing to get around this, or vary the length of pause between the statements, but hopefully it’s obvious that there is a lot of potential for error.</p>
<h2 id="heading-refactoring-to-describable-code">Refactoring to describable code</h2>
<p>Instead we can start by describing the condition with words, and then make the words as clear and concise as possible. We might start with this:</p>
<p>“400 years is a special case. If a year is divisible by 400, then it is a leap  year. 100 years is also a special case. If a year is divisible by 100 then it isn’t a leap year, unless it is also divisble by 400, the 400 year special case takes priority. If there are no special cases, then the year is a leap year if it is divisible by 4.”</p>
<p>This is clear, but isn’t concise, so we would probably want to shrink it a bit:</p>
<p>“If a year is divisible by 400, then it is a leap year. Otherwise if it is divisible by 100 then it is a normal year, otherwise it is a leap year if it is divisible by 4.”</p>
<p>If we turn these words in to code, we probably get something like the following:</p>
<pre><code class="lang-python">    <span class="hljs-keyword">if</span> divisbleBy(<span class="hljs-number">400</span>):
        <span class="hljs-keyword">return</span> LeapYear
    <span class="hljs-keyword">elif</span> divisbleBy(<span class="hljs-number">100</span>)
        <span class="hljs-keyword">return</span> NormalYear
    <span class="hljs-keyword">elif</span> divisbleBy(<span class="hljs-number">4</span>):
        <span class="hljs-keyword">return</span> LeapYear
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> NormalYear
</code></pre>
<h2 id="heading-conclusions">Conclusions</h2>
<p>Hard to understand code is a daily occurrence for virtually all programmers. We can help ourselves and our co-workers by writing code that is easy to describe in words.</p>
<p>And the great thing is that doing so is actually easier than writing code any other way, as there is no mental mapping / wasted mental effort. The only “trick” is to describe the algorithm in words, and then write code to match the words.</p>
<p>In many organisations, the algorithm will already be described in words, as part of acceptance tests or user stories, which will improve productivity even further.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Using the Simple Factory design pattern is a lot like making cheesecake ]]>
                </title>
                <description>
                    <![CDATA[ By Sihui Huang Factory Patterns are about encapsulating object creation. But before diving into details of the patterns, let’s talk about cheesecake. Because cheesecake is about … happiness! ??? Let’s focus our gaze on six of my personal favorites: ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/using-the-simple-factory-design-pattern-is-a-lot-like-making-cheesecake-92a119cde191/</link>
                <guid isPermaLink="false">66c364760002df282f2225ab</guid>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software design patterns ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 26 Dec 2017 12:47:05 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*JtDoAdFERT4heuYF6gGpyg.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Sihui Huang</p>
<p>Factory Patterns are about encapsulating object creation.</p>
<p>But before diving into details of the patterns, let’s talk about cheesecake. Because cheesecake is about … happiness! ???</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*DX0_N89jW5HSmgl5FEuLPQ.png" alt="Image" width="800" height="533" loading="lazy"></p>
<p>Let’s focus our gaze on six of my personal favorites: Original Cheesecake, Ore0 Cheesecake, Coffee Cheesecake, Tiramisu Cheesecake, S’mores Cheesecake, and Hazelnut Cheesecake.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*GB-APPbSeUEBzrrmtsc09w.png" alt="Image" width="790" height="822" loading="lazy"></p>
<p>And here is how we make a cheesecake:</p>
<p>Create a cheesecake instance based on the selected type -&gt; Make crust -&gt; Add layers on top of the crust -&gt; Bake it -&gt; Refrigerate it -&gt; Add toppings to the cake -&gt; Return the cake! ???</p>
<p>Wait … that Mango key lime cheesecake looks very tempting ???.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*oxZrWU870mXJeFCF4RqPBw.png" alt="Image" width="466" height="314" loading="lazy"></p>
<p>Let me add it to my list:</p>
<p>One second …</p>
<p>I have been having too much caffeine lately. I don’t want the coffee cheesecake to be on my list anymore. Let me update the _make<em>cheesecake</em> method again.</p>
<p>Oooh…. they have a low carb version of cheesecake. It’s always nice to have a low carb option. It needs to be on my list!</p>
<p>So since the first time we defined <code>make_cheesecake</code>, we have updated it three times. Each time, the change was for the exact same reason — to update my cheesecake list. And everything else, <code>make_crust</code><em>,</em> <code>add_layers</code><em>,</em> <code>bake</code><em>,</em> <code>refrigerate</code><em>,</em> and <code>add_toppings</code>, remained the same.</p>
<p>Sorry for changing my mind every three seconds. But as they say: <strong>change is the only constant in life (and software development).</strong></p>
<p>To be honest, we will need to change the list at least one more time: pumpkin cheesecake will be available from September. It’s WORLD FAMOUS! Without a doubt, we need to add it to the list once September arrives. Oops, that means we need to remove it from the list when the holiday season passes.</p>
<p>It’s obvious that my cheesecake list changes often.</p>
<p>There is a design principle: <strong>encapsulate what varies</strong>.</p>
<p>We should give it a try.</p>
<h3 id="heading-its-time-for-a-cheesecake-factory">It’s time for a Cheesecake Factory!</h3>
<p>The <code>CheesecakeFactory</code> is a simple class. All it does is create and return the correct cheesecake based on a given type.</p>
<p>With the help of <code>CheesecakeFactory</code>, the <code>make_cheesecake</code> method becomes much simpler.</p>
<p>The <code>make_cheesecake</code> method can now focus on the actual steps that go into making a cheesecake without having to worry about different cheesecake types.</p>
<p>Our <code>CheesecakeFactory</code> is an example of using the Simple Factory. <strong>Simple Factory is used for encapsulating object creation.</strong></p>
<h3 id="heading-the-factory-pattern-family">The Factory Pattern Family</h3>
<p>Besides Simple Factory, there are two other members of the Factory Pattern family: <strong>Factory Method</strong> and <strong>Abstract Factory.</strong> We won’t go into the details of these two patterns.</p>
<p>In a nutshell, Factory Method and Abstract Factory use inheritance. Factory Method is about creating one type of object, and Abstract Factory is about creating a family of different types of objects. All three of them are about encapsulating object creation by using the design principle: encapsulate what varies.</p>
<h3 id="heading-benefits-of-using-simple-factory">Benefits of using Simple Factory</h3>
<p>Pulling the logic of creating the correct cheesecake based on a given type is a small move that gives us lots of benefits. The biggest benefit is that we can modify the cheesecake list without touching the <code>make_cheesecake</code> method and its test. All we need to do is update the <code>CheesecakeFactory</code> class and leave <code>make_cheesecake</code> and its test alone.</p>
<p>We want to separate the parts that vary often from the stable parts. Because each time we modify a part of our code, we might introduce bugs. The parts that vary are the fragile parts of our system. We want to keep the stable parts away from the fragile parts. So if we did introduce bugs when updating a part of the system, it would be easier for us to locate the bug.</p>
<h3 id="heading-takeaways">Takeaways:</h3>
<ol>
<li><strong>Factory Patterns are used for encapsulating object creation.</strong></li>
<li><strong>Design Principle: encapsulate what varies.</strong></li>
</ol>
<p>I need to run to get a cheesecake now.</p>
<p>Don’t forget to subscribe so you won’t miss the next post!</p>
<p>Next time, we will take a look at some waaaaaaaaffles!</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*LvuKW5NzZsznwP-Y3TfInA.png" alt="Image" width="800" height="533" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
