<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Manuel Spagnolo</title>
    <description>The latest articles on DEV Community by Manuel Spagnolo (@shikaan).</description>
    <link>https://dev.to/shikaan</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F55395%2F8c344be0-1a78-4c54-aac8-c1e8514e5bb8.png</url>
      <title>DEV Community: Manuel Spagnolo</title>
      <link>https://dev.to/shikaan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/shikaan"/>
    <language>en</language>
    <item>
      <title>The word development world is missing</title>
      <dc:creator>Manuel Spagnolo</dc:creator>
      <pubDate>Mon, 10 Jun 2019 19:05:57 +0000</pubDate>
      <link>https://dev.to/shikaan/the-word-development-world-is-missing-2o5d</link>
      <guid>https://dev.to/shikaan/the-word-development-world-is-missing-2o5d</guid>
      <description>&lt;p&gt;Following my twit here:&lt;/p&gt;


&lt;blockquote class="ltag__twitter-tweet"&gt;
      &lt;div class="ltag__twitter-tweet__media ltag__twitter-tweet__media__video-wrapper"&gt;
        &lt;div class="ltag__twitter-tweet__media--video-preview"&gt;
          &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0hp0C2jp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://pbs.twimg.com/tweet_video_thumb/D8pExk9XoAsF7HT.jpg" alt="unknown tweet media content"&gt;
          &lt;img src="/assets/play-butt.svg" class="ltag__twitter-tweet__play-butt" alt="Play butt"&gt;
        &lt;/div&gt;
        &lt;div class="ltag__twitter-tweet__video"&gt;
          
            
          
        &lt;/div&gt;
      &lt;/div&gt;

  &lt;div class="ltag__twitter-tweet__main"&gt;
    &lt;div class="ltag__twitter-tweet__header"&gt;
      &lt;img class="ltag__twitter-tweet__profile-image" src="https://res.cloudinary.com/practicaldev/image/fetch/s---54UxOBz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://pbs.twimg.com/profile_images/1086992062405328896/EzomOjQ6_normal.jpg" alt="Manuel Spagnolo profile image"&gt;
      &lt;div class="ltag__twitter-tweet__full-name"&gt;
        Manuel Spagnolo
      &lt;/div&gt;
      &lt;div class="ltag__twitter-tweet__username"&gt;
        @spagmanuel
      &lt;/div&gt;
      &lt;div class="ltag__twitter-tweet__twitter-logo"&gt;
        &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ir1kO05j--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/twitter-f95605061196010f91e64806688390eb1a4dbc9e913682e043eb8b1e06ca484f.svg" alt="twitter logo"&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class="ltag__twitter-tweet__body"&gt;
      How do you call that awesome feeling when after refactoring a piece of code everything around it falls in the right place? 
    &lt;/div&gt;
    &lt;div class="ltag__twitter-tweet__date"&gt;
      19:03 PM - 09 Jun 2019
    &lt;/div&gt;


    &lt;div class="ltag__twitter-tweet__actions"&gt;
      &lt;a href="https://twitter.com/intent/tweet?in_reply_to=1137797483541749760" class="ltag__twitter-tweet__actions__button"&gt;
        &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--fFnoeFxk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/twitter-reply-action-238fe0a37991706a6880ed13941c3efd6b371e4aefe288fe8e0db85250708bc4.svg" alt="Twitter reply action"&gt;
      &lt;/a&gt;
      &lt;a href="https://twitter.com/intent/retweet?tweet_id=1137797483541749760" class="ltag__twitter-tweet__actions__button"&gt;
        &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--k6dcrOn8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/twitter-retweet-action-632c83532a4e7de573c5c08dbb090ee18b348b13e2793175fea914827bc42046.svg" alt="Twitter retweet action"&gt;
      &lt;/a&gt;
      &lt;a href="https://twitter.com/intent/like?tweet_id=1137797483541749760" class="ltag__twitter-tweet__actions__button"&gt;
        &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--SRQc9lOp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/twitter-like-action-1ea89f4b87c7d37465b0eb78d51fcb7fe6c03a089805d7ea014ba71365be5171.svg" alt="Twitter like action"&gt;
      &lt;/a&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/blockquote&gt;


&lt;p&gt;I am totally confident that each and every of you knows that feeling. Is there an English word for that? If not, shall we create it?&lt;/p&gt;

</description>
      <category>discuss</category>
      <category>watercooler</category>
    </item>
    <item>
      <title>Digital music and selfies: the legacy of Jean-Baptiste Joseph Fourier</title>
      <dc:creator>Manuel Spagnolo</dc:creator>
      <pubDate>Sun, 05 May 2019 19:44:40 +0000</pubDate>
      <link>https://dev.to/shikaan/digital-music-and-selfies-the-legacy-of-jean-baptiste-joseph-fourier-co0</link>
      <guid>https://dev.to/shikaan/digital-music-and-selfies-the-legacy-of-jean-baptiste-joseph-fourier-co0</guid>
      <description>&lt;p&gt;Jean-Baptiste Joseph Fourier is one of the most known mathematical personalities in history and with a good reason: he’s the father of Harmonic Analysis also known as Fourier Analysis. We are about to learn how this is the reason why we can stream music, share images and even have echo-cancelling headphones or perform sound searches.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Originally posted on &lt;a href="https://withbenefits.dev/digital-music-and-selfies-fourier"&gt;Full-Stack with Benefits&lt;/a&gt;&lt;br&gt;
Photo by &lt;a href="https://unsplash.com/photos/yEOCA6oiVqg?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;Tim Marshall&lt;/a&gt; on &lt;a href="https://unsplash.com/search/photos/wave?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;Unsplash&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h1&gt;
  
  
  A bit of history
&lt;/h1&gt;

&lt;p&gt;As a lot of the scientists of his time, he was a &lt;em&gt;full-stack&lt;/em&gt; mathematician: his work has spanned Mathematics, Thermodynamics, Chemistry down to Engineering.&lt;/p&gt;

&lt;p&gt;He also contributed to the “Description de l’Égypte”, although I am not sure whether Egyptology falls under the mathematical spectrum of full-stackness…&lt;/p&gt;

&lt;p&gt;Along with his scientific career he was also a key member of the French Revolution and a loyal man in the service of Napoleon Bonaparte. Precisely at that time, he was called to solve a very practical problem which was affecting armed forces: how do we cool down guns and keep them usable during a very busy battle?&lt;/p&gt;

&lt;p&gt;This lead to Fourier’s Theorem (and its byproducts Fourier Transforms) which are exactly the way computers and hi-tech gizmos deal with music and images.&lt;/p&gt;

&lt;h2&gt;
  
  
  Yeah, warm guns really relate to bathroom selfies…
&lt;/h2&gt;

&lt;p&gt;Fourier basic idea was simple yet brilliant: heat waves — no matter how complicated they are — can be decomposed as sum of elementary waves.&lt;/p&gt;

&lt;p&gt;Albeit this was a clever intuition, Fourier did not prove it in modern rigorous terms&lt;sup id="fnref1"&gt;1&lt;/sup&gt;. However, his was not a lucky shot.&lt;/p&gt;

&lt;p&gt;The decomposition of periodic functions in smaller elementary functions dates back to 3rd century BC when Ptolemaic astronomy tried to explain the motion of the planets. Also, the idea that studying heat waves could be related to periodic functions was not entirely new: Euler, d’Alambert and Daniel Bernoulli put together some solutions for the heat problem which happened to work only when the heat source behaved like an elementary wave.&lt;/p&gt;

&lt;p&gt;Anyway, in one hundred years time the whole matter will be completely settled by Dirichlet and Riemann who will put the pieces together and give Harmonic Analysis a proper mathematical foundation.&lt;/p&gt;

&lt;p&gt;As a matter of fact, such mathematical foundation is the very reason why we can use Fourier’s results outside of that domain: heat waves are just… waves, so as long as a given signal can be turned into waves, we can apply Fourier’s results to study them.&lt;/p&gt;

&lt;p&gt;Now your ridiculously boring hours in physics classes make sense: both light which ultimately forms images and sounds are waves. Hence, they can be analyzed using Fourier’s Theorem.&lt;/p&gt;

&lt;h1&gt;
  
  
  Fourier Analysis for the rest of us
&lt;/h1&gt;

&lt;p&gt;First things first: from a mathematical point of view, signals can be thought as functions. So in the following lines — as a common practice in Harmonic Analysis in general — we’ll be referring interchangeably to “functions” and “signals”.&lt;/p&gt;

&lt;p&gt;The whole idea behind Fourier’s work was to rewrite “any given function”&lt;sup id="fnref2"&gt;2&lt;/sup&gt; as sum of elementary periodic chunks. As you remember from high school, the most elementary periodic things you can think of are sine or cosine and these small chunks are usually named &lt;em&gt;oscillations.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Therefore, in Fourier terms all signals can be written like&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--C7_m9VAF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2ApNKPspbq0ngKYdVEHfqw-A.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--C7_m9VAF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2ApNKPspbq0ngKYdVEHfqw-A.png" alt="Simple Fourier sum" width="565" height="23"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;where a coefficients can be thought as the average of the function we want to represent on a given interval. Such interval is called &lt;em&gt;period&lt;/em&gt; and happens to be the period of the oscillations.&lt;/p&gt;

&lt;p&gt;The key idea behind decomposition in oscillations is the following: the more you want to be precise the further you have to go in summing oscillations. Thence, the way to increase precision is to sum infinite chunks. Infinite sums in mathematics are called &lt;em&gt;series&lt;/em&gt; and this is the shape of the &lt;em&gt;Fourier Series&lt;/em&gt; for a given function:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--w1Emm1ey--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2As6zncXijCbappCNWWrsnAw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--w1Emm1ey--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2As6zncXijCbappCNWWrsnAw.png" alt="Fourier Series" width="359" height="61"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;One detail we omitted was that the above works for periodic signals. What happens when the signal is not already periodic? Luckily, the above still holds true to a certain extent and the generalization falls under the name of &lt;em&gt;Fourier Transform.&lt;/em&gt; We’re not going to dig deeper on this.&lt;/p&gt;

&lt;h2&gt;
  
  
  A quick example
&lt;/h2&gt;

&lt;p&gt;A simple way to picture this is thinking about what happens with music. Let’s say, for the sake of the argument, that each note emitted by a piano can be represented as a sinusoidal wave&lt;sup id="fnref3"&gt;3&lt;/sup&gt;. When you play a chord — namely more notes and once — you are producing a wave which is formed by summing all those waves.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--sKEu0eCv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2A4dfCuldZ1t-GKvg5SekpWw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--sKEu0eCv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/2000/1%2A4dfCuldZ1t-GKvg5SekpWw.png" alt="Top wave (the chord wave) is the sum of bottom notes waves (the notes waves)" width="600" height="600"&gt;&lt;/a&gt;&lt;em&gt;Top wave (the chord wave) is the sum of bottom notes waves (the notes waves)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;What you get then is a complex signal which is ultimately given by the sum of elementary signals. The peak of the chord wave (the yellow one) happens when all the three node waves are at their peak, whereas none of the bottoms of the chord wave are as low in comparison: this is due to the fact that there is no moment when the three of them are at their bottom concurrently.&lt;/p&gt;

&lt;h1&gt;
  
  
  Applications in everyday life
&lt;/h1&gt;

&lt;p&gt;Now, what you might be wondering how summing infinite things can lead to a non-infinite, hence meaningful, result. This problem is rather general in Mathematics, it is called &lt;em&gt;convergence&lt;/em&gt; and unfortunately cannot be treated within this article because of its complexity.&lt;/p&gt;

&lt;p&gt;However, one very evident thing can be observed here: to make this sum to not go to infinity (i.e. &lt;em&gt;diverge&lt;/em&gt;), we need chunks which get smaller and smaller. This in turn implies that some items in the sum are holding the greatest part of the information needed to represent the original signal.&lt;/p&gt;

&lt;p&gt;This last observation is what makes Spotify, Shazam, Instagram and even your iPhone’s guitar tuner app or noise canceling headphones possible.&lt;/p&gt;

&lt;p&gt;In fact, when you are playing your music via Spotify you are not listening to the song exactly as it has been recorded. In order to provide a continuous data flow and keep the track going without needing to download it in advance, Spotify applies a compression algorithm which is meant to reduce file size enough to be streamed in real time.&lt;/p&gt;

&lt;p&gt;What this algorithm does is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;spot oscillations related to frequencies at end of or beyond the human audible spectrum and shave them off;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;remove the oscillations which do not hold a lot of information, namely the “rest” of the series.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The same principle applies to Shazam, SoundHound or even Siri and Google Assistant: when you provide a sound input, these software need to clean it, for example, removing frequencies which go beyond the average human voice spectrum and taking away minor oscillations. The actual search then happens comparing the coefficients of same oscillations between your input and a dataset.&lt;/p&gt;

&lt;p&gt;Noise cancelling headphones work the same way: they have a microphone which records the ambient sound and calculates oscillations. Then they flip the oscillations so that the sum with the sound around you yields a silent wave. Eventually they inject this flipped wave in your mix so that frequencies outside of your music are not audible.&lt;/p&gt;

&lt;p&gt;For images the things get a bit trickier because in that case we have to speak about two-dimensional Fourier Transform as the image signal spans across two dimensions. The underlying idea though stays the same: when we share a picture on Instagram, an algorithm chunks the image and applies the same kind of approximation we have seen above on every single pixel. This time around the computation happens on things like color spectrum and brightness and elements which live at the border of our perception are tossed away.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Every time you will see your younger sister’s bathroom selfies on Instagram or you listen to a Ed Sheeran song on Spotify, now you know who to blame. Do you think that in hindsight Fourier would have spread this knowledge?&lt;/p&gt;

&lt;p&gt;Until next time!&lt;/p&gt;




&lt;ol&gt;

&lt;li id="fn1"&gt;
&lt;p&gt;It was not his fault though: at that time we did not have a clear definition of integral nor of function. It was in fact impossible to prove Fourier’s Theorem from a modern perspective. ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn2"&gt;
&lt;p&gt;Mathematically speaking this is sooo wrong. Unfortunately we live in a faulty world, where most of the time engineers go with this kind of assumptions and and we settle for approximated solutions. ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn3"&gt;
&lt;p&gt;Actually each and every note is already a sum of sinusoidal waves. The set of waves which contributes to the sound of a note as we perceive it is called Harmonic Series and the single waves are called Harmonics. ↩&lt;/p&gt;
&lt;/li&gt;

&lt;/ol&gt;

</description>
      <category>algorithms</category>
      <category>webperf</category>
    </item>
    <item>
      <title>A community driven blog: Full-Stack With Benefits</title>
      <dc:creator>Manuel Spagnolo</dc:creator>
      <pubDate>Fri, 19 Apr 2019 04:45:28 +0000</pubDate>
      <link>https://dev.to/shikaan/a-community-driven-blog-full-stack-with-benefits-4143</link>
      <guid>https://dev.to/shikaan/a-community-driven-blog-full-stack-with-benefits-4143</guid>
      <description>&lt;p&gt;There are a few words which can describe the feeling of accomplishment caused by placing the cornerstone of one of your products. &lt;/p&gt;

&lt;p&gt;My English is awful, so I really don't know any of them.&lt;/p&gt;

&lt;p&gt;However, I am excited to share with you the first draft of my community driven blog: &lt;a href="https://withbenefits.dev" rel="noopener noreferrer"&gt;Full-Stack with Benefits&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Name
&lt;/h2&gt;

&lt;p&gt;Well, there is no Rated R background, but it's still worth sharing the story.&lt;/p&gt;

&lt;p&gt;Some months ago a new member of the Design Team joined the company I am currently working for. During the introductory round of presentations, someone was trying to explain what I do on a daily basis. We all agreed that full-stack was not enough, so Luke, a coworker of mine, came up with this title: full-stack with benefits.&lt;/p&gt;

&lt;h2&gt;
  
  
  The history
&lt;/h2&gt;

&lt;p&gt;This is the result of what I started sharing with you here&lt;/p&gt;


&lt;div class="ltag__link"&gt;
  &lt;a href="/shikaan" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F55395%2F8c344be0-1a78-4c54-aac8-c1e8514e5bb8.png" alt="shikaan"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="/shikaan/being-your-own-product-owner-59de" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Being Your Own Product Owner&lt;/h2&gt;
      &lt;h3&gt;Manuel Spagnolo ・ Mar 10 '19&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#discuss&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#productivity&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;


&lt;p&gt;A few things changed in the meantime. &lt;/p&gt;

&lt;p&gt;Since the bureaucracy I was introducing in the process I described in the other article was actually just slowing me down without any concrete benefit, I just decided to shave that off and think about an effective process if and only if I will start having steady collaborators.&lt;/p&gt;

&lt;p&gt;The biggest change though has been the branding. As you might have noticed, the blog had to change name and pretty much all the design compared to what you have there, because apparently Coffee Driven Developer was not the most original name in the world. Try googling it to know why...&lt;/p&gt;

&lt;h2&gt;
  
  
  The future
&lt;/h2&gt;

&lt;p&gt;The Trello board I shared in the other article still holds true and actually hosts almost all the features I want to put into this product, as soon as I have time.&lt;/p&gt;

&lt;p&gt;Content-wise, the blog is meant to be a bit wider spectrum compared to my contributions to the Dev community. Most probably I will write about other important things in my life as music, mathematics, travels and Badu, my dog. &lt;/p&gt;

&lt;p&gt;By the way, I am already mentioning Badu there. Did you spot her?&lt;/p&gt;

&lt;p&gt;Code-wise, the idea is to keep the development of this product open and eventually turn it into a community: you can already contribute to the articles and to the features by submitting a PR here&lt;/p&gt;


&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/shikaan" rel="noopener noreferrer"&gt;
        shikaan
      &lt;/a&gt; / &lt;a href="https://github.com/shikaan/shikaan.github.io" rel="noopener noreferrer"&gt;
        shikaan.github.io
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      Personal blog
    &lt;/h3&gt;
  &lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Next thing is the pipeline is writing proper documentation and contributions guideline, but in the meantime you can start digging into it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;You can check out the blog &lt;a href="https://withbenefits.dev" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I guess this is it. I just want to thank in advance whomever will be spending some time browsing it and as always feel free to reach out should you have any suggestion.&lt;/p&gt;

&lt;p&gt;Until next time!&lt;/p&gt;

</description>
      <category>showdev</category>
      <category>javascript</category>
      <category>react</category>
      <category>gatsby</category>
    </item>
    <item>
      <title>Being Your Own Product Owner</title>
      <dc:creator>Manuel Spagnolo</dc:creator>
      <pubDate>Sun, 10 Mar 2019 20:49:25 +0000</pubDate>
      <link>https://dev.to/shikaan/being-your-own-product-owner-59de</link>
      <guid>https://dev.to/shikaan/being-your-own-product-owner-59de</guid>
      <description>&lt;p&gt;As some of you&lt;sup&gt;1&lt;/sup&gt; might have realized, I am not writing any articles recently. I could state a lot of different reasons why (and some of them will be material for upcoming blog posts, by the way), but the main concrete reason for it is that I am spending most of my spare time creating my blog.&lt;/p&gt;

&lt;p&gt;Whether the world needs another dev-tech-geeky blog made with Gatsby is highly arguable, but what is interesting for me is the process. &lt;/p&gt;

&lt;p&gt;As opposed to my stereotypical pet project, I am trying to stick with a "business-like" process. &lt;/p&gt;

&lt;h2&gt;
  
  
  Design
&lt;/h2&gt;

&lt;p&gt;Following what I learned from &lt;a href="https://www.amazon.com/Elements-User-Experience-User-Centered-Design/dp/0321683684"&gt;this awesome book&lt;/a&gt;, I have split the design of this product into layers, allowing me to get to the design phase with a lot of light already shed.&lt;/p&gt;

&lt;p&gt;The document I produced can be found &lt;a href="https://hackmd.io/s/SJJDvFfvE"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;As you can see, the document is far from the level of details discussed in the book and way more simplistic. Nonetheless, it turned out to be a huge productivity boost for me. With development (and music and other things within my comfort zone) it was crystal clear which kind of difference a proper plan could make. With design, for me, it was &lt;em&gt;mindblowing&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/5aLrlDiJPMPFS/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/5aLrlDiJPMPFS/giphy.gif" alt="Mindblown GIF" width="347" height="404"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;The main focus during this phase has been forgetting I am a developer, forget technical constraints and try as hard as I could to think like a designer.&lt;/p&gt;

&lt;p&gt;This led me to produce the design you can see &lt;a href="https://www.figma.com/file/JBpXSOaeMeN6dDjf4lyQeKxP/CDD?node-id=68%3A7"&gt;here&lt;/a&gt;.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Owning the product
&lt;/h2&gt;

&lt;p&gt;If shifting from the Developer to Designer has been hard, shifting from Developer to Product Owner is actually being even harder. &lt;/p&gt;

&lt;p&gt;Although I thought I knew what to expect from a good user story, producing a good one is actually a completely different story (pun intended).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://trello.com/b/1uRW5ouh/coffee-driven-developer"&gt;This&lt;/a&gt; is the board I am working with.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why this post?
&lt;/h2&gt;

&lt;p&gt;Well, as my own Product Owner I feel a bit at loss right now. &lt;/p&gt;

&lt;p&gt;Maybe I am introducing too much boureaucracy in the process, but I really struggle in dividing my Developer self from my Product Owner self and this is exactly why I am asking for your help.&lt;/p&gt;

&lt;p&gt;As developers, what would you like to see in a board like this? What is missing? &lt;/p&gt;

&lt;p&gt;As product owners, can you suggest any good resource to learn how to write kickass stories and tickets?&lt;/p&gt;

&lt;p&gt;Thank you all!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If you were still wondering, the code is still in a very bad shape, but as soon as I reach the &lt;code&gt;v0.0.1&lt;/code&gt; milestone, I will open source it.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;1. It's actually a lot of you ❤ I never would have thought of having ~3.5k followers. Thanks to each and every one of you!&lt;/p&gt;

</description>
      <category>discuss</category>
      <category>productivity</category>
    </item>
    <item>
      <title>How I Learned to Stop Worrying and Love the Cache - Stick with it</title>
      <dc:creator>Manuel Spagnolo</dc:creator>
      <pubDate>Sun, 06 Jan 2019 19:43:53 +0000</pubDate>
      <link>https://dev.to/shikaan/how-i-learned-to-stop-worrying-and-love-the-cache---stick-with-it-3636</link>
      <guid>https://dev.to/shikaan/how-i-learned-to-stop-worrying-and-love-the-cache---stick-with-it-3636</guid>
      <description>&lt;h4&gt;
  
  
  Check out the updated version &lt;a href="https://withbenefits.dev/cache-fundamentals/"&gt;here&lt;/a&gt;
&lt;/h4&gt;

&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;You might have noticed that this sub-series has just changed the name: it wasn't about Design Patterns, there was no point in keeping those two as part of the same thing.&lt;/p&gt;

&lt;p&gt;As said &lt;a href="https://dev.to/shikaan/-design-patterns-in-web-development----active-caching-1-23e2"&gt;in the first episode&lt;/a&gt;, this article is going to be more about what's already there in the wild in terms of caching and how we as developers should deal with it.&lt;/p&gt;

&lt;p&gt;What we are about to cover is something you typically decide once in a while or you don't decide at all because some frameworks and libraries make these decisions for you. Thus, the idea here is to have a go-to place where you can get an understanding or just dust off those concepts every time you have to deal with caching again.&lt;/p&gt;

&lt;h2&gt;
  
  
  Serving the correct application version
&lt;/h2&gt;

&lt;p&gt;Serving the correct version of a web app started to become something you should be concerned about only "recently". &lt;/p&gt;

&lt;p&gt;Back in the days, we had server-side technologies like Java, JSP and PHP which used to serve thin client applications with small or no logic at all. Over time clients got thicker and we started splitting responsibilities between frontend and backend to the point where frontend and backend are usually two completely different applications&lt;sup&gt;1&lt;/sup&gt; which are just meant to communicate, rather than being "the same thing".&lt;/p&gt;

&lt;p&gt;When the application is run by the server, serving the correct version isn't a concern, because the browser is usually just asking "that page" and the ball it's in the server's court with regards with deciding which version of that page to serve&lt;sup&gt;2&lt;/sup&gt;.&lt;/p&gt;

&lt;p&gt;When the application lives on the client side, unfortunately, the page requested by the browser is usually an &lt;code&gt;index.html&lt;/code&gt; with a &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; which includes the client application via an &lt;code&gt;src&lt;/code&gt; attribute.&lt;/p&gt;

&lt;p&gt;So if the &lt;code&gt;index.html&lt;/code&gt; is something like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Wonderful WebApp&amp;lt;/title&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
      &amp;lt;main id="app"&amp;gt;&amp;lt;/main&amp;gt;

      &amp;lt;script src="app.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we could theoretically just bundle a different &lt;code&gt;app.js&lt;/code&gt; every time keeping the &lt;code&gt;index.html&lt;/code&gt; the same.&lt;/p&gt;

&lt;p&gt;Unfortunately, that is not true any more. Browsers nowadays understand whether something changes&lt;sup&gt;3&lt;/sup&gt;, so rather than asking again &lt;code&gt;app.js&lt;/code&gt;, they will just assume it never changed and serve the old one unless we communicate them to not do so.&lt;/p&gt;

&lt;p&gt;One way of doing this is appending the version of the application as a query string parameter in the &lt;code&gt;src&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Wonderful WebApp&amp;lt;/title&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
      &amp;lt;main id="app"&amp;gt;&amp;lt;/main&amp;gt;

      &amp;lt;script src="app.js?v=1.2.3"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thus every time we bump a new version of the bundle, the browser is forced to perform a new request because the URL and the &lt;code&gt;index.html&lt;/code&gt; changed.&lt;/p&gt;

&lt;p&gt;Another similar (and by far more common nowadays) approach is naming the bundle with a hash which is different on every deploy. The hash can be based on the actual version, on the code, on the latest revision number or even the timestamp of the moment when the build happened.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Wonderful WebApp&amp;lt;/title&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
      &amp;lt;main id="app"&amp;gt;&amp;lt;/main&amp;gt;

      &amp;lt;script src="app.gt8heef.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This technique is rather popular and most of the time is "for free" in CLIs for popular frameworks (like Create React App, Angular CLI, Vue CLI, Ember CLI). &lt;/p&gt;

&lt;p&gt;You can implement it yourself using a build tool which rewrites the &lt;code&gt;index.html&lt;/code&gt; including the version number/hash or, eventually, using &lt;code&gt;manifest.json&lt;/code&gt; to get more fine-grained control. Some references to help you with implementation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://webpack.js.org/guides/caching/"&gt;Webpack - Caching&lt;/a&gt; my preferred way;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://medium.com/@felipebernardes/solving-browser-cache-hell-with-gulp-rev-6349a293abb9"&gt;Medium - Solving Browser Cache Hell With Gulp-Rev&lt;/a&gt; a gentle introduction to &lt;code&gt;manifest.json&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://dzone.com/articles/use-gulp-to-bundle-minify-and-cache-bust"&gt;DZone - Use Gulp to bundle, minify and cache-bust&lt;/a&gt; old, but still relevant;&lt;/li&gt;
&lt;li&gt;
&lt;a href="http://thisisjessie.com/cache-busting-via-per-file-query-strings-with-make/"&gt;Jessie Wong - Cache busting with Makefile&lt;/a&gt; a bit hardcore to me, but still an option.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Optimize content delivery with Service Workers
&lt;/h2&gt;

&lt;p&gt;Among the things going hand in hand with &lt;code&gt;manifest.json&lt;/code&gt; (especially with regards to Progressive Web Apps), we have Service Workers.&lt;/p&gt;

&lt;p&gt;Without going too much in details about the awesome things you can do with service workers&lt;sup&gt;4&lt;/sup&gt;, you can imagine them as a JavaScript thread running in parallel in the browser whose life cycle is not bound to the client application's one.&lt;/p&gt;

&lt;p&gt;The reason why we are so interested in them here is that in Service Worker API we have access to the Cache Interface.&lt;/p&gt;

&lt;p&gt;There are some caching recipes you can follow, but the most common are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;on install&lt;/li&gt;
&lt;li&gt;on user interaction&lt;/li&gt;
&lt;li&gt;on network response&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The naming convention is borrowed from one of the greatest resource on the matter you can find online, namely &lt;a href="https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/"&gt;Google's Offline Cookbook&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;If you followed what happened in previous episodes, you will certainly notice that the role played by Service Workers in those recipes is what in general we have called &lt;em&gt;Resource Manager&lt;/em&gt;. Hence in the following paragraphs, I am about to show how those patterns map to what we said in previous articles.&lt;/p&gt;

&lt;p&gt;Well, to be fair there's another very good resource about this topic which is &lt;a href="https://serviceworke.rs/caching-strategies.html"&gt;Mozilla's Service Workers Cookbook - Caching Strategies&lt;/a&gt;, but I find Google's perspective easier to follow. I strongly encourage you to read both anyway to have a wider spectrum overview.&lt;/p&gt;

&lt;h3&gt;
  
  
  On Install
&lt;/h3&gt;

&lt;p&gt;In this pattern we do a cache write on the &lt;code&gt;install&lt;/code&gt; hook of the Service Worker. It looks particularly useful when you want to store the application shell to be able to provide an offline experience.&lt;/p&gt;

&lt;p&gt;In the Google's cookbook, this comes in two different fashions called "as a dependency" and "not as a dependency", which are basically "Write Through" and "Write Behind" of &lt;a href="https://dev.to/shikaan/-design-patterns-in-web-development----active-caching-2-37jc"&gt;this article&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  On User Interaction
&lt;/h3&gt;

&lt;p&gt;From a caching strategy perspective, this pattern is not that different from &lt;code&gt;On Install&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Suppose you want to implement a "Read Later" button on a blog. What you need to do is fetch the article and store it. Deciding if you want to save is synchronously (as in "Write Through") or asynchronously (as in "Write Behind") depends on your use case, but both the approach are feasible.&lt;/p&gt;

&lt;h3&gt;
  
  
  On Network Response
&lt;/h3&gt;

&lt;p&gt;Of the three examples we are providing, this is by far the most common since you can apply this strategy every time you need to fetch data over network. &lt;/p&gt;

&lt;p&gt;The implementation proposed in the offline cookbook is "Read Through" - no more, no less!&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;span id="http-headers"&gt;W3C standards: HTTP Headers
&lt;/span&gt;
&lt;/h2&gt;

&lt;p&gt;In the wonderful world of web development, finding a new fancy way of being screwed is never a problem. This is precisely why you may want to understand how the browser communicates with the server with regards to cached content. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Disclaimer&lt;/strong&gt;&lt;br&gt;
Even though I will always refer to the browser in the following paragraph, this also applies to server to server communication, so backenders could find this interesting as well.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Again, I am treating only the most interesting cases, but here you can find a list of resources covering more cases:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching"&gt;MDN - HTTP Caching&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.digitalocean.com/community/tutorials/web-caching-basics-terminology-http-headers-and-caching-strategies"&gt;DigitalOcean - Web Caching Basics&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.keycdn.com/blog/http-cache-headers"&gt;KeyCDN - HTTP Cache Headers Explained&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9"&gt;W3C - Cache-Control Specification&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19"&gt;W3C - ETag Specification&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching"&gt;Google - HTTP Caching&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  ETag
&lt;/h3&gt;

&lt;p&gt;Even though the name is not exactly explicit, the ETag HTTP Header is one of the headers we can use to have control over cached content. ETag stands for "Entity Tag" and it is a way of tagging with a hash a specific version of a content we are exchanging.&lt;/p&gt;

&lt;p&gt;In this case, an example will be better than one thousand words.&lt;/p&gt;

&lt;p&gt;Suppose you as a client (both another server or browser) are requesting &lt;code&gt;GET /dogs&lt;/code&gt;. The counterpart will respond with a 200 and the following response headers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;200 OK
Content-length: 512
Cache-Control: max-age=60
ETag: a23g1t4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we'll see in the following sections, &lt;code&gt;max-age=60&lt;/code&gt; tells us that the content will become stale in 60 seconds. &lt;/p&gt;

&lt;p&gt;Suppose that after one minute, we request again the same resource but this time we attach the following request headers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;GET /dogs
If-None-Match: a23g1t4 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;which basically means "give me either valid cached content or stale content as long as its version is a23g1t4".&lt;/p&gt;

&lt;p&gt;At this point the server will try to serve cached content, then falls back on stale content with that version and, if not even that is found, then it performs the actual request. In case the cached content is found the response will be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;304 Not Modified
Content-length: 512
Cache-Control: max-age=60
ETag: a23g1t4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Cache-Control
&lt;/h3&gt;

&lt;p&gt;The Cache-Control HTTP header is used to define a cache policy, both from a client side (for example, "don't give me cached content") and from a server side (for example, "this content will expire in two minutes").&lt;/p&gt;

&lt;p&gt;Cache-Control has &lt;em&gt;tons&lt;/em&gt; of directives which can be combined in a lot of fancy ways which is impossible to cover in a couple of paragraphs. Maybe it makes sense to write a separate article on that (and if you're interested, please let me know!). We'll be covering here only the most common directives.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;code&gt;no-cache&lt;/code&gt; &amp;amp; &lt;code&gt;no-store&lt;/code&gt;
&lt;/h4&gt;

&lt;p&gt;These two bad boys are probably the most mixed up. &lt;/p&gt;

&lt;p&gt;The directive &lt;code&gt;no-store&lt;/code&gt; - used both as a directive in &lt;em&gt;request headers&lt;/em&gt; and &lt;em&gt;response headers&lt;/em&gt; - simply means that any caching mechanism should be skipped. So the client should not cache the response it gets (when used in the request) and the server should not cache the response to speed up following requests (when used in the response). &lt;/p&gt;

&lt;p&gt;When used as &lt;em&gt;response headers&lt;/em&gt;, &lt;code&gt;no-cache&lt;/code&gt; means that the content served won't automatically be valid for subsequent requests. This basically means that the content can be cached or not, but, if it is, it has to be validated (for example using &lt;code&gt;ETag&lt;/code&gt;) before being served.&lt;/p&gt;

&lt;p&gt;When used as &lt;em&gt;request header&lt;/em&gt;, &lt;code&gt;no-cache&lt;/code&gt; means that we don't care about what's cached and we want a fresh request. However, this does not define whether the server can cache the response to speed up following requests (as opposed as &lt;code&gt;no-store&lt;/code&gt;) and usually server will cache that response.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;code&gt;public&lt;/code&gt; &amp;amp; &lt;code&gt;private&lt;/code&gt;
&lt;/h4&gt;

&lt;p&gt;These look pretty obvious, but they actually hide a small quirk.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;public&lt;/code&gt; is most of the time useless and, in fact, you rarely find it. It just means "this content can be safely cached", but usually you have other directives telling you that (for example &lt;code&gt;max-age&lt;/code&gt;, as we're about to see).&lt;/p&gt;

&lt;p&gt;&lt;code&gt;private&lt;/code&gt; instead is a bit more tricky. It doesn't mean that you cannot cache the response at all, but it rather says "you can cache that only if you own the content". &lt;/p&gt;

&lt;p&gt;What does being the owner of the information mean? &lt;/p&gt;

&lt;p&gt;Suppose you have a micro-service built application with an API gateway in front of it. Every single service &lt;em&gt;and&lt;/em&gt; the API gateway can have a cache, but only the micro-services themselves own the information. Usually, the content marked as &lt;code&gt;private&lt;/code&gt; is just for one specific user, so only that user and the originator of that information can cache it. &lt;/p&gt;

&lt;p&gt;Hence, in the example above, a browser could actually cache that information (as the user owns it) and the micro-service originating the information can, but the API gateway can't and any eventually CDN in between can't as well.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;code&gt;max-age&lt;/code&gt;
&lt;/h4&gt;

&lt;p&gt;When used in requests, &lt;code&gt;max-age=n&lt;/code&gt; means that the client is willing to accept content which is not older than &lt;code&gt;n&lt;/code&gt; seconds.&lt;/p&gt;

&lt;p&gt;When used in responses, &lt;code&gt;max-age=m&lt;/code&gt; means that the information delivered will be considered stale in &lt;code&gt;m&lt;/code&gt; seconds.&lt;/p&gt;

&lt;h1&gt;
  
  
  Final Words
&lt;/h1&gt;

&lt;p&gt;This is the end of this Christmas streak, but maybe not the end of this caching series. Who knows? There are a lot more things we can cover...&lt;/p&gt;

&lt;p&gt;As always, if you have any feedback (e.g., why did you stop with memes? why are you so obsessed with caching? how could you complete a whole episode without mentioning food?) feel free to reach out.&lt;/p&gt;

&lt;p&gt;Until next time!&lt;/p&gt;




&lt;p&gt;1. We still have Server Side Rendered applications, but &lt;em&gt;usually&lt;/em&gt; the backend layer responsible of rendering the client is still not taking care of other parts of business logic, making the whole thing still split to a certain extent.&lt;/p&gt;

&lt;p&gt;2. This is not entirely true: there are ways to get stale content even with server rendered applications. We are going to treat how to get fresh content in this (and other cases) in the HTTP Headers section.&lt;/p&gt;

&lt;p&gt;3. We'll dig a bit deeper on how browsers actually understand when to request fresh data or not in the HTTP Headers section&lt;/p&gt;

&lt;p&gt;4. I am not letting you down ❤ &lt;a href="https://developers.google.com/web/fundamentals/primers/service-workers/"&gt;Here&lt;/a&gt;'s a very good introduction by Google on the matter. &lt;/p&gt;

</description>
      <category>webdev</category>
      <category>python</category>
      <category>javascript</category>
      <category>cache</category>
    </item>
    <item>
      <title>How I Learned to Stop Worrying and Love the Cache - Writing</title>
      <dc:creator>Manuel Spagnolo</dc:creator>
      <pubDate>Tue, 25 Dec 2018 19:16:28 +0000</pubDate>
      <link>https://dev.to/shikaan/-design-patterns-in-web-development----active-caching-2-37jc</link>
      <guid>https://dev.to/shikaan/-design-patterns-in-web-development----active-caching-2-37jc</guid>
      <description>&lt;h4&gt;
  
  
  Check out the updated version &lt;a href="https://withbenefits.dev/what-is-cache-part-ii/" rel="noopener noreferrer"&gt;here&lt;/a&gt;
&lt;/h4&gt;

&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;This second episode follows what we started &lt;a href="https://dev.to/shikaan/-design-patterns-in-web-development----active-caching-1-23e2"&gt;here&lt;/a&gt; and will be about cache writing techniques.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Please Note&lt;/strong&gt;&lt;br&gt;
If you're looking for an introduction about caching in general and reading techniques, you can go &lt;a href="https://dev.to/shikaan/-design-patterns-in-web-development----active-caching-1-23e2"&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h1&gt;
  
  
  What?! Writing techniques?!
&lt;/h1&gt;

&lt;p&gt;&lt;strong&gt;I am still food drunk. GIMME THE CODE&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I totally see your surprise here. In the reading techniques we already mentioned how and when to write to Cache Layer, so why in the hell do we have a set of different strategies here?&lt;/p&gt;

&lt;p&gt;We are calling &lt;em&gt;reading techniques&lt;/em&gt; those which are actually concerned with reading actions. For example, &lt;strong&gt;get&lt;/strong&gt; a list of transaction. So, even though we already performed some writing, we were actually performing writing only to serve the purpose of reading actions.&lt;/p&gt;

&lt;p&gt;So, &lt;em&gt;writing techniques&lt;/em&gt; are basically strategies used during write actions to populate or update Cache. The biggest part of the benefits you get out of them is, again, when you are going to read data afterwards. Examples of writing actions are: &lt;strong&gt;create&lt;/strong&gt; a new transaction, &lt;strong&gt;edit&lt;/strong&gt; user info and so forth.&lt;/p&gt;

&lt;p&gt;As mentioned &lt;a href="https://dev.to/shikaan/-design-patterns-in-web-development----active-caching-1-23e2"&gt;in the other article&lt;/a&gt;, we are going to speak about these patterns:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Write Through&lt;/li&gt;
&lt;li&gt;Write Behind&lt;/li&gt;
&lt;li&gt;Write Around&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As last time, these are the participants:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Client&lt;/strong&gt;: who needs data;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cache&lt;/strong&gt;: where you store data;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Resource Manager&lt;/strong&gt;: delivers resources to the Client;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data Accessor&lt;/strong&gt;: fetches data from outside the application.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Write Through (aka Write Inline)
&lt;/h2&gt;

&lt;p&gt;Exactly as for Read Through (or Cache Inline), we have the Resource Manager sitting in line between Client and Data Accessor. &lt;/p&gt;

&lt;p&gt;This diagram illustrates the lifecycle of a writing action using Write Through&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F3s6w39l9kgew5qh2uc27.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F3s6w39l9kgew5qh2uc27.png" alt="Write Through."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;These are the steps:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Client starts a write action calling the Resource Manager;&lt;/li&gt;
&lt;li&gt;Resource Manager writes on Cache;&lt;/li&gt;
&lt;li&gt;Resource Manager writes calling Data Accessor;&lt;/li&gt;
&lt;li&gt;Response is served to the Client.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Rationale
&lt;/h3&gt;

&lt;p&gt;At first glance it doesn't look like the smartest move: we are in fact slowing down the request adding an extra step. What are we gaining from this strategy, then?&lt;/p&gt;

&lt;p&gt;As we have said multiple times, one of the biggest problems with cached data is that they get stale. Well, this pattern solves exactly this problem.&lt;/p&gt;

&lt;p&gt;In the other article we have seen that one way to deal with stale entries is using &lt;strong&gt;TTL&lt;/strong&gt;s and that still holds true, but in that case expiration was the best way to solve the issue since we were not producing the data we were fetching. Now we are in control of data we want to read, then updating the Cache every time we write data will ensure that cached entries &lt;strong&gt;never&lt;/strong&gt; gets stale.&lt;/p&gt;

&lt;p&gt;Of course there is no light without shadows and besides the write latency&lt;sup&gt;1&lt;/sup&gt;, this technique can turn detrimental when the Client doesn't need to read data that often. In this case in fact, you end up wasting the resources needed to keep alive and synchronizing the Cache without gaining the reading benefits. &lt;/p&gt;

&lt;h2&gt;
  
  
  Write Behind (aka Write Back)
&lt;/h2&gt;

&lt;p&gt;This other technique still has the Resource Manager inline, but writing through the Data Accessor happens asynchronously. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fmvdo6l794dxudbo8sws1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fmvdo6l794dxudbo8sws1.png" alt="Write Behind."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;These are the steps involved in action life cycle:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Client starts a write action calling the Resource Manager;&lt;/li&gt;
&lt;li&gt;Resource Manager writes on Cache;&lt;/li&gt;
&lt;li&gt;Response is served to the Client;&lt;/li&gt;
&lt;li&gt;Eventually Resource Manager writes calling Data Accessor.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Rationale
&lt;/h3&gt;

&lt;p&gt;The best way to understand why and how this caching technique can be useful is to give an example. &lt;/p&gt;

&lt;p&gt;Suppose we are now developing &lt;code&gt;TrulyAwesomeBankAPI&lt;/code&gt; and we want to implement the &lt;code&gt;Payment&lt;/code&gt; transaction creation using Cache. Payments need to happen as quick as possible, but &lt;em&gt;Truly Awesome Bank&lt;/em&gt; backing our API is still on an old infrastructure which is not able to handle peaks very well. &lt;/p&gt;

&lt;p&gt;We decide to use Write Behind. This means that every time we perform a &lt;code&gt;Payment&lt;/code&gt; we save that transaction in Cache and return the response to the Client. Then we have another worker routine (running in background, in another process, based on a CRON expression or whatever...) which takes care of synchronizing our cached version of the ledger with the real ledger belonging to &lt;em&gt;Truly Awesome Bank&lt;/em&gt;. This way we can provide responses quickly, regardless of how many requests &lt;em&gt;Truly Awesome Bank&lt;/em&gt; is able to support at a given time.&lt;/p&gt;

&lt;p&gt;We are then gaining on performance and stability, since we don't need to wait for external data sources. This makes the architecture on the whole more fault tolerant towards external services and thus opens new resilience possibilities: we could, for example, implement simple retry strategy or even a circuit breaker without affecting the client at all...&lt;/p&gt;

&lt;p&gt;The price we are paying though is consistency: before worker completes the synchronization process real data (as in data living in &lt;em&gt;Truly Awesome Bank&lt;/em&gt;) and data we serve (as in data living in the Cache) are different and the thing can get a lot more complicated if we start thinking about how to deal with error cases&lt;sup&gt;2&lt;/sup&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Write Around
&lt;/h2&gt;

&lt;p&gt;Well, just for sake of completeness we ought to mention Write Around, but to me it doesn't look like a real pattern. In fact, in the following diagram you won't find any trace of the word "cache". &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fnis5pe9abormsp98zs76.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fnis5pe9abormsp98zs76.png" alt="Write Around."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Basically, &lt;em&gt;Write Around&lt;/em&gt; is "call directly Data Accessor and cache data only at read time" which to me means "apply any reading strategy without a writing one".&lt;/p&gt;

&lt;h3&gt;
  
  
  Rationale
&lt;/h3&gt;

&lt;p&gt;The reason why you would use this non-pattern is just because none of the writing techniques above are good for you: maybe you need to have super consistent data or maybe you don't need to read data that often. &lt;/p&gt;

&lt;p&gt;In those cases not applying a writing technique (or using &lt;em&gt;Write Around&lt;/em&gt;, if you wish) works just fine.&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;span id="code-examples"&gt;Did you &lt;em&gt;write&lt;/em&gt; some code?&lt;/span&gt;
&lt;/h1&gt;

&lt;blockquote&gt;
&lt;p&gt;You can find a more detailed version of these examples here&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/shikaan" rel="noopener noreferrer"&gt;
        shikaan
      &lt;/a&gt; / &lt;a href="https://github.com/shikaan/design-patterns" rel="noopener noreferrer"&gt;
        design-patterns
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      Examples of usage of design patterns in real life code
    &lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="ltag-github-body"&gt;
    
&lt;div id="readme" class="md"&gt;
&lt;div class="markdown-heading"&gt;
&lt;h1 class="heading-element"&gt;design-patterns&lt;/h1&gt;

&lt;/div&gt;
&lt;p&gt;Examples of usage of design patterns in real life code&lt;/p&gt;
&lt;p&gt;These are the reference resources for &lt;a href="https://dev.to/shikaan/design-patterns-in-web-development-2gbp" rel="nofollow"&gt;this series of articles&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;

  &lt;/div&gt;
  &lt;div class="gh-btn-container"&gt;&lt;a class="gh-btn" href="https://github.com/shikaan/design-patterns" rel="noopener noreferrer"&gt;View on GitHub&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;/blockquote&gt;

&lt;p&gt;Yes, I did. Python this time around.&lt;/p&gt;

&lt;p&gt;The example I am providing here is simulating a slow writing external service using timers. In particular, we are about to simulate more or less what happens in &lt;code&gt;TrulyAmazingBankAPI&lt;/code&gt;: we create a transaction we want to save.&lt;/p&gt;

&lt;p&gt;Launch the app and in some seconds you are able to see exactly the trace of what happens during the &lt;em&gt;Write Through&lt;/em&gt; and the &lt;em&gt;Write Behind&lt;/em&gt; cases. &lt;/p&gt;

&lt;p&gt;Let's examine the output case by case.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Write Though&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; Save transaction
[14:59:17.971960] CacheManager.set
[14:59:17.971977] TrulyAwesomeBankAPIClient.save_transaction
&amp;gt;&amp;gt;&amp;gt; Get transaction
[14:59:19.974781] CacheManager.get
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here the first thing we do is saving the entry in the Cache, then we save it in the AwesomeBank and when after a couple of seconds we want to get the transaction we have just saved, we are using the Cache to retrieve it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Write Behind&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; Save transaction
[14:59:24.976378] CacheManager.set
&amp;gt;&amp;gt;&amp;gt; Get transaction
[14:59:21.978355] CacheManager.get

--------------------------------------------
|    AWESOME BANK DATABASE (before sync)   |
--------------------------------------------
{}

[14:59:26.974325] TrulyAwesomeBankAPIClient.save_transaction

--------------------------------------------
|    AWESOME BANK DATABASE (after sync)    |
--------------------------------------------
{
   UUID('0f41f108-0859-11e9-a138-b46bfc6c5cb9'): {
      'id': UUID('0f41f108-0859-11e9-a138-b46bfc6c5cb9'), 
      'transaction': {
         'type': 'PAYMENT', 
         'amount': 100, 
         'currency': 'EUR'
      }
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we call request the couple of actions "set transaction" and "get transaction", we can see from the output that during the whole life of the request the only involved participant is CacheManager. &lt;/p&gt;

&lt;p&gt;The sole moment when we are calling the TrulyAwesomeBankAPIClient is 5 seconds after the end of the request, when we are completing the synchronization.&lt;/p&gt;

&lt;p&gt;Please note that also the synchronization is a process purposely dumb and slow because of timers here. In real world synchronization process can be (and usually is) way more complicated than that and, in fact, it should be a major concern when data consistency is a game changer.&lt;/p&gt;

&lt;p&gt;After synchronization, as you can see database is up to date with what we have in Cache. From this point on this entry is up to date and it will always be, until other writing actions happen.&lt;/p&gt;

&lt;h1&gt;
  
  
  Final words
&lt;/h1&gt;

&lt;p&gt;Well, this closes active caching part.&lt;/p&gt;

&lt;p&gt;First thing, thanks for feedback on previous article! Apparently naming wasn't so clear, so I updated it a bit here. I took the opportunity to revisit diagrams as well so that they won't make you eyes bleed. Not that much at least.&lt;/p&gt;

&lt;p&gt;Please continue with feedbacks ❤&lt;/p&gt;

&lt;p&gt;Until next time!&lt;/p&gt;




&lt;p&gt;1. It's worth mentioning that users usually tolerate writing latency way better than reading latency. Unfortunately I can't remember where I got this data from, so I cannot show real metrics of this. Take this with a grain of salt.&lt;/p&gt;

&lt;p&gt;2. These issues are all related to what is generally named "Eventual Consistency" and this is the reason why I used the word "eventually" in the last step of the action life cycle. The topic is big enough to deserve an article on its own, but you really want to get a grasp of what's going on &lt;a href="https://www.youtube.com/watch?v=6R1WhWkh6pg" rel="noopener noreferrer"&gt;check this out&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>python</category>
      <category>javascript</category>
      <category>node</category>
      <category>cache</category>
    </item>
    <item>
      <title>How I Learned to Stop Worrying and Love the Cache - Reading</title>
      <dc:creator>Manuel Spagnolo</dc:creator>
      <pubDate>Fri, 21 Dec 2018 22:48:00 +0000</pubDate>
      <link>https://dev.to/shikaan/-design-patterns-in-web-development----active-caching-1-23e2</link>
      <guid>https://dev.to/shikaan/-design-patterns-in-web-development----active-caching-1-23e2</guid>
      <description>&lt;h4&gt;
  
  
  Check out the updated version &lt;a href="https://withbenefits.dev/what-is-cache/"&gt;here&lt;/a&gt;
&lt;/h4&gt;

&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;It took me just three episodes to become inconsistent in my writing schedule. It has to be a record of some sort. To keep me motivated though I decided to spend the season back in Italy, so that I &lt;em&gt;desperately&lt;/em&gt; needed to practice some English.&lt;/p&gt;

&lt;p&gt;Well it's not entirely true: I am passing the season here because of food. As usual, this leads me to this article's topic: &lt;strong&gt;caching&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Readers right now are probably divided into two groups: the one knowing the famous joke about caching and the others. For both of you here's &lt;a href="https://martinfowler.com/bliki/TwoHardThings.html"&gt;a curated list of tremendously sad variations of it&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Needless to say, I find &lt;strong&gt;all of them&lt;/strong&gt; hilarious.&lt;/p&gt;

&lt;p&gt;Either way, this piece is going to be part of a Christmas series about caching techniques. I am about to cover &lt;em&gt;active caching&lt;/em&gt; (as in, what I can do to cache without suffer too much) and &lt;em&gt;passive caching&lt;/em&gt; (as in, how to stick with browser cache and similarities).&lt;/p&gt;

&lt;p&gt;This article is the first in the &lt;em&gt;Active Caching&lt;/em&gt; part.&lt;/p&gt;

&lt;h1&gt;
  
  
  What is this about?
&lt;/h1&gt;

&lt;p&gt;Do you still wonder what has food to do with caching? You'd better do, else I need to seriously improve my cliffhangers skills.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example: Christmas Dinner
&lt;/h2&gt;

&lt;p&gt;Let's start with a simple out-of-IT problem. It's Christmas eve and you're planning to arrange a mouthwatering dinner for you friends and family. For the sake of the argument we're going to use one traditional Italian Christmas recipe: "il capitone"&lt;sup&gt;1&lt;/sup&gt;.&lt;/p&gt;

&lt;p&gt;Let's start cooking. First thing in the list of the ingredients is the eel. You call your favourite fish shop, you get your fish delivered. Second item, extra-virgin olive oil. You call your favourite farm, order a bottle of oil and you get that delivered. Third, lemon... &lt;/p&gt;

&lt;p&gt;You can see by yourself how inconvenient this is, don't you? What you start doing then is buying in advance and storing stuff in a more convenient place, closer to where you actually use it, to make the access to these ingredients more efficient. Let's call this place cupboard.&lt;/p&gt;

&lt;p&gt;Once you realize you can store things at home, you might be tempted to call the delivery person just once to collect all the ingredients not only for Christmas but also for New Year's Eve's dinner. So when you are at the fish shop, you buy the eel and the king prawns which you are actually planning to prepare a week later.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/l4-Ya_Xa3f8"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;After a couple of days, the funky smell killing any living being in the area makes you realize that probably prawns are now expired and you should have prepared them fresh.&lt;/p&gt;

&lt;p&gt;Well, caching has exactly the same kind of problems and perks: we usually cache items to save some computations, time or to avoid calling uselessly an external data source, but we should be extremely careful about expiration of entries because they can eventually get to an inconsistent (and very smelly) state down the line.&lt;/p&gt;

&lt;h2&gt;
  
  
  Caching patterns
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;I am late buying Christmas presents. SHOW ME THE CODE.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As usual, let me introduce some jargon&lt;sup&gt;2&lt;/sup&gt; which will help us in communication before diving into the patterns (maybe &lt;em&gt;strategies&lt;/em&gt; is a better suited word here).&lt;/p&gt;

&lt;p&gt;These are the participants:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Client&lt;/strong&gt; needs data (either fresh or from the cache);&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data Access Component&lt;/strong&gt; is called to get non-cached entries (e.g., HTTP Client, ORM...);&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cache Layer&lt;/strong&gt; stores cached entries (e.g., Memory, Local Storage...);&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Resource Manager&lt;/strong&gt; communicates with the Cache Layer.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In our previous example, these roles are mapped this way:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Client&lt;/strong&gt; is you;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data Access Component&lt;/strong&gt; is the delivery person;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cache Layer&lt;/strong&gt; your cupboard;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Resource Manager&lt;/strong&gt; someone so kind to administer resources in your cupboard.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Caching involves both &lt;em&gt;reading&lt;/em&gt; (using the ingredients) and &lt;em&gt;writing&lt;/em&gt; (storing the ingredients), so categorization follows accordingly. In this article we'll speak about reading techniques.&lt;/p&gt;

&lt;p&gt;Reading strategies:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Cache Inline&lt;/li&gt;
&lt;li&gt;Cache Aside&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Writing strategies:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Write Through&lt;/li&gt;
&lt;li&gt;Write Behind&lt;/li&gt;
&lt;li&gt;Write Around&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Warning&lt;/strong&gt;&lt;br&gt;
Unfortunately naming convention for these patterns is not that consolidated, so you can find them under different names.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To get an understanding of how does work and why we should use them, we will analyse the following scenarios for all the aforementioned patterns:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;cached entry is present and valid (&lt;strong&gt;Cache Hit&lt;/strong&gt;);&lt;/li&gt;
&lt;li&gt;cached entry is missing or invalid (&lt;strong&gt;Cache Miss&lt;/strong&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Disclaimer&lt;/strong&gt;&lt;br&gt;
As usual, we are tackling these strategies in isolation for sake of simplicity. In real world, those techniques are combined to get the best out of them.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Cache Inline (aka Read Through)
&lt;/h3&gt;

&lt;p&gt;The reason for this name is that in this pattern the Client is never responsible of calling the Data Access Component directly, but instead it delegates the responsibility of knowing whether a cached entry is enough or a fresh entry is required to the Resource Manager. &lt;/p&gt;

&lt;p&gt;Resource Manager then sits &lt;strong&gt;in line&lt;/strong&gt; between Client and Data Access Component.&lt;/p&gt;

&lt;h4&gt;
  
  
  Cache Miss
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--pw7TIuV9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/209c1ie202o6q6k77ml2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pw7TIuV9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/209c1ie202o6q6k77ml2.png" alt="Inline Cache Miss" width="671" height="321"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Following the numbers on the arrows, you should easily get a grasp of what's going on here: &lt;/p&gt;

&lt;p&gt;1) Client asks Resource Manager for data;&lt;br&gt;
2) Resource Manager gets no cached entries from cache, so it calls Data Access Component;&lt;br&gt;
3) Resource Manager gets data, stores it and then returns it to Client.&lt;/p&gt;
&lt;h4&gt;
  
  
  Cache Hit
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--GE5CIJx8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/1vdzru4ptrnsp3tawz10.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--GE5CIJx8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/1vdzru4ptrnsp3tawz10.png" alt="Inline Cache Hit" width="671" height="321"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see, using cache here is reducing the number of steps, hence the strategy is actually working!&lt;/p&gt;
&lt;h4&gt;
  
  
  Rationale
&lt;/h4&gt;

&lt;p&gt;From a caching standpoint, this approach makes sure that we are caching only data we actually use. This is usually called &lt;strong&gt;lazy caching&lt;/strong&gt;. This approach also promotes splitting responsibilities across different components, how can it have drawbacks?!&lt;/p&gt;

&lt;p&gt;Well, unfortunately this is the case :( &lt;/p&gt;

&lt;p&gt;The first issue is of course that, when you are in a &lt;em&gt;Cache Miss&lt;/em&gt; scenario, the request has to do a longer trip before getting to the Client, making the first request actually &lt;em&gt;slower&lt;/em&gt; than if we didn't have cache at all.&lt;/p&gt;

&lt;p&gt;One way of dealing with this is doing a &lt;em&gt;cache primer&lt;/em&gt;: when the system starts we pre-populate the Cache Layer so we'll always be in a &lt;em&gt;Cache Hit&lt;/em&gt; case. Obviously this will make our caching mechanism not-so-lazy. As always, what's best depends on the actual scenario.&lt;/p&gt;

&lt;p&gt;The second drawback is that, since data is cached only once (on &lt;em&gt;Cache Miss&lt;/em&gt;) data can become quickly stale.&lt;/p&gt;

&lt;p&gt;Again, this is not the end of the world: as for food, you can set &lt;strong&gt;expiration&lt;/strong&gt; for entries. It is usually called &lt;strong&gt;TTL&lt;/strong&gt; (namely &lt;em&gt;Time To Live&lt;/em&gt;). When entries are expired, Resource Manager can call again the Data Access Component and refresh the cache&lt;sup&gt;3&lt;/sup&gt;. &lt;/p&gt;
&lt;h3&gt;
  
  
  Cache Aside
&lt;/h3&gt;

&lt;p&gt;As opposed to Cache Inline, Cache Aside will make the Client responsible of communicating with Cache Layer to understand if a Cache Entry is needed or not.&lt;/p&gt;

&lt;p&gt;The pseudo code for this behaviour can be as easy as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;Client&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;CacheLayerManager&lt;/span&gt; &lt;span class="nx"&gt;cacheLayerManager&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nx"&gt;DataAccessComponent&lt;/span&gt; &lt;span class="nx"&gt;dataAccessComponent&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nx"&gt;getResource&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Resource&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;resource&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;cacheLayerManager&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;getResource&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;resource&lt;/span&gt;
            &lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;dataAccessComponent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;getResource&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;resource&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h4&gt;
  
  
  Cache Miss
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--8Up6FNgA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/e5v9e78xb4gh4flfgtni.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8Up6FNgA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/e5v9e78xb4gh4flfgtni.png" alt="Aside Cache Miss." width="671" height="321"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can follow what's going on here by looking at the pseudo code above. As you can see, responsibility of calling Data Access Component is now in the Client and the Cache is actually... aside.&lt;/p&gt;
&lt;h4&gt;
  
  
  Cache Hit
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--SRbnLitB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/ufun4iillk5rp4vugjsl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--SRbnLitB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/ufun4iillk5rp4vugjsl.png" alt="Aside Cache Hit." width="671" height="321"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Again the trip here is shorter, so the pattern is actually working.&lt;/p&gt;
&lt;h4&gt;
  
  
  Rationale
&lt;/h4&gt;

&lt;p&gt;This technique, as Cache Aside, is a &lt;em&gt;lazy caching&lt;/em&gt; technique, unless we want to do a &lt;em&gt;cache primer&lt;/em&gt;. Also, exactly as with Cache Aside, there is the problem of stale data, but again that problem can be tackled with &lt;em&gt;TTL&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;So, why should anyone go for Cache Aside over Cache Inline?&lt;/p&gt;

&lt;p&gt;Since the Client now is responsible of communicating directly with the Cache Layer, when the Resource Manager fails, we pay a penalty only on the first request - when we go through the &lt;em&gt;Cache Miss&lt;/em&gt; path -, making our system on the whole more robust.&lt;/p&gt;

&lt;p&gt;Also, having removed the dependency between what we cache and what we get from Data Access Component, we could potentially have two different kind of model: a &lt;code&gt;Model&lt;/code&gt;, which is representing what we get from Data Access Componentm and &lt;code&gt;CachedModel&lt;/code&gt; representing what we cache.&lt;/p&gt;

&lt;p&gt;This will indeed widen the spectrum of what you can achieve with cache: you can, for example, hydrate or transform cached data to gain on performance on multiple operation with just one cached entry.&lt;/p&gt;

&lt;p&gt;Let's give an example of this. &lt;/p&gt;

&lt;p&gt;Suppose you are serving a list of bank transactions you get from this &lt;code&gt;AwesomeBankAPI&lt;/code&gt;. Your application is supposed to expose two different endpoints: &lt;code&gt;getAllTransactions&lt;/code&gt; and &lt;code&gt;getPayments&lt;/code&gt;. Of course &lt;code&gt;AwesomeBankAPI&lt;/code&gt; does not expose any filtering function. What you could do is storing the the list of all the transactions on the first call to any of those endpoints. &lt;/p&gt;

&lt;p&gt;From this point on, if the call is towards &lt;code&gt;getAllTransactions&lt;/code&gt;, you return the list as is. If the call is towards &lt;code&gt;getPayments&lt;/code&gt; you will take the whole list from cache (rather than calling &lt;code&gt;AwesomeBankAPI&lt;/code&gt; again) and you just need to do the filtering on your end.&lt;/p&gt;
&lt;h1&gt;
  
  
  &lt;span id="code-examples"&gt;Code or it never happened&lt;/span&gt;
&lt;/h1&gt;

&lt;blockquote&gt;
&lt;p&gt;You can find a more detailed version of these examples here&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--566lAguM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/github-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/shikaan"&gt;
        shikaan
      &lt;/a&gt; / &lt;a href="https://github.com/shikaan/design-patterns"&gt;
        design-patterns
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      Examples of usage of design patterns in real life code
    &lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="ltag-github-body"&gt;
    
&lt;div id="readme" class="md"&gt;
&lt;h1&gt;
design-patterns&lt;/h1&gt;
&lt;p&gt;Examples of usage of design patterns in real life code&lt;/p&gt;
&lt;p&gt;These are the reference resources for &lt;a href="https://dev.to/shikaan/design-patterns-in-web-development-2gbp" rel="nofollow"&gt;this series of articles&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;

  &lt;/div&gt;
  &lt;div class="gh-btn-container"&gt;&lt;a class="gh-btn" href="https://github.com/shikaan/design-patterns"&gt;View on GitHub&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;br&gt;
&lt;/blockquote&gt;

&lt;p&gt;The &lt;a href="https://github.com/shikaan/design-patterns/tree/master/chistmas-caching"&gt;example&lt;/a&gt; I am showing here is written in Node. It's a simple application meant to communicate with &lt;a href="https://xkcd.com/"&gt;XKCD&lt;/a&gt; to fetch latest comics.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;CacheLayer&lt;/code&gt; in this example is represented by a simple &lt;code&gt;Map&lt;/code&gt;. I am using a &lt;code&gt;CacheManager&lt;/code&gt; to deal with it, so that if you want to experiment with a real caching engine (like &lt;a href="https://redis.io/"&gt;redis&lt;/a&gt;, or &lt;a href="https://memcached.org/"&gt;memcached&lt;/a&gt;) you can do that without much effort.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;DataAccessComponent&lt;/code&gt; is represented by a simple &lt;code&gt;XKCDClient&lt;/code&gt; which exposes (in a Vanilla JavaScript fashion...) only a &lt;code&gt;getLastComics&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;The other component is indeed &lt;code&gt;ResourceManager&lt;/code&gt; which is being used only in the inline-caching example.&lt;/p&gt;

&lt;p&gt;Since all these components are eventually the same, I just created two different clients sharing and using them in different ways, based on the strategy we want to follow.&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;Cache Inline&lt;/em&gt; example is about requesting twice the same resource (namely, last three XKCD comics), but the second time the request is way faster. This is because we are not doing any cache-primer, so the first time we are actually calling XKCD API, the second time we are retrieving information from the cache.&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;Cache Aside&lt;/em&gt; example instead, shows how powerful can be caching when we want to request resources which can calculated from what we already have. In this specific example, we are fetching last five comics from XKCD and then we are fetching only last two. The second call of course is not calling the API. &lt;/p&gt;

&lt;p&gt;The main difference here is then that we are using the cache to get a resource we &lt;em&gt;didn't have&lt;/em&gt; before, rather than using &lt;code&gt;CacheLayer&lt;/code&gt; to get something we already fetched.&lt;/p&gt;

&lt;p&gt;Again, those two strategies can (and usually do) live together. If you want to play a bit with these examples, you might try to make the &lt;code&gt;ResourceManager&lt;/code&gt; from the first example a bit smarter so that it can either use the entries as they are (hence, what's already in the &lt;a href="https://github.com/shikaan/design-patterns/tree/master/chistmas-caching"&gt;repo&lt;/a&gt;) or it can try to extract the required info from &lt;code&gt;CacheLayer&lt;/code&gt; and decide whether calling the API or not.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final words
&lt;/h2&gt;

&lt;p&gt;This closes the first episode of this Christmas special (yes, as TV shows). &lt;/p&gt;

&lt;p&gt;As you might have noticed I am trying to keep this shorter and easier than usual, so you can easily follow without your laptop when you are hallucinating because of Christmas-sized food portions. &lt;/p&gt;

&lt;p&gt;As always, if you have any feedback (the thing is too simplified, you miss my memes, I suck at naming things), please drop a comment and make this better together :D&lt;/p&gt;

&lt;p&gt;Until next time!&lt;/p&gt;




&lt;p&gt;1. Pretty much anywhere else in Italy people eat meat for Christmas. I am from a messed up place where eating a giant eel should symbolize victory of Good against the Evil in the shape of a snake...&lt;/p&gt;

&lt;p&gt;2. Unfortunately there no standard jargon here, so I had to make up these names. If you have any suggestions to improve them, please tell me (:&lt;/p&gt;

&lt;p&gt;3. Knowing what is the right expiration date for every entry is something between wisdom and black magic. Most likely a lot of errors and trials (or experience, if you wish) will guide in choosing the best TTL for your case&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>node</category>
      <category>cache</category>
    </item>
    <item>
      <title>Design Patterns in Web Development - #2 Memento</title>
      <dc:creator>Manuel Spagnolo</dc:creator>
      <pubDate>Sun, 25 Nov 2018 11:01:00 +0000</pubDate>
      <link>https://dev.to/shikaan/design-patterns-in-web-development---2-memento-253j</link>
      <guid>https://dev.to/shikaan/design-patterns-in-web-development---2-memento-253j</guid>
      <description>&lt;h4&gt;
  
  
  Check out the updated version &lt;a href="https://withbenefits.dev/design-patterns-memento/" rel="noopener noreferrer"&gt;here&lt;/a&gt;
&lt;/h4&gt;

&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;As some of you may remember, in the &lt;a href="https://dev.to/shikaan/design-patterns-in-web-development-2gbp"&gt;pilot episode&lt;/a&gt; I said I was about to explain &lt;em&gt;Command&lt;/em&gt; with three examples: a UI kit, a CQRS application and an undo/redo implementation in Electron. In the &lt;a href="https://dev.to/shikaan/design-patterns-in-web-development---1-command-2jf"&gt;Command episode&lt;/a&gt; though I didn't provide the latter and the reason is extremely simple: I am a jerk.&lt;/p&gt;

&lt;p&gt;Furthermore, it made much more sense to me using that example to explain another Behavioral Pattern&lt;sup&gt;1&lt;/sup&gt; belonging to the classic patterns in the &lt;a href="https://en.wikipedia.org/wiki/Design_Patterns" rel="noopener noreferrer"&gt;Gang of Four&lt;/a&gt;: &lt;strong&gt;Memento&lt;/strong&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  Memento
&lt;/h1&gt;

&lt;p&gt;&lt;strong&gt;Bla, bla, bla. Code please&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Example: Calculator
&lt;/h2&gt;

&lt;p&gt;Suppose you are working on a calculator. You provide an expression and it will do the maths for you. For simplicity's sake, we just take in account one of its methods: &lt;code&gt;power&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The logic behind this calculator is in a class called &lt;code&gt;Calculator&lt;/code&gt; which should look something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Calculator&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// State&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt; &lt;span class="nx"&gt;display&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="c1"&gt;// and a whole lot of unrelated other fields&lt;/span&gt;

    &lt;span class="c1"&gt;// Resolves expressions like x^y&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nf"&gt;power&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kr"&gt;string&lt;/span&gt; &lt;span class="nx"&gt;expression&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kr"&gt;number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="c1"&gt;// Writes on display&lt;/span&gt;
    &lt;span class="nf"&gt;setState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kr"&gt;string&lt;/span&gt; &lt;span class="nx"&gt;display&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="c1"&gt;// Parse what's on the display, calculates and overrides the display&lt;/span&gt;
    &lt;span class="nf"&gt;calculate&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kr"&gt;number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;One fine day, we decide it's time to implement an undo mechanism for this application. One first idea of implementing this mechanism could be simply apply the inverse function of what you just did. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F80njban6utua2t3wfkd1.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F80njban6utua2t3wfkd1.jpg" alt="Quick maths"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Unfortunately this just does not work for the &lt;code&gt;power&lt;/code&gt; function. &lt;/p&gt;

&lt;p&gt;For example: undoing &lt;code&gt;y = power(x, 2)&lt;/code&gt; is going to be applying &lt;code&gt;sqrt(y, 2)&lt;/code&gt;, but both &lt;code&gt;power(2, 2)&lt;/code&gt; and &lt;code&gt;power(-2, 2)&lt;/code&gt; yield the same result, so you won't be able to get unambiguously to the &lt;code&gt;x&lt;/code&gt; just by having the &lt;code&gt;y&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;At this point saving the previous state in a snapshot when you &lt;code&gt;calculate&lt;/code&gt; and, upon &lt;code&gt;undo&lt;/code&gt;, using such snapshot to reset the state of the calculator looks simpler and more effective.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Memento&lt;/strong&gt; offers one neat way to deal with this problem.&lt;/p&gt;
&lt;h2&gt;
  
  
  What is this about?
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Intent&lt;/strong&gt;&lt;br&gt;
Without violating encapsulation, capture and externalize an object's internal&lt;br&gt;
state so that the object can be restored to this state later.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Yes, you have just won this "Guess the quote" round: it comes from the &lt;em&gt;Gang of Four&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The idea here is pretty straightforward: we want to have a systematic way to store a snapshot of the internal state a given object, without exposing such state, in order to be able restore later on. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftytcjrif2w0rma1o0et4.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftytcjrif2w0rma1o0et4.jpg" alt="Good Will Hunting"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you are wondering why you shouldn't expose the state, maybe you are still not fearing coupling as you should. This is definitely bad. However, you are still in time to get this fixed by &lt;a href="https://dev.to/shikaan/design-patterns-in-web-development---1-command-2jf"&gt;reading this article&lt;/a&gt;. I will wait for you here.&lt;/p&gt;

&lt;p&gt;...&lt;/p&gt;

&lt;p&gt;Done? We can get started with &lt;strong&gt;Memento&lt;/strong&gt; in practice.&lt;/p&gt;
&lt;h2&gt;
  
  
  Pattern in practice
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh1k110f5w3081rojl18a.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh1k110f5w3081rojl18a.jpg" alt="99 problems"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First things first: why this pattern is called Memento? &lt;em&gt;Memento&lt;/em&gt; is a Latin word which can be safely translated into &lt;em&gt;reminder&lt;/em&gt;&lt;sup&gt;2&lt;/sup&gt;. This is the object in which we store the part of the state of the &lt;code&gt;Calculator&lt;/code&gt; we are interested in. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;Calculator&lt;/code&gt;, which is where the state originates from, is called &lt;strong&gt;Originator&lt;/strong&gt; and the third character of this story is going to be the one which takes care of making the whole thing work, which is called the &lt;strong&gt;CareTaker&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;So, to wrap it up, these are the participants in Memento with their responsibilities:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Originator&lt;/strong&gt;: 

&lt;ul&gt;
&lt;li&gt;creates a Memento to store the internal state;&lt;/li&gt;
&lt;li&gt;uses Mementos to restore its state; &lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Memento&lt;/strong&gt;: 

&lt;ul&gt;
&lt;li&gt;stores an immutable snapshot of the internal state of Originator;&lt;/li&gt;
&lt;li&gt;can be accessed &lt;em&gt;only&lt;/em&gt; by the Originator;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Caretaker&lt;/strong&gt;: 

&lt;ul&gt;
&lt;li&gt;stores Mementos;&lt;/li&gt;
&lt;li&gt;never operates on or read Mementos;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In practice these will become something like:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Originator&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Calculator&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt; &lt;span class="nx"&gt;display&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nf"&gt;power&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kr"&gt;string&lt;/span&gt; &lt;span class="nx"&gt;expression&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kr"&gt;number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nf"&gt;setState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kr"&gt;string&lt;/span&gt; &lt;span class="nx"&gt;display&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nf"&gt;calculate&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kr"&gt;number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nx"&gt;Snapshot&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nf"&gt;restore&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;Snapshot&lt;/span&gt; &lt;span class="nx"&gt;snapshot&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Memento&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Snapshot&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt; &lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nf"&gt;getState&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// CareTaker&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Application&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;Calculator&lt;/span&gt; &lt;span class="nx"&gt;calculator&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nb"&gt;Array&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;Snapshot&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;undoSnapshots&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nb"&gt;Array&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;Snapshot&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;redoSnapshots&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nf"&gt;calculate&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;snapshot&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;calculator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;undoSnapshots&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;snapshot&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;redoSnapshots&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;calculator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;calculate&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nf"&gt;undo&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;snapshot&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;undoSnapshots&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;redoSnapshots&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;snapshot&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;calculator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;restore&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;snapshot&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nf"&gt;redo&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;snapshot&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;redoSnapshots&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;undoSnapshots&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;snapshot&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;calculator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;restore&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;snapshot&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Nice! How can I use this s**t tomorrow?
&lt;/h2&gt;

&lt;p&gt;With &lt;strong&gt;Memento&lt;/strong&gt; we are kind of lucky: you don't need to find super complex use cases to go for it. The undo/redo scenario is by far the most common place where this pattern shines, but it can easily be reused every time you need to revert an object to a previous stage.&lt;/p&gt;

&lt;p&gt;You need another example, don't you? &lt;/p&gt;

&lt;p&gt;Suppose you have a profile age for a web application. The user clicks on "edit profile" but, after doing some things, they "cancel" the operation. Unless you wan to do the AJAX call to re-get user information every time this happens, a good idea can be storing a Memento containing a snapshot of the user profile to be restored upon cancellation.&lt;/p&gt;

&lt;p&gt;Is &lt;strong&gt;Memento&lt;/strong&gt; the &lt;em&gt;only&lt;/em&gt; way to achieve this? No. Another fairly common pattern to go for in these cases is &lt;strong&gt;Prototype&lt;/strong&gt;, which might be the subject of next episode. Or not, who knows? Either way, all you need to know now about &lt;strong&gt;Prototype&lt;/strong&gt; is that it provides another way to create a copy of the state of an object, but in a different manner. &lt;/p&gt;

&lt;p&gt;Bottom line, taking snapshots makes your life easier when you have to time-travel the history of your objects.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmemegenerator.net%2Fimg%2Finstances%2F64082371%2Fyo-dawg-i-heard-you-like-snapshots-so-i-snapshotted-your-snapshot-so-you-can-snapshot-your-snapshot.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmemegenerator.net%2Fimg%2Finstances%2F64082371%2Fyo-dawg-i-heard-you-like-snapshots-so-i-snapshotted-your-snapshot-so-you-can-snapshot-your-snapshot.jpg" alt="Snapshots"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Your next question could be, is this just convenient or it is necessary? We have seen in the Calculator example that sometimes inverting last action could not be enough to get to the previous state. This is unfortunately true not only with non-invertible maths functions, but it applies every time any of your methods has side effects. In these cases usually taking snapshots is the only way to revert to a previous state safely. &lt;/p&gt;
&lt;h2&gt;
  
  
  Well, where's the catch then?
&lt;/h2&gt;

&lt;p&gt;This pattern has a couple of gotchas you should be very aware of.&lt;/p&gt;

&lt;p&gt;The first and most obvious one is that, if the object you want to restore is big, having a history of snapshots can become cumbersome. One way to work this around is storing just a diff of the changes, but this works only in scenarios in which you know exactly the order of snapshots to apply (for example in undo/redo).&lt;/p&gt;

&lt;p&gt;The other, sneakier, is that snapshots, if not created correctly, can easily create and accumulate errors upon traversing the history. Let's give an example of this case.&lt;/p&gt;

&lt;p&gt;Let's suppose you have the dumbest game ever: every time you click a button you earn 10 points, if score gets to 100 you earn a badge. We want to implement an undo mechanism here, so we store snapshots on every click of the &lt;code&gt;score&lt;/code&gt; variable.&lt;/p&gt;

&lt;p&gt;We click up to 100, we earn a badge, we undo, we re-click and we earn a second badge.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fwww.callcentermemes.com%2Fwp-content%2Fuploads%2F2015%2F12%2F1449610204609.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fwww.callcentermemes.com%2Fwp-content%2Fuploads%2F2015%2F12%2F1449610204609.jpg" alt="Bug feature"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Why did that happen? Because we forgot to keep track of the badges in the snapshot, thus on undo we just reverted the score, without cleaning the badge list.&lt;/p&gt;
&lt;h1&gt;
  
  
  &lt;span id="code-examples"&gt;A little less conversation, a little more action, please&lt;/span&gt;
&lt;/h1&gt;

&lt;blockquote&gt;
&lt;p&gt;You can find a more detailed version of these examples here&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/shikaan" rel="noopener noreferrer"&gt;
        shikaan
      &lt;/a&gt; / &lt;a href="https://github.com/shikaan/design-patterns" rel="noopener noreferrer"&gt;
        design-patterns
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      Examples of usage of design patterns in real life code
    &lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="ltag-github-body"&gt;
    
&lt;div id="readme" class="md"&gt;
&lt;div class="markdown-heading"&gt;
&lt;h1 class="heading-element"&gt;design-patterns&lt;/h1&gt;

&lt;/div&gt;

&lt;p&gt;Examples of usage of design patterns in real life code&lt;/p&gt;

&lt;p&gt;These are the reference resources for &lt;a href="https://dev.to/shikaan/design-patterns-in-web-development-2gbp" rel="nofollow"&gt;this series of articles&lt;/a&gt;&lt;/p&gt;

&lt;/div&gt;
&lt;br&gt;
&lt;br&gt;
  &lt;/div&gt;
&lt;br&gt;
  &lt;div class="gh-btn-container"&gt;&lt;a class="gh-btn" href="https://github.com/shikaan/design-patterns" rel="noopener noreferrer"&gt;View on GitHub&lt;/a&gt;&lt;/div&gt;
&lt;br&gt;
&lt;/div&gt;
&lt;br&gt;
&lt;br&gt;
&lt;/blockquote&gt;

&lt;p&gt;Finally code time! &lt;/p&gt;

&lt;p&gt;As I promised in the introduction, I am about to show how the same undo problem can be solved both via Command and via Memento.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Disclaimer&lt;/strong&gt;&lt;br&gt;
I decided to not use Electron for this example for the simple reason that it makes the whole thing more complicated for people not familiar with it and it's not bringing any value to Electron experts. If you're really upset about this, drop a comment and I will add also that example.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The example is a very simple React application which is supposed to be a game: sort the tiles to win.&lt;/p&gt;

&lt;p&gt;It basically sets a listener on &lt;code&gt;keyDown&lt;/code&gt; and based on that it either calls a method (Memento) or issues a command (Command).&lt;/p&gt;

&lt;p&gt;In the Memento example we have the &lt;code&gt;Game&lt;/code&gt; component which is dealing with all the game logic: moving tiles, selecting tiles, calculate if the user is winning... This makes it the perfect &lt;strong&gt;Originator&lt;/strong&gt;, because it's also where we store the state we might want to revert via undo. Being the Originator also means that it's responsible of creating and restoring the &lt;code&gt;Snapshot&lt;/code&gt;s.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Snapshot&lt;/code&gt; is of course &lt;strong&gt;Memento&lt;/strong&gt; and it's "private" to the &lt;code&gt;Game&lt;/code&gt; ES6-module, to prevent the &lt;code&gt;KeyboardEventHandler&lt;/code&gt; (aka the &lt;strong&gt;CareTaker&lt;/strong&gt;) to know it.&lt;/p&gt;

&lt;p&gt;In the Command example, we have an additional component: &lt;code&gt;CommandManager&lt;/code&gt; acting as &lt;strong&gt;Invoker&lt;/strong&gt;. Roles of &lt;code&gt;Game&lt;/code&gt; and &lt;code&gt;KeyboardEventHandler&lt;/code&gt; are unchanged, but given the different implementation, they are doing things differently. &lt;code&gt;Game&lt;/code&gt; now is the &lt;strong&gt;Receiver&lt;/strong&gt; of the command, whereas &lt;code&gt;KeyboardEventHandler&lt;/code&gt; is the &lt;strong&gt;Client&lt;/strong&gt;, the sole owner of &lt;code&gt;Command&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;As you might already have noticed, we can use interchangeably &lt;strong&gt;Command&lt;/strong&gt; and &lt;strong&gt;Memento&lt;/strong&gt; here because the action we are encapsulating (&lt;code&gt;moveSelectedTile&lt;/code&gt;) is a pure action, with no side effects, so we actually &lt;em&gt;don't necessarily need&lt;/em&gt; a Snapshot to reconstruct the state: applying inverse functions is enough.&lt;/p&gt;

&lt;p&gt;Does this mean that Memento and Command &lt;em&gt;cannot&lt;/em&gt; live together? By no means. As a matter of fact, you can encapsulate in a Command the &lt;code&gt;takeSnaphot&lt;/code&gt; method to decouple the &lt;code&gt;CareTaker&lt;/code&gt; and the &lt;code&gt;Originator&lt;/code&gt;. Or also, you can encapsulate &lt;code&gt;moveSelectedTile&lt;/code&gt; - as we already did - and in the Command, besides executing the method, you also take a snapshot. This last one is the most common way to make Command and Mememto live together.&lt;/p&gt;

&lt;p&gt;You can start from &lt;a href="https://github.com/shikaan/design-patterns/tree/master/2-memento" rel="noopener noreferrer"&gt;the repo&lt;/a&gt; and experiment with it as an exercise. If you're evil and want to spoil everyone else's party, you can submit a PR.&lt;/p&gt;

&lt;h1&gt;
  
  
  Final words
&lt;/h1&gt;

&lt;p&gt;Well, things start to become a bit more exciting as we start adding knowledge and mixing cards on the table. This will definitely improve over time, so hang on for it :D&lt;/p&gt;

&lt;p&gt;If you have any sort of feedback ("Don't tell me how to code. You're not my real mom!"), opinion ("You code like shit, but your memes are awesome"), comment ("Yeah, okay, Behavioral Patterns are cool, what's next?"), please drop a message or a comment and let's make this series better together.&lt;/p&gt;

&lt;p&gt;Until next time!&lt;/p&gt;




&lt;p&gt;1. If you're unsure about what a behavioral pattern is, take a look &lt;a href="https://dev.to/shikaan/design-patterns-in-web-development---1-command-2jf"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;2. To void to forget this, you should keep in mind that &lt;strong&gt;mem&lt;/strong&gt;ento and &lt;strong&gt;mem&lt;/strong&gt;ory share the same origin. A memory trick to memorize something related to memory. Boom!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>typescript</category>
      <category>react</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>Design Patterns in Web Development - #1 Command</title>
      <dc:creator>Manuel Spagnolo</dc:creator>
      <pubDate>Sat, 10 Nov 2018 21:57:42 +0000</pubDate>
      <link>https://dev.to/shikaan/design-patterns-in-web-development---1-command-2jf</link>
      <guid>https://dev.to/shikaan/design-patterns-in-web-development---1-command-2jf</guid>
      <description>&lt;h4&gt;
  
  
  Check out the updated version &lt;a href="https://withbenefits.dev/design-patterns-command/" rel="noopener noreferrer"&gt;here&lt;/a&gt;
&lt;/h4&gt;

&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;As spoiled in the introduction, the first article will be about the &lt;em&gt;Command Pattern&lt;/em&gt;. This pattern is one of the classic patterns you can find in the &lt;a href="https://en.wikipedia.org/wiki/Design_Patterns" rel="noopener noreferrer"&gt;Gang of Four&lt;/a&gt; and it belongs to the set of patterns called &lt;strong&gt;Behavioral Patterns&lt;/strong&gt;. &lt;/p&gt;

&lt;h2&gt;
  
  
  Behavioral Patterns
&lt;/h2&gt;

&lt;p&gt;As the name suggest, behavioral patterns are concerned about behavior of objects. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgp5l74s2ddsx7phh5v5l.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgp5l74s2ddsx7phh5v5l.jpg" alt="Zoidberg"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Unlike other kind of patterns, behavioral patterns are not only patterns of objects and classes, but also pattern of communication between them. Their main purpose is to outline and distribute responsibilities across components in the application using abstractions meant to simplify complex control flow.&lt;/p&gt;

&lt;p&gt;This last sentence was complicated enough to deserve a real life example.&lt;/p&gt;

&lt;p&gt;Let's say you are in a restaurant and you want to eat a juicy T-Bone steak (I guess now it's obvious I have something for food). One way of getting that is to stand-up, going into the kitchen, and asking the chef to prepare a steak for you. At that point you realize that the kitchen is full of people with the same bright idea which are ultimately creating chaos and confusion in kitchen staff. Only one thing can be worse: your former girlfriend/boyfriend, yes the one with a thing for poisons, is the chef.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc9b4eir7ipaht709ibaf.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc9b4eir7ipaht709ibaf.jpg" alt="Sad Panda"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As a matter of fact, a customer is only interested in getting food. Direct communication with the chef is not serving this purpose and it's actually only bringing problems. At the same time, this direct communication does not scale when you have multiple requests and it wouldn't even when you have multiple listeners for those requests. This is a perfect example of the kind of problems that &lt;em&gt;coupling&lt;/em&gt; can bring in software development.&lt;/p&gt;

&lt;p&gt;The good news though is that even before software development was invented, human beings found a way to solve this obnoxious issue: placing orders.&lt;/p&gt;

&lt;p&gt;Let's suppose, for the sake of the argument, to have a mailbox attached to the kitchen door. Whenever you want to have your food, you just write everything you need on a piece of paper and you mail your order. &lt;/p&gt;

&lt;p&gt;This simple trick magically solved our issues. We are not forced to know who is cooking our food. We don't even know whether anyone is actually cooking our food or if they buy-resell, for example. This means a huge gain in flexibility (and maybe a bit of loss of trust in restaurants which work this way). Furthermore, this improved the whole process in the kitchen, as they can prioritize, prepare concurrently, throw in the bin, log or do whatever they want with the orders.&lt;/p&gt;

&lt;p&gt;Everyone (panda included) lived happily ever after&lt;sup&gt;1&lt;/sup&gt;!&lt;/p&gt;

&lt;p&gt;Oh, by the way, this was the Command Pattern.&lt;/p&gt;

&lt;h1&gt;
  
  
  Command Pattern
&lt;/h1&gt;

&lt;p&gt;&lt;strong&gt;SHOW ME THE CODE&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What is this about?
&lt;/h2&gt;

&lt;p&gt;Lets start with a quote from the one and only GoF.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Intent&lt;/strong&gt;&lt;br&gt;
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In substance, Command is all about encapsulating a routine in an object. In the example above, we encapsulated the request for food in an object, which was the piece of paper used to place the order. The encapsulating object is what we call &lt;code&gt;Command&lt;/code&gt;, hence the name of the pattern&lt;sup&gt;2&lt;/sup&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Effects
&lt;/h2&gt;

&lt;p&gt;Applying command has mainly two effects: reducing coupling between the invoker and the executor of the command, make a routine a first class object.&lt;/p&gt;

&lt;p&gt;The ex scenario in the example above should be enough to convince you that coupling can be dangerous even outside Computer Science.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2s0m2trt2q2t5xoozha1.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2s0m2trt2q2t5xoozha1.jpg" alt="Overly attached girlfriend"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you're not in the mood for thinking about your paranoid acquaintances you can also consider that the procedure you had to fulfill to get your meal is essentially unchanged if your meal needs to be cooked by two teams one specialized in steaks and one in sides.  &lt;/p&gt;

&lt;p&gt;At the same time, the kitchen staff does not care if the order comes from the waiter, from a phone call, an order or whatever. As long as they receive a command they can execute, they are fine.&lt;/p&gt;

&lt;p&gt;This is just a part of the gain we have in transforming routines in objects. The best part is... wait for it... they are objects! That means you can manipulate routines as objects, as in you can store them to have a transaction history, you can delay the execution, you can ignore them if s**t comes out of the pipe, you can extend those to add debugging inspections, you name it!&lt;/p&gt;

&lt;h2&gt;
  
  
  Awesome! Will I ever need this in my lifetime?
&lt;/h2&gt;

&lt;p&gt;No.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foh8rt55mcydwpun4u4y2.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foh8rt55mcydwpun4u4y2.jpg" alt="Just kidding"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There are some situations in which &lt;strong&gt;Command&lt;/strong&gt; is not only extremely handy, but almost needed.&lt;/p&gt;

&lt;h3&gt;
  
  
  Callbacks
&lt;/h3&gt;

&lt;p&gt;Every time the executor of a command and the issuer not only they don't know each other, but they &lt;em&gt;cannot&lt;/em&gt; know each other in advance.&lt;/p&gt;

&lt;p&gt;Let's say you are developing a fancy UI kit. You are of course developing something that needs to be reused, so if you build a &lt;code&gt;Button&lt;/code&gt; component, you want it to be able to execute &lt;em&gt;any&lt;/em&gt; action, you don't want to hard-code one.&lt;/p&gt;

&lt;p&gt;"Hey, bro! We have callbacks for that!" Yes, I know, but not everyone in the world is so lucky to work with JavaScript on a daily basis (sorry, biased comment). When you want to (or have to) be strictly Object Oriented, this is the way to implement callbacks.&lt;/p&gt;

&lt;h3&gt;
  
  
  Transactions and logs
&lt;/h3&gt;

&lt;p&gt;Having all the commands as first class objects allows you to store them and hence to create an history of transactions.&lt;/p&gt;

&lt;p&gt;This comes extremely handy in systems in which you &lt;em&gt;need&lt;/em&gt; a transaction history, like banking, for example. Furthermore, you get another pleasant side effect: you can reconstruct the state of the system at any point in time just traveling back the transaction history, making your life extremely easier if something goes off.&lt;/p&gt;

&lt;p&gt;You can of course do the other way around: instead of storing the commands after executing them as a reference for what already happened, you can make the list of commands a queue of task to be executed, as within the restaurant example. &lt;/p&gt;

&lt;p&gt;If you need more "workforce", you just need to add some more consumers for that queue, making your application on the whole more scalable.&lt;/p&gt;

&lt;h3&gt;
  
  
  Undo/Redo
&lt;/h3&gt;

&lt;p&gt;Making the execution of an action an object, allows you to create an object with two methods: &lt;code&gt;execute&lt;/code&gt; and &lt;code&gt;undo&lt;/code&gt;. The first is meant to do something, whilst the latter is supposed to undo what you have just done.&lt;/p&gt;

&lt;p&gt;Add up what's above about transactions and you can easily build and undo/redo history.&lt;/p&gt;

&lt;h2&gt;
  
  
  One last effort before code...
&lt;/h2&gt;

&lt;p&gt;Before diving into code examples we need to build a bit of jargon, so we can understand each other. I will be using the exact same language as used in GoF, so that if you want to follow from there it will be easier.&lt;/p&gt;

&lt;p&gt;The participants in this pattern are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Receiver&lt;/strong&gt;: 

&lt;ul&gt;
&lt;li&gt;knows how to execute the command;&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;strong&gt;Command&lt;/strong&gt;: 

&lt;ul&gt;
&lt;li&gt;declares the interface for executing an operation; &lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;strong&gt;Concrete Command&lt;/strong&gt;: 

&lt;ul&gt;
&lt;li&gt;defines the binding between the Receiver and the action to execute;&lt;/li&gt;
&lt;li&gt;invokes methods on the Receiver to fulfill the request;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;strong&gt;Client&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;creates the Concrete Command and sets its Receiver;&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;strong&gt;Invoker&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;issues the request to execute the command;&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;In the example restaurant example we would have:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Cook&lt;/code&gt; as &lt;em&gt;Receiver&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Order&lt;/code&gt; as &lt;em&gt;Concrete Command&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Restaurant&lt;/code&gt; as &lt;em&gt;Client&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Customer&lt;/code&gt; as &lt;em&gt;Invoker&lt;/em&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Some pseudocode to look a bit more serious:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kr"&gt;interface&lt;/span&gt; &lt;span class="nx"&gt;Command&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Concrete Command&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;Command&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;Cook&lt;/span&gt; &lt;span class="nx"&gt;cook&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nx"&gt;Meal&lt;/span&gt; &lt;span class="nx"&gt;meal&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;cook&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;prepare&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;meal&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Receiver&lt;/span&gt;
&lt;span class="kr"&gt;interface&lt;/span&gt; &lt;span class="nx"&gt;Cook&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;prepare&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;Meal&lt;/span&gt; &lt;span class="nx"&gt;meal&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Invoker&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;Order&lt;/span&gt; &lt;span class="nx"&gt;order&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nx"&gt;Meal&lt;/span&gt; &lt;span class="nx"&gt;meal&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nf"&gt;mailOrder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;Order&lt;/span&gt; &lt;span class="nx"&gt;order&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;order&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Client&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Restaurant&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;Cook&lt;/span&gt; &lt;span class="nx"&gt;cook&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nx"&gt;Customer&lt;/span&gt; &lt;span class="nx"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;order&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;cook&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;meal&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nx"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mailOrder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;order&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h1&gt;
  
  
  &lt;span id="code-examples"&gt;Code examples&lt;/span&gt;
&lt;/h1&gt;

&lt;blockquote&gt;
&lt;p&gt;You can find a more detailed version of these examples here&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/shikaan" rel="noopener noreferrer"&gt;
        shikaan
      &lt;/a&gt; / &lt;a href="https://github.com/shikaan/design-patterns" rel="noopener noreferrer"&gt;
        design-patterns
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      Examples of usage of design patterns in real life code
    &lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="ltag-github-body"&gt;
    
&lt;div id="readme" class="md"&gt;
&lt;div class="markdown-heading"&gt;
&lt;h1 class="heading-element"&gt;design-patterns&lt;/h1&gt;

&lt;/div&gt;

&lt;p&gt;Examples of usage of design patterns in real life code&lt;/p&gt;

&lt;p&gt;These are the reference resources for &lt;a href="https://dev.to/shikaan/design-patterns-in-web-development-2gbp" rel="nofollow"&gt;this series of articles&lt;/a&gt;&lt;/p&gt;

&lt;/div&gt;
&lt;br&gt;
&lt;br&gt;
  &lt;/div&gt;
&lt;br&gt;
  &lt;div class="gh-btn-container"&gt;&lt;a class="gh-btn" href="https://github.com/shikaan/design-patterns" rel="noopener noreferrer"&gt;View on GitHub&lt;/a&gt;&lt;/div&gt;
&lt;br&gt;
&lt;/div&gt;
&lt;br&gt;
&lt;br&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Frontend: UI kits
&lt;/h2&gt;

&lt;p&gt;Following the first example above, here you are a simple example of how you can use the Command Pattern on the frontend. I have chosen to not use any framework, as the idea is general enough to be applied also to vanilla JavaScript.&lt;/p&gt;

&lt;p&gt;In this example we will just create and render a &lt;code&gt;Button&lt;/code&gt; component (Invoker) which will execute an &lt;code&gt;OpenAlertCommand&lt;/code&gt; (Concrete Command). The Window (Receiver) is actually responsible for doing the job, whilst Application (Client) is wrapping everything up.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;You may argue that doing the same thing without the pattern would have taken less then 10 LOC. You are actually right, but, for the reasons we discussed earlier, this scales better and will be more flexible when you will get new requirements.&lt;/p&gt;

&lt;p&gt;In &lt;a href="https://github.com/shikaan/design-patterns" rel="noopener noreferrer"&gt;the repo&lt;/a&gt; we are actually proving how more flexible this is, adding to this example a couple of other things: we reuse the same button with the same command with two different receivers, we use the same button to trigger two different commands at the same time.&lt;/p&gt;

&lt;h2&gt;
  
  
  Backend: CQRS in Python
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;A good introductory article on the matter is &lt;a href="https://medium.com/eleven-labs/cqrs-pattern-c1d6f8517314" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The following example will contain a &lt;strong&gt;super simple&lt;/strong&gt; CQRS application written in Python. It's supposed to be a banking app in which you can only deposit and get the list of all the deposits. Everything is stored in memory and will vanish as soon as the process ends.&lt;/p&gt;

&lt;p&gt;The architecture of the app, even though it's super basic, contains everything you need to call it a CQRS app.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxqc1zv1zvh3osj8682no.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxqc1zv1zvh3osj8682no.png" alt="Diagram"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Strap yourselves because here we have two concurrent implementation of the Command Pattern: one for writing (Command) and one for reading (Queries). Both share the same Client though.&lt;/p&gt;

&lt;p&gt;1) The Application (Client) creates the &lt;code&gt;Deposit&lt;/code&gt; command and calls the &lt;code&gt;handle_deposit&lt;/code&gt; method on the Command Handler (Command Invoker) &lt;br&gt;
2) The WriteStore (Command Receiver) saves data&lt;br&gt;
3) Right after the Command Handler fires an event to notify the ReadStore (Query Receiver) which updates&lt;br&gt;
4) The Application (Client) then creates the &lt;code&gt;GetLastDeposit&lt;/code&gt; query and calls the &lt;code&gt;handle&lt;/code&gt; method on the QueryHandler (Query Invoker)&lt;br&gt;
5) The ReadStore (Query Receiver) will then save the value into the query&lt;br&gt;
6) The result stored in the query returns to the user&lt;/p&gt;

&lt;p&gt;The code for this is of course available in &lt;a href="https://github.com/shikaan/design-patterns" rel="noopener noreferrer"&gt;the repo&lt;/a&gt;. Python is not my main language, so if you see something off, feel free to submit a pull request or open an issue there.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final words
&lt;/h2&gt;

&lt;p&gt;Well, this has been massive. Hopefully you got to read at least half of what I have written :D As always, if you have any feedback about how to make this series better, please let me know. &lt;/p&gt;

&lt;p&gt;Until next time!&lt;/p&gt;




&lt;p&gt;1. This kind of patterns actually modified the &lt;em&gt;behavior&lt;/em&gt; (in common English sense) of customers and cooks. Hopefully this will be enough to fix forever in your mind what a &lt;em&gt;behavioral&lt;/em&gt; pattern is.&lt;/p&gt;

&lt;p&gt;2. You language geeks may want to know that "order" in the restaurant context in Italian it's actually called "comanda". Just one word to remember both the pattern and the example. Lovely.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>python</category>
      <category>architecture</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>Design Patterns in Web Development</title>
      <dc:creator>Manuel Spagnolo</dc:creator>
      <pubDate>Sun, 04 Nov 2018 12:06:19 +0000</pubDate>
      <link>https://dev.to/shikaan/design-patterns-in-web-development-2gbp</link>
      <guid>https://dev.to/shikaan/design-patterns-in-web-development-2gbp</guid>
      <description>

&lt;h4&gt;
  
  
  Check out the updated version &lt;a href="https://withbenefits.dev/design-patterns-in-web-development-intro/"&gt;here&lt;/a&gt;
&lt;/h4&gt;

&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;h2&gt;
  
  
  Foreword
&lt;/h2&gt;

&lt;p&gt;Before diving down in this series you might want to know why I am writing this.&lt;/p&gt;

&lt;p&gt;My name is Manuel and I am a more-or-less Italian more-or-less lifelong geek.  Although I am doing web development since the dark ages of &lt;code&gt;&amp;lt;tables&amp;gt;&lt;/code&gt;, I decided to make software development a full time job only three years ago.&lt;/p&gt;

&lt;p&gt;As you can imagine, I didn't have my Computer Science education, so I am continuously striving to fill this gap studying "academic" topics as much as I can.&lt;/p&gt;

&lt;p&gt;Moreover, I recently moved away from my home country, thus I also need a good excuse to practice my English.&lt;/p&gt;

&lt;p&gt;This is exactly where this series of articles comes from.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is this about?
&lt;/h2&gt;

&lt;p&gt;What I'd like to do is writing articles about Design Patterns based on what I learned mainly from &lt;a href="https://en.wikipedia.org/wiki/Design_Patterns"&gt;the Gang of Four&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The difference between this and the overflowing amount of other articles doing the same, is that I will be trying to stick with full stack web development with extremely practical examples. Most of them are going to be in JavaScript or Python, as other languages have plenty of resources about this topic.&lt;/p&gt;

&lt;p&gt;Something along the lines of: How to use Command Pattern in a React component, in a CQRS Node application and to implement an Undo/Redo history in an Electron application.&lt;/p&gt;

&lt;p&gt;However this first article is going to be the Pilot Episode of the series. So still no patterns in here :(&lt;/p&gt;

&lt;h1&gt;
  
  
  Let's get started!
&lt;/h1&gt;

&lt;blockquote&gt;
&lt;p&gt;If you want to know more about design patterns in general I can recommend &lt;a href="https://refactoring.guru"&gt;this website&lt;/a&gt; which is my go-to place when I need to dust off those concepts.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  What is a design pattern?
&lt;/h2&gt;

&lt;p&gt;As much as everyone of you claims to be the best cook in the world because of their special, unique, one-of-a-kind touch (well, maybe this affects Italy more than other places...), we can all agree that having a grandma-crafted recipe book can take a good cook out of almost everyone.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--SE4FZDNS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.ecolutionhome.com/wp-content/uploads/2018/02/C-Cooking-Memes27.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--SE4FZDNS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.ecolutionhome.com/wp-content/uploads/2018/02/C-Cooking-Memes27.png" alt="Dog - I have no idea what I'm doing"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The reason is pretty straightforward: all those recipes have been created by someone who - eventually making a huge amount of mistakes along the way - fixed, corrected and amended those procedures over time. Using those well packaged bits of knowledge makes you avoid lots of common pitfalls and wrong decisions. This is extremely useful in circumstances in which the choice you make looks unharmful, but it doesn't look so when you serve your dish to someone which might not be as polite as you expect (food in Italy is really something serious).&lt;/p&gt;

&lt;p&gt;At the same time recipes can be used as a template to build upon rather than as a set of rules carved in stone. There are plenty of extremely good chefs which revisit their family cookbook to make a business out of it or, in general, to serve their purposes which might be different from their grandma's ones.&lt;/p&gt;

&lt;p&gt;In software development the whole thing works pretty much the same way. The main difference though is that software development projects usually last more than a bunch of minutes and you cannot get away with brushing your teeth &lt;br&gt;
at the end. Apart from this though, the main ideas are the same: having a very strong starting point to solve common problems which you might want to customize when you get to an expertise level which allows you to do so.&lt;/p&gt;

&lt;h2&gt;
  
  
  Criticism
&lt;/h2&gt;

&lt;p&gt;As for all the things which are too good to be true, this has to be either not so good or not so true.&lt;/p&gt;

&lt;p&gt;The good news is that this is true 😀 The bad news is, though, that your decision-making process cannot &lt;strong&gt;completely&lt;/strong&gt; be replaced by &lt;em&gt;The Wisdom of the Ancients&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kseaCHX---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.pinimg.com/originals/72/5d/29/725d29ab0d189c2220a8c398af687871.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kseaCHX---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.pinimg.com/originals/72/5d/29/725d29ab0d189c2220a8c398af687871.jpg" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is by far the most common argument raised against the pattern approach in software development: solutions provided via patterns tend to be not as efficient as they could be for very specific problems.&lt;/p&gt;

&lt;p&gt;To me this is kind of a weak point as you should always improve on or at least adapt one of those solutions to your needs. Being backed by something which passed the test of time will give you the advantage of knowing in advance most of the weaknesses of you choice, so you have a better understanding of how to address issues coming down the line.&lt;/p&gt;

&lt;p&gt;The other common argument against design patterns is that some of the classic ones (aka in the Gang of Four) exists only because of the state of software development in those days, which was a bit more "primitive" compared to what we have today. &lt;/p&gt;

&lt;p&gt;Well, I cannot disagree with this, but (as Francis up here says) "Knowledge is power" and I'd rather have a tool I don't use than lacking a tool I need.&lt;/p&gt;

&lt;p&gt;This, however, leads to the last criticism I want to address here. One of the risks of introducing patterns is that you might end up using them even in situations which do not require them at all. &lt;/p&gt;

&lt;p&gt;I guess this is something we cannot help and it's a fairly common problem with anything which is learned in schemes (e.g., when you start learning scales in music). Unfortunately, experience is the best teacher in this case, but being aware of the risks will definitely help you throughout the way. &lt;/p&gt;

&lt;h2&gt;
  
  
  Classification
&lt;/h2&gt;

&lt;p&gt;As you might have understood by now, the Gang of Four was really the s***t when it came out (which is, by the way, 1995). &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--M33vaJme--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.coengoedegebure.com/content/images/2017/08/onedoesnotsimplygof-1.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--M33vaJme--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.coengoedegebure.com/content/images/2017/08/onedoesnotsimplygof-1.jpg" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So nowadays, we're still somewhat classifying design patterns based on their classification.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The following list will become a list of links as long as I write articles on the subject&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Creational Patterns&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Abstract Factory&lt;/li&gt;
&lt;li&gt;Builder&lt;/li&gt;
&lt;li&gt;Factory&lt;/li&gt;
&lt;li&gt;Prototype&lt;/li&gt;
&lt;li&gt;Singleton&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Structural Patterns&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Adapter&lt;/li&gt;
&lt;li&gt;Bridge&lt;/li&gt;
&lt;li&gt;Composite&lt;/li&gt;
&lt;li&gt;Decorator&lt;/li&gt;
&lt;li&gt;Facade&lt;/li&gt;
&lt;li&gt;Flyweight&lt;/li&gt;
&lt;li&gt;Proxy&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Behavioral Patterns&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Chain of responsibility&lt;/li&gt;
&lt;li&gt;&lt;a href="https://dev.to/shikaan/design-patterns-in-web-development---1-command-2jf"&gt;Command&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Interpreter&lt;/li&gt;
&lt;li&gt;Iterator&lt;/li&gt;
&lt;li&gt;Mediator&lt;/li&gt;
&lt;li&gt;&lt;a href="https://dev.to/shikaan/design-patterns-in-web-development---2-memento-253j"&gt;Memento&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Observer&lt;/li&gt;
&lt;li&gt;State&lt;/li&gt;
&lt;li&gt;Strategy&lt;/li&gt;
&lt;li&gt;Template method&lt;/li&gt;
&lt;li&gt;Visitor&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Final words
&lt;/h1&gt;

&lt;p&gt;This was a brief and hopefully not-so-boring general introduction to Design Patterns. Next articles will be more practical, less wordy and maybe with the same amount of memes. &lt;br&gt;
Let me know if you are interested in the topic, as I really need motivation to continue writing :D&lt;/p&gt;


</description>
      <category>javascript</category>
      <category>python</category>
      <category>architecture</category>
      <category>designpatterns</category>
    </item>
  </channel>
</rss>
