<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Thomas Ferro on Medium]]></title>
        <description><![CDATA[Stories by Thomas Ferro on Medium]]></description>
        <link>https://medium.com/@thomasferro?source=rss-4b4931861afc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uwHGEAVL9bdFElxCCYGPdA.png</url>
            <title>Stories by Thomas Ferro on Medium</title>
            <link>https://medium.com/@thomasferro?source=rss-4b4931861afc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:23:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thomasferro/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Parlons Front !]]></title>
            <link>https://medium.com/codeshake/parlons-front-d3687f90f7cf?source=rss-4b4931861afc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3687f90f7cf</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[newsletter]]></category>
            <dc:creator><![CDATA[Thomas Ferro]]></dc:creator>
            <pubDate>Fri, 12 Feb 2021 11:00:40 GMT</pubDate>
            <atom:updated>2021-02-12T11:00:40.186Z</atom:updated>
            <content:encoded><![CDATA[<h3>Parlons Front !</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ayudPlNMyd_mNC9wYDQy8w.png" /><figcaption>Parlons Front ! Revue de presse #9</figcaption></figure><p>Tout votre temps normalement consacré à la veille est parti dans la recherche de cadeaux de Saint-Valentin pour votre bien-aimé(e) ? Ne vous inquiétez pas, on s’occupe de tout 💝</p><p>Chez SFEIR Lille, nous sommes nombreux à faire partie de la team #front et il nous tient à cœur de vous partager régulièrement nos dernières trouvailles en matière de veille technique.</p><p>Cette semaine, on casse le Web et on revoit nos bases du JS et on analyse des éléments de réponse pour la question qu’on n’osait pas se poser: avons-nous besoin de Vue 3 ?</p><ul><li><a href="https://jakearchibald.com/2021/function-callback-risks/"><strong>Don’t use functions as callbacks unless they’re designed for it</strong></a></li></ul><p>Selon vous, quel résultat retourne ce bout de code ?</p><pre>[&quot;1&quot;, &quot;2&quot;, &quot;3&quot;].map(parseInt)</pre><p>Un tableau avec les nombres 1, 2 et 3 ? Essayez-le dans une console, vous risquez d&#39;être surpris.</p><p>Un article assez détaillé, utile pour éviter les pièges à l’utilisation des fonctions comme callbacks !</p><ul><li><a href="https://catchjs.com/Blog/ErrorsInTheWild"><strong>We rendered a million web pages to learn how the web breaks</strong></a></li></ul><p>On continue cette sélection d’article avec une étude sur les erreurs au rendu des pages Web.</p><p>Un point qui va sans doute résonner avec des expériences personnelles présenté par l’article — traduit approximativement — est que “lorsque le Web casse, c’est à cause de fausses assomptions dans le code qui causent des erreurs au runtime. Le document où les types ne sont pas tels qu’attendus, les librairies où les données n’ont pas réussi à charger depuis le réseau.”</p><p>Découvrez les résultats de cette étude et des pistes pour créer des applications moins sujettes aux erreurs.</p><p>De quoi nous sensibiliser sur les points importants à vérifier via différents types de tests lorsqu’on développe des pages Web !</p><ul><li><a href="https://dev.to/alexdevero/the-javascript-event-loop-explained-4be5"><strong>The JavaScript Event Loop Explained</strong></a></li></ul><p>Il n’est pas nécessaire de connaître toutes les subtilités du fonctionnement interne d’un langage pour développer des applications de qualité. Il reste cependant intéressant de se pencher sur ces sujets une fois l’outil pris en main.</p><p>Découvrez ou redécouvrez le fonctionnement de l’Event Loop en JS au travers d’exemples détaillés 👍</p><ul><li><a href="https://2ality.com/2021/01/undefined-null-revisited.html"><strong>undefined vs. </strong></a><a href="https://2ality.com/2021/01/undefined-null-revisited.html"><strong>null revisited</strong></a></li></ul><p>Un mot clef pour les variables non assignées et un autre pour représenter l’absence intentionnelle de valeur ? Pourquoi cette différence ? Une <a href="https://www.youtube.com/watch?v=ybrQvs4x0Ps">erreur à un milliard de dollars</a> n’était pas suffisante ?</p><p>Les spécifications, les cas où le langage traite ces valeurs identiquement ou de façon différente et globalement comment gérer ces deux non-valeurs: tout ce qu’il faut savoir se trouve ici !</p><h3>Radar des sorties</h3><ul><li><a href="https://github.com/vuejs/vuex/releases/tag/v4.0.0"><strong>Vuex 4.0</strong></a>: une version principalement axée sur la compatibilité avec Vue 3. Quelques <em>breaking changes</em> sont présents dans cette version, notamment pour l’installation du plugin. Pensez à jeter un œil sur la note de mise à jour avant de migrer ! En parlant de migration…</li></ul><p>En plus des traditionnels articles et sorties de la semaine, nous vous proposons une analyse un peu plus poussée sur des sujets qui nous tiennent à cœur.</p><p>Pour cette première, penchons-nous sur les arguments exposés dans l’article <a href="https://itnext.io/yes-vue-3-is-out-but-you-probably-dont-need-it-%EF%B8%8F-3e60634991b4">“Yes, Vue 3 is out but you probably don’t need it 🤷‍♂️”</a>.</p><p>Nous avons hâte de connaître votre avis sur la question, rendez-vous <a href="https://medium.com/codeshake/oui-vue-3-est-sorti-est-vous-devriez-consid%C3%A9rer-dy-migrer-a09b32a45f5b">ici</a> !</p><p><em>Rien de prévu ce 12 février à 22h ? Rendez-vous </em><a href="https://www.meetup.com/fr-FR/GitHub-Virtual-Meetup/events/276304992/"><em>sur Twitch</em></a><em> avec </em><strong><em>Brian Douglas</em></strong><em>, developer advocate chez Github, et </em><strong><em>Evan You</em></strong><em>, créateur et mainteneur de Vue, pour découvrir Vite !</em></p><p>Et de votre côté, vous avez des nouveautés #front à partager avec nous ?</p><p>Merci à l’équipe et plus particulièrement <a href="https://twitter.com/HeryDev">Julien</a>, <a href="https://twitter.com/AxelLatour23">Axel</a>, <a href="https://twitter.com/raphaelbd">Raphaël</a>, <a href="https://twitter.com/GeromeGrignon">Gérôme</a> et <a href="https://twitter.com/RuelleAnthony">Anthony</a> pour leurs suggestions de cette semaine !</p><p>À la semaine prochaine 😃</p><p>#js #javascript #null #undefined #eventloop #vuejs #vue.js #vuex</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3687f90f7cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/parlons-front-d3687f90f7cf">Parlons Front !</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oui, Vue 3 est sorti et vous devriez considérer d’y migrer]]></title>
            <link>https://medium.com/codeshake/oui-vue-3-est-sorti-est-vous-devriez-consid%C3%A9rer-dy-migrer-a09b32a45f5b?source=rss-4b4931861afc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a09b32a45f5b</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Thomas Ferro]]></dc:creator>
            <pubDate>Thu, 11 Feb 2021 14:57:30 GMT</pubDate>
            <atom:updated>2021-02-11T14:58:19.565Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-13HGdH2cYm4O01r9npcMg.png" /><figcaption>Analyse d’article par l’équipe Parlons Front !</figcaption></figure><p>En plus des traditionnels articles et sorties de la semaine, nous vous proposons une analyse un peu plus poussée sur des sujets qui nous tiennent à coeur.</p><p>Pour cette première, penchons-nous sur les arguments exposés dans l’article <a href="https://itnext.io/yes-vue-3-is-out-but-you-probably-dont-need-it-%EF%B8%8F-3e60634991b4">“Yes, Vue 3 is out but you probably don’t need it 🤷‍♂️”</a>. Je n’ai malheureusement pas trouvé le nom de la personne ayant rédigé cet article et devrais me contenter de le nommer “l’auteur”.</p><p>Quelques précisions avant de rentrer dans le vif du sujet, il n’est pas question de déconstruire entièrement l’article ni d’essayer de le discréditer. Il me semble cependant important d’apporter un autre point de vue (🙃) sur certaines questions abordées dans l’article, afin de vous donner toutes les clefs pour savoir si vous n’avez vraiment pas besoin de passer à Vue 3 🤷‍♂️</p><p>Tout d’abord, je rejoins entièrement l’auteur sur le sujet de l’engouement. Il y a énormément de bonnes raisons de migrer vers une nouvelle version majeure : corriger des failles de sécurité, améliorer les performances ou encore augmenter la vélocité de l’équipe lorsque la nouvelle version introduit des outils le permettant.</p><p>Migrer un projet dans une nouvelle version majeure uniquement pour suivre la mode actuelle, ça peut être tentant, mais ça n’a rien de productif. On ne produit aucune valeur pendant ce temps et, pire, on risque de perdre en vélocité pendant le temps la montée en compétence de l’équipe ou encore en découvrant des problèmes apportés par cette nouvelle version.</p><p>Autre point entièrement objectif présenté par l’auteur : la compatibilité IE11. Si votre produit doit être compatible avec ce navigateur, ce n’est pas le moment de migrer puisque Vue 3 ne le gère pas encore.</p><p>Les points sur lesquels j’aimerais revenir et sur lesquels nous ne sommes apparemment pas en accord me semblent plus subjectifs. Ils concernent deux problèmes soulevés par l’auteur et les solutions de contournement proposées.</p><p>Le premier point concerne l’extraction de logique réutilisée à plusieurs endroits dans l’application. Ce point est traité par les versions précédentes de Vue via les <a href="https://v3.vuejs.org/guide/mixins.html">“mixins”</a>. Ces dernières permettent d’injecter de la logique dans plusieurs composants, en ajoutant notamment des data, des computed, methods et autres <a href="https://v3.vuejs.org/guide/composition-api-lifecycle-hooks.html#lifecycle-hooks">lifecyle hooks</a>.</p><p>Le problème ? Une fois injectés, ces éléments sont rendus disponibles de façon transparente dans les composants, on ne sait donc pas quel <em>mixin</em> a injecté quelles options, et on introduit un risque de collision lorsqu’on injecte plusieurs <em>mixins</em>.</p><p>La solution proposée par l’auteur consiste à créer une “factory de mixins”, permettant de préciser un contexte (ou namespace) qui sera ajouté devant chaque option injectée.</p><p>La problématique de conflit dans les noms des options semble donc corrigée, mais de façon transparente une fois encore. Il nous faut toujours parcourir les mixins pour savoir quelles données sont misent à disposition.</p><p>Les <a href="https://adamwathan.me/renderless-components-in-vuejs/">Renderless Components, tels évoqués par Adam Wathan</a>, sont aussi proposés en solution alternative.</p><p>Il s’agit, selon moi, d’un très bon pattern pour séparer intention et implémentation, je l’utilisais très souvent et peux attester des avantages en terme de lisibilité et maintenabilité. Problème, on ajoute un composant dans l’arbre pour chaque utilisation d’un renderless component et on complexifie grandement la partie HTML qui devrait être réservée au templating. Ce pattern est toujours utilisable, mais il semble moins intéressant que <a href="https://dev.to/thomasferro/composition-api-v-renderless-components-let-s-use-vue-3-s-features-to-clean-our-components-n25">l’utilisation combinée des Composition et Reactive APIs</a>.</p><p>Dernier point abordé sur lequel j’aimerais revenir, le fait de se passer de la Composition API dans des cas d’usages où les hooks peuvent être utilisés plus intelligemment.</p><p>L’exemple utilisé est effectivement plus simple sans Composition API, mais il ne présente qu’une toute petite feature, un <em>timeout</em> à initialiser et détruire, sans donnée exposée. La Composition API est prévue pour faire — justement — de la composition de plusieurs features de toutes tailles sans polluer le composant de détails d’implémentation.</p><p>On ne répond pas au problème de lisibilité lorsque le composant aura plus de tâches, autres que la gestion d’une sauvegarde automatique.</p><p>On ne profite pas non plus de la possibilité de séparer intention et implémentation. Ce dernier point peut sembler peu important pour un simple interval, mais il est crucial pour la maintenabilité du projet au long terme.</p><p>En résumé, rien ne vous oblige effectivement à passer sur Vue 3, mais il serait dommage de ne pas profiter des nouvelles fonctionnalités pour rendre votre code plus lisible et maintenable au fil des nouveaux développements.</p><p>Je vous encourage grandement à lire <a href="https://itnext.io/yes-vue-3-is-out-but-you-probably-dont-need-it-%EF%B8%8F-3e60634991b4">l’article en question</a> et nous partager votre ressenti face à cette problématique de montée de version !</p><p>J’ai moi-même écrit une série d’articles sur la dernière version de Vue 3, n’hésitez pas à <a href="https://dev.to/thomasferro/the-state-of-vue-will-the-3-0-still-be-approachable-4mgc">les parcourir</a> pour aller plus loin sur le sujet 😁</p><p><em>Un grand merci à </em><a href="https://twitter.com/AxelLatour23"><em>Axel</em></a><em> pour la relecture !</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a09b32a45f5b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/oui-vue-3-est-sorti-est-vous-devriez-consid%C3%A9rer-dy-migrer-a09b32a45f5b">Oui, Vue 3 est sorti et vous devriez considérer d’y migrer</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parlons Front!]]></title>
            <link>https://medium.com/codeshake/parlons-front-cea6d2ba11e1?source=rss-4b4931861afc------2</link>
            <guid isPermaLink="false">https://medium.com/p/cea6d2ba11e1</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Thomas Ferro]]></dc:creator>
            <pubDate>Tue, 22 Dec 2020 16:15:57 GMT</pubDate>
            <atom:updated>2020-12-22T16:15:57.930Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lklwHu98e1CxayydSS-Fw.png" /><figcaption>Parlons Front! Revue de presse #4</figcaption></figure><p>Vous reprendriez bien un peu de Front avant les fêtes ? 🎅</p><p>Chez SFEIR Lille, nous sommes nombreux à faire partie de la team #front et il nous tient à cœur de vous partager régulièrement nos dernières trouvailles en matière de veille technique.</p><p>Cette semaine est placée sous le thème des outils de développement et des bases du Javascript moderne, bonne lecture !</p><ul><li><a href="https://vuejsdevelopers.com/2020/12/07/vite-vue-cli/"><strong>Has Vite Made Vue CLI Obsolete?</strong></a></li></ul><p>Vous avez sans doute entendu parler de <strong>Vite</strong> si vous suivez <a href="https://twitter.com/youyuxi">Evan You</a>, le créateur de Vue.js, sur Twitter. Il s’agit d’un nouvel outil de build pour vos projets, théoriquement <em>10 à 100 fois plus rapide que Vue CLI</em> !</p><p>Pas de Webpack ou autre outil similaire, on se base ici sur les modules ES natifs dans les navigateurs qui les supportent.</p><p>Quelle est cette magie (<a href="https://www.youtube.com/watch?v=H7cAkkz0gEI">de Noël</a>) ? On vous laisse découvrir tout cela en détail dans l’article.</p><ul><li><a href="https://svelte.dev/blog/whats-the-deal-with-sveltekit"><strong>What’s the deal with SvelteKit?</strong></a></li></ul><p>On aurait pu mettre cet article dans la partie “Radar des non-sorties” puisqu’on y découvre entre autres la date de sortie de Sapper 1.0: Jamais ? 🤨</p><p>Découvrez pourquoi <a href="https://sapper.svelte.dev/">Sapper</a> (le NextJS/NuxtJs de Svelte) ne verra jamais le jour, et de quoi sera fait l’avenir du développement Web a base de <a href="https://www.snowpack.dev/">Snowpack</a>.</p><ul><li><a href="https://javascript.info/"><strong>The Modern JavaScript Tutorial</strong></a></li></ul><p>Et si votre bonne résolution 2021 était de consolider vos connaissances en Javascript ?</p><p><em>“The Modern JavaScript Tutorial”</em> est une véritable bible pour découvrir ou apprendre plus en profondeur ce langage !</p><p>Et vous, quels articles <strong>#front</strong> avez-vous mis sous le sapin ? On attend votre sélection en commentaire 👇</p><p>Merci à <a href="https://twitter.com/BMondolot">Bertrand</a>, <a href="https://twitter.com/raphaelbd">Raphaël</a> et toute l’équipe pour les suggestions d’articles !</p><p><strong>#front #js #javascript #vue #vite #svelte #svelteKit</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cea6d2ba11e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/parlons-front-cea6d2ba11e1">Parlons Front!</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Internationalize your Svelte app with reactive stores]]></title>
            <link>https://medium.com/codeshake/internationalize-your-svelte-app-with-reactive-stores-32875e306d26?source=rss-4b4931861afc------2</link>
            <guid isPermaLink="false">https://medium.com/p/32875e306d26</guid>
            <category><![CDATA[internationalization]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[svelte]]></category>
            <dc:creator><![CDATA[Thomas Ferro]]></dc:creator>
            <pubDate>Tue, 03 Nov 2020 15:06:25 GMT</pubDate>
            <atom:updated>2020-11-03T15:06:25.803Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>You either pick a i18n library or live long enough to write your own</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lYyqjd7HjsmIfi0PHVX4TA.jpeg" /><figcaption><strong>Kyle Glenn </strong>(<a href="https://unsplash.com/photos/nXt5HtLmlgE">https://unsplash.com/photos/nXt5HtLmlgE</a>)</figcaption></figure><p>I must confess something to you, and I hope that you will forgive me for it: I am French 🇫🇷🥖🧀🍷🐸🇫🇷.</p><p>I tend to write my applications in English in order to make them accessible to the greatest number of developers around the world. However, I sometime forget about the people closest to me.</p><p>I recently asked my family to beta test an <a href="https://dev.to/thomasferro/introduction-to-svelte-adapting-a-board-game-emc">adaptation of a board game</a> that I am building and the first feedback that I got was my girlfriend asking me “<em>pourquoi c’est en anglais ?</em>” (“<em>why is your game in English?</em>”).</p><p>Fair point. I immediately added an issue on this subject and start thinking about how to internationalize the application. Oh, and for those who wonder what <strong>i18n</strong> means, it is a commonly used abbreviation for <em>internationalization</em>, where the eighteen characters between the <em>i</em> and the <em>n</em> are represented by the <em>18</em>.</p><p>I already worked on that subject in my early days of Vue.js developer, using <a href="https://kazupon.github.io/vue-i18n/">Kazupon’s </a><a href="https://kazupon.github.io/vue-i18n/">Vue I18n library</a>. I loved the ease of use of the API, simply calling a $t method with the translation key in order to make everything work.</p><p>I wanted to find a Svelte alternative with the same appeal, but then think that it could make a great use case to learn to use a tool that I never practice before: the stores.</p><p>Again, I do not encourage you to build a new solution from scratch for every technical subject, especially when there is already <a href="https://github.com/kaisermann/svelte-i18n">well maintained alternatives</a>. However, for now, let us learn how to use Svelte’s stores to build a reactive internationalization mechanism 😁</p><h3>Building the i18n mechanism</h3><p>Practicing <em>Test Driven Development</em> has taught me something that I love to use when I have the opportunity, always starts by building the API that fits you the most. Only starts working on implementation details once the intention is clear.</p><p>Let us do just that and imagine the API of our dreams, starting with how to ask the system for a specific translation.</p><p>I like the idea of calling a simple method, directly from the template or from the &lt;script&gt;, something like this:</p><pre>&lt;script&gt;<br>  import { i18n } from &#39;./i18n&#39;;</pre><pre>// A localized message injected in the script<br>  $: authenticationErrorMessage = i18n(&#39;authenticationError&#39;)<br>&lt;/script&gt;</pre><pre>&lt;!-- A localized message directly called from the template --&gt;<br>&lt;h1&gt;{i18n(&#39;welcomeMessage&#39;)}&lt;/h1&gt;</pre><pre>&lt;p&gt;{authenticationErrorMessage}&lt;/p&gt;</pre><p>Obviously we will need a method to change the current locale, a method that will hopefully be able to change automatically every translation in the page without a refresh (spoiler alert: it will).</p><pre>&lt;script&gt;<br>  import { i18n, changeLocale } from &#39;path/to/i18n&#39;;<br>&lt;/script&gt;</pre><pre>&lt;button on:click={() =&gt; changeLocale(&#39;fr&#39;)}&gt;{i18n(&#39;switchToFrench&#39;)}&lt;/button&gt;<br>&lt;button on:click={() =&gt; changeLocale(&#39;en&#39;)}&gt;{i18n(&#39;switchToEnglish&#39;)}&lt;/button&gt;</pre><p>We could use <em>JSON</em> objects to manage the translations, one file per locale for instance:</p><pre>{<br>  &quot;welcomeMessage&quot;: &quot;Welcome!&quot;,<br>  &quot;authenticationError&quot;: &quot;Unable to authenticate...&quot;,<br>  &quot;switchToFrench&quot;: &quot;Switch to french&quot;,<br>  &quot;switchToEnglish&quot;: &quot;Switch to english&quot;<br>}</pre><p>Having already worked in large scoped projects, I know that the number of labels can grow pretty fast. It would be nice if we could allow for the use of nested objects.</p><pre>&lt;h1&gt;{i18n(&#39;home.welcomeMessage&#39;)}&lt;/h1&gt;</pre><pre>&lt;!-- With the JSON formatted like this: <br>{<br>  &quot;home&quot;: {<br>    &quot;welcomeMessage&quot;: &quot;Welcome!&quot;<br>  }<br>}<br> --&gt;</pre><p>Knowing our expected behaviour, it seems that we need a reactive mechanism accessible from any component in our application. We can manage this by using a global store, but how to implement it in Svelte? Heck, what is a global store?</p><h3>Read the fantastic manual!</h3><p>Leaving the Svelte world for a paragraph or two, a store can be seen as a way to manage reactive data outside of a component. It is especially useful when a lot of components share logic for a given matter.</p><p>Take the connected user management for instance. You may have one component managing the authentication process, another one responsible for the display of the connected user information, another one who takes care of editing the profile, etc. They all play with the same data and they need to be informed when this piece of data changes to update themselves accordingly.</p><p>This is where you could be tempted to create a user store. I am too, so let us create it!</p><p>Svelte provide us with a module for creating stores. We can create:</p><ul><li><a href="https://svelte.dev/docs#readable"><em>readable stores</em></a>: See them as read-only stores. I have no use case for them by now, but they must be useful since they are available 🤷‍♀️</li><li><a href="https://svelte.dev/docs#writable"><em>writable stores</em></a>: “Classical” stores, offering us ways to subscribe and unsubscribe to the data’s changes and methods to actually modify the data.</li><li><a href="https://svelte.dev/docs#derived"><em>derived stores</em></a>: A store based on other stores. We will see a specific use case for our i18n mechanism.</li></ul><p>Here is a minimalist user store:</p><pre>import { writable } from &#39;svelte/store&#39;;</pre><pre>export const user = writable({});</pre><p>I warned you, it is minimalist. Here is how you can consume and change this store’s data:</p><pre>&lt;script&gt;<br>  import { user } from &#39;path/to/user/store&#39;</pre><pre>let username <br>  user.subscribe(newUserInformation =&gt; {<br>    username = newUserInformation.name<br>  });</pre><pre>// Can be called when typing the name in an input for instance<br>  user.set({ name: &#39;Thomas Ferro&#39; });<br>&lt;/script&gt;</pre><pre>&lt;h1&gt;Welcome {username}!&lt;/h1&gt;</pre><p>Subscribing to a store can seem like a lot of busy work with this method. Svelte also provide a way to subscribe with a shortcut, prefixing your store name with $:</p><pre>&lt;script&gt;<br>  import { user } from &#39;path/to/user/store&#39;<br>&lt;/script&gt;</pre><pre>&lt;h1&gt;Welcome {$user &amp;&amp; $user.name}!&lt;/h1&gt;</pre><p>The complete API can be found, as always, in the <a href="https://svelte.dev/docs#svelte_store">documentation</a>.</p><p>Here is one extra feature that I enjoy a lot: any object with a correctly implemented .subscribe and .unsubscribe and optionally .set methods can be considered as a store by Svelte. Kudo for being able to create a framework-agnostic module.</p><p>However, for the sake of simplicity and brevity, we will use the provided methods to create our stores.</p><h3>Finally building something</h3><p>We know what we want to build, we know how we are going to build it… Time to code!</p><p>The first thing we want is a store with the labels for the current locale. We can manage this by creating a <em>writable store</em> with the labels and a method changing this store’s data according to the new locale:</p><pre>import { derived, writable } from &#39;svelte/store&#39;;<br>import enLabels from &#39;./en.json&#39;;<br>import frLabels from &#39;./fr.json&#39;;</pre><pre>const labelsStore = writable(enLabels);</pre><pre>export const EN_LOCALE = &quot;en&quot;;<br>export const FR_LOCALE = &quot;fr&quot;;<br>export let currentLocale = EN_LOCALE;</pre><pre>export const changeLocale = (newLocale) =&gt; {<br>    if (newLocale === EN_LOCALE) {<br>        labelsStore.set(enLabels)<br>        currentLocale = newLocale<br>    } else if (newLocale === FR_LOCALE) {<br>        labelsStore.set(frLabels)<br>        currentLocale = newLocale<br>    }<br>}</pre><p>One could use these exposed method and constants to make a local switcher:</p><pre>&lt;script&gt;<br>  import { changeLocale, EN_LOCALE, FR_LOCALE } from &#39;./i18n&#39;;<br>&lt;/script&gt;</pre><pre>&lt;button on:click={() =&gt; changeLocale(FR_LOCALE)}&gt;🇫🇷&lt;/button&gt;<br>&lt;button on:click={() =&gt; changeLocale(EN_LOCALE)}&gt;🇬🇧&lt;/button&gt;</pre><p>As explained in the description of the targeted API, I do not want the developers to directly access the labelsStore. Instead, I want them to use an exposed method and provide a translation key.</p><p>How can we expose this store in a way that fits our expected API? Using a <strong>derived store</strong>! This derived store will be called i18n and will not return directly an object with the labels, but a function that takes the translation key as an argument and return the label:</p><pre>import { derived, writable } from &#39;svelte/store&#39;;</pre><pre>// [...] labelsStore implementation</pre><pre>export const i18n = derived(labelsStore, (labelsForCurrentLocale) =&gt; {<br>    return key =&gt; labelsForCurrentLocale[key]<br>})</pre><p>This way, when the labels <em>store</em> is updated, the i18n derived store is notified and update itself too, making the components who depends on it refresh their templates.</p><p>We now need to manage the nested objects. We can extract this logic and use it directly in the method returned by the i18n store:</p><pre>import { derived, writable } from &#39;svelte/store&#39;;<br>import enLabels from &#39;./en.json&#39;;<br>import frLabels from &#39;./fr.json&#39;;</pre><pre>const labelsStore = writable(enLabels);</pre><pre>const OBJECT_PROPERTY_SEPARATOR = &quot;.&quot;</pre><pre>const crawlLabelsToFindRequestedTranslation = (currentLabels, translationKey) =&gt; {<br>    const pathToFollowInLabels = translationKey.split(OBJECT_PROPERTY_SEPARATOR)<br>    let currentPositionInLabels = currentLabels<br>    for (let i = 0; i &lt; pathToFollowInLabels.length; i++) {<br>        currentPositionInLabels = currentPositionInLabels[pathToFollowInLabels[i]]<br>        if (!currentPositionInLabels) {<br>            return translationKey<br>        }<br>    }<br>    return currentPositionInLabels<br>}</pre><pre>export const i18n = derived(labelsStore, (labelsForCurrentLocale) =&gt; {<br>    return (translationKey) =&gt; {<br>        if (!translationKey.includes(OBJECT_PROPERTY_SEPARATOR)) {<br>            return labelsForCurrentLocale[translationKey] || translationKey<br>        }<br>        return crawlLabelsToFindRequestedTranslation(labelsForCurrentLocale, translationKey)<br>    }<br>})</pre><p>There we go, our i18n is fully implemented, let us use it in a component 😃</p><pre>&lt;script&gt;<br>  import { i18n } from &#39;./i18n&#39;;</pre><pre>// A localized message injected in the script<br>  $: authenticationErrorMessage = $i18n(&#39;authenticationError&#39;)<br>&lt;/script&gt;</pre><pre>&lt;!-- A localized message directly called from the template --&gt;<br>&lt;h1&gt;{$i18n(&#39;welcomeMessage&#39;)}&lt;/h1&gt;</pre><pre>&lt;p&gt;{authenticationErrorMessage}&lt;/p&gt;</pre><p>Notice the slight difference in the usage, we need to prefix the store’s call with a $ to directly access the value and for this value to be reactive. See the <a href="https://svelte.dev/docs#4_Prefix_stores_with_%24_to_access_their_values">documentation</a> for more details on that matter.</p><h3>Possible next steps</h3><p>I do not think that I will continue to work specifically on the i18n mechanism since it already covers everything I needed in my application.</p><p>However, they are some possible improvements and new features.</p><p>I think that it could be great to manage the pluralization and the translation with parameters. For instance, when a translation takes a parameter that won’t go in the same place for different languages.</p><p>A dynamic local management could add value too, so the core of the mechanism won’t change when adding new managed language.</p><p>And of course, one could think that this mechanism could be a standalone library 😬</p><h3>A last word</h3><p>I learned a lot while building this i18n mechanism and writing this article. I think that it is the best kind of learning, picking a specific subject only when you actually need it. I do not have the time not the will to go through the entire Svelte documentation and make a project that mixes all of the framework’s features.</p><p>I hope that you discovered something too!</p><p>Localization is a common need for a lot of applications. I think that it would be a blast to have the communities of every front-end frameworks work together on a framework-agnostic reactive internationalization mechanism, don’t you? 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32875e306d26" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/internationalize-your-svelte-app-with-reactive-stores-32875e306d26">Internationalize your Svelte app with reactive stores</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Summary of a four days DDD training]]></title>
            <link>https://thomasferro.medium.com/summary-of-a-four-days-ddd-training-74103a6d99a1?source=rss-4b4931861afc------2</link>
            <guid isPermaLink="false">https://medium.com/p/74103a6d99a1</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Thomas Ferro]]></dc:creator>
            <pubDate>Wed, 06 Nov 2019 20:05:36 GMT</pubDate>
            <atom:updated>2019-11-08T08:03:38.670Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Make your domains shine!</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1UWSI-VPt4UK4900" /></figure><p>I think that one could say I was already convinced by the benefits of the <em>Domain Driven Design</em>.</p><p>I learned the hard way that driving your software engineering by the technical end can lead to pretty catastrophic situations.</p><p>Technical debt, hard coupling with any data provider, having to translate every domain feature request to fit in the already infected code base… I found myself in this situation not long ago and it was really hard for me to find the root cause.</p><p>This is when I found out about DDD. It immediately connects to me as it was exactly the thing that I was not able to name! All of those smells could be avoided by working with the domain to create a software that really reflects it.</p><p>I started diving into the subject by reading <em>Eric Evans</em>’ <a href="https://www.oreilly.com/library/view/domain-driven-design-tackling/0321125215/">Blue Book</a> and <em>Vaughn Vernon</em>’s <a href="https://www.oreilly.com/library/view/domain-driven-design-distilled/9780134434964/">Green Book</a> and we started implementing a few of the principles in my job, with the help of a coworker that already did in a previous mission.</p><p>I followed a four days (french) training given by <a href="https://twitter.com/hackyrjob"><em>HackYourJob</em></a>’s <a href="https://twitter.com/florentpellet">Florent Pellet</a> on <em>DDD</em> and its implementation. It was an excellent experience as he was able to validate what I already learned while teaching me a whole lot of new concepts.</p><p>Here are my organized thoughts and notes about those great four days.</p><blockquote><em>Disclaimer: I wrote this article mainly to have a clean trace of this training. I would be glad if you find it interesting and if you use it as a quick reference, but I highly recommend that you dig deep into each subject.</em></blockquote><h3>My own expectations</h3><p>My main expectations for the whole training was the following:</p><ul><li>Validate what I previously learned;</li><li>Learn how to introduce the subject and onboard a tech-oriented team;</li><li>Hear some real world stories about the usage of <em>DDD</em>;</li><li>Have a clear definition of two <em>DDD</em> terms that I often mixed up: <em>Strategic</em> and <em>Tactical</em> patterns;</li><li>Learn more about <em>DDD-lite</em>, is it a fraud?</li></ul><h3>What is DDD?</h3><p>We started the training with some theoretical definitions.</p><blockquote><em>Note: Every definition will be stated as blockquotes. They are rewording of concept that I learned about in the training and do not engage anyone but myself.</em></blockquote><p>Obviously, it was a good idea to start with the explanation of <em>what is DDD</em>:</p><blockquote>DDD (Domain Driven Design)<em>: A set of tools aiming to manage software complexity.</em></blockquote><p>But what is <em>software complexity</em>? <em>Ben Moseley</em> and <em>Peter Marks</em> started their essay Out of the tar pit by stating that <em>“Complexity is the single major difficulty in the successful development of large-scale software systems”</em>. It can be divided into three types:</p><blockquote>Essential complexity<em>: The complexity that cannot be reduced, that is required to answer the need.</em></blockquote><blockquote>Mandatory accidental complexity<em>: The one we cannot do without (the network, the programming language, etc).</em></blockquote><blockquote>Optional accidental complexity<em>: The complexity caused by the use of an inadequate framework, by the use of a different language between the domain concerns and the development one, etc.</em></blockquote><p>The latest complexity type is the one that we are trying to reduce, while trying to manage the three of them better with <em>DDD</em>.</p><h3>It’s all about context</h3><p>Writing a piece of software can be reduced as finding the right abstraction to answer a need. This abstraction is deeply linked to the context of the need.</p><p>We are trying to answer a specific need, as opposed to a generic one.</p><p>Take this common example of a map. If you try to help a friend reaching his destination using the subway, you are not going to give him the entire map of the city. You will certainly give him the subway map, the <em>abstraction of the city in the context of the subway lines</em>.</p><blockquote>Bounded context<em>: Set of elements (classes, services, etc) containing only what is needed in a specific context. You should not be afraid to duplicate code between contexts for them to be the clearest possible.</em></blockquote><h3>The tools you need to understand your needs</h3><p>Here are few of the tools we should use to truly understand our needs when building software:</p><ul><li>User meetings;</li><li>Domain experts interviews;</li><li>Event Storming (more on that later);</li><li>US Mapping (more on that online);</li><li>Impact Mapping: The goal of this workshop is to identify a goal, define actors, the impacts of each of the actors and the deliverables linked to these impacts.</li></ul><p>The point here is to <em>speak to the actors</em>, and not to base our choices on assumptions and transcriptions.</p><p>Those tools and other communication medium can help us create an <em>Ubiquitous Language</em>.</p><blockquote>Ubiquitous Language<em>: Common language spoken by every member of the team. Here, two identical words should have the same domain meaning and two different ones should not designate the same concept.</em></blockquote><p>The <em>Ubiquitous Language</em> helps us align the source code with the domain. A domain expert should be able to understand the source code (the domain one, obviously).</p><h3>Focus on Event Storming</h3><p>This type of workshop was not discussed on the <a href="https://www.oreilly.com/library/view/domain-driven-design-tackling/0321125215/">Blue Book</a>, but it is still a quite relevant tool.</p><p>You could use it as a way to grasp the big picture of your project, or to try to find insight about a specific part of your domain. It is a medium of communication for every team members, where we start from the objectives and take a step back.</p><p>There are many ways to conduct the workshop, but here is how we did it at the training. The example is for a betting application, with the team trying to do a Big Picture Event Storming.</p><p>The <em>Product Owner</em> tells the story of the product, based on his vision of it.</p><p>Every time someone find a domain event related to the story told, he writes it down on a sticky-note of any color (usually an orange one) and put it on a timeline.</p><blockquote><em>Example: Goal scored</em></blockquote><p>Once the <em>Product Owner</em> finished his story, the team tries to associate a command (blue sticky-note) and an actor (yellow sticky-note) on every domain event. This process reverse the narration.</p><blockquote><em>Example: Score a goal, by a player.</em></blockquote><p>The next step is to regroup the events/commands/actors in aggregates, the timeline can be ignored for the end of the workshop.</p><blockquote><em>Example: A “match” aggregate arise with the “Goal scored” event and the associated command and actor, plus other events related to the players.</em></blockquote><p>The final step is to regroup aggregates in contexts.</p><blockquote><em>Note: We did use this tool in my current mission, but with a more anarchist twist: we started by adding every domain events that crossed our mind, then we filtered them. I personally find this start to be less productive since you spend most of the workshop sorting sticky-notes.</em></blockquote><p>When doing this workshop, you should be careful to always use the <em>Ubiquitous Language</em>, and you can mark the uncertainties with red sticky-notes.</p><p>This is a really diminishing description, I urge you to read <a href="https://www.eventstorming.com/"><em>Alberto Bradolini</em>’s Event Storming materials</a> for more information.</p><h3>Organize your inter-contexts communications</h3><p>When using <em>DDD</em> at the enterprise scale, you need to set up inter-teams and inter-contexts strategies.</p><p>This is where the <em>Strategic Patterns</em> play their part.</p><blockquote>Strategic Patterns<em>: Communication patterns used to organize the exchanges between contexts.</em></blockquote><blockquote>Upstream<em>: The upstream can be seen as the owner of the data, of the features.</em></blockquote><blockquote>Downstream<em>: The downstream can be seen as the client, he will usually be influenced by the upstream.</em></blockquote><p>Here is a quick description of each of the patterns introduced during the training:</p><ul><li><em>Big Ball of Mud</em>: Basically any situation where the communications go in every direction. Spoiler alert: it is bad;</li><li><em>Partnership</em>: When two contexts work together in a situation when if one fails, the other goes down with him;</li><li><em>Conformist</em>: One context comply to the other one’s vision. The downstream does not have his word to say in the choices made by the upstream;</li><li><em>Customer/Supplier</em>: Like the <em>Conformist</em> approach, the downstream consumes the upstream’s features but the downstream can makes requests for changes or new features;</li><li><em>Separate ways</em>: In the not-so-rare situation when you have two different solutions to the same problem, two contexts can decide to have zero communication and find their own way;</li><li><em>Published language</em>: Everyone follows a contract, a standard;</li><li><em>Open Host Service</em>: The upstream’s provide an <em>API</em> that is consumed by everyone who needs it;</li><li><em>Shared Kernel</em>: This is the one that I personally dislike the most. It is basically sharing some code between multiple contexts, via a library for instance. I dislike it because I found it odd to have to share some code, I cannot think of any case where this is not a smell of a bad responsibilities split. Feel free to prove me wrong!</li></ul><p>Now, if you want to protect your context from the outer world’s noises, you could put an <em>Anticorruption Layer</em> (or <em>ACL</em>) in your inputs and outputs. You can do so just by making the communications from and to your <em>domain</em> going through an <em>interface</em>. Your infrastructure layer will have the responsibility to implements this interface and by doing so translate the messages for the world to understand.</p><p>To visualize the whole <em>Strategic Patterns</em> and contexts in play, you can draw a <em>Context Map</em>. This is a map of all of the contexts, their interactions and the type of those. Take <a href="http://verraes.net/2014/01/bandwidth-and-context-mapping/">Mathias Verraes’s example</a> for a more in-depth look.</p><p>We have seen the patterns used to communicate between the contexts, now we will see the patterns used in the actual code.</p><h3>Organize your code</h3><blockquote>Tactical patterns<em>: Engineering patterns used to organize the code-base in order to reflect the domain.</em></blockquote><p>Here is a quick description of the building blocks described in <em>Eric Evans</em>’ <a href="https://www.oreilly.com/library/view/domain-driven-design-tackling/0321125215/">Blue Book</a>, please go back to this book if you want more information.</p><blockquote><em>Value Object</em>: An object that has no identity, no lifetime and who is compared based on his values.</blockquote><p>Example: the red color can be represented as an object with the <em>hexadecimal</em> value set to <em>“#FF0000”.</em></p><blockquote><em>Aggregate</em>: Special kind of <em>Entity</em>, has an identity and a lifetime. Can be composed of <em>Value Objects</em> and <em>Entities</em>, but not of other <em>aggregates.</em></blockquote><ul><li>Responsible for the domain logic for a single <em>aggregate</em>, every action on the aggregate or the elements inside it must go through him;</li><li>Cannot directly communicate with other <em>aggregates</em>, those communications must go through a <em>service.</em></li></ul><p>Example: A person can be represented as an object with attributes and identified with his social security number. Actions on this person’s tooth must go through the <em>aggregate</em> representing him, not directly on the tooth.</p><blockquote><em>Entity</em>: An object with an identity unique inside the aggregate.</blockquote><p>Example: The front-left wheel in a car;</p><blockquote><em>Service</em>: Has no lifetime nor data. Used to synchronize aggregates.</blockquote><ul><li><em>Domain Event</em>: Used to communicate with the world. Can be seen as a <em>Value Object</em> representing a decision made.</li></ul><p>Additionally, two patterns are usually used to manipulate <em>aggregates</em>:</p><blockquote><em>Repository</em>: Used to manipulate collections of <em>aggregates</em>, to persist them for example.</blockquote><blockquote><em>Factory</em>: Used to build non-trivial <em>aggregates</em>. To be used when the <em>aggregate</em>’s constructor is not enough and the creation logic is too complicated.</blockquote><h3>DDD and Software Architecture</h3><p>Loose coupling / high cohesion is something you want to achieve when building an application with the <em>DDD</em> tools.</p><p>I will list some architectural patterns that you can use to do so, but please remember to be practical. You can combine all of those patterns, but it will create complexity. You should always ask yourself if it is worth the investment before implementing one of those.</p><h3>Hexagonal architecture / Ports and Adapters</h3><blockquote>Hexagonal architecture<em>: Also known as </em>Ports and Adapters<em>. Pattern coined by </em><a href="https://twitter.com/totheralistair"><em>Alistair Cockburn</em></a><em> aiming to isolate the domain concerns from the infrastructure ones.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OqndNdiIsY2S9qkW.png" /></figure><blockquote><em>Credits to </em>Maxime COLIN<em> for the schema on the </em>Elao<em>’s blog.</em></blockquote><p>This pattern is quite simple to put in place. It is mainly about interfacing the interaction with the outer world.</p><p>You have two kind of ports:</p><ul><li>“In”: the entry points to the domain;</li><li>“Out”: the exit points.</li></ul><p>For instance, you will have an entry port as an interface with the actions available in your domain. This interface could be implemented by a <em>REST API</em>, a <em>Message Queue</em> or event a <em>Command Line Interface</em>, the domain concern will not change.</p><p>The same goes for the exit points, no matter where you are retrieving or persisting your data, the domain is not impacted.</p><p>A more advanced architectural pattern based on the same principles is <em>Robert C. Martin</em>’s <a href="https://www.goodreads.com/book/show/18043011-clean-architecture">Clean Architecture</a>. I wont go into much details here since we did not see it in the training, but I do think that it is a great way to respect the <em>Clean Code</em> principles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*QpTjJrG6zmaOLxsW.jpeg" /></figure><h3>Event Sourcing</h3><blockquote>Event Sourcing<em>: Architectural pattern focusing on the path that led us there instead of where we are right now.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1wBXVf58rFsZtUs9.png" /></figure><p>It all start with an <em>aggregate</em> receiving a <em>command</em>. Based on this <em>command</em>, the <em>aggregate</em> will make decisions in the — wait for it — <em>decision methods</em>.</p><p>Those <em>decision methods</em> will then return events.</p><p>Those events will be applied to the <em>aggregate</em> in order to modify his current state. This process is done in <em>application methods</em>.</p><p>The events are not only applied, they can also be sent outside the <em>aggregate</em>, stored and published for side-effects. For instance, an event can trigger a mail notification when published.</p><p>You might need a concrete example, here is one in the context of our Betting app:</p><ul><li>A goal is scored, represented as a <em>command</em> in the Match <em>aggregate</em>;</li><li>The <em>decision method</em> handling the command, based on the data inside the command, decide to send the following event: ScoreGoaled with the player who scored, the time, etc;</li><li>This event is applied to the current match, updating his state;</li><li>It is also stored and published, triggering the notification system for the users who bet on the match.</li></ul><p>This example does not go into details about how to loop in the <em>decide/events/apply</em> iteration, but know that there are use cases when you will need to.</p><p>We talked about storing events, but what about persistency ? Do we still be using a relational database ?</p><blockquote>Event Store<em>: Persistency mechanism where you are not storing the current state of a data, but all the events that led to this state.</em></blockquote><p>Take for example an <em>aggregate</em> representing a car. You can choose to store the current state of the car, of his wheels, engine, etc in a relational database, or you can store every events that occurred on the car. May they be a <em>gas refuel</em>, <em>oil change</em>, <em>wheel change</em>, etc.</p><p>You can then rebuild the <em>aggregate</em> by replaying all of the events since they are idempotents.</p><p>This approach works especially well with <em>DDD</em> since you can use the <em>domain events</em> already discovered in workshop such as Event Storming. Events applied on <em>aggregates</em> should match 1:1 those <em>domain events</em>.</p><p>You can go even further by combining <em>Event Sourcing</em> with another mechanism, <em>CQRS</em> who come in handy when dealing with performance issues.</p><h3>CQRS</h3><blockquote>Command Query Responsibility Segregation<em> (or </em>CQRS<em>): Split your application in two components: the </em>Command<em> to update the data and the </em>Query<em> to retrieve it.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gOq8ZZskiCWnuD_m.png" /></figure><p>This pattern is especially useful when the update requests and the read ones happen at a very different rate.</p><p>For instance, take a booking application. You can have a huge traffic, meaning a lot of query request, while only a small portion of those visitors end up booking an actual trip. In this situation, having a lightweight application managing the <em>commands</em> can be enough, and you can focus your efforts on the <em>query</em> application that will need to manage the load.</p><p>To oversimplify the process, you can put it this way :</p><ol><li>A <em>command</em> is played on an <em>aggregate</em>;</li><li>This command generate <em>events</em>, modifying the <em>aggregate</em>;</li><li>Those events can be stored, but they especially are catched by the projections impacted;</li><li>Those projections update themselves, updating the <em>queries</em>.</li></ol><p>The clients only consume projections, which is faster than having to rebuild the <em>aggregates</em> every time.</p><h3>Back to the training</h3><p>The training did a great job introducing the tools and concepts while making us practice with a lot of examples.</p><p>I tried to put in this article every major themes, consider it a quick go-to when trying to explain what is <em>DDD</em>.</p><p>Events and projections persistency, transactions, events lifetime and more details about the implementation of a <em>CQRS / ES</em> (<em>Command Query Responsibility Segregation</em> / <em>Event Sourcing</em>) architecture are not discussed here. Those advanced concepts are yours to discover and practice!</p><p>I want to thank <a href="https://symbol-it.fr/">Symbol-it</a>, the company I work for, for the logistic and for listening to my personal training wishes.</p><p>And of course, a huge thank you to <em>Florent Pellet</em> for sharing his knowledge and spending those enlightening four days with us!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74103a6d99a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golog : My take on palindromes and Go logging]]></title>
            <link>https://thomasferro.medium.com/golog-my-take-on-palindromes-and-go-logging-8946b7fe2b0f?source=rss-4b4931861afc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8946b7fe2b0f</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[Thomas Ferro]]></dc:creator>
            <pubDate>Fri, 04 Oct 2019 12:53:32 GMT</pubDate>
            <atom:updated>2019-10-04T12:53:32.919Z</atom:updated>
            <content:encoded><![CDATA[<h3>Golog : My take on palindromes and Go logging</h3><blockquote><em>Logging enhanced, plus a quick integration with the ELK stack</em></blockquote><h3>Should I write logs?</h3><p>Yes.</p><p>Logging is a key part of debugging. How can we understand what went wrong in our application if we are in the dark?</p><p>However, logging for the sake of logging is never enough. For the messages to be useful, they need to be contextualized. What is the level of the log? What data are attached to it?</p><p>This way, we are able to quickly understand the root cause, which actions led to the observed behavior.</p><p>Still need to be convinced ? Want a more in-depth presentation of the why and how ? Please take a look at <a href="https://medium.com/@edouard.cattez/the-art-of-talkative-application-489f03bd89f4">Edouard Cattez’s awesome article on the subject</a>.</p><h3>The standard way</h3><p>The Go programming language offers a standard way of logging via the <a href="https://golang.org/pkg/log">log package</a>.</p><p>I really like how this package <em>abstract the output</em>. It makes it so easy to start logging right away for any little project, without having to deal with the low level details. Nobody wants to deal with low level details anyway, right ? <em>Right ?</em></p><p>On the other hand, I feel like too much is going on under the hood, especially with the call to os.Exit(1) or the panic with the Fatal and Panic methods. I also am not found of the fact that there is <em>no logging level nor metadata management</em> out of the box. It makes me very sad and grumpy.</p><p>As I do not like to be sad and grumpy, and as I plain to start a <a href="https://medium.com/p/building-a-blogging-application-part-1-the-goals-b4a99847584">quite big project of my own</a>, I need a solution to the previously listed issues.</p><h3>Building the new logger</h3><p>Disclaimer : The point here is not to reinvent the wheel — even tho I will — but to play around with a real example. I also wanted to create a logger that suits my own needs for further projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*JUh-UtFl9A2ij8gp.png" /></figure><blockquote><em>Credits to XKCD for the comics, </em><a href="https://xkcd.com/license.html"><em>link to the licence page</em></a></blockquote><p>Rest assure, I wont describe the whole process like I did in <a href="https://medium.com/p/tdd-in-action-debouncer-in-go-b0f7d7d75931">TDD in action : Debouncer in Go</a>.</p><p>I did however built this logger following the TDD principles, to be sure that it worked the way I expected. “It does not work if it is not tested”, as a wise human being once said, I guess. But how did I expected it to work again ?</p><p>Many loggers such as <a href="https://github.com/sirupsen/logrus">Sirupsen’s </a><a href="https://github.com/sirupsen/logrus">logrus</a> already tackle the issues of not having metadata nor levels of tracing.</p><p>The API of golog is as simple as the logrus one. You have one method per level of log (Debug, Info, Warn, Error and Fatal) and an <em>entry</em> system for the metadata.</p><p>To add metadata to a log, you can use (and chain) the WithFields method :</p><pre>golog.WithFields(entries.Fields{<br>	&quot;answer&quot;: 42,<br>	&quot;title&quot;: &quot;The Hitchhiker&#39;s Guide to the Galaxy&quot;,<br>}).WithFields(entries.Fields{<br>	&quot;author&quot;: &quot;Douglas Adams&quot;,<br>}).Debug(&quot;Unashamed reference dropping&quot;)</pre><p>You can also log a message without any metadata :</p><pre>golog.Debug(&quot;My message without context&quot;)</pre><p>Unlike the standard API, golog does not panic nor exit the program when using the Panic or Fatal method. This is because I personally think that it breaks the Single Responsibility Principle and it make the behavior non-obvious. We may disagree on this point but for me it is an unwanted side-effect.</p><p>Here is a sneak peak of the project’s current structure.</p><p>In order to <em>format</em> the logs, a Formatter must be provided with the following method Format(fields entries.Fields, level string, message string) string.</p><p>The <em>fields</em> are simply a map with the metadata’s names and values (type Fields map[string]interface{}).</p><p>In the same package (entries) you will find the actual Entry, with a few methods :</p><pre>type Entry interface {<br>	Fields() Fields<br>	WithFields(fields Fields) Entry<br>	Debug(message string)<br>	Info(message string)<br>	Warn(message string)<br>	Error(message string)<br>	Fatal(message string)<br>	WriteLog(level string, message string)<br>}</pre><p>The project also has a loggers package with the interface of a logger and a method to create a new one. As you may have understand already, a logger must have a Formatter and an Output :</p><pre>func NewLogger(output io.Writer, formatter formatters.Formatter) Logger {<br>	return GoLogger{<br>		output,<br>		formatter,<br>	}<br>}</pre><p>With these concerns split, I was able to add the last feature : Being able to configure multiple loggers. This way, I can have the log written as key-value pair in the terminal and as JSON in a file.</p><p>The method used to actually write a logging message iterates through all of the configured loggers. For each of them, it then write the message formatted using the provided formatter.</p><pre>func (entry LogEntry) WriteLog(level string, message string) {<br>	for _, logger := range GetLoggers() {<br>		logger.Output().Write(<br>			[]byte(<br>				logger.Formatter().Format(entry.Fields(), level, message),<br>			),<br>		)<br>	}<br>}</pre><p>Perfect, we know write the formatted message! The time is upon us when we will need no debugging tool, all we need to do is to read the logs! …But wait, how could we configure <em>golog</em> ?</p><p>The next step was to provide a configuration system with the following rules :</p><ol><li>Have a default configuration with a log file and a console output;</li><li>Being able to override the configuration with in-code configuration.</li></ol><p>This is where the configurations package steps in. It provides the following default configuration :</p><pre>var defaultLoggers = []gologgers.Logger{<br>	gologgers.NewLogger(os.Stdout, formatters.NewKvpFormatter()),<br>	gologgers.NewLogger(outputs.NewSimpleLogFile(<br>		&quot;log&quot;,<br>	), formatters.NewKvpFormatter()),<br>}</pre><p>It also exposes a SetLoggers method, used to override the default configuration.</p><p>When fetching the loggers to use, the default ones are used when no other are provided.</p><h3>Going further : integration with centralized logs manager</h3><p>Before we wrap it all up, let us integrate the new logging system with a centralized logs manager.</p><p>The main focus for me was to decorrelate the application from the logs manager. <a href="https://www.elastic.co/products/beats/filebeat"><em>Filebeat</em> modules</a> allows me to do so by simply reading log files and sending the data wherever I want. For this example, I will be sending those data to an <a href="https://www.elastic.co/what-is/elk-stack"><em>ELK</em> stack</a>.</p><p>In order to easily start an <em>ELK</em> stack, I have started a <em>Elastic Cloud</em> free trial.</p><p>Then, I installed and configure <em>Filebeat</em> (v7.4.0) based on the <a href="https://www.elastic.co/products/beats/filebeat">documentation</a>.</p><p>I decided to configure my logger to write the message as <em>JSON</em> object in a file, so the <em>Filebeat</em>’s input configuration will look like this :</p><pre>filebeat.inputs:<br>- type: log<br>  enabled: true<br>  paths:<br>    - /my/path/to/the/log/files/*.log<br>  json.keys_under_root: true</pre><p>One use case that I do not cover yet is the rotating logs. When log files start to get too big, one common practice is to keep the oldest messages in “archive” files. <em>Filebeat</em> is able to manage this use case, you can find the related documentation <a href="https://www.elastic.co/guide/en/beats/filebeat/current/filebeat-input-log.html#rotating-logs">here</a>.</p><p>The <em>Filebeat</em> now watch the log files and send the data to <em>Elasticsearch</em>, and here is the result in <em>Kibana</em> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SmeNIR9ToEGg8fPP.png" /></figure><p>You may have noticed that I cheated a little. I needed to log the message as <em>JSON</em> object because I could not find any documentation about decoding key-value pair in the <em>Filebeat</em>. Feel free to let me know if you have any information about this subject.</p><p>Anyway, no reference to the <em>ELK</em> nor <em>Filebeat</em> are in the Go code, mission accomplished!</p><h3>Special thanks</h3><p>I would like to thanks <a href="https://twitter.com/fabriceclaeys">Fabrice Claeys</a> and <a href="https://twitter.com/passionne42">Matthieu Fernandes</a>, two of my coworkers who helped me with their knowledge on logging et the Go language!</p><p>Another special thanks to my friend and coworker <a href="https://twitter.com/ecattez">Edouard Cattez</a> for his precious inputs on logging, the <em>ELK</em> stack and <em>Filebeat</em>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8946b7fe2b0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The smell of change management]]></title>
            <link>https://thomasferro.medium.com/the-smell-of-change-management-9c2eac05b4f0?source=rss-4b4931861afc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c2eac05b4f0</guid>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[change-management]]></category>
            <dc:creator><![CDATA[Thomas Ferro]]></dc:creator>
            <pubDate>Wed, 25 Sep 2019 11:37:09 GMT</pubDate>
            <atom:updated>2019-09-25T11:37:09.096Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Code smell: In software development, any symptom of a greater sin within the product.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zVdNif6DuONifHBh.png" /></figure><p>Ladies and gentlemen, members of the board and shareholders, I am glad to welcome you to this year’s leaders meeting.</p><p>For those of you who do not know me, the name is Thomas Doe, co-creator of Pentathlon and head of the IT department.</p><p>I hope that everyone made a fine trip and that you all enjoyed the petits fours. It is now time to kick-start this meeting with the less enjoyable news. Yes, I am talking about the migration to our new set of applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y92wVCkayLH3KKDB" /></figure><p>Last year at this very meeting I announced you that our company’s biggest pain was about to be cured. That all of our collaborators will finally be able to stop using our legacy catch-all solution.</p><p>Not only did we miss the milestone, but we also have seen our expenses exploded and our satisfaction reports are lower than ever. I am here today to explain the hows and whys and introduce our next steps to bounce of this failure.</p><p>But first, let me do a quick recap of the whole situation. Since the beginning of Pentathlon, our collaborators working in stores can take of their businesses via the <em>All4Sales</em> application.</p><p>This application includes the stocks management, actions surrounding the prices, customer relationship, etc…</p><p>Feature after feature, the monolith became unmanageable. We never took the time to look at the big picture and realize that all we did was add to the already enormous technical debt.</p><p>It was already too late when we came to the conclusion : If we want to be competitive, we cannot continue down this way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3T8h8P_wOAv84rou.png" /></figure><p>We gather every member of the IT department to find a solid and sustainable solution. At the time, every tech radar and every blog posts praised microservices and the whole ecosystem behind them. It also seems to correspond to our needs at the time, to split the monolith !</p><p>A year and a half ago, we rushed heads down in that idyllic direction, the one that I introduced to you in the last leaders meeting.</p><p>I am not going to explain the technical difficulties we encountered. Just know that we really struggled to deliver in due time. The new solution was finally there, ready to be used by our collaborators. A shinny new set of applications available in our custom store, <em>Apps4Stores</em>. However, the hype was not quite there… just the opposite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P9USgObQfA_3vWuD.png" /></figure><p>Based on anonymous reports, 89% of our users found the new set of applications to be counter intuitive. 80% of them are not ready to stop using the legacy application. The stores where the usage of Apps4Stores was made mandatory have seen their “happiness at work” surveys’ results dropped by up to 50 points in two months. One could call that a catastrophic launch.</p><p>But what went wrong? How could the users not see that everything they need is right there, under their nose?</p><p>We could not — or wanted not to — answer these questions at the time. All that mattered was to migrate every user and to decommission the legacy application.</p><p>What we did, however, is to start a massive change management plan. We brought every region managers for a three days training. Everything they needed to know about how to use the applications and how to train people themselves was explained to them. After that, we published a series of video tutorials and let two months to the managers to train the collaborators in their region.</p><p>Let us just say that it may not have been our smartest nor our most appreciated move.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*inGbDmysh58i1Wmb.png" /></figure><p>With no precise directive and no shared values, nearly all of the managers failed to make everyone walk in the same direction.</p><p>Some stores finally dropped the legacy app, under the pressure of the deadline. Most of them, however, did not was the value of changing and just postponed.</p><p>When the date was finally there, only 8% of the stores completely dropped All4Sales. We just could not shut it down without losing billions dollars a day. One could call that a catastrophic migration.</p><p>Where could we go from there? We could choose to keep going with the same approach or to rethink the whole problem from the ground up, from an empty page. We started both of these solution and decided to see which one offers the greatest results after a few months.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/0*Kzz7s7Bv53FoQVWf.png" /></figure><p>We kept going with our change management and tried to create <a href="https://www.goodreads.com/book/show/22668729-hooked">Habit Forming Products</a>. We put a tremendous effort on adding socialization and gamification elements in our products. One could earn experience by using the set of applications on a daily basis, share his thoughts with other collaborators and fulfill diverse achievements.</p><p>It connected at first with our youngest users, but most of them disliked being addressed to as children in their workplace, according to anonymous surveys. One could call that a failed last stand from a stillborn project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WW_IyJ_0ciOWBzIQ.png" /></figure><p>In the meantime, another team was put together to try out a completely opposite approach : learn from the previous mistakes and put the collaborator in the center of the debate.</p><p>The team was made of a consulting evangAgilist, a product owner and three software engineers. They had carte-blanche to do whatever they needed to provide a well-received and promising solution. We expected them to deliver a small Proof of Concept, a little side project with a workflow we could follow for out next products. They blew this expectation away and may have changed the while mindset of Pentathlon’s IT department.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AjqKNuuJNMkg-Nb-.png" /></figure><p>The first action they took may seem quite simple : they put their offices next to an actual store.<br>They are the first IT team to localize themselves out of the department, and to go closer to their clients. This way, they were able to find allies in the store’s collaborators. A lot of informal discussions were made for the team to really understand their users.</p><p>When the time was there to start brainstorming , they invited a representative of the domain and two sellers. They all tried to pinpoint the actual domains behind the users’ work.</p><p>These workshops took a certain amount of time to get right, and they needed to iterate a lot on their discoveries, but it really makes the team understands their domains.</p><p>While continuing to iterate on the discovery work, they started implementing the more matured domain, the stock management.</p><p>Knowing every events occurring in this domain and every associated actors, they could relatively quickly provide an answer tailored to the users’ needs.</p><p>The first store to try this solution out was the one next to the team. They loved the product and the approach so much that the word swiftly spread out. Tutorials and formations was not needed since the user experience was so well mapped on their behaviors.</p><p>A few other stores already uses the new solution and it will be available to everyone in the very near future. One could call that a complete success!</p><p>We have already planned to follow the same schema for the other domains. There is still a lot of work to do, but we believe that this mindset is the right one to build the best solutions for our users. Solutions that are helping our collaborators, not constrain them.</p><p>I would like to thank you all for coming, do not hesitate if you have any questions or if you want to meet the team!</p><p><em>This article is a satire, it does not represent any actual individuals or companies. It was initially made to be presented in Agile and IT conferences.</em></p><p><em>The main goal is to initiate debates and you can do so in the comments section.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c2eac05b4f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test, build and Dockerize your Go app with no effort ! — Building a blogging application part 3]]></title>
            <link>https://thomasferro.medium.com/test-build-and-dockerize-your-go-app-with-no-effort-building-a-blogging-application-part-3-2f360fa2bc73?source=rss-4b4931861afc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f360fa2bc73</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[feedback-loop]]></category>
            <category><![CDATA[feedback]]></category>
            <dc:creator><![CDATA[Thomas Ferro]]></dc:creator>
            <pubDate>Sat, 20 Jul 2019 13:26:55 GMT</pubDate>
            <atom:updated>2019-07-20T13:26:55.273Z</atom:updated>
            <content:encoded><![CDATA[<h3>Test, build and Dockerize your Go app with no effort ! — Building a blogging application part 3</h3><blockquote><em>My take on the application of the Docker’s promises</em></blockquote><h3>Do we transvestite Docker ?</h3><p>As you may notice through the reading of my articles, I am no Docker expert.</p><p>On the other hand, the premises and the potential of containerization really speak to me. That is why I am willing to step out of my comfort zone to learn the principles and apply them as much as I can !</p><p>The thing that really bugs me about Docker is its usage that seems to be generally done.</p><p>I may be mistaking, but the really strength of Docker for me is in the ability to have the certainty to put in production the exact same environment that you developed on your machine.</p><p>However, all I see is people (including myself) developing software locally, pushing the code in any repository and only then building a Docker image based on the latest sources.</p><p>Docker seems to be relegated to an afterthought, as if we were building the image because of the containerization hype ?</p><p>Am I wrong when I picture the following development workflow ?</p><ol><li>Do the needed changes in your IDE / text editor;</li><li>Build a Docker image;</li><li>Run the container, check if the work is done;</li><li>Promote the image in any staging area for the domain experts to test it;</li><li>Promote the image in the production environment.</li></ol><p>Only then will we be sure that the image used in production is working just like the one on our machine.</p><p>With that in mind, let us talk a little bit about a very important matter when developing before diving into the main subject.</p><h3>On feedback loop</h3><p>This may be an opinion-based subject, but I do think that this is the most frustrating part when I first started using Docker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w1hZ9VU8KfEOprPn.jpg" /><figcaption>Scrum feedback loop</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lJNpzVFDKXl8Emfq.jpg" /><figcaption>Kanban feedback loop</figcaption></figure><p>You may be familiar with the concept of feedback loop if you are working in an Agile team. The point is to have the shortest loop possible in order to now right away if you are heading in the right direction. You want to have regular feedback from your clients, remember that they are the reasons you are making the software in the first place !</p><p>Now, in software development, you can see the feedback loop just as described above. The only change is in the actors.</p><p>The first actor is the compiler. Take a software that does not compile, do you really need to wait for the end user to tell you that it does not work ? No, you have the information right away in your IDE / terminal. The compilation is the shortest feedback loop when developing.</p><p>Things start to get more interesting with the second actor : the tests. I am not making any distinction between the different kinds of tests, they complete each other so you have to run them all locally. Trust me, you want your tests to run as fast and as frequently as possible.</p><p>The third actor is you, the developer, the (wo)man in the chair. After testing and building your app, you should be checking by hand your work. This is most likely to be the longest feedback loop of the three since you have to wait for the software to compile and run.</p><p>To summarize, here are the three actors of the development feedback loop :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5ok49qrvaWPUF6CX.jpg" /><figcaption>Development feedback loops</figcaption></figure><ol><li>The compiler (if you got one) : If the software does not compile, <em>it does not work</em>;</li><li>The tests (if you got some AND YOU SHOULD) : If the test suites does not pass, <em>it does not work</em>;</li><li>The human (if indeed you are human) : If it does not work, <em>it does not work</em>;</li></ol><p>When talking about this software development feedback loop, how long is too long ?</p><p>This is when things get even more opinionated. For me it is when I have the time to think of something else, when I lose focus. It is up to you to decide your own limit.</p><p>Going back to the subject, how is this all related to me building a Go development environment ?</p><p>When I first started to play with Go, I had this “all by hand” workflow :</p><ol><li>Change the code;</li><li>Run the tests;</li><li>Build;</li><li>Run;</li><li>When everything was ok, build a Docker image and run a container;</li></ol><p>Notice the similarities with the Docker usage described in the first part.</p><p>It may seem like a standard development workflow, but boy if it is a long one when entering every command by hand. Especially when you are a Go and a Docker neophyte like me !</p><p>Here is how I tried to reduce the loop, and greatly simplify my life while training my Go and Docker skills.</p><h3>Introduction go-dev-env !</h3><p>First thing first, we need to make sure that the initial needs are being addressed.</p><p>The main issue is to reduce the time of the development feedback loop by providing a solution that runs frequently and requires minimum effort from the developer.</p><p>This minimum effort could be just a button to press, but it will be even better if the process starts itself whenever a file has been modified.</p><p>The second issue is to build an artifact that the developer could use instantly and deploy in any environment.</p><p>Using the same terms as the ones that described the needs, here is a draft of a solution.</p><p>I need a development environment that runs a <em>workflow</em> (this workflow will eventually build a Docker image) every time I receive a notification from a <em>trigger</em> (for instance, a “file changed trigger”).</p><p>We can clearly see the two main parts of the project from this sentence :</p><ul><li>The workflow; and</li><li>The trigger.</li></ul><h3>The workflow</h3><p>A workflow is the description of everything that needs to happen for the artifact to be built.</p><pre>package workflows</pre><pre>import &quot;github.com/go-dev-env/triggers&quot;</pre><pre>// Workflow A workflow to be executed in the dev env<br>type Workflow interface {<br>	Execute()<br>	Init()<br>	Trigger() triggers.Trigger<br>}</pre><p>A workflow is composed of an Execute method that start the workflow and an Init method to initiate the process. We also have a reference to the workflow&#39;s trigger.</p><p>For now, I only need to manage workflow that are based on a builder (here, a Dockerfile). To do so, I only needed to create a BuildWorkflow, that calls the builder every time a notification is sent from the trigger.</p><p>The builder is also quite simple :</p><pre>package builders</pre><pre>// ArtifactPath The path to the built artifact<br>type ArtifactPath string</pre><pre>// Builder An artifact builder<br>type Builder interface {<br>	Build(contextPath string) (ArtifactPath, error)<br>}</pre><p>It builds an artifact and can also throw an error in the process. The last part is to create a DockerBuilder for our specific case.</p><p>This builder uses the standard library to create and execute a docker build command.</p><h3>The trigger</h3><p>Here is how I describe a Trigger :</p><pre>package triggers</pre><pre>/// Trigger A standard trigger<br>type Trigger interface {<br>	Init() chan bool<br>}</pre><p>We simply have to call the Init method to initiate the trigger, and what we get in return is a new channel through which we will be notified.</p><p>We need to know when to start the workflow. As I said earlier, we can achieve that with a simple button to press, ordering the workflow to run again.</p><p>However, I found it more interesting to have a trigger based on the modification in the source code.</p><p>This is one of the few places where I have allowed myself to rely on an external library : <a href="https://github.com/fsnotify/fsnotify">fsnotify, a file system notifications library.</a>.</p><p>With a little bit of setup, I was able to wrap this tool under the FileWatcherTrigger. I can now simply create a new trigger using the exposed method :</p><pre>// NewFileWatcherTrigger Create a new file watcher trigger<br>func NewFileWatcherTrigger(path string) *FileWatcherTrigger {<br>	log.Println(&quot;Creating a new file watcher trigger&quot;)</pre><pre>	return &amp;FileWatcherTrigger{<br>		path: path,<br>	}<br>}</pre><p>Few noticeable details :</p><ul><li>This trigger uses a homemade debouncer to avoid duplicate notifications (<a href="https://medium.com/@t.ferro184/tdd-in-action-debouncer-in-go-b0f7d7d75931">here is an article describing the making of this debouncer</a>);</li><li>It only notifies if a file or a folder is created, modified or deleted;</li><li>It will watch everything inside the provided path, including files inside a newly created folder.</li></ul><p>Putting it all together, as done in the main.go file, we can now create our workflow :</p><pre>package main</pre><pre>import (<br>	&quot;os&quot;</pre><pre>	&quot;github.com/go-dev-env/triggers&quot;<br>	&quot;github.com/go-dev-env/workflows&quot;<br>	&quot;github.com/go-dev-env/builders/docker&quot;<br>)</pre><pre>func getPath() string {<br>	path := os.Getenv(&quot;SRC_PATH&quot;)<br>	if path == &quot;&quot; {<br>		path = &quot;/src&quot;<br>	}<br>	return path<br>}</pre><pre>func main() {<br>	path := getPath()<br>	<br>	trigger := triggers.NewFileWatcherTrigger(path)<br>	builder := docker.NewBuilder()</pre><pre>	workflow := workflows.NewBuildWorkflow(path, trigger, builder)<br>	workflow.Init()</pre><pre>	for {}<br>}</pre><p>How does it all look from the developer perspective ?</p><h3>Story time</h3><p>Let us say I am a developer working on a blogging application in Go (which turns out to be true).</p><p>The first thing I will need to do in order to use the development environment is to describe my workflow. Lucky for us, it is a pretty straightforward one :</p><ol><li>Run the test suites;</li><li>Build the application;</li><li>Run it.</li></ol><p>This workflow can be translated as this multistep Dockerfile :</p><pre># Run the tests with a Go specific version<br>FROM golang:1.12.6 as tests</pre><pre>WORKDIR /src</pre><pre>ADD . .</pre><pre>RUN go test ./...<br></pre><pre># Build the artifact for the same Go version<br>FROM golang:1.12.6 as builder</pre><pre>WORKDIR /src</pre><pre>ADD . .</pre><pre>RUN CGO_ENABLED=0 GOOS=linux go build -o /dist/go-app</pre><pre># Run the software from an empty Docker image<br>FROM scratch</pre><pre>WORKDIR /root</pre><pre>COPY --from=builder /dist .</pre><pre>CMD [ &quot;./go-app&quot; ]</pre><p>Setup time is over, I can now run the go-dev-env and start to work on the actual blogging application ! Every time I change something in my code base, the workflow will run and I will be noticed about every issue in the test suites or the compilation.</p><p>The last thing I need to do is to run the Docker container based on the image generated by the development environment 😃.</p><h3>Next steps</h3><p>Obviously, this environment only provide a solution for my current needs.</p><p>In order to go full circle, it would be nice if the development environment was himself inside a Docker container. I have tried to tackle this feature, but I was not able to build a Docker image inside a Docker container.</p><p>The other and more important feature to be added is the possibility to make it work on bigger project, with more than one code bases. I will certainly work on this when building an application with many microservices.</p><p>Do not hesitate to give me your opinion on the project, and even submit or work on an issue, it is <a href="https://github.com/ThomasFerro/go-dev-env">hosted on GitHub and is open source</a> !</p><h3>In the next episode…</h3><p>This article was part of my “Building a blogging application” series, where I describe the steps that seem important to me while working on this project.</p><p>It was really fun to learn all those new things while making a development environment that tackles my actual issues. I do encourage you to build things really useful when learning a new language or a new technology. It feels way more rewarding than building a todo app for instance, and you are way less likely to give up if you need that piece of software.</p><p>Stay tuned for more articles, the next ones are going to be focused on the implementation of the first features !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f360fa2bc73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD in action : Debouncer in Go]]></title>
            <link>https://thomasferro.medium.com/tdd-in-action-debouncer-in-go-b0f7d7d75931?source=rss-4b4931861afc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0f7d7d75931</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Thomas Ferro]]></dc:creator>
            <pubDate>Fri, 14 Jun 2019 20:11:00 GMT</pubDate>
            <atom:updated>2019-06-14T20:11:00.505Z</atom:updated>
            <content:encoded><![CDATA[<h3>TDD in action : Debouncer in Go</h3><blockquote><em>Applying TDD principles to the making of a helper in Go</em></blockquote><h3>Introduction</h3><p>I may be new to the Golang world, but here is something I am already familiar with: Building things in Go feels great !</p><p>What feels event better is to build those things with the absolute certainty that it works the way it was meant to be.</p><p>I am leaving the preaching and teaching parts to <em>Kent Beck</em> and consort. I can, however, tell you that the <em>Test Driven Development</em> (or <em>TDD</em>) principles are perfect to give you that certainty.</p><p>Following the TDD principles in Go does not require any particular setup. No dependency or IDE plugin to install and configure. You just grab your favorite text editor, a terminal plus a notebook and a pen if it suits you better !</p><h3>Writing tests in Go</h3><p>Follow those few steps to start writing tests in Go :</p><ol><li>In the same folder as the file under test, write a new file following this pattern : yourFile_test.go;</li><li>In this test file, create a new function with the specific name and signature : func TestXxx(*testing.T)</li><li>Manage your test the way you need to, using the API provided by the testing.T object;</li><li>Run the go test command</li><li>Analyse the result to see if the tests succeed</li></ol><p>The standard API does not provide any fancy testing feature, but all we need for writing basic tests is there <em>out of the box</em>.</p><h3>The context</h3><p>I am currently building a development environment in Go. This dev env will be capable of running all of the tests and building and executing the program under development.</p><p>To do so, I need a files watcher, notifying the dev env each time a file is created, modified or deleted.</p><p>The main issue I ran into is that the event triggered by the files watcher may be emitted too many times at once.</p><p>Nothing too fancy here, all I need is a rather common feature called debouncing.</p><p>I am sure that a lot of libraries may tackle this issue in Go. However, I found it to be a great challenge for the beginner that I am with this language.</p><p>So, let’s write this in tiny little tested steps, making <em>Kent Beck</em> and the Clean Code community pride in the process !</p><h3>How does a debouncer look like ?</h3><p>I am willing to create a debouncer in its most common API.</p><p>This means providing a debouncer as a helper function which takes a function as his first parameter and a timer as the second one. The timer represents how long should the program wait after the last call before executing the method.</p><p>The user will wrap his treatment in a debounced method, and call the wrapped function :</p><pre>// Wrapping the debounced treatment<br>myDebouncedFunction := debounce(func() {<br>    // The treatment...<br>}, 500)</pre><pre>// Example 1 - Simple call<br>myDebouncedFunction() // The method will be called in 500ms</pre><pre>// Example 2 - Multiple calls<br>myDebouncedFunction() // Method&#39;s execution cancelled by the next call to myDebouncedFunction<br>time.Sleep(100 * time.Millisecond)<br>myDebouncedFunction() // Method&#39;s execution cancelled by the next call to myDebouncedFunction<br>time.Sleep(100 * time.Millisecond)<br>myDebouncedFunction() // The method will only be called once in 500ms</pre><h3>TDD</h3><p>As I said earlier, I am not going into much details about what is TDD and why it is great. If you have not already, please read “Test Driven Development: By Example” by Kent Beck and try to apply the principles described there if they suits you.</p><p>Here is my take on the subject, if you are not familiar with it :</p><p>In order to build a product that really fits the needs that it addresses, the <em>TDD</em> proposes to first write the tests that the program should be able to pass.</p><p>To do so, we need to reduce the feedback loop to the bare minimum by following those three steps :</p><ol><li>Write a test with a dreamed API, the way you think the program should work. This test should not go green yet;</li><li>Write the simpliest, dumbest implementation to make the test succeed. This way, you will know if the following modifications break the promise;</li><li>Refactor the code (and the test if needed) in order to really solve the problem raised by the test. You have restrain yourself to the scope of the test, do not refactor or optimise the code to solve future features just now.</li></ol><p>Then you repeat the process with the next test, until all of the use cases are tackled and all of the features implemented</p><p>Let’s jump into it, one test at the time !</p><h3>Calling the provided method after the timer has ended</h3><p>The first thing I want to check is very basic, <em>is the provided method called ?</em></p><p>Using only the standard API, and following the guideline introduced in the “<em>How does a debouncer look like ?</em>” chapter, one could implement this test like this :</p><pre>func TestShouldCallTheFunctionAfterTheProvidedTime(t *testing.T) {<br>    called := false<br>    debouncedMethod := Debounce(func() {<br>        called = true<br>    }, 1)</pre><pre>    debouncedMethod()</pre><pre>    time.Sleep(10 * time.Millisecond)</pre><pre>    if called == false {<br>        t.Error(&quot;The method was not called&quot;)<br>    }<br>}</pre><p>The test wraps a method in a very short debouncer, then it waits for the debounce to happen. The last step is to check if the method was called, throwing an error if it does.</p><p>Now that we have a test in place, we can try to make it pass with the most obvious implementation.</p><p>We can just return a function that calls the provided method, without taking care of the timer :</p><pre>func Debounce(function func(), executeAfter int) func() {<br>    return func() {<br>        function()<br>    }<br>}</pre><p>The test is green, we could now focus on refactoring. However, we will wait for the next test to be written before doing any refactoring, you will understand why shortly.</p><h3>Calling the method only after the timer</h3><p>Next, we need to check that the method was only called after the provided duration.</p><p>The test will look very similar to the last one, but we will check the opposite assertion and wait less than the timer :</p><pre>func TestShouldNotCallTheFunctionBeforeTheProvidedTime(t *testing.T) {<br>    called := false<br>    debouncedMethod := Debounce(func() {<br>        called = true<br>    }, 10)</pre><pre>    debouncedMethod()</pre><pre>    time.Sleep(1 * time.Millisecond)</pre><pre>    if called == true {<br>        t.Error(&quot;The method was called too early&quot;)<br>    }<br>}</pre><p>If you run it immediately, this test will not pass. The simplest way of changing that is to wait for the provided time before executing the function :</p><pre>func Debounce(function func(), executeAfter int) func() {<br>    return func() {<br>        go (func() {<br>            time.Sleep(time.Duration(executeAfter) * time.Millisecond)<br>            function()<br>        })()<br>    }<br>}</pre><p>We need to wrap the method in a goroutine in order for the program to continue its execution, and not wait for the time.Sleep method to finish. Remember, the point here is to make the tests pass, and both did !</p><p>Now, we clearly have a design issue, even a standard API misusage. Time for a little refactoring !</p><p>We can change the behavior, while launching the tests at every step to assure everything still runs smoothly.</p><p>We have used the time.Sleep where the <a href="https://golang.org/pkg/time/#NewTimer">NewTimer method of the same package</a> seems more appropriate.</p><p>First, we need to create a new timer based on the parameters and immediatly stop it :</p><pre>func Debounce(function func(), executeAfter int) func() {<br>    duration := time.Duration(executeAfter) * time.Millisecond<br>    t := time.NewTimer(duration)<br>    t.Stop()<br>    // [...]</pre><p>A goroutine can be started next with an infinite loop, watching for the timer to be finished and calling the debounced method :</p><pre>// [...]<br>    go (func() {<br>        for {<br>            select {<br>            case &lt;-t.C:<br>                log.Println(&quot;Executing the debounced method&quot;)<br>                go function()<br>            }<br>        }<br>    })()<br>    // [...]</pre><p>Then we can return a function that restarts the timer :</p><pre>return func() {<br>        log.Println(&quot;Reset the debouncer timer&quot;)<br>        t.Reset(duration)<br>    }</pre><p>This implementation lets the tests green, we can now move to the next tests with a little surprise…</p><h3>The last tests</h3><p>Finally, the goal of the debouncer is to ensure that the method is only executed once if called multiple times.</p><p>We can check that by creating a new test that keeps track of the execution count. If this number is not one, the test fails :</p><pre>func TestShouldCallTheFunctionOnlyOnceAfterTheProvidedTime(t *testing.T) {<br>    executionCount := 0<br>    debouncedMethod := Debounce(func() {<br>        executionCount++<br>    }, 1)</pre><pre>    debouncedMethod()<br>    debouncedMethod()<br>    debouncedMethod()<br>    debouncedMethod()</pre><pre>    time.Sleep(5 * time.Millisecond)</pre><pre>    if executionCount != 1 {<br>        t.Errorf(&quot;The method was not called only once, called %v time(s)&quot;, executionCount)<br>    }<br>}</pre><p>The good news is… our implementation already validates this rule ! No refactoring seems to be needed, we are just making our API more robust with the previous test and the following.</p><p>We also need to check that the method is executed multiple times if enough time was spent between the calls.</p><p>We just need to tweak the previous test a little :</p><pre>func TestShouldBeAbleToCallTheFunctionAgainAfterTheTimer(t *testing.T) {<br>    executionCount := 0<br>    debouncedMethod := Debounce(func() {<br>        executionCount++<br>    }, 5)</pre><pre>    debouncedMethod()</pre><pre>    time.Sleep(10 * time.Millisecond)</pre><pre>    debouncedMethod()</pre><pre>    time.Sleep(10 * time.Millisecond)</pre><pre>    if executionCount != 2 {<br>        t.Errorf(&quot;The method was not called twice, called %v time(s)&quot;, executionCount)<br>    }<br>}</pre><h3>Conclusion</h3><p>I cannot think of any other use case for this basic debouncer, and the API feels fine to me.</p><p>The complete implementation looks like this :</p><pre>func Debounce(function func(), executeAfter int) func() {<br>    duration := time.Duration(executeAfter) * time.Millisecond<br>    t := time.NewTimer(duration)<br>    t.Stop()</pre><pre>    go (func() {<br>        for {<br>            select {<br>            case &lt;-t.C:<br>                log.Println(&quot;Executing the debounced method&quot;)<br>                go function()<br>            }<br>        }<br>    })()</pre><pre>    return func() {<br>        log.Println(&quot;Reset the debouncer timer&quot;)<br>        t.Reset(duration)<br>    }<br>}</pre><p>This may not be the best debouncer out there, nor that it is the best scenario of a <em>test driven development</em>.</p><p>Yet I think it illustrates how natural it is to write tests and little helpers in Go.</p><p>I started writing the debouncer with no tests, leading to a wanky unpredictable API, that I had to test manually with a real world example to validate.</p><p>Starting over and driving the develoment by the tests helped me writing a way simpler helper that I could rely on !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0f7d7d75931" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Am I really unprofessional ?]]></title>
            <link>https://thomasferro.medium.com/am-i-really-unprofessional-c36272c73f07?source=rss-4b4931861afc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c36272c73f07</guid>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[professionalism]]></category>
            <dc:creator><![CDATA[Thomas Ferro]]></dc:creator>
            <pubDate>Wed, 22 May 2019 08:01:33 GMT</pubDate>
            <atom:updated>2019-05-22T08:01:33.164Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Am I really unprofessional ?</strong></h3><blockquote><em>A story about ego, pride and communication in the IT world.</em></blockquote><h3>What happened</h3><p>A few months ago, somebody said that I was unprofessional and, I admit, I was pretty mad about it.</p><p>But do not worry, this is not an article about proving him wrong, even if it was my first thought back then.</p><p>First, in order to fully understand the story, a little bit of context is needed.</p><h3>The context</h3><p>I am a software developer, currently working in a big retail company on behalf of my employer, a small IT services business.</p><p>The mission started out six months ago, with a team of four developers, a product owner, a devops and our customers support staff.</p><p>The latest is composed of a member whose time is split between two applications. She is backed by the rest of the support team, but we almost exclusively reach out to her.</p><p>We are lucky enough to be truly Agile, thanks to our PO’s experience and expertise.</p><p>Kanban is the framework we use, which means continuous flow of issues and deliveries, no sprint and — thanks to the old and new gods — <em>no estimate</em>.</p><p>This last part is very important for me, who has always struggled with the very principle of estimates.</p><p>One last detail, we are a team of relatively young and open-minded people, and the atmosphere can easily be described as light.</p><h3>The cursed word</h3><p>We were in the last stages of the opening of a new store in a new country when it all started.</p><p>A leader of the customers support team, who was in the store to be open, spotted a bug that could potentially delay a step of the operation.</p><p>The team was asked for prioritizing the issue’s resolution, and we did put it on top of our list.</p><p>I took the issue and started working on it. After talking with our customers support member, we found a workaround, using old tools that could prevent the opening to be delayed. As you may imagine, I was very happy with this idea. Not having to work under a whole amount a pressure and being able to deliver a solid solution and not some dirty hot fix is always nice.</p><p>After a few hours of hard-working, an update was asked to know when the fix will be deployed.</p><p>As it was a casual request, I replied with our usual catchphrase: “<em>When it’s done, no estimate!</em>”. Oh boy did I was wrong to say that this way.</p><p>The next thing I remember, I received a direct message from the customers support leader saying that I am not thinking about the greater good for the company. That I should be able to give an estimation. That I act <em>unprofessional</em>.</p><p>…what was that? Is it now unprofessional to only deliver the best possible piece of software? I was outrage! I do think about the greater good when I don’t write a quick and dirty duct taped fix! How could someone dare to say that about my work! About me!</p><p>Well, things have calmed down since then and it turns out that he might not have been that wrong..</p><h3>What is professionalism?</h3><p>I could have just moved on and forget about that whole situation, but here comes Uncle Bob and his book “The Clean Coder : A Code of Conduct for Professional Programmers”.</p><p>I have bought this book a few weeks ago and started to read it just now. As I was eating the first chapters, some memories started to emerge.. The very same memories that I discussed above.</p><p>So, what is Robert C. Martin’s take on professionalism ? Turns out it is not what I was thinking. It is not just about delivering the best product no matter how, nor that it is about sticking to the processes at all costs.</p><p>I am not about to paraphrase the points made by Uncle Bob in his book, and I urge you to read it if you have not already.</p><p>The most important aspect of professionalism is about communication. There are several chapters where the author talks about what it means to say yes or no in a professional context, and the implications of such decisions.</p><p>For instance, a professional <em>must</em> say no when asked to do impossible things. That is a concept that I already apply when the occasion comes.</p><p>So, one could say that I am acting professionally? Well, not really..</p><p>The point is not about saying no to every impossible deadlines, it is about searching for a compromise.</p><p>You cannot finish this task before the end of the week? Fine, but we really need some critical parts of it to work by then. Maybe it can be done by reducing the scope? Canceling some meetings? Changing the priority of some other tasks?</p><p>Anyway, it is our duty to act in order to find the right comprise that suits everyone, and to make sure that the job is properly done.</p><p>Of course, the book is not just about saying no — though it would be a fun 200 pages piece of literature. This is just one part of the requirements in order to call yourself a professional.</p><h3>Back to the story</h3><p>But what does any of those concepts have to do with the story?</p><p>Can we say that a lot of parties in the story act unprofessional? I think so. At least I did.</p><p>Instead of searching for the best solution — and there was an easy one already in place — I stayed in my position and kept on coding.</p><p>It seems to be the most professional outcome at the time for me, providing the cleanest solution. But in these cases you have to take a step back, share your point of view and listen the other’s in order to do the most appropriate action.</p><h3>Conclusion</h3><p>It is crucial to stick to your moral values and not to let the pressures and deadlines pollute your work. But in the other hand, we should all have the same goal — to create business value. It is essential that we work together, as professionals, toward it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c36272c73f07" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>