<?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 Pierre G. on Medium]]></title>
        <description><![CDATA[Stories by Pierre G. on Medium]]></description>
        <link>https://medium.com/@pja-g?source=rss-416eed7e9a66------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ikefrlGiCnXJjNHVLxe-yA.jpeg</url>
            <title>Stories by Pierre G. on Medium</title>
            <link>https://medium.com/@pja-g?source=rss-416eed7e9a66------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:51:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pja-g/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[Let’s Be Serious About Node Dependency Injection.]]></title>
            <link>https://pja-g.medium.com/lets-be-serious-about-node-dependency-injection-73bcf9ac394c?source=rss-416eed7e9a66------2</link>
            <guid isPermaLink="false">https://medium.com/p/73bcf9ac394c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Pierre G.]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 15:29:38 GMT</pubDate>
            <atom:updated>2025-02-19T15:29:38.209Z</atom:updated>
            <content:encoded><![CDATA[<h4>Once you’ve tasted this approach, your Node apps will never look the same again.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cZzrjr_qi8a0HAjl" /><figcaption>Photo by <a href="https://unsplash.com/@nm_runners?utm_source=medium&amp;utm_medium=referral">Natalie Runnerstrom</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hey, you! Yes, I’m talking to you… You look like a JavaScript developer, don’t you? Passionate and motivated — you even take the time to read Medium articles about Node. Congratulations, that’s a good start toward coding a better world.</p><p>I have (again) an indiscreet question: what do your dependency injections look like in your Node apps? Have you ever taken the time to think about this topic?</p><p>Are you the kind of dev who simply relies on ECMAScript modules to import and export functions and underlying logic across the whole application? Randomly passing data through the seven (or more 😔) parameters of never-ending chained functions? Passing the same information through six layers of abstraction by drilling function parameters? Ending up with an inconsistent mix of functional and <em>whatever-unknown</em> pattern architecture — very classic in JavaScript?<br>If yes, be reassured: you’re not alone. However, it doesn’t mean that it shouldn’t change…<br>You don’t have excuse anymore: thanks to Typescript, you can develop beautiful Object-Oriented apps that can rely on proper dependency injections. Once you’ve tasted this, impossible to go back to your spaghettis: I can warranty. Unless they look like those.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nc2lXtXhT5xYkOw_" /><figcaption>Photo by <a href="https://unsplash.com/@sociravegna?utm_source=medium&amp;utm_medium=referral">Sofia Ciravegna</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>What will it bring?</p><ul><li>You will be able to rely on the robustness of <strong>Object-Oriented</strong> <strong>Programming</strong>, benefiting from <strong>encapsulation</strong>, <strong>abstraction</strong>, <strong>polymorphism</strong>, and <strong>inheritance</strong>.</li><li>You will be able to apply <strong>SOLID principles</strong>, significantly improving <strong>extensibility</strong>, <strong>testability</strong>, <strong>readability</strong>, and <strong>reliability</strong>.</li><li>You will control <strong>asynchronous operations</strong> at app <strong>startup</strong>.</li></ul><p>Let’s explore one approach to implementing a proper OOP architecture with Node. No need to reinvent the wheel — so let’s take a classic approach (if you’re familiar with Java, you won’t be thrown off).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*Ij920uujgLaT6ymEyTO2zg.png" /></figure><p>The approach relies on the following concepts:</p><h4>The Controller-Service-Repository Pattern</h4><p>Three layers for three concerns:</p><ul><li><strong>Controllers</strong>: Manage <strong>I/O</strong> and ensure the link between the app <strong>framework</strong> (REST, Kafka) and its business logic.</li><li><strong>Services</strong>: Contain the<strong> business logic</strong> of the app, i.e., business <strong>rules</strong> and <strong>policies</strong>.</li><li><strong>Repositories and clients</strong>: Integrate <strong>external dependencies</strong> like third-party APIs.</li></ul><p>You can learn more about it 👉 <a href="https://levelup.gitconnected.com/your-express-app-isnt-great-here-s-why-84003bbce092">here</a>.</p><h4>The Singleton Pattern</h4><p>Repositories, services, and controllers are <strong>classes</strong> that should be <strong>instantiated once</strong>. The instantiations are done in a function named getControllers(), responsible for returning <strong>all controllers</strong> of the application.</p><p>Repositories and clients are instantiated first, then <strong>injected</strong> into services, which are finally injected into controllers — like <strong>nested dolls</strong>.</p><p>This approach allows you to keep full control over the creation of resources in your app. You can easily manage the synchronous and asynchronous steps required to create controllers.</p><h4>One Controller = One Route</h4><p><strong>Controllers</strong> are then <strong>mapped</strong> to<strong> API routes</strong> through a router. Each controller handles a single route request.</p><p>Ok, let’s see in practice what a service looks like with this approach.</p><p>We want to enable a new endpoint responsible for returning formatted information about a given customer. The data is fetched from different sources:</p><ul><li>The <strong>database</strong> of the backend application, which owns customer data.</li><li>A <strong>third-party products API</strong>.</li><li>A <strong>third-party API</strong> that provides <strong>merchandising</strong> data.</li></ul><p>Below are the different classes required to enable the GET /customer/:id/info endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*mzXwztCRqCYUi3JX0T9tbA.png" /></figure><p>We can implement</p><pre>import { Customer, CustomerRegistry } from &#39;./registries/CustomerRegistry&#39;<br>import { ProductCatalogClient } from &#39;./clients/ProductCatalogClient&#39;<br>import { Logger } from &#39;./Logger&#39;<br>import { MerchandisingProfile } from &#39;./types&#39;<br>import { MerchandisingClient } from &#39;./clients/MerchandisingClient&#39;<br><br>export class CustomerInfo {<br>  readonly customerRegistry: CustomerRegistry<br>  readonly productsClient: ProductCatalogClient<br>  readonly merchandisingClient: MerchandisingClient<br>  readonly formatter: InfoFormatter<br>  readonly logger: Logger<br><br>  constructor(<br>    customerRegistry: CustomerRegistry,<br>    productsClient: ProductCatalogClient,<br>    merchandisingClient: MerchandisingClient,<br>    formatter: InfoFormatter,<br>    logger: Logger,<br>  ) {<br>    this.customerRegistry = customerRegistry<br>    this.productsClient = productsClient<br>    this.merchandisingClient = merchandisingClient<br>    this.formatter = formatter<br>    this.logger = logger<br>  }<br><br>  public async getCustomerInfo(id: string): Promise&lt;string&gt; {<br>    const customer = await this.customerRegistry.getCustomerById(id)<br>    const { email } = customer<br><br>    const products = await this.productsClient.getCustomerProducts(email)<br>    const profile = await this.getMerchandisingProfile(customer)<br><br>    return this.formatter.formatCustomerInfo(customer, products, profile)<br>  }<br><br>  private async getMerchandisingProfile({<br>    id,<br>    email,<br>    fullname,<br>  }: Customer): Promise&lt;MerchandisingProfile | undefined&gt; {<br>    try {<br>      return await this.merchandisingClient.getUserProfile(fullname, email)<br>    } catch (e) {<br>      this.logger.warn(<br>        `could not get merchandising profile of user with ID = ${id}`<br>      )<br>    }<br>  }<br>}</pre><p>Wahoo, this looks so clean 🤩! What’s your secret?</p><ul><li><strong>Types</strong> are the only entities imported through modules.</li><li>Class <strong>dependencies</strong> are passed through <strong>constructor parameters</strong> and then bound to <strong>class members</strong>, making them <strong>directly accessible</strong> at runtime inside all methods.</li><li>Method <strong>signatures</strong> stay <strong>clean</strong> since dependencies don’t need to be passed as parameters. <strong>Parameters</strong> are reserved for <strong>context specific</strong> to a given request (e.g., the consumer ID in our example).</li></ul><p>And here we are! Another way to impress your colleagues and make them fall in love with your code.<br>Inconsistent dependency injection through function parameters will be a thing of the past.<br>I hope you’ve enjoyed this article. Feel free to share your constructive feedback so we can discuss this topic further.</p><p>And don’t forget: keep your code clean 🧹.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73bcf9ac394c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Express App Isn’t Great — Here’s Why.]]></title>
            <link>https://levelup.gitconnected.com/your-express-app-isnt-great-here-s-why-84003bbce092?source=rss-416eed7e9a66------2</link>
            <guid isPermaLink="false">https://medium.com/p/84003bbce092</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pierre G.]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 14:00:40 GMT</pubDate>
            <atom:updated>2025-02-10T14:00:40.878Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your Express App Isn’t Great — Here’s Why.</h3><h4>Some Tips to Help You Become a Star in Express.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDgVf8sUp7X2ZRDJFEcpYw.png" /></figure><p>The famous Node framework was released in November 2010 to simplify the handling of HTTP servers and REST endpoints.<br>Based on middleware, it allows the development of <strong>asynchronous</strong>, <strong>high-performance</strong> web servers. However, in practice, Express apps often face issues similar to those common in the JS community: existing tools are highly flexible but <strong>lack</strong> <strong>shared guidelines</strong> for proper use.</p><p>Let’s start with an embarrassing question (I have the unfortunate habit of being curious…): do your Express handlers look like this 👇?</p><pre>const yourExpressHandler = (req: Request, res: Response) =&gt; {<br>  if(/* some checks about REST parameters */) {<br>    if(/* some checks on the authorization token */) {<br>      let someBusinessData = null<br>      try {  <br>        // Call the database client to get some data.<br>        // ...<br>        someBusinessData = ...<br>      } catch (err) {<br>        log.error(&#39;cannot fetch data from database&#39;, err)<br>        res.status(500).send(&#39;cannot fetch data from database&#39;)<br>      } <br>      // Some business logic to check whether we can perform the action further.<br>      // ...<br>      try {<br>        // Some mapping and transformation based on parameters.<br>        // Check if the data input is correct.<br>        // What line are we at? l.79<br>        // ...<br>      } catch (err) {<br>        log.error(&#39;cannot do some stuff&#39;, err)<br>        res.status(500).send(&#39;cannot do some stuff&#39;)   <br>      }<br>      <br>      // It starts being complex for your beloved and patient colleagues...<br>      try {  <br>        // Call an external API.<br>        // Handle the data.<br>        // Transform the data for your business case.<br>        // ...         <br>      } catch (err) {<br>        log.error(&#39;cannot fetch data from external dependency&#39;, err)<br>        res.status(500).send(&#39;cannot fetch data from external dependency&#39;)<br>      }<br>      try {<br>        // Store data in database.<br>        // l.189<br>        // ...  <br>      } catch (err) {<br>        log.error(&#39;cannot store data in database&#39;, err)<br>        res.status(500).send(&#39;cannot store data in database&#39;)   <br>      } <br>    } else {<br>      // What was this else for? Ah right... the authorization checks.<br>      res.status(403).send(&#39;user is not allowed&#39;)<br>    }<br>  } else {<br>    res.status(400).send(&#39;wrong parameters&#39;)<br>  }<br>  // l.257 :( <br>}</pre><p>If yes, let’s outline the <strong>structure</strong> of your handler and the different responsibilities it handles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*p29h8JCgp1Bh2Ws0swh-9w.png" /><figcaption>Your handler stacks different responsibilities making it simply unreadable and untestable.</figcaption></figure><p>As you can see, your handler deals with <strong>various tasks</strong>, increasing its <strong>cognitive complexity</strong> and making it <strong>difficult to test</strong>.<br>We can significantly improve this by introducing a three-layer pattern called the <strong>Controller-Service-Repository</strong>:</p><ul><li><strong>Controllers</strong> are responsible for handling the application’s <strong>I/O</strong> — in a nutshell, ensuring the connection between the application framework (i.e., the REST server) and the business logic.</li><li><strong>Services</strong> contain the <strong>business logic</strong>, i.e., the <strong>rules</strong> and <strong>policies</strong> that transform data.</li><li><strong>Repositories</strong> <strong>abstract data</strong> fetched from <strong>external sources</strong> like databases or third-party APIs, ensuring it is directly usable by the business logic layer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*38OdTnHNP3JThLhazXJLpA.png" /></figure><p>Let’s go through the components from the left to the right.</p><h4>The Controller Layer</h4><ul><li>The handler calls a <strong>sanitizer</strong> that removes data potentially <strong>harmful</strong>, e.g., special characters that could allow code injection.</li><li><strong>Validators</strong> ensure that inputs like query parameters or request bodies comply with the <strong>API’s expectations</strong>.</li><li>The <strong>authorization</strong> module contains the rules that determine whether a given <strong>user </strong>(or service) is <strong>allowed</strong> to <strong>access</strong> the endpoint.</li><li>The <strong>error middleware</strong> is the <strong>top-level fallback</strong> where errors thrown across the application end up. Thrown errors should be instances of classes defined within the app, containing information to handle them properly, e.g., the <strong>client message</strong>, the <strong>log message</strong>, and the <strong>REST status</strong> to respond with.</li><li>The <strong>handler</strong> acts as a <strong>controller</strong> responsible for managing <strong>inputs and outputs</strong> to interface with the external world. It <strong>orchestrates data flows</strong> and <strong>logs</strong> valuable information to ease debugging.</li></ul><h4>The Service Layer</h4><ul><li><strong>Services transform, map, sort, organise, calculate and filter data</strong> to generate new data sets based on <strong>business rules</strong> and <strong>policies</strong>.</li></ul><h4>The Repository Layer</h4><ul><li><strong>Repositories interface</strong> with the application <strong>database</strong>. They <strong>abstract data models</strong> so that services don’t depend on concrete implementations (like the database system). You should be able to switch database tools without modifying the services’ logic.</li><li><strong>Clients</strong> play a similar role to repositories, as they <strong>interface</strong> with <strong>external API</strong>.</li></ul><p><em>Note: Avoid branching and prefer polymorphism to handle different use cases. Minimizing the number of if- and switch-statements will greatly improve the quality of your deliverables, making them easier to extend, test, and read.</em></p><p>Here we are. These few tips should make your Express app much better, and I’m sure your colleagues will thank you for it 🙏. <br>If you’re interested in learning how to improve your Express apps further by introducing OOP patterns and proper Dependency Injection, let me know in the comments section.<br>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84003bbce092" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/your-express-app-isnt-great-here-s-why-84003bbce092">Your Express App Isn’t Great — Here’s Why.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your React App Isn’t Great — Fix It With Controllers.]]></title>
            <link>https://levelup.gitconnected.com/your-react-app-isnt-great-fix-it-with-controllers-ffa3db89cbb0?source=rss-416eed7e9a66------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffa3db89cbb0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Pierre G.]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 20:28:25 GMT</pubDate>
            <atom:updated>2025-01-20T19:41:20.555Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your React App Isn’t Great — Fix It With Controllers.</h3><h4>Leverage the Power of Controllers and Make Your React Apps Invincible.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0IrIB1fvTEYNyt92" /><figcaption>Photo by <a href="https://unsplash.com/@demure_storyteller?utm_source=medium&amp;utm_medium=referral">Demure Storyteller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As your colleagues struggled with debugging overly coupled code, I shared some tips to help you create React apps they’ll love (<a href="https://levelup.gitconnected.com/your-react-app-isnt-great-here-s-why-5eb61b3f110b">read this through</a> if you haven’t yet). I hope you’re not too overwhelmed with congratulations and romantic messages — great code, after all, can evoke strong emotions.</p><h4>Technical Discovery</h4><p>Let’s explore <strong>controllers</strong> a bit further through a <strong>classic example</strong> of a frontend application — you guessed it: the <strong>To-Do List </strong>📝. Keep it simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*5eUQCnT1QgzY1bQuECN2zQ.png" /><figcaption>My Todo is a stateful application that stores items through a REST API.</figcaption></figure><p>So far, nothing extraordinary. How about we <strong>break down </strong>the <strong>UI</strong> into view components?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*mkbNNLLC3UbltkMMr9h-Ww.png" /><figcaption>Simple UI breakdown.</figcaption></figure><p>Here we are. Now that we have a clear breakdown of the UI, we need to define <strong>controllers</strong> and their <strong>responsibilities</strong> — basically, what <strong>interfaces</strong> will be exposed to the <strong>view components</strong> (and other controllers).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*p_LscfLvPkhbLP0ompIVFQ.png" /><figcaption>Controllers and their dependencies.</figcaption></figure><ul><li><strong>ErrorController [stateful]</strong>: Handles the error state — a simple string visible by end users. Most controllers depend on it.</li><li><strong>CreateItem [stateful]</strong>: Handles <strong>changes</strong> made by <strong>end users</strong> through the <strong>form</strong>. It also makes <strong>API calls </strong>to create a new item—that&#39;s why it depends on the API client.</li><li><strong>ListItems [stateful]</strong>: <strong>Fetches</strong> the <strong>items</strong> of the current user and stores them in a React state. It exposes a refresh() function that the CreateItem controller uses to update items after a successful creation.</li><li><strong>DeleteItem</strong> <strong>[stateless]</strong>: Handles clicks on <em>delete</em> buttons.</li></ul><p>On top of these controllers:</p><ul><li>A simple <strong>sanitizer</strong> that allows for removing<strong> extra characters</strong>, like spaces at the start and end of input strings. To ease <strong>unit testing</strong>, it is <strong>isolated</strong> in a dedicated module.</li><li>An <strong>API client</strong> exposing asynchronous functions to <strong>create</strong>, <strong>read</strong>, and <strong>delete</strong> To-Do items.</li></ul><p><em>Note: If you plan to create a real Todo for real users (and aim for lofty ambitions with it), you should also add a loader. To keep the example concise, I’ve skipped it, but the principle remains the same.<br>You could also add validators with feedback messages while the user is typing, along with all sorts of lovely features to improve the UX.</em></p><p>This approach strongly <strong>decouples</strong> the <strong>UI frame</strong> from the <strong>controlling</strong> logic. You’ll be able to update views by <strong>extracting DOM nodes</strong> and <strong>inserting new components </strong>as much as you want, without even thinking about how to access data and handle user actions. Consequently, <strong>connecting views with data</strong> becomes an <strong>easy game</strong> 💪. <br>Additionally, <strong>testing</strong> the controlling logic separately from the UI presents <strong>significant benefits</strong> by reducing the complexity of unit tests.</p><h4>Implementation</h4><p>Ok, we now have a <strong>clear overview</strong> of how to implement our app: it’s time to code.</p><p>Let’s dive into the CreateItem controller. How will it look?</p><pre>import React, { createContext, useContext, useState, ReactNode } from &#39;react&#39;<br>import { useErrorController } from &#39;./errorController&#39;<br>import { todoClient } from &#39;../clients/todo&#39;<br>import { sanitizeFormInput } from &#39;../sanitizers/strings&#39;<br><br><br>interface CreateItemType {<br>  onChange: (itemValue: string) =&gt; void<br>  createItem: () =&gt; Promise&lt;void&gt;<br>}<br><br>interface CreateItemProviderProps {<br>  children: ReactNode<br>}<br><br>const CreateItem = createContext&lt;CreateItemType | null&gt;(null)<br><br>export const CreateItemProvider: React.FC&lt;CreateItemProviderProps&gt; = ({<br>  children,<br>}) =&gt; {<br>  const { displayError } = useErrorController()<br><br>  const [itemValue, setItemValue] = useState&lt;string&gt;(&#39;&#39;)<br><br>  const createItem = async () =&gt; {<br>    try {<br>      const sanitizedValue = sanitizeFormInput(itemValue)<br>      await todoClient.createItem(sanitizedValue)<br>    } catch (err) {<br>      displayError(err)<br>    }<br>  }<br><br>  const onChange = (value: string) {<br>    setItemValue(value)<br>  }<br><br>  const value: CreateItemType = {<br>    createItem,<br>    onChange<br>  }<br><br>  return (<br>    &lt;CreateItem.Provider value={value}&gt;<br>      {children}<br>    &lt;/CreateItem.Provider&gt;<br>  )<br>}<br><br>export const useCreateItem = (): CreateItemType =&gt; {<br>  const context = useContext(CreateItem)<br>  if (!context) {<br>    throw new Error(&#39;useCreateItem must be used within a CreateItemProvider&#39;)<br>  }<br>  return context<br>}</pre><p>The file createItem.tsx<em> </em>contains:</p><ul><li>A React <strong>context provider</strong>, CreateItemProvider which embeds the controlling logic and exposes the controller interface, i.e., two functions: onChange(), which updates the state of the form input, and createItem(), which triggers API calls.</li><li>A React <strong>hook</strong>,useCreateItem(), eases access to the context. It can be consumed as follows within view components (or other controllers):</li></ul><pre>const Form = () =&gt; {<br>  const { onChange, createItem } = useCreateItem()<br>  // View component logic<br>}</pre><p><strong>How to connect view components with controllers?</strong></p><p>For a given view component to consume a given controller, the view component must be a <strong>child</strong> of the <strong>controller provider</strong>.<br>To <strong>clarify dependencies</strong> and <strong>ease</strong> <strong>data access</strong>, I recommend instantiating all controller providers within the <strong>same file</strong> at the <strong>top of the page</strong>. This way, controllers can be accessed by any view component.<br>Ultimately, if you face performance issues, you can adjust the approach and refine the hierarchy.</p><pre>const TodoApp = () =&gt; {<br>  // Mount controllers providers to make them accessible from <br>  // any view component.<br>  // Page is the root of view components.<br>  return (<br>    &lt;ErrorController&gt;<br>      &lt;ListItems&gt;<br>        &lt;CreateItem&gt;<br>          &lt;DeleteItem&gt;<br>            &lt;Page /&gt;<br>          &lt;/DeleteItem&gt;<br>        &lt;/CreateItem&gt;<br>      &lt;/ListItems&gt;<br>    &lt;/ErrorController&gt;<br>  )<br>}<br></pre><p><em>Important note: when calling providers ensure the order matches the dependencies between controllers.</em></p><p>And that’s it! This is a way to build <strong>robust controllers</strong> with React native tools. I hope you enjoyed this article. Let me know if you’d like to dive deeper into certain aspects.<br>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffa3db89cbb0" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/your-react-app-isnt-great-fix-it-with-controllers-ffa3db89cbb0">Your React App Isn’t Great — Fix It With Controllers.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your React App Isn’t Great — Here’s Why.]]></title>
            <link>https://levelup.gitconnected.com/your-react-app-isnt-great-here-s-why-5eb61b3f110b?source=rss-416eed7e9a66------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eb61b3f110b</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pierre G.]]></dc:creator>
            <pubDate>Sun, 15 Dec 2024 18:07:47 GMT</pubDate>
            <atom:updated>2025-01-20T19:45:33.027Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your React App Isn’t Great — Here’s Why.</h3><h4>How to Make Your Colleagues Fall in Love with Your React Applications.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l1urW1ea-IcYcS9G" /><figcaption>Photo by <a href="https://unsplash.com/@ospanali?utm_source=medium&amp;utm_medium=referral">OSPAN ALI</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Since its first public release in May 2013, React has offered <strong>tools</strong> for building web applications in a more <strong>modular way</strong>. However, the famous library doesn’t provide much guidance on how to <strong>structure code</strong>, bringing great flexibility — for the best and the worst.</p><p>Let’s start with an indiscreet question (apologies in advance): Do your React components look like the one below?</p><pre>const YourComponent = ({ props1, ..., props7 }: MyComponentProps) =&gt; {<br>  const { state1, setState1 } = useState&lt;...&gt;(...)<br>  const { state2, setState2 } = useState&lt;...&gt;(...)<br>  const { state3, setState3 } = useState&lt;...&gt;(...)<br>  // More states stacking here...<br>  // ...<br>  <br>  useEffect(() =&gt; {<br>    // About twenty lines (or more) responsible for fetching <br>    // and mapping data that will be used in the JSX <br>    // section just below.<br>  },[/* A list of several variables to watch. */])<br>   <br>  // Instructions to process data, to handle user actions.<br>  // ...<br>  // Maybe another useEffect() to make things more confusing?<br>  // ...<br>  // What line are we at? Maybe line 105 already?<br>  // ...<br>  // Helpers to generate JSX codes.<br>  // ...<br>  // Line 145 :(<br>  // ...<br>  return (<br>    &lt;div&gt;<br>      &lt;...<br>         (...)  <br>         Thirty (or more) lines of JSX...<br>         (...)<br>      ...&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br></pre><p>If yes, let’s <strong>reflect</strong> on how we can <strong>improve things.</strong>..</p><p>I’ll try to sell you something — it will cost a bit of your time and attention, but (hopefully) save you and your colleagues hours of <strong>strugglin</strong>g with <strong>debugging overly coupled</strong> code that handles <strong>too many responsibilities </strong>at once.</p><p>We can create a <strong>diagram</strong> to represent the above React component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*fVEF8IPLaGbYz4mGV9el1A.png" /><figcaption>How your React component may look like…</figcaption></figure><p>As you can see, our React component handles at least <strong>five different responsibilities</strong>:</p><ol><li>Managing React <strong>states</strong></li><li>Handling <strong>user actions</strong></li><li>Fetching <strong>data</strong> from <strong>APIs</strong>, catching exceptions, and managing loading phases</li><li><strong>Transforming</strong> and <strong>mapping</strong> data from different sources</li><li>Defining the UI and <strong>DOM</strong> with <strong>JSX</strong></li></ol><p>It’s a lot, isn’t it? Beyond <strong>readability</strong> issues (it’s often hard to understand what’s going on), the logic is difficult <strong>to test</strong> and <strong>extend</strong>. Moreover, applications relying on these kinds of components <strong>lack consistency</strong> in <strong>data flow</strong>. Information is randomly spread across the app, increasing confusion.</p><p>So, let’s try to fix this by <strong>separating concerns</strong>. How could it look like?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*fiViiv29XLqRPWwjcV3K2Q.png" /><figcaption>Separation of concerns helps make your React App readable, testable and maintainable. Your colleagues will love it ❤️.</figcaption></figure><p>Let’s understand the <strong>responsibilities</strong> of entities introduced in the diagram above. From the left to the right:</p><h4><strong>Clients</strong></h4><ul><li>Clients are responsible for <strong>interfacing</strong> with <strong>external data sources</strong>, typically through APIs. They expose <strong>typed structures </strong>that <strong>controllers</strong> can <strong>directly process</strong>.</li><li>They are <strong>decoupled</strong> from the <strong>React</strong> <strong>lifecycle</strong>, meaning they don’t depend on React entities at all. They are simple classes (or functions) that contain information about APIs.</li><li>They <strong>handle API errors</strong> and re-throw errors that can be handled by the app (typically through an Error Fallback).</li></ul><h4>Stateful Controllers</h4><ul><li><strong>Stateful Controllers</strong> are responsible for handling <strong>React states</strong>.</li><li>They expose <strong>data interfaces</strong> to <strong>View Components,</strong> and the exposed data is directly usable in the JSX code where it’s injected. This mechanism can be called <strong>data hydration</strong>.</li><li>Stateful Controllers also expose <strong>callback functions</strong> to allow users to modify the state and trigger API calls.</li><li>Stateful Controllers can be built by associating <strong>React hooks </strong>and <strong>React contexts</strong>. React hooks allow you to easily <strong>connect</strong> controllers with View Components, while React contexts make <strong>states global</strong>. This way, you can easily connect any View Component with any Stateful Controller, ensuring the <strong>state</strong> is <strong>shared across</strong>.</li><li>Stateful Controllers do not deal with a single line of JSX, which makes testing easier, as the output is a set of structured data and callback functions.</li></ul><p>Stateful (and Stateless) Controllers deserve a dedicated article. Read <a href="https://levelup.gitconnected.com/your-react-app-isnt-great-fix-it-with-controllers-ffa3db89cbb0">this article</a>, if you’re interested in diving deeper into these concepts.</p><h4>Data Mappers and Transformers</h4><ul><li>In some cases, data fetched through APIs (or data sent to APIs) requires <strong>advanced transformations</strong>. These can be extracted into dedicated modules to improve testability.</li><li>Data Mappers and Transformers are decoupled from the React lifecycle.</li></ul><h4>View Components</h4><ul><li>View Components are <strong>simple</strong> components that connect to controllers and <strong>inject data into JSX</strong> code.</li><li>They don’t process, transform, or handle data. Instead, they delegate these tasks to controllers.</li><li>They don’t use props anymore because they get data from controllers by consuming hooks. This clarifies data flow and ensures consistency.</li><li>They don’t handle states.</li><li>They can be easily tested through snapshots or basic Jest assertions.</li></ul><p>With this approach, prop drilling, callback hell, and high cognitive complexity (and even Redux 🎉) become bad memories.</p><p>Here we are. This short article aimed to give you a <strong>quick overview </strong>of how to <strong>improve</strong> your React application. If you’re interested in diving deeper into specific concepts with more concrete examples, I’d be happy to write more articles on this topic. Please leave your requests and feedback in the comments.<br>Thanks for reading!</p><p><em>If you want to learn more about controllers, read </em><a href="https://levelup.gitconnected.com/your-react-app-isnt-great-fix-it-with-controllers-ffa3db89cbb0"><em>the follow-up article</em></a><em>.</em></p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li></ul><p>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></p><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eb61b3f110b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/your-react-app-isnt-great-here-s-why-5eb61b3f110b">Your React App Isn’t Great — Here’s Why.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solitary Tests Over Social Tests: A Smarter Approach to Code Quality]]></title>
            <link>https://levelup.gitconnected.com/solitary-tests-over-social-tests-a-smarter-approach-to-code-quality-389b98cf19a1?source=rss-416eed7e9a66------2</link>
            <guid isPermaLink="false">https://medium.com/p/389b98cf19a1</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code-quality]]></category>
            <dc:creator><![CDATA[Pierre G.]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 02:10:57 GMT</pubDate>
            <atom:updated>2024-11-18T02:10:57.613Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s explore why solitary tests are much more maintainable.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BjOfnhscidzkGxSu" /><figcaption>Photo by <a href="https://unsplash.com/@johnnyboylee?utm_source=medium&amp;utm_medium=referral">Johnny Briggs</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Have you ever found yourself in this situation?</strong><br>Your Product Manager brings you a new requirement from the business team. Your backend system needs a small adjustment to update an access management rule. After a moment’s thought, you confidently reply, <em>‘That should be simple and quick — I can handle it.’</em></p><p>You open your IDE, and within 10 minutes, you pinpoint the logic that needs to be updated. You add the missing permission to an array, and it’s done. Oh, wait… almost done — you need to fix the unit tests too. Let’s run them.</p><p><em>17 failures across 5 classes… how is that possible?</em></p><p>It happens because the service’s <strong>unit tests aren’t written in isolation</strong>, causing tests for classes that depend on the modified logic to fail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*GbRBigWd0WheAsKOOSQUuQ.png" /><figcaption>Social unit tests do not mock dependencies making maintenance more challenging.</figcaption></figure><blockquote>Test one thing at the time, and test it once.</blockquote><p>This is the <strong>Single Responsibility Principle</strong> for unit tests, which significantly improves <strong>maintainability</strong> and <strong>extensibility</strong>. To follow this rule, you need to <strong>avoid side effects</strong> and ensure tests run in <strong>strict isolation</strong> by using <strong>mocks</strong> or <strong>stubs</strong>. These types of unit tests are often called <strong>solitary unit tests.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*Sth4aOuH_iTP026hc5xIFQ.png" /><figcaption>Solitary unit tests focus on one single unit in strict isolation.</figcaption></figure><p><strong>How do you test the integration between units?</strong></p><p>That’s exactly what <strong>integration tests</strong> are for. Their purpose is to ensure that units interact correctly. Integration tests <strong>validate interfaces</strong> and check the <strong>consistency</strong> of the <strong>entire service</strong>, while unit tests focus on the <strong>internal logic</strong> of each unit, aiming for wide coverage that includes all use cases and corner cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*oLe6_FjxqwfJ6ysDlmHqAQ.png" /><figcaption>Solitary unit tests focus on testing the internal logic of units (red areas) in strict isolation, using mocks (blue circles).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*Es0bYJUvtWAY5nwUzA__Tg.png" /><figcaption>Integration tests focus on testing the internal integrations of the service (red arrows), ensuring that the units work well together.</figcaption></figure><h3>Conclusion</h3><p>Solitary unit tests offer <strong>significant benefits</strong> in terms of <strong>maintainability</strong> by helping you comply with the<strong> Single Responsibility Principle</strong> for unit tests. Testing in strict <strong>isolation</strong> <strong>complements</strong> <strong>integration tests</strong>, which focus on the interconnections between the service units.<br>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=389b98cf19a1" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/solitary-tests-over-social-tests-a-smarter-approach-to-code-quality-389b98cf19a1">Solitary Tests Over Social Tests: A Smarter Approach to Code Quality</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The True Cost of Technical Debt: Why Software Debt is a Trillion-Dollar Challenge]]></title>
            <link>https://levelup.gitconnected.com/the-true-cost-of-technical-debt-why-software-debt-is-a-trillion-dollar-challenge-8d83213628a5?source=rss-416eed7e9a66------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d83213628a5</guid>
            <category><![CDATA[business]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Pierre G.]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 02:09:53 GMT</pubDate>
            <atom:updated>2024-11-18T02:09:53.484Z</atom:updated>
            <content:encoded><![CDATA[<h4>In 2022, software technical debt cost the United States $2.4 trillion. Let’s explore why.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0ohlVqUnPaDI6fA4" /><figcaption>Photo by <a href="https://unsplash.com/@pokmer?utm_source=medium&amp;utm_medium=referral">Jingming Pan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As per Consortium for Information and Software Quality (1) findings, the expenses attributed to <strong>subpar software quality </strong>in 2022 amounted to a astonishing $2.4 trillion —$ 2 400 000 000 000 — solely within the United States. To provide perspective, in 2022, the GDP of the United States stood at $25.5 trillion. Specifically, the cost incurred due to <strong>technical debt </strong>— resulting from challenging-to-maintain or extend poor-quality code — reached a significant $1.54 trillion.</p><p>Also, the 2020 software quality report from the organization underscores a crucial point:</p><p><em>“ […] Software quality lags behind other objectives in most organizations. That lack of primary attention to quality comes at a steep cost, which is revealed in this report. While organizations can monetize the business value of speed, they rarely measure the offsetting cost of poor quality.”</em></p><p>Can you imagine the actual gains from reducing maintenance effort by 20% only? It would represent <strong>hundreds of billions </strong>of dollars per year in the US alone.</p><p>Let’s explore why the software industry is <strong>atypical</strong> and why it faces <strong>challenges</strong> that explain the <strong>scale</strong> of its <strong>technical</strong> <strong>debt</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UC1QM2Bi83jwYdgSZbD7Jg.png" /></figure><h3>A new discipline for the masses</h3><p>Software engineering has been around for nearly a century, but it has only experienced <strong>exponential growth</strong> in the last <strong>few decades</strong>, resulting in a substantial <strong>increase in the number of software engineers</strong>. By the end of the 1980s, there were only hundreds of thousands of software engineers worldwide. However, as of 2023, this number has soared to an estimated 25 million, and predictions suggest that around 45 million people will be working in this sector by 2030 (2).</p><p>This<strong> explosive growth</strong> presents a unique challenge: experienced and proficient engineers<strong> struggle to pass on their knowledge</strong> to the new generation of engineers, many of whom have to independently discover the fundamentals of the field. It partially explains why software engineering faces <strong>difficulties in consistently delivering high-quality results</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1gs2aOhEW6Mm6hib" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=medium&amp;utm_medium=referral">National Cancer Institute</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Learning takes time</h3><p>Consider this: Would you expect a surgeon to become fully proficient in just three months? The time required for comprehensive surgical training does not align with the immediacy of addressing patients’ needs.</p><p>While many software engineers can readily develop algorithms to solve basic or even complex problems, creating <strong>consistent designs</strong> is a different challenge — it is not something that comes naturally. It demands training in <strong>pattern recognition</strong>, a commitment to studying and addressing hundreds of use cases, and a profound mastery of <strong>design structures</strong>.</p><p>The u<strong>nprecedented growth</strong> of the software engineering sector in recent years has created a <strong>demand for engineers </strong>at an unprecedented pace. This presents an good opportunity for individuals to secure new jobs. However, there is a drawback: many<strong> inexperienced engineers</strong> are pushed to deliver production code daily and too early in their professional journey.</p><p>More concerning, some <strong>engineers with years of experience</strong> find themselves needing to learn fundamental principles they missed during their career paths due to a<strong> lack of</strong> <strong>exposure to the right resources</strong>.</p><p>This reality also partially explains why the software industry faces challenges in delivering high quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tLaK0hIPPXpQ6KXc" /><figcaption>Photo by <a href="https://unsplash.com/@homaappliances?utm_source=medium&amp;utm_medium=referral">Homa Appliances</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What sets software apart?</h3><h4>Data factories</h4><p>When we think about software systems, it is more appropriate to compare them to <strong>complex</strong>, <strong>dynamic</strong>, <strong>modular</strong>, and <strong>adaptable factories</strong> constantly <strong>producing</strong>, <strong>processing</strong>, and <strong>digesting data</strong>, rather than traditional structures like cars, buildings, or airplanes.</p><p>Imagine a robot employed by an airplane manufacturer to assemble tiny mechanical components. You might assume that the robot is <strong>highly reliable</strong> due to its <strong>frequent, repetitive operations</strong> performed thousands of times each day. Indeed, any <strong>discrepancies</strong> or <strong>errors</strong> in its operations can <strong>propagate</strong> across all manufactured items, potentially leading to <strong>severe consequences.</strong></p><p>The same principle applies to running code that processes data. In many use cases, the logic within software systems should be <strong>highly reliable </strong>because it generates <strong>numerous datasets </strong>that other services rely upon. Correcting corrupted data, when possible, is a complex and time-consuming endeavor.</p><h4>Complexity</h4><p>Software systems are undeniably complex, but what does that really mean? The complexity of any system can be gauged by measuring <strong>its degrees of freedom </strong>— how many parameters define its state. Software systems, by nature, are <strong>composite</strong> and encompass numerous degrees of freedom. They comprise numerous entities, such as services, classes, types, and functions, each interdependent with many others.<br>This complexity when not mastered can generate many <strong>side effects</strong> and issues that require a <strong>large workforc</strong>e to manage. Due to the <strong>scale</strong> and <strong>pace</strong> inherent to software systems, especially in hypergrowth environments, these side effects can escalate, generating <strong>increasing costs</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*da8hQUF31vnM-wEn" /><figcaption>Photo by <a href="https://unsplash.com/@aldyrkhanov?utm_source=medium&amp;utm_medium=referral">Artur Aldyrkhanov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Easy to create, costly to scale.</h4><p>Creating a simple website can be done by almost anyone in an afternoon by following an online tutorial. However, ensuring that the same website is <strong>scalable</strong> and <strong>extensible</strong>— able to adapt to evolving requirements and support millions of active users — introduces entirely <strong>different challenges</strong>.</p><p>Unlike typical physical products, software has <strong>unique characteristics</strong>. Building a <strong>Minimum Viable Product</strong> (MVP) requires <strong>minimal upfront cost</strong>, energy, or investment. This often leads entrepreneurs to be <strong>overly optimistic</strong> at the outset. However, it’s not immediately obvious why the 100th iteration might take ten times longer than the first, even if the website looks nearly the same.</p><p>Software development <strong>differs</strong> starkly from <strong>other industries</strong>. Building a car prototype, for example, requires substantial time and money, so automakers are deliberate in designing and conceptualizing these prototypes.</p><p>This doesn’t mean software development should adopt car manufacturing practices. Instead, this comparison highlights <strong>key differences</strong> with <strong>traditional industries.</strong> Software benefits from an iterative development approach — its <strong>strength</strong> lies in <strong>adaptability</strong> to<strong> changing requirements</strong>. However, this flexibility is <strong>sustainable</strong> only when <strong>high-quality standards</strong> are established.</p><h3>Conclusion</h3><p>Creating high-quality software is primarily a <strong>strategic matter</strong> as it necessitates the establishment of <strong>appropriate</strong> <strong>conditions</strong> for its production. It requires hiring <strong>skilled individuals </strong>who possess the necessary knowledge and expertise to produce it and allowing them the freedom to do so. It is a key factor that can help the software industry more effectively <strong>manage</strong> its <strong>resources</strong> and <strong>costs</strong>. Raising the global standard of software quality to reduce the overall technical debt should be <strong>one of our first priorities</strong> as it has the potential to be a <strong>gold mine</strong>.</p><h4><strong>Footnotes</strong></h4><ul><li><em>(1) Consortium for Information and Software Quality: US organization founded in 2009 responsible for driving the awareness, adoption and deployment of software standards. It is managed by the Object Management Group (OMG), a global, open membership and non-profit consortium that crafts technology standards.</em></li><li><em>(2) Source: Evans Data Corporation.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d83213628a5" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-true-cost-of-technical-debt-why-software-debt-is-a-trillion-dollar-challenge-8d83213628a5">The True Cost of Technical Debt: Why Software Debt is a Trillion-Dollar Challenge</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns to the Rescue: 7 Strategies for Cleaner, Extensible Code]]></title>
            <link>https://levelup.gitconnected.com/design-patterns-to-the-rescue-7-strategies-for-cleaner-extensible-code-141d936481cb?source=rss-416eed7e9a66------2</link>
            <guid isPermaLink="false">https://medium.com/p/141d936481cb</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[best-practice-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Pierre G.]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 01:56:21 GMT</pubDate>
            <atom:updated>2024-11-18T01:56:21.316Z</atom:updated>
            <content:encoded><![CDATA[<h4>Best practices to significantly boost code quality</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w1_6wedA_hz1bUKc" /><figcaption>Photo by <a href="https://unsplash.com/@gecko81de?utm_source=medium&amp;utm_medium=referral">Patrick Baum</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the <a href="https://medium.com/gitconnected/the-devil-is-in-the-details-1-2-c6d8e516d812">first part</a> of this article, we introduced three of the seven <strong>DETAILS patterns</strong> designed to <strong>enhance application development</strong> by improving code readability and extensibility:</p><ul><li>[D]RY state</li><li>[E]xception flow efficiency</li><li>[T]able of content</li><li>[A]bstraction consistency</li><li>[I]n-line logging</li><li>[L]ifecycle consistency</li><li>[S]tart-up separation</li></ul><p>Now, let’s explore the <strong>four remaining patterns:</strong></p><ul><li>DRY state</li><li>Abstraction consistency</li><li>In-line logging</li><li>Lifecycle consistency</li></ul><h3>1. The DRY State Pattern</h3><p><strong>[D]</strong>ETAILS</p><h4>Problem</h4><p><strong>Corrupted data</strong> stored in databases or file systems can have severe consequences as it generates unexpected behaviors. These <strong>inconsistencies</strong> are persistent and can <strong>propagate silently across system entities</strong>, creating additional issues.</p><h4>Principle</h4><p><em>Definition of a </em><strong><em>system state</em></strong><em>: The state of a software system includes all </em><strong><em>persistent</em></strong><em> data sets that represent the </em><strong><em>current</em></strong><em> </em><strong><em>sources of truth</em></strong><em> of information. This data is typically stored in databases and file systems. Consequently, duplicated data sets used solely to improve performance, such as indexes or cached data, do not belong to the system’s state.</em></p><p>To keep a system state consistent, you should consider dryness in two ways:</p><ol><li>The dryness of <strong>data models</strong> is widely known and crucial. Remember <strong>not to duplicate</strong> sources of truth. That’s where the structuration of models is essential. Your models must be <strong>nonreducible</strong>, so removing any element without losing information is impossible.<br>Don’t use cache systems or indexes (e.g., Redis, Elasticsearch indexes) as sources of truth. For this reason, you should be able to wipe out and re-populate data through dedicated jobs.</li><li>The dryness of <strong>data sets</strong>. In other words, keep the data <strong>consistent</strong> by <strong>avoiding duplicates </strong>or <strong>corrupted</strong> entries. Implementing robust, well-tested, and reliable validation flows remains essential. Indeed, cleaning up corrupted data, when possible, is generally a strenuous process.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*-l9QqT55WxoVIS5NBDtWtQ.png" /><figcaption><strong>Data Model Dryness</strong> — Example of a simple and DRY architecture</figcaption></figure><h4>Purpose</h4><p>Ensuring the <strong>consistency</strong> and <strong>integrity</strong> of the system’s state is a critical concern that requires significant effort.</p><p>Here are a few points to validate when storing a new data set in the system state:</p><ul><li>Does the new entry <strong>comply</strong> with its <strong>model</strong>? Is the data consistent and matches the business logic rules?</li><li>Does the entry <strong>already exist</strong>? Do we <strong>duplicate</strong> its creation?</li><li>If the new data set references data sets? Do those <strong>relationships</strong> actually <strong>exist</strong>?</li></ul><h3>2. The Abstraction Consistency Pattern</h3><p>DET<strong>[A]</strong>ILS</p><h4>Problem</h4><p>Writing functions that deal with entities from different natures and abstraction levels can lead to <strong>unclarity</strong> and highly <strong>degraded testability</strong>.</p><p>Here are some examples of inconsistent approaches:</p><ul><li>Operate the business logic from within controllers.</li><li>Checking REST parameters directly inside controllers through regular expressions.</li></ul><h4>Principle</h4><p>Within a <strong>function</strong>, all entities should operate at the <strong>same level of abstraction</strong>. Similarly, two <strong>classes</strong> with a <strong>similar purpose</strong> should each work at a unique, consistent level of abstraction. Classes can be considered similar if:</p><ul><li>They are instantiated in <strong>comparable ways</strong> and <strong>locations</strong>.</li><li>Their instances are handled in similar <strong>areas</strong> of the application.</li></ul><h4>Purpose</h4><p>The Abstraction Consistency principle for functions remains a direct consequence of the <strong>Single Responsibility Principle</strong> and the<strong> cohesion principle</strong>. If a function does one single thing, it can’t, with even greater reason, handle things on different levels of abstraction.</p><p>For classes, the Abstraction Consistency principle allows for generating <strong>consistent layers of abstraction</strong> inside the application.</p><h3>3. The In-Line Logging Pattern</h3><p>DETA<strong>[I]</strong>LS</p><h4>Problem</h4><p>Logging information from anywhere within the application <strong>conceals</strong> the <strong>core business</strong> logic by <strong>hiding</strong> core instructions.</p><h4>Principle</h4><p><a href="https://medium.com/gitconnected/the-devil-is-in-the-details-1-2-c6d8e516d812">In the first part of this article</a>, we’ve introduced the <strong>Table of Contents</strong> pattern, which enables us to manage the control flow clearly and transparently. The <strong>primary function</strong> responsible for managing the higher level of the control flow <strong>summarizes the main steps of the action</strong>. To improve readability within the business logic of the application, favor logging as much as possible from within it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*BXVFckPW_UF21Hxi-H5ufg.png" /><figcaption><strong>High-level logging — </strong>Example 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*TjYTbqjV7Zvqr8TZtGIRlA.png" /><figcaption><strong>High-level logging — </strong>Example 2: Exception to the rule.</figcaption></figure><h4>Purpose</h4><p>A simple and consistent logging approach helps make the code source more <strong>transparent</strong> and <strong>understandable</strong>.</p><h3>4. The Life Cycle Consistency Pattern</h3><p>DETAI<strong>[L]</strong>S</p><h4>Purpose</h4><p>Entities associated with inappropriate lifecycles can lead to <strong>severe</strong> <strong>consequences</strong> like <strong>memory</strong> <strong>leak</strong> or <strong>incorrect</strong> <strong>values</strong>.</p><h4>Principle</h4><p>Any <strong>software entity</strong> (e.g. instances of classes, variables, closures) should have a <strong>lifetime </strong>(and, consequently, a life cycle) that <strong>matches</strong> their <strong>purpose</strong>.</p><p>In practice, we can distinguish between <strong>two noticeable categories</strong> of time scales:</p><ul><li>The <strong>application cycle</strong> represents the lifetime of the service/application from its start until its shutdown.</li><li>The <strong>action cycle</strong> represents the time linked to the execution of an action handled by a service/application, for instance, between the time an HTTP request is handled and its response to the client.</li></ul><h4>Purpose</h4><p>By appropriately<strong> managing data storage</strong> at <strong>runtime</strong> — assigning data scope to the correct context and lifecycle — you <strong>enhance</strong> <strong>consistency</strong> and prevent issues like memory misuse or accessing outdated data from previous cycles.</p><p>For example, store data tied to the <strong>application lifecycle</strong>, such as client hosts or dependencies, as <strong>class members</strong>. For data specific to a <strong>single HTTP request</strong>, pass it through <strong>method parameters</strong> rather than storing it as global variables.</p><p>Thank you for reading, and feel free to share any feedback!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=141d936481cb" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/design-patterns-to-the-rescue-7-strategies-for-cleaner-extensible-code-141d936481cb">Design Patterns to the Rescue: 7 Strategies for Cleaner, Extensible Code</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns to the Rescue: 7 Strategies for Cleaner, Extensible Code]]></title>
            <link>https://levelup.gitconnected.com/the-devil-is-in-the-details-1-2-c6d8e516d812?source=rss-416eed7e9a66------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6d8e516d812</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[best-practice-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Pierre G.]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 17:39:06 GMT</pubDate>
            <atom:updated>2024-11-06T20:30:17.420Z</atom:updated>
            <content:encoded><![CDATA[<h4>Best practices to significantly boost code quality</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*srUt1rP3GxB3B2NW" /><figcaption>Photo by <a href="https://unsplash.com/@robin_schreiner?utm_source=medium&amp;utm_medium=referral">Robin Schreiner</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The DETAILS principles listed below encompass <strong>seven best practices</strong> that will help you <strong>enhance</strong> <strong>code quality.</strong></p><ul><li>[D]RY state</li><li>[E]xception flow efficiency</li><li>[T]able of content</li><li>[A]bstraction consistency</li><li>[I]n-line logging</li><li>[L]ifecycle consistency</li><li>[S]tart-up separation</li></ul><p>In this context, do not interpret <em>details </em>as insignificant. Instead, consider the following:</p><blockquote>The devil is in the details.</blockquote><p>In the first part of this article, we present three of them:</p><ul><li>Exception flow efficiency</li><li>Table of content</li><li>Start-up separation</li></ul><p>We’ll introduce the four remaining patterns in the second part.</p><p>Also, it is essential to note that <strong>software design patterns</strong> require <strong>practice</strong>, like grammar. To master them, you must have applied them <strong>many times</strong> in <strong>several situations</strong> and adjusted them depending on the practical use case you encounter.</p><h3>1. The Table of Content Pattern</h3><p>DE<strong>[T]</strong>AILS</p><h4>Problem</h4><p>When complying with Clean Code guidelines, logic is split into <strong>atomic functions</strong>. An atomic function is one from which you can’t extract another function and which complies with the <strong>Single Responsibility Principle</strong>. The natural tendency when using atomic functions is to write a function that calls a function that calls another function, etc, generating <strong>long chains</strong> of functions.</p><p>This pattern forces the reader to follow the chaining to <strong>understand the global process</strong>. As a result, getting an overview of the code becomes a real challenge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*KfesOBXx8_tkCg7FLQKGjg.png" /><figcaption><strong>Functions chaining</strong> — This pattern doesn’t allow readers to get an overview on the main control flow.</figcaption></figure><h4>Principle</h4><p>To avoid the chaining of functions, we propose to adhere to the <strong>Table of Contents</strong> pattern: each action is associated with a <strong>primary function</strong> (e.g., an express handler) that handles the <strong>main control flow</strong>. The primary function <strong>centralizes</strong> an ordered set of <strong>sub-functions</strong> (that could gather an ordered set of sub-functions). It acts as a <strong>pivot</strong> that <strong>orchestrates</strong> sub-actions and <strong>connects</strong> the <strong>interfaces</strong> it depends on to manage data <strong>input</strong> and <strong>output</strong>.</p><p>Consequently, the principal function <strong>highlights</strong> the <strong>actions’ sequence</strong> from the beginning to the end.</p><p>Additionally, this approach allows developers to keep consistent abstraction levels across functions. Indeed, sub-functions called from a given function are linked to the same level of abstraction.</p><p>If you know how to use the Table of Contents pattern, five minutes is enough to understand the global structure of any module/class, regardless of its size and complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*yZ_okcPQ3-Bo9gh3fDMyZQ.png" /><figcaption><strong>Table of Content</strong> — The primary function is responsible for centralizing the main steps of the action. It summarizes what the action does.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*xcqCTtPEpCiY8S8SgoAIGQ.png" /><figcaption><strong>Table of Content — </strong>The pattern can be repeated several times across the different levels of control flow (level 0 being the highest level of control flow).</figcaption></figure><h4>Purpose</h4><p><strong>Understandability</strong> remains one of the most significant software engineering challenges. Indeed, code <strong>readability</strong> is a crucial concern, especially for larger projects.</p><p>Nevertheless, software systems are not the first complex entity that humanity has to deal with. Encyclopedias, topographic, or telecommunication systems, for instance, also contain many complex data sets that must be organized, classified, and categorized. These systems all handle their data by abstracting it. What exactly does abstracting mean? It means summarizing, that is, simplifying things so they are manageable and handleable.</p><p>The <em>Table of Contents</em> pattern aims to generate <strong>appropriate abstractions</strong> to make any operation understandable. By abstracting (and then simplifying) the action sub-steps, you allow your readers to answer their first question: <strong>what does this action do?</strong></p><h3>2. The Start-up Separation Pattern</h3><p>DETAIL<strong>[S]</strong></p><h4>Problem</h4><p>Mixing up the logic responsible for preparing, instantiating, and configuring resources (e.g., clients, database clients, loggers) with the logic accountable for handling actions and processing business logic can lead to <strong>unclarity</strong> and <strong>misuse of resources</strong>.</p><h4>Principle</h4><p>The logic responsible for <strong>building up </strong>the application, which occurs at the start of the application life cycle, must be clearly <strong>distinguished</strong> from the logic responsible for <strong>handling actions </strong>and processing <strong>business logic</strong> during the application’s<strong> run-time</strong>.</p><p>The diagram below illustrates an example where you can distinguish the start-up logic during which the application instantiates and injects resources and services from the runtime logic during which handlers operate actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*iUKfbYLDYKqpcYOoHBLaeA.png" /><figcaption><strong>Start-up Separation </strong>— An example</figcaption></figure><h4>Purpose</h4><p>Keeping separation between the startup logic and the run-time logic allows developers:</p><ul><li>to instantiate <strong>resources</strong> and <strong>clients</strong> in a <strong>centralised process</strong>;</li><li>to deal with the <strong>graceful shutdown</strong> of the application by closing the external connections and freeing up memory in a <strong>centralised process</strong>;</li><li>to improve the <strong>testability</strong> of the <strong>business logic</strong>;</li><li>to avoid some anti-patterns linked to the use of resources, like instantiating a new client object each time the service handles a request.</li></ul><p>Let’s use an analogy to emphasize the importance of this principle. In airplane factories, advanced robots, complex machinery, and assembly lines allow engineers and specialized technicians to assemble aircraft components. Would you imagine this robotic equipment to be built at the same moment as mounting airplanes? You expect the factory to be ready with its equipment before starting aircraft production.</p><p>Separating these two phases is also essential when building applications. You should neatly distinguish the startup phase from the action handling phase.</p><h3>3. The Exception Flow Efficiency Pattern</h3><p>D<strong>[E]</strong>TAILS</p><h4>Problem</h4><p>The use of <strong>exceptions</strong> can be highly beneficial, as they allow programs to enable a <strong>secondary control flow</strong> that is independent of the main one. However, their handling shouldn’t hide the business logic and be done discreetly at <strong>key places</strong>.</p><p>The misuse of try/catch statements adds noise to the business logic without value. That’s why it is essential to understand <strong>why</strong>, <strong>when</strong>, and <strong>how</strong> to catch exceptions. Services must rely on <strong>appropriate structures</strong> and <strong>classes</strong> to enable <strong>efficient</strong> exception management.</p><h4>Principle</h4><ol><li>Define <strong>internal classes</strong> responsible for supporting error management. Those classes must extend a generic <em>BaseError</em> and contain members and methods related to error handling and logging (e.g., error messages for client side, context information to be logged, stack traces, REST status codes). This approach enables a <strong>standard</strong> and <strong>consistent</strong> behavior across the whole application.</li><li>Ensure each error created in the application is an instance of classes defined in [1]. Intercept <strong>external</strong> <strong>errors</strong> as soon as possible and transform them into internal errors by using classes defined in [1] that the main error handler defined in [3] can process.</li><li><strong>Handle</strong> errors at a<strong> high level </strong>in a single place within the application.<br>For instance, in Express, catch and handle all exceptions from within a dedicated middleware. This middleware is accountable for logging errors with a unique format and for sending HTTP responses by setting REST statuses that are consistent with the type of error.</li><li>Inside the business logic, i.e., inside services, <strong>catch errors with parsimony</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*FdiW2nTgAqCpzPopBfZjzQ.png" /><figcaption><strong>Error Flow — Example 1 — </strong>Standard control flow without error.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*LRB_ocFdjE6K86uPv_fEUw.png" /><figcaption><strong>Error Flow — Example 2 — </strong>Simplest error flow.</figcaption></figure><p>You should handle errors in the business logic in the following cases (rely on the diagrams below to understand each use case further):</p><ul><li>You want to <strong>add context</strong> to the thrown error (e.g., by adding business information to the error message — example 3).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*zOWlsDSVhTHngpsa3pqX0w.png" /><figcaption><strong>Error Flow — Example 3 </strong>— Context enrichment.</figcaption></figure><ul><li>You want to <strong>break the control flow</strong> of errors to switch to the standard flow (example 4). This is useful when an exception is not critical, and you want to continue handling the action.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*d64xEXHF5BdJsVxIgogN-g.png" /><figcaption><strong>Error Flow — Example 4 </strong>— Non-blocking error.</figcaption></figure><ul><li>You want to <strong>transform an external error</strong> into an internal error to comply with [2] (example 5).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*vkoI0nUwLUTWyINQkiZmgQ.png" /><figcaption><strong>Error Flow — Example 5 — </strong>Transformation of external errors.</figcaption></figure><p>To summarize:</p><ol><li>Set clear definitions of error <strong>classes</strong>.</li><li>Ensure all errors are instances of classes defined in (1) by transforming <strong>external</strong> <strong>errors as soon as possible.</strong></li><li><strong>Handle</strong> exceptions at a <strong>unique high-level point</strong>.</li><li>Use the most <strong>simple control flow</strong> of exceptions to enhance transparency.</li></ol><p>In the second part of this article, we’ll explore four more patterns:</p><ul><li>The DRY state pattern</li><li>The abstraction consistency pattern</li><li>The in-line logging pattern</li><li>The lifecycle consistency pattern</li></ul><p>Thanks for reading, and feel free to share your comments and feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6d8e516d812" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-devil-is-in-the-details-1-2-c6d8e516d812">Design Patterns to the Rescue: 7 Strategies for Cleaner, Extensible Code</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Robust Approach for Event Sourcing Systems]]></title>
            <link>https://medium.com/swlh/a-robust-approach-for-event-sourcing-systems-6055a2d82bc8?source=rss-416eed7e9a66------2</link>
            <guid isPermaLink="false">https://medium.com/p/6055a2d82bc8</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <dc:creator><![CDATA[Pierre G.]]></dc:creator>
            <pubDate>Thu, 21 Jan 2021 19:59:27 GMT</pubDate>
            <atom:updated>2022-01-30T19:57:35.100Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to take advantage of Event Sourcing</h4><p>Event Sourcing is a powerful design that enables <strong>reliable</strong>, <strong>mutable,</strong> and <strong>scalable</strong> systems. <br>This article doesn’t deal with the basics of this approach. It aims at providing some <strong>patterns</strong> and <strong>guidelines</strong> for proper implementation.</p><p><strong>The main principle of Event Sourcing:</strong></p><p>The state of any system can be seen as the <strong>outcome of all past mutations</strong> to the initial state. <br><strong>Events</strong> are responsible for <strong>triggering</strong> state <strong>mutations</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KDPiYRRHFBEsCKhi" /><figcaption>Photo by <a href="https://unsplash.com/@mansonyms?utm_source=medium&amp;utm_medium=referral">Manson Yim</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Some definitions</h3><p><em>Note: These definitions are valid within the context of the article. They do not aim at being universal.</em></p><p><strong>Component:</strong> Any <strong>piece of software</strong>. It is a generic term that names (micro)services, modules (in Javascript/TS), packages (Golang), or even instances of classes.</p><p><strong>Action: </strong>An <strong>operation</strong> executed inside the system. It can mutate the system’s state (by updating stored data) or not (by fetching data without modifying it).</p><p><strong>Controller: </strong>A specific component that plays the role of <strong>pivot</strong> by handling and <strong>orchestrating</strong> input and output of sub-components. You can get more insights on this topic by reading <a href="https://medium.com/swlh/how-to-organize-your-express-application-45cd825b81c6">this article</a>. <br>For instance, a public method can act as a controller by calling and handling private methods.</p><p><strong>Event broker: </strong>A software system that enables <strong>events’ transmission</strong> between producers and consumers (e.g Kafka or RabbitMQ).</p><p><strong>Topic: </strong>A <strong>queue</strong> in which <strong>events </strong>are stocked. This article won’t deal with Kafka’s configuration. A <em>topic</em> should be understood as a basic mechanism that enables events’ production and consumption.</p><p><strong>Event: </strong>An <strong>elementary entity</strong> handled by an event broker which can be generated by producers and consumed by consumers. Each event contains a set of <strong>raw data</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*UxGFogenV0oMfKsdyUMYXw.png" /><figcaption>Figure 1 — Event Sourcing concepts</figcaption></figure><h3>Why Should You Use Event Sourcing?</h3><p>Event Sourcing enables the following noteworthy assets:</p><ul><li><strong>Flexibility:</strong> Event Sourcing systems being organized around event brokers, new features can be added independently of existing ones. <br>Events are <strong>agnostic</strong> and can be consumed by <strong>current</strong> and <strong>future</strong> microservices with much adjustability. <br>By <strong>decoupling scopes</strong> and responsibilities, you enable the <em>Open-Closed Principle</em>: high-level components (usually microservices) are <strong>open to extensions</strong> and <strong>closed to modification</strong>.</li><li><strong>Reliability: </strong>Properly implemented, <strong>data integrity</strong> is ensured. <br>We’ll see some patterns to improve the robustness. Even if some components are down, you don’t <em>“lose”</em> any information and you can recover a correct state — once the incident is over.</li><li><strong>Scalability: </strong>Event brokers act like <strong>buffers</strong> and <strong>load balancers</strong> that <strong>distribute</strong> events among services. By adjusting instances through your system, you can scale it and deal with the expected load.</li><li><strong>Trackability: </strong>By storing events responsible for state mutations, you can <strong>calculate</strong> <strong>past states</strong> at any point in time.</li></ul><p>In my opinion, you should think about using Event Sourcing if several of the following assertions are true:</p><ul><li>your system aims at being large with <strong>many business scopes</strong></li><li>business requirements might <strong>mutate</strong> a lot</li><li>you are expected to <strong>track</strong> any change</li><li>your system aims at supporting a <strong>large load</strong></li><li>it requires a <strong>high availability</strong> rate</li><li>it is maintained and developed by <strong>large team(s)</strong> of engineers</li></ul><p>Event Sourcing can make your system more <strong>transparent</strong>. By <strong>externalizing business logic</strong> outside services, topics contain much information on the <strong>system’s status</strong>. Metrics such as stuck events or speed of events’ consumption can help to get insights into <em>what’s going on.</em></p><h3>Setup and Conventions of Event Brokers</h3><p>Event brokers being the<strong> core</strong> of Event Sourcing systems, setup and naming choices are critical. Here are non-comprehensive guidelines to improve maintainability.</p><h4>Event’s format</h4><p>Each event is composed of <strong>metadata</strong> shared through your system. You should define metadata fields in the <strong>early stages</strong> and be aware that any modification will later be painful (the larger is the system, the more unpleasant is any modification).</p><p>Here are some examples of fields that must be useful:</p><ul><li><em>generated_at: </em>the date-time of the event’s <strong>creation</strong>.</li><li><em>generated_by: </em>the <strong>identifier</strong> of the producer.</li><li><em>action_type</em>: the type of action or the <strong>nature</strong> of the event (e.g. <em>create, update, delete, log, notification,</em> etc).</li><li><em>auth: </em><strong>authentication</strong> data of the end-user if any. For instance, it could be a JWT containing an email address and a set of permissions.</li><li><em>payload: </em>custom data.</li></ul><h4>Topics naming</h4><p>The naming of topics (topics in Kafka, queues, and exchanges in RabbitMQ) is crucial. From the beginning, you should agree on a<strong> stable convention</strong> because updating topics remains tricky.</p><p>I strongly recommend avoiding the following semantics in topics’ names:</p><ul><li>products’ or teams’ names</li><li>(micro)services’ names</li><li>any business semantic that is not directly and tightly linked to the topic’s action</li></ul><p>Here is an <strong>example</strong> of convention:</p><p><strong><em>&lt;domain&gt;.&lt;classification&gt;.&lt;target&gt;.&lt;version&gt;</em></strong></p><p>Where:</p><ul><li><strong>domain</strong> represents a <strong>global</strong> and <strong>generic scope</strong> that helps to sort out topics. Obviously, it should be stable and immutable (e.g. customers, products, authentication).</li><li><strong>classification</strong> deals with the <strong>nature</strong> of the events and how they should be <strong>interpreted</strong> (some values are proposed and described below).</li><li><strong>target</strong> represents the targeted object. For instance, if your topic deals with orders’ creation, you should use <em>orders.</em></li><li><strong>version </strong>deals with the version of the events’ format.</li></ul><p>Here are some values for <em>classification </em>(as examples):</p><ul><li><strong><em>FCT</em></strong><em>: </em>raw fact, i.e. an <strong>immutable event</strong> that occurs at a <strong>specific point of time</strong> (e.g. a measure taken by a sensor, an end-user action).</li><li><strong><em>CMD</em></strong><em>: </em>any <strong>command</strong>/action triggered by an end-user, third party, internal or external services (which automate actions). Events of type <em>CMD </em>are directly responsible for <strong>updating</strong> the system’s <strong>state</strong>.</li><li><strong><em>CDC</em></strong><em>: </em><strong><em>a</em>cknowledge</strong> any state’s change within the system. The event’s payload should contain the <strong>diff</strong>, i.e. the previous value and the updated one.</li></ul><h4>Some general guidelines</h4><p><strong><em>Use of controllers:</em></strong> Regarding events’ consumption, you should implement a <strong>unique controller </strong>responsible for <strong>processing one action</strong> (i.e. consuming events from one topic). <br>The controller handles the <strong>control flow</strong>. Generally, the first step consists of events’ consumption (by calling the dedicated library) and the last one in acknowledging the execution of the action.</p><p><strong><em>Use of gateway:</em></strong><em> </em>You should implement a gateway responsible for handling <strong>client requests</strong> and <strong>producing associate events</strong>. The gateway should handle and check <strong>authentication</strong>.</p><p><strong><em>Check of events’ integrity:</em></strong> You should check the <strong>format </strong>of every event. Does the payload match requirements? <strong>Dependencies</strong> through <strong>high-level components</strong> are handled by events. It is your responsibility to ensure data integrity at events’ consumption (as you would do for a REST API). <br>The use of <a href="https://docs.confluent.io/platform/current/schema-registry/index.html">schema registries</a> (with Kafka/Confluent) helps a lot.</p><p><strong><em>Eventing for mutation:</em></strong> You should use eventing for <strong>states mutations</strong>. API should be preferred for reading actions. You could use tools such as GraphQL to ease the reading of more complex data structures. <br>You can use the FCT classification to track the actions of reading. A dedicated topic can be used for this.</p><p><strong><em>Use of library:</em></strong> I recommend creating a library (package, gem, etc) responsible for <strong>mutualizing logic linked to events’ consumption</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*jK0hi4jqgnyKYcwhX4qfRQ.png" /><figcaption>Figure 2 — A basic example of Event Sourcing architecture</figcaption></figure><h3>State Consistency and Integrity</h3><p><strong>State consistency</strong> is one of the greatest challenges in software engineering. In this section, I describe <strong>two patterns</strong> that allow your system to process any action <strong>reliably</strong>. These patterns<strong> prevent</strong> from:</p><ul><li>entries <em>duplications</em></li><li>entries <em>discrepancies</em> (e.g. if you store entries into a database <em>and</em> index them into Elasticsearch)</li><li>losing data in case some consumers are down</li></ul><h4>Atomic action</h4><p>Basically, you should try to make any action an <em>atomic action</em>. <br>By definition, an atomic action <strong>doesn’t enable any semi-execution</strong> and then <strong>doesn’t allow any inconsistent state.</strong><br>In other words, if an atomic action hasn’t been correctly executed, the system’s state remains unchanged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*puud8Dz8kKc4iiTBLOZQ6g.png" /><figcaption>Figure 3 — Atomic action workflow</figcaption></figure><p>For instance:</p><ul><li>adding one entry into a database table is an atomic action, whereas</li><li>adding one entry into a database table and then updating an index is not.</li></ul><p>An event that triggered an atomic action represents a <strong>promise of a state’s transformation</strong>. You get a perfect equivalence between the event’s consumption and the correct update of the state (so that it is consistent).</p><h4>Idempotent action</h4><p>Some practical cases do not allow you to create atomic actions only. An <strong>alternative</strong> consists in creating idempotent actions.</p><p>By definition, an idempotent action will generate a <strong>unique final state</strong> regardless of the number of times it has been triggered — as soon as it has been executed successfully one time at least.</p><p><em>How to make any action an idempotent action?</em></p><p>Any action could be <strong>broken down</strong> into <strong>atomic subtasks</strong>. Before executing any of the subtasks, check whether the subtask has already been executed: do not process the subtask if it has already modified the state as expected.</p><p>Figure 4 deals with an action that is <strong>neither atomic nor idempotent</strong>. <br>Let’s imagine the following scenario. At first execution, subtask 1 succeeds but subtask 2 doesn’t. Then, the event is not acknowledged. Later the event is consumed again: subtask 1 is executed again and may modify the state twice (for instance, it could duplicate entries within a database). The state is <strong>not consistent</strong> anymore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*fKr4sshIUZQb5Ya_Wlx83g.png" /><figcaption>Figure 4 — Non-atomic and non-idempotent action workflow</figcaption></figure><p>Figure 5 deals with an idempotent action. Before executing subtask 1, the state is read to check whether subtask 1 has already been executed (e.g. could consist in checking any entry within a database). Subtask 1 is executed only if required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*DQj5PayhVw7tQKw37kFfbw.png" /><figcaption>Figure 5 — Idempotent action workflow</figcaption></figure><h4>Conclusion</h4><p>Properly implemented, Event Sourcing enables <strong>reliable</strong>, <strong>maintainable</strong>, and <strong>scalable</strong> systems. However, it remains a vast and complex topic with open issues. <br>So, feel free to comment and share feedback.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6055a2d82bc8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/a-robust-approach-for-event-sourcing-systems-6055a2d82bc8">A Robust Approach for Event Sourcing Systems</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to organize your Express application]]></title>
            <link>https://medium.com/swlh/how-to-organize-your-express-application-45cd825b81c6?source=rss-416eed7e9a66------2</link>
            <guid isPermaLink="false">https://medium.com/p/45cd825b81c6</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Pierre G.]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 11:08:59 GMT</pubDate>
            <atom:updated>2020-12-29T16:08:08.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rid9j_jBy_gHE_tO" /><figcaption>Photo by <a href="https://unsplash.com/@dnevozhai?utm_source=medium&amp;utm_medium=referral">Denys Nevozhai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article will help you to:</p><ul><li>keep the code <strong>readable</strong> and <strong>sustainable,</strong></li><li>structure the code with <strong>normalized patterns</strong> and schemes,</li><li>manage the <strong>JS asynchronous flow execution</strong> and avoid callback hell.</li></ul><h3>Software patterns</h3><h4>Rope and nodes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rsKf14Rm30Sj3QDI" /><figcaption>Photo by <a href="https://unsplash.com/@siora18?utm_source=medium&amp;utm_medium=referral">Siora Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To provide a readable and maintainable code you should <strong>split your code into atomic functions</strong>. An atomic function is a compact function that does one only thing and cannot be split.</p><p>The natural trend when using atomic functions is to write a function that calls a function that calls an another function, etc. It looks like a <strong>long rope </strong>with many nodes and loops. This pattern forces the reader to follow the whole rope to understand the global process.</p><p>The <em>rope pattern</em> is one of the consequence of the the use of atomic functions. As a result, getting an <strong>overview</strong> on the code becomes a real challenge for developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fv6c2KIqDt_L0LJrZ-KcJw.png" /><figcaption>The rope pattern looks like a treasure hunt. It’s quite difficult to get quickly an overview.</figcaption></figure><h4>Table of contents</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-aCqLEtQ00cEIcdT" /><figcaption>Photo by <a href="https://unsplash.com/@ninjason?utm_source=medium&amp;utm_medium=referral">Jason Leung</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You will need only 5 minutes to understand the global organization of any module regardless of its size, if you know how to use the <em>table of contents </em>pattern.</p><p>A main process is linked to a main function which <strong>centralizes</strong> an <strong>ordered set of sub-functions</strong> (that could centralize an ordered set of sub-functions too, etc).</p><p>Consequently the main function <strong>highlights</strong> the<strong> actions’ sequence</strong> from the beginning to the end.</p><p>In order to adequately use the <em>table of contents</em>, each process should be divided in <strong>elementary </strong>(or atomic) <strong>sub-processes</strong> (easily understandable) which will make your code readable.</p><p>Longer functions containing many lines are harder to understand. They should be split into <strong>sub-functions</strong>.<br>The <em>table of contents</em> structure may contain <strong>several abstraction levels</strong> (in case of complex tasks).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4dlyn7wEjJ2ne0NrD0ahPA.png" /><figcaption>One-level table of contents pattern</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDnIl8g4Dmcp5vC3MSsPcg.png" /><figcaption>Two-level table of contents pattern</figcaption></figure><p><em>Key points :</em></p><ul><li>A feature / action is associated with a main function that <strong>centralizes</strong> process steps.</li><li>A set of ordered functions doing <strong>intermediate tasks </strong>is called from the main function.</li></ul><h3>Controller, routes and services</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cFThz7DhWhR-1d5v" /><figcaption>Photo by <a href="https://unsplash.com/@samloyd?utm_source=medium&amp;utm_medium=referral">Sam Loyd</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>One route linked to one main function</h4><p>Here is a way to apply the <em>table of contents</em><strong> </strong>pattern in your <em>Express</em> application.</p><p>A request processed by <em>Express</em> should be associated with a <strong>unique main function</strong> belonging to the controller.</p><p>As a result:</p><ul><li>The <em>Express </em>route handler calls directly the <strong>main controller function.</strong></li><li>The request’s <strong>response </strong>and <strong>status</strong> are sent back from that main function.</li><li>The main function calls a <strong>set of functions.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3YY-a8-kEL8LXHEoXFtbg.png" /><figcaption>One route, one main function</figcaption></figure><p>NB : In the example below, promises are used to process asynchronous flow management. The principle would remain the same by using a <em>Node </em>module such as <em>Async</em>.</p><p><em>Routes file</em></p><pre>app.route(‘/api/route/task0’)<br> .get(controller.mainFunctionTask0)</pre><pre>app.route(‘/api/route/task1’)<br> .get(controller.mainFunctionTask1)<br></pre><p><em>Controller file</em></p><pre>const mainFunctionTask0 = (req, res) =&gt; {<br>    subTask00({ req, res })<br>       .then(subTask01)<br>       .then(subTask02)<br>       .then(subTask03)<br>       .then(handleResponseTask0)<br>       .catch(err =&gt; handlerError(err, req, res))<br>}</pre><pre>const mainFunctionTask1 = (req, res) =&gt; {<br>    subTask10({ req, res })<br>       .then(subTask11)<br>       .then(subTask12)<br>       .then(handleResponseTask1)<br>       .catch(err =&gt; handlerError(err, req, res))<br>}</pre><p>Consequences:</p><ul><li>For each module there are <strong>as many routes as main functions</strong> in the main controller.</li><li>Each main function is divided into a <strong>set of ordered tasks</strong>. This type of structure could be compared to a <strong>table of contents </strong>that helps the reader getting <strong>an overview. </strong>The functions must be named clearly to enable this principle.</li></ul><h4>Use of services</h4><p>To get a clear and readable code you should:</p><ul><li>organize files into a <strong>coherent tree diagram,</strong></li><li>prefer <strong>short and medium-size </strong>files than longer ones,</li><li>sort functions called by the main controller into <strong>services </strong>linked to <strong>categories of tasks or functionalities.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJQlQq6D9AhkgzRGelvP3g.png" /><figcaption>Use of services sorted into thematic files</figcaption></figure><p>Key points:</p><ul><li><strong>One route </strong>is associated with <strong>a unique main function.</strong></li><li>The main functions of the module are put into the controller.</li><li>The intermediate functions are sorted into <strong>services</strong>.</li><li>A service is linked to a <strong>category of tasks</strong>.</li></ul><h3>The Async module</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vOWxX8U8zVZSVepR" /><figcaption>Photo by <a href="https://unsplash.com/@mikeanywhere?utm_source=medium&amp;utm_medium=referral">Mike Lewis HeadSmart Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Objectives</h4><p>The <em>Async</em> module enables you to manage <strong>non-blocking</strong> and <strong>blocking </strong>tasks execution.<br>A complex <strong>task</strong> may be divided into:</p><ul><li>a set of <strong>blocking </strong>tasks (synchronous execution) that may be divided into</li><li>a set of <strong>non-blocking</strong> tasks (asynchronous execution). Each non-blocking task may be divided into a set of blocking tasks, etc.</li></ul><p>This pattern enables you to split the main complex task into <strong>atomic functions</strong>.</p><p>Each task is performed by a function belonging to a service.<br>Consequently, to build algorithms identify:</p><ul><li><strong>independent</strong> tasks,</li><li>tasks that need <strong>other tasks results</strong> to be executed .</li></ul><p>Independent tasks should be executed (as far as possible) in non-blocking mode to improve the execution speed.</p><h4>The Parallel and Waterfall functions</h4><p>The <em>Async </em>module offers a complete set of <strong>flow management</strong> functions. Here are two of them:</p><ul><li><em>Async.waterfall</em> enables to execute a <strong>chronologically ordered</strong> set of functions (blocking execution) and calls a callback function when all tasks are performed.</li><li><em>Async.parallel </em>enables to execute <strong>simultaneously</strong> a set of<br> functions (non-blocking) and execute a callback function when all tasks are performed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03LH33_OWQrPHVo4i5yBHg.png" /><figcaption>Controller main function structure</figcaption></figure><pre>// Main function <br>const mainFunction = (req, res) =&gt; {<br>  async.waterfall([<br>    service.task0,<br>    parallelTasks1and2,<br>    service.task3<br>  ], (err, data) =&gt; {<br>    // Final callback<br>    if (err) {<br>      handleError(err)<br>    } else {<br>      generateResponse(res, data)<br>    }<br>  })<br>}</pre><pre><br>const parallelTasks1and2 = (req, next) =&gt; {<br>  async.parallel([<br>    cb =&gt; service.task1(req, cb),<br>    cb =&gt; service.task2(req, cb) <br>  ], (err, results) =&gt; {<br>    // results === [result1, result2]<br>    req.key1 = results[0]<br>    req.key2 = results[1]<br>    next(err, req)<br>  })<br>}</pre><p><em>Key points:</em></p><ul><li>The <em>Async </em>module permits to manage <strong>asynchronous execution</strong>.</li><li>A task must be divided into <strong>atomic tasks</strong>, easily understandable.</li><li>Atomic tasks must be <strong>ordered </strong>and <strong>sorted</strong> according to their <strong>dependencies</strong>.</li></ul><h3>Global organization and best practices</h3><h4>Principle</h4><p>If a function can be called from any file, the project may quickly look as a spaghetti. <strong>Restricting</strong> the calls of functions facilitates the <strong>clarification </strong>of the architecture.</p><p>Creating rules on services and functions calls generate an understandable<br>organization. There should be a <strong>balance</strong> between <strong>flexibility</strong> and <strong>structure</strong>.<br>The right choice will depend on needs.</p><h4>Rules proposition</h4><p>Here are my own rules on the use of functions and services in an <em>Express </em>application.</p><p>What I <strong>really </strong>avoid:</p><ul><li>Call the controller of module 1 from the routes manager of module 0</li><li>Call a service of module 1 from the controller of module 0</li><li>Call a service of module 0 from a service of module 1</li></ul><p>What I try to avoid (if possible):</p><ul><li>Call a service of module 0 from an other service of module 0</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rcdipHu4oD9kJLaWin11g.png" /></figure><p><em>Key points:</em></p><ul><li>Rules on <strong>modules</strong> and <strong>files</strong> <strong>interactions </strong>enables to build a <strong>readable</strong> project.</li><li>There should be a <strong>balance </strong>between flexibility and structure.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45cd825b81c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-organize-your-express-application-45cd825b81c6">How to organize your Express application</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>