<?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 Guillaume Pichot on Medium]]></title>
        <description><![CDATA[Stories by Guillaume Pichot on Medium]]></description>
        <link>https://medium.com/@guillaume-pichot?source=rss-3ef7ebc13616------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wTDC0a8Spuy5xSPRIDIuzA.jpeg</url>
            <title>Stories by Guillaume Pichot on Medium</title>
            <link>https://medium.com/@guillaume-pichot?source=rss-3ef7ebc13616------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:34:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guillaume-pichot/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[Three Tips For Storing Data Using a Document Database]]></title>
            <link>https://guillaume-pichot.medium.com/three-tips-for-storing-data-using-a-document-database-612ea25011a6?source=rss-3ef7ebc13616------2</link>
            <guid isPermaLink="false">https://medium.com/p/612ea25011a6</guid>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[craftsmanship]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Guillaume Pichot]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 11:14:10 GMT</pubDate>
            <atom:updated>2023-07-07T08:50:17.927Z</atom:updated>
            <content:encoded><![CDATA[<h4>for which I prompted ChatGPT to assist me</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQzpA6ao88YVasMRAk4rhw.png" /><figcaption>Photo by <a href="https://unsplash.com/@mrsunflower94?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Matteo Vistocco</a> on <a href="https://unsplash.com/photos/KOUvMTHK64I?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Document databases have gained popularity due to their flexibility, scalability, and ease of use. When storing data in a document database, it’s crucial to follow best practices to ensure efficient storage, preservation of incoming payloads, and support for access patterns that align with users’ needs.</p><p>In this article, we will explore some of the best practices for storing data in a document database and make it super easy for a user to write, update and retrieve the information it needs.</p><h4>First Tip: Preserving User Provided Payloads</h4><p>When storing information in a document database, one of the key considerations is the preservation of the payload provided by the user. Why is it so important to hold onto that precious payload, you ask? Well, let’s dive in and explore the reasons behind the significance of preserving user-provided data.</p><ol><li>Data Integrity and Consistency</li></ol><p>User-provided payloads contain a wealth of valuable information. By preserving the original payload as a whole, you ensure the integrity and consistency of the stored data. The payload serves as a digital fingerprint, capturing the user’s intentions and the precise state of the data at the time of submission.</p><p>Without preserving the payload, there is a risk of losing or altering crucial details. By holding onto the original payload, you can confidently maintain data consistency and ensure that the information accurately reflects the user’s input.</p><p>2. User Experience and Transparency</p><p>Preserving user-provided payloads can enhance the user experience and foster transparency. Imagine a scenario where a user needs to refer back to the exact information they submitted. By preserving the payload, you empower users with a sense of control and transparency, allowing them to access and review their original input whenever needed.</p><p>Moreover, if discrepancies arise or disputes occur, having access to the preserved payload can serve as a foundation for open and honest communication. It enables you to demonstrate that you respect and value user-provided data, building trust and confidence in your application or service.</p><h4>Second Tip: Storing Data as a Whole</h4><p>In the realm of document databases, one of the fascinating aspects is the ability to store data as a whole, without the constraints of a rigid schema. But why is this schema-less approach so valuable? Let’s explore the advantages of storing data as a cohesive unit while also incorporating specific attributes that facilitate user focused data access.</p><ol><li>Flexibility and Adaptability</li></ol><p>By storing data as a whole, document databases allow for remarkable flexibility and adaptability. Unlike traditional relational databases that require a predefined schema, document databases embrace a more fluid structure. This means that as the data evolves or new requirements emerge, you can seamlessly incorporate additional fields or modify existing ones without the need for complex schema migrations.</p><p>This flexibility enables organisations to respond quickly to changing business needs, experiment with new data models, and iterate on application functionality without being bound by rigid schemas. The ability to store data as a cohesive unit allows for a dynamic and agile approach to data management.</p><p>2. Improved Read and Write Performance</p><p>Storing data as a whole can significantly enhance read and write performance in document databases. When a document contains all the necessary information within its structure, retrieving and manipulating that data becomes more efficient. There is no need for complex joins or multiple queries to gather related information scattered across various tables or collections.</p><p>3. Simplified Data Access and Retrieval</p><p>One of the key benefits of storing data as a whole with accompanying attributes is simplified data access and retrieval. With the complete dataset encapsulated within a single document, accessing and retrieving specific information becomes a breeze. The document acts as a self-contained entity, eliminating the need to traverse multiple relationships or tables.</p><p>By including essential attributes alongside the payload, you can optimise access patterns specific to your application’s requirements focusing on your users’ needs. These attributes act as valuable indexes that accelerate data retrieval, sorting, filtering, and aggregation. This streamlined approach improves the overall performance of your application and enhances the user experience.</p><h4>Third tip: Construct Primary Keys With User Provided Information</h4><p>Constructing primary keys using information available in the data provided by the user brings a plethora of benefits. Not only does it simplify the process of updating and retrieving information, but it also eliminates the need for external systems to store identifiers. Let’s dive into the advantages of constructing primary keys and witness the magic unfold.</p><ol><li>Simplified Updating of Data</li></ol><p>Constructed primary keys using user-provided data offer tremendous convenience when updating information. By leveraging known inputs related to the data being stored, such as unique identifiers like usernames, email addresses, or even parcel tracking numbers, you can effortlessly identify and modify specific documents without the need to know the document’s identifier itself.</p><p>Let’s envision a scenario where a user wants to update the tracking status of a parcel. By constructing the primary key using the parcel’s unique tracking number, for instance, you can effortlessly locate and update the corresponding document. This streamlined approach eliminates the complexity and overhead of searching for identifiers and simplifies the update process, ensuring a seamless and efficient user experience.</p><p>With this approach, users can easily interact with the system using familiar and meaningful identifiers. They don’t need to remember or manage internal document identifiers, making the update process more intuitive and user-friendly. Constructed primary keys using user-provided information simplify data management and ensure a smooth, hassle-free experience for both users and administrators.</p><p>2. Effortless Retrieval of Specific Data</p><p>Constructed primary keys also simplify the retrieval of specific data. By utilising known inputs that uniquely identify the desired information, you can directly access the document without the need to know its internal identifier.</p><p>For instance, consider an application that stores customer information with primary keys constructed using their phone numbers. When a user wants to retrieve their details, they can simply provide their phone number, allowing direct access to the corresponding document. This reduces the complexity of retrieving specific information and enhances the user experience by providing quick and accurate access to the desired document.</p><p>3. Elimination of External Identifier Storage</p><p>Constructing primary keys using available user-provided data eliminates the need for external systems to store internal identifiers. In traditional systems, managing identifiers separately introduces complexity, synchronisation challenges, and potential inconsistencies between the external storage and the database itself.</p><p>By leveraging constructed primary keys composed of information known to the user then you no longer need to expose this primary key. This approach simplifies the architecture, reduces dependencies on external systems, and streamlines the overall data management process.</p><h4>In conclusion</h4><p>Adopting a comprehensive approach to data storage in document databases brings a multitude of benefits. By preserving user-provided payloads, we ensure data integrity, historical analysis, and transparency, fostering trust and confidence in our applications.</p><p>Storing data as a whole in a schema-less manner enhances flexibility, adaptability, and simplifies data access. By including attributes that align with user access patterns, we optimise read and write performance, streamline data retrieval, and empower users with a seamless and efficient experience.</p><p>Furthermore, constructing primary keys from user-provided information eliminates the need for external identifier storage. This greatly simplifies the integration between systems by keeping loosely coupled.</p><p>By embracing these best practices collectively, we unleash the true potential of document databases. We create an environment where user-provided data is valued, preserved, and leveraged for improved performance, enhanced user experiences, and insightful data analysis.</p><p>So, let’s preserve those payloads, store data as a whole in a schema-less manner, incorporate essential attributes, and construct primary keys from user-provided information. By doing so, we unlock a world of possibilities, simplifying data management, elevating user satisfaction, and embracing the full potential of our document databases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=612ea25011a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips for Integrating With External Dependencies]]></title>
            <link>https://medium.com/better-programming/tips-for-integrating-with-external-dependencies-912b6d44663c?source=rss-3ef7ebc13616------2</link>
            <guid isPermaLink="false">https://medium.com/p/912b6d44663c</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Guillaume Pichot]]></dc:creator>
            <pubDate>Wed, 01 Jun 2022 17:41:32 GMT</pubDate>
            <atom:updated>2022-06-01T17:41:32.525Z</atom:updated>
            <content:encoded><![CDATA[<h4>Secure your components by asking these questions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5r5uGjorHbGr2amjxnayA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@diesektion?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Robert Anasch</a> on <a href="https://unsplash.com/s/photos/steampunk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>“Resilience is based on compassion for ourselves as well as compassion for others.” — Sharon Salzberg</blockquote><p>Let’s look at a few things to consider when integrating a component with an external dependency.</p><h3>Is the Connection Secure?</h3><p>Use a secure protocol with encryption when exchanging data with an external dependency. Adopting an encrypted channel as a default strategy will prevent any attackers from accessing information maliciously no matter the location of the attack, whether it is within a local network or over the Internet.</p><h3>Is the Connection Controlled?</h3><p>It is the responsibility of the component that initiates a connection with an external dependency to ensure that such connection is properly managed.</p><ul><li>Use an asynchronous and non-blocking pattern to handle the interaction between a component and the external dependency. As an example, use a Promise to initiate a connection, then react to an event or catch an exception, this being done without blocking other processing.</li><li>Use an acceptable timeout to close hanging connections.</li><li>Adopt a retry strategy where appropriate. Retrying once is often enough.</li><li>Handle back pressure coming from the external dependency. Use a Dead Letter Queue to store failed events and retry these events over a specified retention period to avoid retrying events indefinitely.</li><li>Adopt a defaulting strategy when a connection to an external dependency cannot be established.</li></ul><h3>Are Exceptions Handled?</h3><p>Integrating a component with an external dependency requires an error-handling strategy as things will inevitably go wrong. Either data flowing through will fail the processing or the infrastructure transporting the data will experience outages.</p><p>It is important to differentiate exceptions related to a system failure from exceptions related to the data being exchanged. The reason for it is that the nature of an exception dictates what actions are needed in order to resolve or prevent such an incident.</p><h3>Are Error Logs Useful?</h3><p>The purpose of logging errors is to support the individuals within a team in charge of operating the related component.</p><p>So, error logs need to be shaped in such a way that a human being can quickly access useful information and understand the impact of an error, its origin, and decide on a plan of action.</p><p>Error logs are dated using a timestamp of some sort, like 2022–05–31T15:11:25.349Z.</p><p>Error logs include error codes that quickly help identify the nature of errors and impacted components.</p><p>A proposed format for an error code is[{COMPONENT}-{DEPENDENCY}-{SYSTEM|DATA}]</p><p>As an example, the following code [ABC-XYZ-SYSTEM] tells us that component ABC is experiencing a SYSTEM issue when communicating to the dependency XYZ.</p><p>The error code [ABC-XYZ-DATA] tells us that component ABC is exchanging invalid DATA with the dependency XYZ. It informs about the function within the component that is impacted by this error.</p><p>An error log should also contain a message that confirms the nature of the error in order to confirm the initial assumption driven by the error code.</p><p>As an example, such an error message [ABC-XYZ-DATA] All-But-Crazy failed to submit recipe to Xtra-Yummy-Zinger confirms in plain English the component that is failing the processing of the data returned by the dependency.</p><p>Finally, the error log should include the inputs communicated to a dependency and the outputs received from it. Ideally in a shape that would be easy to query, such as JSON.</p><p>So, a useful error log really looks like this:</p><pre>2022-05-31T15:11:25.349Z [ABC-XYZ-DATA] All-But-Crazy failed to submit recipe to Xtra-Yummy-Zinger.<br>Inputs:<br>{<br>  &quot;ingredient1&quot;: &quot;chocolate&quot;,<br>  &quot;ingredient2&quot;: &quot;sand&quot;,<br>  ...<br>}<br>Outputs:<br>{<br>  &quot;message&quot;: &quot;The value for ingredient2 is not supported: &#39;sand&#39;&quot;<br>}</pre><h3>Are Errors Monitored?</h3><p>Monitoring errors is critical to understanding the health of a system. It helps show the degradation or the improvement of the health of a system over time as the system changes while an ongoing flow of data is processed.</p><p>Monitoring enables refining error handling strategies currently in place in order to continuously improve the resiliency of the system and prevent the recurrence of past incidents.</p><p>Such monitoring can be achieved by creating metrics on error codes that will then be used to create visualisation or set up alerts when necessary.</p><p>Gauge the health of your system through these fine-grained insights. Tune it and decide on the next step.</p><h3>Last But Not Least, Who Are You?</h3><p>Identify the component that integrates with an external dependency. It’s really the bare minimum that one can do prior to engaging in active communication with a third party.</p><blockquote>“Hi, I’m All-But-Crazy. Pleased to meet you.”</blockquote><p>Thanks for reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=912b6d44663c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/tips-for-integrating-with-external-dependencies-912b6d44663c">Tips for Integrating With External Dependencies</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Have You Considered Serverless Yet?]]></title>
            <link>https://aws.plainenglish.io/have-you-considered-serverless-yet-56704b81b3ea?source=rss-3ef7ebc13616------2</link>
            <guid isPermaLink="false">https://medium.com/p/56704b81b3ea</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Guillaume Pichot]]></dc:creator>
            <pubDate>Wed, 08 Dec 2021 05:01:12 GMT</pubDate>
            <atom:updated>2021-12-08T09:52:29.198Z</atom:updated>
            <content:encoded><![CDATA[<h4>The questions organisations need to ask themselves to empower their workforce to change things, make things better, and find new solutions.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iz62DEWesPo0UUJvvSC5tw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@austinchan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Austin Chan</a> on <a href="https://unsplash.com/s/photos/future?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Do you always solve the same problem the same way?</p><p>A simple yes or no question that illustrates the divide that exists in technology companies that can limit or empower businesses to grow and innovate.</p><p>Technology companies’ success is short-lived and the reason for it is technology. Technology is an ongoing evolving force that continuously steers towards reducing the effort required for solving greater problems.</p><p>Many complex problems of the past are no longer obstacles as the industry always figures out better ways of solving known problems by improving on its technology.</p><p>As such, cloud providers continuously offer new services that abstract the complexity of solving complex problems and enable companies to focus on their core business.</p><p>One recent increment to the service offering from cloud providers is Serverless.</p><p>With cloud providers already offering great services for managing and scaling existing infrastructures, how is Serverless any different?</p><p>The thing is, it is different, and also better.</p><p>Just a few years back, start-ups would have been working with servers on-premises. This was a fine way to operate servers by then, directly from an office, and rely on the office network capacity to be sufficient. This was, among other things, a quick way to get things done and bring in more revenue. The risk though was as high as it was underestimated. What if there is a power outage? Think of someone that unplugs a cable to vacuum a floor. What if there is a break-in? What if a company gets so successful with their services that the traffic grows beyond the office network capacity? Scary stuff really, especially because such risks would put a company’s reputation at risk. And once trust is lost, trust is gone.</p><p>Luckily, the industry is never short on new ideas to improve on ways of working, operating complex systems, and starting businesses.</p><p>Since then, servers would be installed in the data center properly secured and powered, applications and services would run on virtualised infrastructure instead of dedicated machines, containers would abstract dependencies on operating systems, and so forth.</p><p>Every time, things just got better and simpler. One reason for it is that companies gradually outsource some of the complexity of operating infrastructure to companies specialised in doing so, while they focus on solving for their core business. This is a powerful force in the industry that cannot be ignored or dismissed. This force needs to be embraced as it enables a company to innovate and compete more efficiently.</p><p>How does adopting Serverless be transformative for a technology company? Let’s explore what Serverless means and its implications.</p><p>Serverless? Really? Surely, there is a server somewhere, there has to be, right? How could we run our software otherwise?</p><p>Well, yes, there are servers in Serverless, but as users of Serverless services, we just don’t worry about it. It is the responsibility of cloud providers to worry about it. What we do as users is to specify our requirements for a given processing. It’s configuration, stupid. We only need to work out a suitable configuration for given processing to work, done. As an example, if processing involves a high volume of data transformation, then allocating a large amount of memory will prevent running out of memory that would slow down the processing. If another processing requires a large number of concurrent executions, then allocating more threads to the processing would prevent thread starvation to handle a flow of incoming requests.</p><p>When adopting Serverless for running software, organisations owning the software outsource to cloud providers the responsibility to run it. Organisations no longer run their software. Organisations no longer operate their software either. Cloud providers do it. And guess what, cloud providers do it very well because that is their expertise and value proposition at the core of their business. It is in their interest to deliver on this as to not lose the trust of companies that operate with their services.</p><p>What do organisations gain out of outsourcing their operations to cloud providers?</p><p>Focus! The fact that operating the infrastructure is becoming effortless when organisations adopt gradually cloud capabilities, enables these organisations to focus their effort on building the technology that supports their core business. The equation is simple:</p><blockquote>Less distraction means greater focus. Greater focus yields to better execution and higher quality. And it eventually yields to better products, faster.</blockquote><p>Innovation! As organisations explore new business opportunities, focusing on building quickly solutions that support new ideas and being able to demonstrate the value of these ideas can be accelerated by reducing as much as possible the friction on the path to production for a new service or application. Serverless achieves this as teams only need to implement the core functions specific to an idea without worrying about the infrastructure that will run it. It means that pretty much 100% of the engineering effort within an organisation can be dedicated to innovating and supporting the core functions of a business.</p><p>Cost and Risk! Cloud providers have greatly transformed the way organisations pay for a service, hardware, licenses. Organisations no longer need to put a large up-front investment to try out an idea. Organisations no longer need to budget for buying hardware or licenses that would eventually be needed if the idea succeeds. The only thing Organisations need to focus on is human beings, their workforce, and allocate their workforce in the most efficient way as to produce the most value. That’s it. As for the cost of implementing new systems, simple or highly complicated, well, it’s close to nothing. Organisations would pay for the number of resources they consume from a cloud provider. A development cycle would consume very little resources. Even when a solution is production-ready and live, it would only start costing money when the solution receives traffic and becomes successful. This means, ideally, when it starts generating revenue. And if it does not work, just kill it, no harm done. It is an opportunity for organisations to pivot, try out new ideas, and refine their strategy.</p><p>So, how do we get started with Serverless?</p><p>Organisations need to ask themselves the questions that will empower their workforce to change things, make things better and find new solutions.</p><p>Is <em>{this}</em> core to our business? Does <em>{this} </em>support or strategy? Is there a more efficient way for solving <em>{this}? </em>What is the risk of outsourcing <em>{this}</em>? What if we no longer need to do <em>{this}</em>, how would that look like?</p><p>It’s up to an organisation, a department, a team, an individual to define {this} and get started.</p><p>Thank you for reading.</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><em>free weekly newsletter here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56704b81b3ea" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/have-you-considered-serverless-yet-56704b81b3ea">Have You Considered Serverless Yet?</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Few Simple Tips for Implementing Kick-Ass APIs]]></title>
            <link>https://javascript.plainenglish.io/few-tips-for-implementing-kick-ass-apis-2c563670fff8?source=rss-3ef7ebc13616------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c563670fff8</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Guillaume Pichot]]></dc:creator>
            <pubDate>Tue, 09 Nov 2021 09:28:31 GMT</pubDate>
            <atom:updated>2021-11-12T13:43:36.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGPgMa-poSycJJUWlacUOw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@justinveenema?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Justin Veenema</a> on <a href="https://unsplash.com/s/photos/kick-ass?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this article, I will be sharing tips learned from experience about implementing APIs, kick-ass APIs!</p><p>Why implement APIs in the first place?</p><p>An API is a great way to define a boundary that defines the interaction between API users and API providers. This achieves the following outcomes:</p><ul><li>API users know only about what an API does and how to integrate with it successfully, and do not require knowledge of its underlying implementation.</li><li>API providers document what an API does and how to use it, and retain the freedom of changing the underlying implementation of the API as they see fit.</li></ul><p>What makes an API a kick-ass API?</p><p>A kick-ass API is defined by its ease of use. It should be easy for API users to understand what an API operation does, its inputs and its outcome. It should be easy to integrate, easy to test, and safe to operate.</p><p>Also, a kick-ass API never breaks, continuously evolves, delivers value, scales and performs accordingly.</p><p>What kind of APIs make for kick-ass APIs?</p><p>Let’s start with the ones that do not make for kick-ass APIs: Web Services, SOAP, XML/Atom-based APIs. Although these types of APIs have proven to work and deliver great value, tremendous value even, they have also proven to be tremendously costly to integrate, maintain, evolve, operate, change, retire, decommission, exterminate… It is a minefield yielding to over-engineered, overcomplicated and coupled systems.</p><p>What is left then?</p><p>Well, we might have read about REST, HATEOAS, Richardson Maturity Model… All fine and good… elegant, smart, clever… sometimes genius. But is this the perspective of API users or API providers? I have to admit that there is an engineering delight into achieving the highest level of maturity in the Richardson Maturity Model which yields to a glorified REST API! But honestly who cares? Do API users see the same great glory in this model or is it just an over-engineered API yet again?</p><p>So what then?</p><p>Well, a good principle here is to <em>Keep Things Simple Stupid</em>. HTTP is a great specification of a protocol that defines the semantic that API users would expect and API providers should support.</p><p>Is that it then? HTTP really? What about the content type to transport data?</p><p>JSON is a good one, <em>JavaScript Object Notation, </em>I love it. It is concise enough, readable, easy to learn and easy to shape. It has everything an API needs to handle data, no more, no less. Also, it comes with a schema, which is a handy way to specify and validate the shape of the things that an API supports.</p><p>Are we saying that HTTP and JSON are the keys to implementing kick-ass APIs? Isn’t this the same as REST?</p><p>Well, not quite, it is a simplification over REST, a style that exposes HTTP endpoints as operations able to process data in JSON, without the complexity of managing resources exposed in a REST API via their URIs.</p><p>But there is more to it, and this lands with solving a complex problem via a simple interface. Remember:</p><blockquote>Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away (Antoine de Saint-Exupéry)</blockquote><p>Great APIs focus on users’ needs and offer intelligent ways to fulfil these needs by adopting a language understood by their users.</p><p>As APIs are a way to communicate information between two parties, great APIs adopt a language that resonates with the one spoken by their users. Defining such language should drive the naming of endpoints and the naming of the things processed by the API. It is key to elevate an API to the level where users can reason about this API and understand how they will use it to support their functional needs without having to translate their domain into technical terms.</p><p><em>Domain Driven Design</em> and the exercise of defining the <em>ubiquitous language</em> spoken by both API users and API providers will greatly contribute to the ease of use of an API, prior to anything being implemented. As an API is designed, it is the responsibility of API providers to ensure that the language spoken by their APIs is understood by their targeted API users and resonates with their users’ needs. It is then critical to capture this information by engaging early with API users, showing these users drafts of the API, and functional scenarios supported by the API. Demos, workshops, inviting customers, but also looking at how other companies do it, all contribute to an ongoing feedback loop that will help API providers design kick-ass APIs.</p><p>There are usually two classes of problems that APIs solve:</p><ul><li>Ingesting data</li><li>Accessing data</li></ul><p>On the data ingestion side, let’s try to make it as easy as possible for API users to ingest the data needed by API providers.</p><p>What can we do to make data ingestion easy?</p><p>Find out about the origin of the data that API users are intended to ingest, shape it using a language that is easy to match with API users backend systems, and make the effort required for successfully ingesting data as little as possible in order to start operating with the API successfully. As an example, design your API to require only the minimum amount of information that is absolutely critical to the underlying system and leave the rest optional. Let API users decide what additional data can be added, for which purposes, so that API users gradually increase the value achieved by their API integration.</p><p>Ideally, as long as the data being ingested is compliant with the schema specified in API definition, API producers should just accept it, and then let internal processes enrich this data to deliver the targeted value.</p><p>On the data access side, API users need to access the information they need using the information they know. So, API providers should focus on exposing and enriching access patterns that will best support their users. Defining how information is accessed is critical to the ease of integrating with APIs. The good news is that such access patterns are already known as they can be derived from the language spoken by API users when they talk about their functional needs. And when API providers get this right, it makes for a kick-ass APIs!</p><p>What about making APIs safe to use and safe to operate?</p><p>It is the responsibility of API providers to guarantee that APIs can be used safely by their API users. This can take many different shapes and forms driven by what APIs do and the nature of the data being processed.</p><p>API providers should know about who uses their APIs using adequate identification mechanism of their API users. They should also ensure that API users are authorised accordingly when ingesting and accessing data as to guarantee the integrity of the data being processed by their APIs. Transport of the data should be encrypted obviously. As for storage, it has to be done in accordance with the sensitivity of this data (encode, encrypt, redact).</p><p>At the end of the day, API users decide if an API deserves the title of kick-ass API, only then can API providers claim that they have done it!</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c563670fff8" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/few-tips-for-implementing-kick-ass-apis-2c563670fff8">A Few Simple Tips for Implementing Kick-Ass APIs</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Processing Pipeline With JavaScript Step by Step]]></title>
            <link>https://guillaume-pichot.medium.com/implementing-a-processing-pipeline-with-javascript-step-by-step-13f2ce0ebdee?source=rss-3ef7ebc13616------2</link>
            <guid isPermaLink="false">https://medium.com/p/13f2ce0ebdee</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[processing-pipeline]]></category>
            <category><![CDATA[better-programming]]></category>
            <dc:creator><![CDATA[Guillaume Pichot]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 14:56:01 GMT</pubDate>
            <atom:updated>2021-10-05T10:37:03.522Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rristvaRG29tPBljv_4A5Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ernestovdp?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ernesto Velázquez</a> on <a href="https://unsplash.com/s/photos/spiral-steps?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>What is a processing pipeline exactly?</p><blockquote>A processing pipeline is a design pattern made of a chain of steps that compose the domain logic of a function where a step processes the result from a previous step and yields its result to the following step in the chain.The function returns the result yielded by the final step of the processing pipeline.</blockquote><p>Now that we have a definition for a processing pipeline, let’s define the problem that we will be solving in this article as to give us a bit more substance to work with.</p><p>The problem is rather simple and is stated as follow:</p><blockquote>Given a criteria, I want to delete all authorised items that matches this criteria from the database where these items are stored.</blockquote><p>Understanding the problem statement is key to defining the steps that compose the domain logic required to solve this problem. Identifying these steps does not require implementing code up front and can be part of the overall analysis for solving a problem. What are these steps then?</p><p>Given a criteria implies that such criteria is required in order to proceed with the operation, this leading to some form of validation to ensure that a criteria is provided.</p><p>Authorised items implies that the caller on such operation can be identified in order to ensure that the caller can only delete items for which they are authorised.</p><p>Delete all items that matches a criteria implies that the criteria defines the condition for finding the items for which the caller is requesting deletion.</p><p>From the database where these items are stored does not constitute a step part of the processing but identifies an external dependency that we will have to deal with eventually in our implementation. Dealing with external dependencies should remain a separate concern that does not interfere with the implementation of the domain logic.</p><p>How does this translate in terms of steps? Maybe something like this:</p><pre>validate that the criteria is provided<br>then proceed with:<br>  retrieve all items matching the criteria<br>  retain authorised items only<br>  delete each item<br>  respond with the number of deleted items<br>else reject with:<br>  throw an error</pre><p>For the remainder of the article, I will walk you through step by step how to implement a solution to this problem that adopts the processing pipeline design pattern using JavaScript. I will use <em>Test Driven Development </em>as the practice for driving the implementation and I will include examples for refactoring functions from an imperative programming style to a declarative programming style. I will also share techniques to deal with external dependencies and I will explain how to abstract and mock such dependencies while focusing on implementing the domain logic.</p><p>First, let’s define the contract for the function that we need to implement. This function accepts a criteria and the caller identifier, and returns the number of items deleted or throw an exception in case of an error.</p><pre>deleteItemsByCriteria(criteria: string, callerId: string) throw exception: int</pre><p>Now that we have define a contract for our implementation, we can setup our JavaScript project using NPM and start coding. A few commands should be enough to get us running.</p><pre>&gt; npm init ...<br>test command: &#39;nyc mocha&#39;</pre><p>We will install the following dependencies that we will be using for testing our implementation.</p><pre>&gt; npm install chai chai-as-promised mocha nyc --save-dev</pre><p>Next, we need to create the directory and the file that will contain our tests.</p><pre>&gt; mkdir test<br>&gt; touch test/processing_pipeline_test.js</pre><p>And the folder and file that will contain our implementation.</p><pre>&gt; mkdir src<br>&gt; touch src/processing_pipeline.js</pre><p>We can now start implementing our function driven by an initial test where we expect the function to reject the call by throwing an exception when no criteria is provided. We will use the async keyword to our function declaration, and expect our function to return a promise that will be rejected.</p><pre>const chai = require(&#39;chai&#39;);<br>const chaiAsPromised = require(&#39;chai-as-promised&#39;);<br>const { expect } = chai;</pre><pre>chai.use(chaiAsPromised);</pre><pre>const { deleteItemsByCriteria } = require(&#39;../src/processing_pipeline&#39;);</pre><pre>describe(&#39;Delete items by criteria&#39;, () =&gt; {<br>  it(&#39;should reject the call by default&#39;, async () =&gt; {<br>    return expect(deleteItemsByCriteria()).to.be.rejected;<br>  });<br>});</pre><p>The initial implementation for our function could look like this:</p><pre>const deleteItemsByCriteria = async (criteria, callerId) =&gt; { throw new Error() };</pre><p>We run the test and ensure that our project is correctly configured.</p><pre>&gt; npm test</pre><pre>Delete items by criteria<br>    ✔ should reject the call by default</pre><pre>1 passing (7ms)</pre><p>This initial step helps setup the test harness that we will be utilising to gradually implement and evolve the domain logic for this function.</p><p>At this point, the implementation is simple enough that refactoring is not needed prior to writing the next test.</p><p>This is a good place for committing our implementation. We will use Git for source control.</p><pre>&gt; git init<br>&gt; echo node_modules/ &gt;&gt; .gitignore<br>&gt; echo .nyc_output/ &gt;&gt; .gitignore<br>&gt; git add .<br>&gt; git commit -m &quot;Delete items by criteria rejects the call by default&quot;</pre><p>Moving forward with our next test, we want to start working on the happy path for our function. The second tests is to ensure that no items are deleted when the criteria does not match.</p><pre>it(&#39;should not delete items when the criteria does not match&#39;, async () =&gt; {<br>  const result = await deleteItemsByCriteria(&#39;NO_MATCH&#39;);<br>  expect(result).to.eq(0);<br>});</pre><p>In order to get this test to pass we will introduce a first check that verifies that the criteria is provided to the function in order to return a result.</p><pre>const deleteItemsByCriteria = async (criteria, callerId) =&gt; {<br>  <strong>if (criteria) {<br>    return 0;<br>  }</strong><br>  throw new Error();<br>};</pre><p>Our second test is passing, and this gives us the chance to refactor our function prior to implementing the next test.</p><pre>const deleteItemsByCriteria = async (criteria, callerId) =&gt; <strong>criteria ? proceed() : reject()</strong>;</pre><pre><strong>const proceed = () =&gt; 0;</strong></pre><pre><strong>const reject = () =&gt; { throw new Error() };</strong></pre><p>At this point, we have introduced a disjunction by validating that the criteria is provided so that our implementation can handle the happy path within the proceed function and the unhappy path for exceptions implemented by the reject function. Let’s commit and move on.</p><p>The next thing that we want to cover with our tests is that an item should be deleted when the criteria matches.</p><pre>it(&#39;should delete one item when the criteria matches&#39;, async () =&gt; {<br>  const result = await deleteItemsByCriteria(&#39;MATCH&#39;);<br>  expect(result).to.eq(1);<br>});</pre><p>This requires us to modify our implementation and pass the value of the criteria to the proceed function so that we can distinguish cases when items are matching the given criteria or not.</p><pre>const deleteItemsByCriteria = async (criteria, callerId) =&gt; criteria ? proceed(<strong>criteria</strong>) : reject();</pre><pre>const proceed = (<strong>criteria</strong>) =&gt; {<br>  <strong>return STUB_ITEMS[criteria] || 0;</strong><br>};</pre><pre><strong>const STUB_ITEMS = { MATCH: 1 };</strong></pre><p>In this step we are also introducing a stub for handling the items that we want to delete. This stub will eventually be replaced by the database integration, but such integration is not needed yet as we are still focusing on implementing the domain logic.</p><p>Looking at what the function proceed currently does, it looks up and return the number of items that will eventually be deleted. Unfortunately, when reading the implementation, it does not quite stands out. Let’s try to refactor our implementation as to make this more visible.</p><p>First, let’s introduce a function that validates our criteria and will return a promise that yields the criteria when it is provided, or throws an exception when the criteria is undefined. This can be done simply by using the keyword async .</p><pre>const deleteItemsByCriteria = async (criteria, callerId) =&gt; <strong>validate(criteria).then(proceed)</strong>;</pre><pre><strong>const validate = async (criteria) =&gt; criteria ? criteria : reject();</strong></pre><p>Introducing this refactoring is a key step towards turning a function written in an imperative style towards a function written in a declarative style. Adopting a declarative syntax is what will enable implementing a function using the <em>processing pipeline design pattern</em> as it gives us the opportunity to increment the complexity of the domain logic by implementing the steps that compose the domain logic as small functions that will be chained using promise.then() function. Refactoring done, let’s commit and move on to the next test.</p><p>The next test is to ensure that all items that match the given criteria will eventually be deleted from the database.</p><pre>it(&#39;should delete all items when the criteria matches&#39;, async () =&gt; {<br>  const result = await deleteItemsByCriteria(&#39;MATCH_MANY&#39;);<br>  expect(result).to.eq(2);<br>});</pre><p>One of the issue that we are now experiencing with our tests is the lack of visibility regarding the way data is setup in order to get our tests to pass. Although we introduced a stub within our implementation, the stub is hidden from the tests making it difficult to understand why our tests are passing. We can fix this by introducing a mock in our tests that will override the behaviour of a function in the module that we are testing.</p><p>We will need to install a new package proxyquire that we will use for mocking.</p><pre>npm install proxyquire --save-dev</pre><p>We will then introduce a new module data_store with a retrieveItems function that defines the abstraction layer with the database that contains items.</p><p>New file for the module:</p><pre>&gt; touch src/data_store.js</pre><p>Content for the new data_store module:</p><pre>const retrieveItems = (criteria) =&gt; undefined;</pre><pre>module.exports = { retrieveItems };</pre><p>We will then use the retrieveItems function in the proceed function as follow</p><pre>const { retrieveItems } = require(&#39;./data_store&#39;);</pre><pre>const proceed = (criteria) =&gt; {<br>  return <strong>retrieveItems(criteria).length</strong>;<br>};</pre><p>We can now update our tests and introduce the mock for the function retrieveItems in the data_store module.</p><p>Replace the import of the deleteItemsByCriteria function:</p><pre>const { deleteItemsByCriteria } = require(&#39;../src/processing_pipeline&#39;);</pre><p>With the following:</p><pre>const proxyquire = require(&#39;proxyquire&#39;);</pre><pre><strong>const retrieveItemsStub = (criteria) =&gt; ITEM_STUBS[criteria];</strong></pre><pre>const ITEM_STUBS = {<br>  NO_MATCH: [],<br>  MATCH: [{}],<br>  MATCH_MANY: [{}, {}]<br>}</pre><pre><strong>const { deleteItemsByCriteria } = proxyquire(&#39;../src/processing_pipeline&#39;, { &#39;./data_store&#39;: { retrieveItems: retrieveItemsStub } });</strong></pre><p>Our test now specifies which values should be returned by the data store layer for a given criteria. All tests should now be passing following this refactoring so let’s commit.</p><p>The next test to implement will ensures that only items authorised to a caller are deleted. We will add a <em>ownerId </em>field to the item object which identifies the owner of the item that needs to match the caller identifier in order to authorise the deletion of the item.</p><pre>const ITEM_STUBS = {<br>  NO_MATCH: [],<br>  MATCH: [{ <strong>ownerId: &#39;LEGIT&#39; </strong>}],<br>  MATCH_MANY: [{ <strong>ownerId: &#39;LEGIT&#39; </strong>}, { <strong>ownerId: &#39;LEGIT&#39; </strong>}]<br>};</pre><pre>it(&#39;should not delete items when the caller is not authorised&#39;, async () =&gt; {<br> const result = await deleteItemsByCriteria(&#39;MATCH_MANY&#39;, &#39;PIRATE&#39;);<br> expect(result).to.eq(0);<br>});</pre><p>This is a new step within the domain logic that will filter authorised items using the caller identifier from the ones retrieved by the criteria.</p><pre>const deleteItemsByCriteria = async (criteria, callerId) =&gt; validate(criteria).then((validCriteria) =&gt; proceed(<strong>validCriteria</strong>, <strong>callerId</strong>));</pre><pre>const proceed = (criteria, callerId) =&gt; {<br>  return retrieveItems(criteria).<strong>filter((item)=&gt; {<br>    const { ownerId } = item;<br>    return ownerId === callerId;<br>  })</strong>.length;<br>};</pre><p>This change is enough to get our new test to pass. We still need to fix our previous tests so that a legit callerId is passed when calling the deleteItemsByCriteria function.</p><pre>it(&#39;should delete one item when the criteria matches&#39;, async () =&gt; {<br>  const result = await deleteItemsByCriteria(&#39;MATCH&#39;, <strong>&#39;LEGIT&#39;</strong>);<br>  ...<br>});<br>...</pre><p>All tests should be passing now. The domain model for an <em>Item </em>is taking shape. The domain logic though remains a bit difficult to read and understand. We will refactor the <em>deleItemsByCriteria</em> function so that we make the steps in this function more visible.</p><p>Let’s add a new function <em>filterUnauthorisedItems </em>for the filtering step.</p><pre>const filterUnauthorisedItems = (items, callerId) =&gt; {<br>  return items.filter((item) =&gt; {<br>    const { ownerId } = item;<br>    return ownerId === callerId;<br>  });<br>};</pre><p>Now, we want to make the steps for retrieving items and filtering items visible in the <em>deleteItemsByCriteria </em>function. We can achieve this by chaining these functions using <em>promise.then()</em>.</p><pre>const deleteItemsByCriteria = async (criteria, callerId) =&gt; {<br>  return validate(criteria)<br>    <strong>.then(retrieveItems)<br>    .then((candidates) =&gt; filterUnauthorisedItems(candidates, callerId))<br>    .then((authorisedItems) =&gt; authorisedItems.length);</strong><br>}</pre><p>We can delete the <em>proceed</em> function which has been replaced by the chain of steps added to the promise created by the initial validation step.</p><p>With this refactoring, the <em>deleteItemsByCriteria </em>function is now written as a <em>processing pipeline</em> that describes the steps to perform in the domain logic. This syntax will greatly reduce the effort needed for adding steps to the domain logic as its complexity increases to satisfy new requirements.</p><p>We have now achieved our goal to implement our function as a processing pipeline. Let’s commit and move on with writing our final test.</p><p>The final test will ensure that the authorised items that match the given criteria will actually be deleted from the datastore.</p><p>We will add an <em>id </em>field to the <em>Item </em>that will be used when calling a new <em>deleteItem</em> function in the <em>data_store</em> module. We will mock the <em>deleteItem</em> function to capture the identifiers of the items that have been deleted.</p><pre>const ITEM_STUBS = {<br>  NO_MATCH: [],<br>  MATCH: [{ <strong>id: &#39;ID0&#39;</strong>, ownerId: &#39;LEGIT&#39; }],<br>  MATCH_MANY: [{ <strong>id: &#39;ID1&#39;</strong>, ownerId: &#39;LEGIT&#39; }, { <strong>id: &#39;ID2&#39;</strong>, ownerId: &#39;LEGIT&#39; }]<br>};</pre><pre><strong>let deletedItemIds = [];</strong></pre><pre><strong>const deleteItemStub = async (id) =&gt; { <br>  deletedItemIds.push(id);<br>  return id;<br>};</strong></pre><pre>const { deleteItemsByCriteria } = proxyquire(&#39;../src/processing_pipeline&#39;, {<br>  &#39;./data_store&#39;: {<br>    retrieveItems: retrieveItemsStub,<br>    <strong>deleteItem: deleteItemStub</strong><br>  }<br>});</pre><pre><strong>beforeEach(&#39;Reset data store stub&#39;, () =&gt; {<br>  deletedItemIds = [];<br>});</strong></pre><pre>it(&#39;should delete items authorised to the caller using the item identifier&#39;, async () =&gt; {<br>  await deleteItemsByCriteria(&#39;MATCH_MANY&#39;, &#39;LEGIT&#39;);<br>  expect(deletedItemIds).to.deep.equal([&#39;ID1&#39;, &#39;ID2&#39;]);<br>});</pre><p>As for the implementation, the data store now looks like this:</p><pre>const retrieveItems = (criteria) =&gt; undefined;</pre><pre><strong>const deleteItem = async (id) =&gt; undefined;</strong></pre><pre>module.exports = { retrieveItems, <strong>deleteItem</strong> };</pre><p>It is fine for now to keep the implementation of these methods undefined. They will eventually be implemented as the integration layer to the database.</p><p>The <em>deleteItemsByCriteria</em> function is now enriched with a new step that will delete all authorised items, and yields the list of deleted item ids.</p><pre>const { retrieveItems, <strong>deleteItem</strong> } = require(&#39;./data_store&#39;);</pre><pre>const deleteItemsByCriteria = async (criteria, callerId) =&gt; {<br>  return validate(criteria)<br>    .then(retrieveItems)<br>    .then((candidates) =&gt; filterUnauthorisedItems(candidates, callerId))<br>    <strong>.then((authorisedItems) =&gt; deleteAllItems(authorisedItems))</strong><br>    .then((deletedItemIds) =&gt; deletedItemIds.length);<br>}</pre><pre><strong>const deleteAllItems = async (items) =&gt; {<br>  return Promise.all(items.map((item) =&gt; {<br>    const { id } = item;<br>    return deleteItem(id);<br>  }));<br>};</strong></pre><p>Et voilà!</p><p>Let’s summarise what we have achieved by doing this exercise.</p><p>By using JavaScript <em>promise, </em>we successfully manage to:</p><ul><li>Turn an imperative function into a declarative function.</li><li>Implement a processing pipeline to describe the steps that compose the domain logic of a function.</li><li>Add new steps to a processing pipeline with little effort.</li><li>Parallelise asynchronous operations within the processing pipeline.</li></ul><p>By driving our implementation from our tests, we successfully manage to:</p><ul><li>Refactor the implementation with confidence.</li><li>Evolve the domain model and domain logic incrementally.</li><li>Stub external dependencies that abstract a database.</li><li>Specify the expected behaviour of our function.</li></ul><pre>Delete items by criteria<br>    ✔ should reject the call by default<br>    ✔ should not delete items when the criteria does not match<br>    ✔ should delete one item when the criteria matches<br>    ✔ should delete all items when the criteria matches<br>    ✔ should not delete items when the caller is not authorised<br>    ✔ should delete items authorised to the caller using the item identifier</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13f2ce0ebdee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Turning an Imperative Function Into a Declarative One]]></title>
            <link>https://guillaume-pichot.medium.com/the-art-of-turning-a-imperative-function-into-a-declarative-one-240ade3c04d6?source=rss-3ef7ebc13616------2</link>
            <guid isPermaLink="false">https://medium.com/p/240ade3c04d6</guid>
            <category><![CDATA[data-transformation]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[declarative-programming]]></category>
            <category><![CDATA[better-programming]]></category>
            <dc:creator><![CDATA[Guillaume Pichot]]></dc:creator>
            <pubDate>Fri, 16 Jul 2021 15:46:07 GMT</pubDate>
            <atom:updated>2021-10-01T08:29:37.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uaFBdLVAFHKmZnaLKPp3BQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@wes_c">Wes Carpani</a> on Unsplash</figcaption></figure><p>Implementing software using a programming language is an art equivalent to writing a novel as it requires practice and experience to make the best use of a language in order to write a compelling story or program.</p><p>There are two main programing paradigms that a developer can use when writing a program:</p><ul><li>imperative (procedural, object-oriented)</li><li>declarative (functional, reactive)</li></ul><p>Each paradigm is valid as the same thing can be achieved in many ways and styles when programming. The difference is that a paradigm suits a language better than others and that some languages are more expressive than others. This means that adopting the best suited paradigm to a language when writing software will bring the greatest value towards the quality of the code produced for running such software. The achieved quality will be critical to maintain, evolve and change an implementation as it enables a human being to reason about it by lowering its cognitive complexity.</p><p>When writing a program by adopting an imperative approach such as procedural code, a developer takes on the responsibility of implementing not only the logic required for this program but also of ensuring that a program is safe to run and handles edge cases and unexpected issues seamlessly. This results in writing additional defence mechanisms as to protect a program from failing which result in additional complexity and more code to maintain.</p><p>In this article, I will take as an example a procedure that performs a “complex” logic and identify how to modify this procedure by adopting a more declarative style of programming. I will also use JavaScript as the language for the implementation.</p><p>And here it is, a trully magnificent procedure:</p><pre>function transformStringOfTokensIntoArrayOfUpperCaseTokens (stringOfTokens, separator) {</pre><pre>  let result = [];<br>  if (stringOfTokens !== undefined &amp;&amp; separator !== undefined) {<br>    if (stringOfTokens === &#39;&#39;) {<br>      return result;<br>    } else {<br>      const tokens = stringOfTokens.split(separator);<br>      for (let i = 0; i &lt; tokens.length; i++) {<br>        result.push(tokens[i].toUpperCase());<br>      }<br>      return result;<br>    }<br>  } else {<br>    return result;<br>  }<br>};</pre><p>Let’s try to understand what this procedure does and let’s step in the shoes of a developer who would read it for the first time.</p><p>Looking at it, this procedure is implemented as a function in Javascript. It seems to be a rather old way of writing a function and does not use the more modern syntax supported by the language. From reading its name, it can be used to split a string with a given separator into an array of upper case tokens. But what does it do exactly?</p><p>Let’s see what the pseudo code for the logic look like:</p><pre>- Define the default result of the function to be an empty array<br>- Verify that the parameters are defined otherwise return the default result<br>- If the string parameter is empty return the default result<br>- Otherwise split the string using the separator into an array of token<br>- Upper case each token and add them to the result<br>- Return the result that contains the upper case token in the array</pre><p>This function does a lot of things in order to ensure that it is safe to execute and produce the expected result. This means that the developer had to implement all of these checks and the actual transformation logic as to guarantee that the procedure will not fail even when processing edge cases.</p><p>But is this what was really required? All this complexity for turning a string into an array of upper case tokens?</p><p>How could we describe the transformation that is required instead in a succession of logical steps?</p><p>Maybe it could look like this:</p><pre>&gt; From a given string and given a separator<br>| Split the string using the separator into an array<br>| Then upper case each item in the array<br>| Then return the array</pre><p>OK, that’s interesting, now the same logic is represented as a succession of steps where each step takes an input and yields a result. But how could we implement this?</p><pre>const transformStringOfTokensIntoArrayOfUpperCaseTokens = (stringOfTokens = &#39;&#39;, separator = &#39;&#39;) =&gt; {<br>  <br>  return stringOfTokens.split(separator)<br>    .map((item) =&gt; item.toUpperCase);<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uaFBdLVAFHKmZnaLKPp3BQ.jpeg" /></figure><p>Is that it really?</p><p>So what has changed with this new implementation?</p><p>Looking at it, although this implementation achieves exactly the same procedure as the previous one, there are fundamental differences to it.</p><p>It uses a more modern syntax and uses additional capability of the language like defining a default value on the parameters in order to handle edge cases.</p><p>It also use a more declarative syntax that describe the processing that needs to be performed on the input which greatly reduces the cognitive complexity of the implementation. Indeed, each step is clearly defined and quite easy to understand as it only does one thing.</p><p>In summary, implementing a procedure that performs complex operations for transforming an input to a result is all about understanding the logical steps of the transformation and orchestrating these steps into a succession of small operations where each operation yields its result to the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=240ade3c04d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What can I do about it?]]></title>
            <link>https://guillaume-pichot.medium.com/what-can-i-do-about-it-1fddf8511ef2?source=rss-3ef7ebc13616------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fddf8511ef2</guid>
            <category><![CDATA[change-your-life]]></category>
            <category><![CDATA[empowerment]]></category>
            <category><![CDATA[take-control]]></category>
            <category><![CDATA[take-control-of-your-life]]></category>
            <category><![CDATA[awareness]]></category>
            <dc:creator><![CDATA[Guillaume Pichot]]></dc:creator>
            <pubDate>Tue, 11 May 2021 15:01:05 GMT</pubDate>
            <atom:updated>2021-06-02T09:52:51.621Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixfEWwS-60p2TNEZRycrvA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@shotbyrain?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ave Calvar</a> on <a href="https://unsplash.com/s/photos/hands?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I often find myself in a situation where the things I see or hear bother me to the point where I feel frustrated, angry, upset. It can be such strong feelings that my behaviour towards people would be impacted and my relationship with them would suffer. And this happens over and over again, every day. So, what can I do about it?</p><p>I need to find a way to take control over a situation that impacts me so that I can decide what to make of such situation and reassess the way I feel about it. Recognising that my feelings are impacted by what I see or hear is a first step in the process of taking control. I call it Awareness.</p><p>As I recognise that something is wrong with the way I feel towards a particular situation, I create the opportunity to address this initial reaction, process it with my observations and articulate a response. It is a natural and instinctive trait to react to what we see or hear. Such reactions can drive strong feelings which are greatly influenced by our environment and state of mind. Now I that I am aware of this reaction, I can take the next step to process it. I call it Acknowledgment.</p><p>The act of acknowledgment is the key step towards gaining control of a situation. As I acknowledge the need for understanding the reasons for my feelings, I have actively made the first decision to do something about the situation that triggered such feelings. And this is a powerful first act as it enables the process that will eventually lead to a decision. I go through this process by asking myself questions and by trying to find answers to these questions. Why am I feeling like this? Would I have done things differently? What is this really about? What outcome would I like? Is this a priority for me?… This exercise of questioning a situation based on observable facts enables for constructing a better understanding of a situation, decoupled from an initial reaction. I call this step Exploration.</p><p>Exploration consist of acquiring information about something unknown by closing the gaps between what I know and what I observe. From my observations I have naturally made assumptions. By exploring, I give myself the opportunity to prove or disprove my assumptions and refine my understanding of a situation. Now that I have a clear appreciation of a situation I can start formulating a response. I call this last step Acting.</p><p>As I formulate my response, I will have answered the question “what can I do about it?”, ‘it’ referring to both the situation and my feelings regarding this situation. I can decide to act on this situation as I believe that there is something in my control that I can do to address it or I can decide that this situation is not to be addressed. There will be many reasons why I will decide one way or the other, and exploring this situation would have helped me with assessing its importance, its priority, and the impact that I can have about it. The act of deciding will turn an initial feeling towards a situation into the stronger feeling of empowerment, regardless of the choice that I have made to do something about it or not.</p><p>Awareness, Acknowledgement, Exploration and Acting is the framework that I use every day to find ways of addressing new situations by achieving this empowering feeling that will help myself and the people around me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fddf8511ef2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[There is no value in being right]]></title>
            <link>https://guillaume-pichot.medium.com/there-is-no-value-in-being-right-ccaa6e2ef49a?source=rss-3ef7ebc13616------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccaa6e2ef49a</guid>
            <category><![CDATA[rigtht]]></category>
            <category><![CDATA[behaviour]]></category>
            <category><![CDATA[wrong]]></category>
            <category><![CDATA[serving]]></category>
            <category><![CDATA[values]]></category>
            <dc:creator><![CDATA[Guillaume Pichot]]></dc:creator>
            <pubDate>Thu, 21 Jan 2021 15:41:20 GMT</pubDate>
            <atom:updated>2021-01-22T12:15:24.522Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eoJAFB4mDXMgNII96GfTFg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@thematthoward?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Matt Howard</a> on <a href="https://unsplash.com/s/photos/journey?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>For a long time, I thought that being right was the most important thing to pursue, that there was tremendous value in being right and that it was expected by my peers that I had to be right. I wanted to have the right idea, share the right opinion, come up with the right solution to any problems. This was particularly true at the time I entered adulthood as I wanted to assert my authority with my peers. And this need of always being right has caused me and my peers lots of harm.</p><p>At the time, I was more interested in being right rather than doing the right thing, and this drove poor behaviours from my part towards my peers. I would often attempt to dominate a conversation by imposing my view on a topic, I would pressure my peers to accept my opinions or solutions, I would create an environment where communication would only go one way, my way.</p><p>These behaviours brought frustrations, stress and sadness that would negatively impact my life, my well-being as much as the well-being of my peers.</p><p>I later on realised what I was missing by trying to always be right. I was missing opportunities to learn from others and grow as an individual, I was missing opportunities to understand what was really important for myself and my peers.</p><p>As I made this observation, I decided to take a step back and I started rethinking how I should engage with my peers and how I should share my opinions and ideas. And here is what I did and what I continue doing ever since.</p><p>Let my peers be judge and let my peers decide if my opinions, ideas, solutions are right, most importantly right from their perspective. This required that I had to let go of the need of proving myself right. It brought the benefits of reducing the stress and pressure for being right. I no longer needed to dedicate my effort at proving my points, I would let others be my advocates. And most of all it gave me the chance to know when I was wrong through the feedback that I received.</p><p>This led to new opportunities with reassessing the righteousness of my behaviours when sharing opinions, ideas or solutions. By dropping the responsibility and the expectation that I had to be right, it enabled me to know when I was wrong. I would stop telling and start listening. I would stop reacting and start responding. I would make assumptions and validate them with my peers. I would reassess, and try again, until I finally understand what is needed and expected from me. And this is where my actions started to take a new meaning. I was no longer focusing on serving my personal interests. Instead, my focus switched towards serving my peers interest and supporting them with what they needed.</p><p>Understanding someone else’s needs is difficult but this is where the value and the purpose that drive our behaviours originate from. It requires tenacity, perseverance and an open mind in order to achieve this. It requires trying and failing relentlessly until finally clarity happens and a mutual understanding is reached.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccaa6e2ef49a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>