<?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[LinkApi Solutions - Medium]]></title>
        <description><![CDATA[Artigos sobre engenharia de software, ágil, inovação e tecnologia em geral do time LinkApi - Medium]]></description>
        <link>https://medium.com/linkapi-solutions?source=rss----ec64f022756c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>LinkApi Solutions - Medium</title>
            <link>https://medium.com/linkapi-solutions?source=rss----ec64f022756c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 23:15:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/linkapi-solutions" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What is the Difference between API Observability and API Monitoring]]></title>
            <link>https://medium.com/linkapi-solutions/what-is-the-difference-between-api-observability-and-api-monitoring-2b29545a3b06?source=rss----ec64f022756c---4</link>
            <guid isPermaLink="false">https://medium.com/p/2b29545a3b06</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[linkapi]]></category>
            <dc:creator><![CDATA[Gabriel Nascimento Costa]]></dc:creator>
            <pubDate>Wed, 11 Nov 2020 14:17:15 GMT</pubDate>
            <atom:updated>2020-12-05T15:33:51.031Z</atom:updated>
            <content:encoded><![CDATA[<h4>What’s their importance for building successful and scalable APIs and how they’re being used inside LinkApi</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCjgOCVMj_vGi_aoO3zAbA.png" /></figure><p>The API market is experiencing a fast growth rate in the past years. Every piece of software built today either uses an API or is an API. They have become an essential element in today’s digital economy and along with that the need to understand precisely how to observe them grow accordingly.</p><p>In this article, we’ll talk about the definition of API monitoring and observability as well as the difference between them, their importance for building successful and scalable APIs and how they’re being used inside LinkApi.</p><h4>What are API Monitoring and Observability?</h4><p>For starters, the Site Reliability Engineering <a href="https://landing.google.com/sre/sre-book/toc/">(SRE)</a> book states:</p><blockquote>Monitoring is Collecting, processing, aggregating, and displaying real-time quantitative data about a system, such as query counts and types, error counts and types, processing times, and server lifetimes.</blockquote><p>Following this definition, both API monitoring and observability are ways of monitoring that are used to monitor application program interfaces (APIs) to gain insight into their availability, performance, and proper functionality. They allow you to see how your APIs are performing, how they are being used, and how they are driving business value.</p><p>They may appear to be different names to say the same thing, however, the two of them have different ways of giving you insight of your API, and that’s what we’re going to see now.</p><h3>API Monitoring</h3><p>Starting with the tradition way of monitoring APIs, also know as <strong>API Monitoring. </strong>API monitoring<strong> </strong>is a way of monitoring that allow teams to watch and understand the state of their APIs, or even systems depending on where it’s being. In other words, monitoring is based on gathering predefined sets of metrics or logs.</p><p>While the traditional API monitoring allows you to check for your API status, errors and timeouts, it’s also intrinsically limited for being a <strong>black-box</strong> form of monitoring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*9aKWkuOiW_auz8O7nlaT6Q.png" /></figure><h4>Black-box monitoring</h4><p>Black-box monitoring is a form of monitoring made by testing externally visible behavior as a user would see it. In other words, it’s not that much different from having to guess which parts of your API may cause problems as it relies on making assumptions about what can be broken before it happens.</p><p>The downside of this is that you have to manually write the checks you need ahead of time and in the end of the day your API monitoring will only be able to check on the traffic that your tests generates, not an actual customer API traffic.</p><h3>API Observability</h3><p>On the other hand, API observability is all about making our API observable rather than only being able to debug what we’d thought to log or monitor in advance. Unlike traditional monitoring, API observability is a form of <strong><em>white-box</em> monitoring.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*JJ29yTO9BIgoNSwe7sXKDw.png" /></figure><h4>White-box monitoring</h4><p>The idea of a white-box invokes a feeling of transparency, it is a form of monitoring based on metrics exposed by the internals of the system, so it requires an agent or SDK, such as LinkApi, to passively log API traffic to an observability service in order to allows teams to actively debug their system.</p><p>Observability is based on exploring properties and patterns not defined in advance, the core of observability breaks down into three key areas: <strong>structured logs</strong>, <strong>metrics</strong>, and<strong> traces.</strong></p><p>To give you a better explanation of those pillars, we’ll see how they’re used inside LinkApi monitoring system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBCmP0oUkHMLe4vzQcEqwQ.png" /></figure><h4>Structured Logs</h4><p>Structured logs give your API the ability to inspect calls in real-time for debugging and auditing. API logs show you the exact calls in an instant in time. Because an API is by definition structured unlike traditional logging, API logs can also be used for generating aggregations and metrics while maintaining context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYkujsiGjRwOwDl5E1uqbw.png" /><figcaption>LinkApi logs</figcaption></figure><p>LinkApi structure logs you have the flexibility to configure the data you want to log, this data may or not be emitted by each process and may contain a mixture of information, ranging from records of individual user queries to debugging information generically associated with our service.</p><h4>Metrics</h4><p>The objective of metrics is to aggregate-type data about the performance of services, API metrics enable you to monitor both engineering and business KPIs such as performance and customer usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8j3AJA7GzeFhTjNxfpIBkQ.png" /><figcaption>LinkApi metrics</figcaption></figure><p>Inside LinkApi, metrics allow you to have each request’s detailed logs, monitoring access, data traffic, performance and more. With that you can observe which resources of your API are most used, find information about errors and allow you to prevent them from happening.</p><h4>Traces</h4><p>And finally, traces allow individual execution flows to be traced through the system, including timing and dependency details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rYrBl5SOLWrtjsDjwXCthQ.png" /><figcaption>LinkApi tracing</figcaption></figure><p>The tracing system in LinkAPI platform, together with the endpoints details inside metrics, make it easy to understand how long different services take to respond and where timing errors can occur, enabling you to further explore which logs to look at for a particular session or related set of API calls.</p><h3>Closing thoughts</h3><p>Nowadays APIs are everywhere, the API market doesn’t stop growing and neither does its importance inside the software ecosystem, however, API monitoring can only do so much for you. If your team needs to answer arbitrary questions required for data-driven engineering and business teams, consider using an <strong>API</strong> <strong>observability </strong>approach to your API or hiring an platform who can do that for you, such as LinkApi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b29545a3b06" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkapi-solutions/what-is-the-difference-between-api-observability-and-api-monitoring-2b29545a3b06">What is the Difference between API Observability and API Monitoring</a> was originally published in <a href="https://medium.com/linkapi-solutions">LinkApi Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve your commits with conventional commits]]></title>
            <link>https://medium.com/linkapi-solutions/improve-your-commits-with-conventional-commits-72134a852d19?source=rss----ec64f022756c---4</link>
            <guid isPermaLink="false">https://medium.com/p/72134a852d19</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[conventional-commits]]></category>
            <dc:creator><![CDATA[Gabriel Nascimento Costa]]></dc:creator>
            <pubDate>Wed, 21 Oct 2020 18:33:54 GMT</pubDate>
            <atom:updated>2020-10-21T18:33:54.309Z</atom:updated>
            <content:encoded><![CDATA[<h3>Improve your commits with Conventional Commits</h3><h4>Learn how to use CommitLint and Husky to add structure and improve the readability of your commits</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rgEpGMRh2i93o54b.jpg" /></figure><p>If you’ve been in the world of development for some time it is very likely that the image above feels familiar to you, every software developer already wrote bad commits at some point in their career, and who can shame them?</p><p>Writing consistent, meaningful commit messages are hard, that’s why in this guide we’ll learn a way to improve commits messages with Conventional Commits.</p><h3>What are Conventional Commits?</h3><p>The <a href="https://www.conventionalcommits.org/">Conventional Commits</a> specification is a simple convention on top of commit messages. It provides an easy set of rules for creating an explicit commit history.</p><p>Below you can see the structure that Conventional Commits follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*HWJzzMqxUOuR-9TMObKr2Q.png" /></figure><h4><strong><em>&lt;type&gt;</em></strong></h4><p>The <strong>type </strong>is intended to describe the category of your change. The most common types are: build, chore, ci, docs, feat, fix, perf, refactor, revert, style and test.</p><h4>[optional scope]</h4><p>The second, optional part is the so called <strong>scope</strong>. The scope Describes the module affected by your change.</p><h4>&lt;description&gt;</h4><p>The <strong>description </strong>is where describe the alterations made by your commit.</p><p>The easiest way to get an idea of what it looks like is by seeing some examples. Here are some minimal commit messages satisfying the rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QzWD7g-xMfu91gQeN-RdSw.png" /></figure><p>You can learn more about how to format your commits by reading the conventional commits <a href="https://www.conventionalcommits.org/en/v1.0.0/"><em>specification</em></a>.</p><h3>Husky and CommitLint</h3><p>Now that you know about Conventional Commits you can already start following the specification rules by your own, but easier said than done, right? To help us maintain a good commit pattern we can use two Javascript libraries, <strong>CommitLint</strong> and<strong> Husky,</strong> first let’s talk about CommitLint.</p><p>CommitLint checks if our commit messages meet the <a href="https://conventionalcommits.org/">conventional commit format</a>, so we don’t have to worry about making a mistake, for as long as we set the right rules CommitLint will be there for us.</p><p>If you’re programming in a language other than Javascript don’t worry, there are a lot of other libraries like CommitLints for other languages, you just need to find the one that suits your needs.</p><h3>Installing CommitLint</h3><p>Let’s start by installing CommitLint and their CLI on your repository as a development dependency.</p><h4>Windows</h4><pre>npm install --save-dev @commitlint/config-conventional</pre><h4>Mac/Linux</h4><pre>npm install --save-dev @commitlint/{config-conventional,cli}</pre><p>Now let’s configure commitlint to follow conventional commits specification.</p><p>First start by creating commitlint.config.js file, you can do it either manually or by your terminal.</p><pre>echo &quot;module.exports = {extends: [&#39;@commitlint/config-conventional&#39;]}&quot; &gt; commitlint.config.js</pre><p>Inside our commitlint.config.js we can set some rules, for this article I’ll use the rules from <a href="https://github.com/conventional-changelog/commitlint/blob/master/@commitlint/config-conventional/index.js"><strong>commitlint’s rules configuration example</strong></a>, but feel free to check their<strong> </strong><a href="https://github.com/conventional-changelog/commitlint/blob/master/docs/reference-rules.md"><strong>docs</strong></a> for a better explanation about all different rules and settings that commitlint have for you.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52d9bca0a783823dadde109f75f695a1/href">https://medium.com/media/52d9bca0a783823dadde109f75f695a1/href</a></iframe><p>Now that we’re done with CommitLint you could start using their CLI to check our commits, however, I prefer using Husky to do that automatically for me.</p><h4>Husky</h4><p>Husky is a library that allows us to use Git Hooks on our commits. Git hooks permit custom scripts to be ran on your repository before a set action, like a commit or a push. We’ll use this in conjunction to CommitLint to check if our Commit is following the rules we’ve set on our commitlint config file.</p><h4>Setup</h4><pre>npm install husky --save-dev</pre><p>Now let’s tell our package.json file to use Husky hooks with commitlint rules:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cedb9b9c54aa59e2de6ce803a4e9a6f2/href">https://medium.com/media/cedb9b9c54aa59e2de6ce803a4e9a6f2/href</a></iframe><p>Now we can test if everything is working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4QLDYyvFrZarK01w9fmUsg.png" /></figure><h3>Conclusion</h3><p>Good commit messages are important for maintaining any long-term project. It helps you to keep track of all of your commits and know which changes were made in each commit and with Conventional Commits you can start doing that extremely fast, I highly recommend you give it a try and learn more about it on their <a href="https://www.conventionalcommits.org/"><strong>official site</strong></a>.</p><p>If you wanna check the configuration files I created on this project then you can get them on my <a href="https://medium.com/r?url=https%3A%2F%2Fgithub.com%2FGabrielncosta%2Fconventional-commits-configuration"><strong>GitHub’s repository</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72134a852d19" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkapi-solutions/improve-your-commits-with-conventional-commits-72134a852d19">Improve your commits with conventional commits</a> was originally published in <a href="https://medium.com/linkapi-solutions">LinkApi Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conventional Commits Pattern]]></title>
            <link>https://medium.com/linkapi-solutions/conventional-commits-pattern-3778d1a1e657?source=rss----ec64f022756c---4</link>
            <guid isPermaLink="false">https://medium.com/p/3778d1a1e657</guid>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[linkapi]]></category>
            <category><![CDATA[conventional-commits]]></category>
            <dc:creator><![CDATA[Victor Ribeiro]]></dc:creator>
            <pubDate>Mon, 19 Oct 2020 13:13:44 GMT</pubDate>
            <atom:updated>2020-10-19T13:13:44.617Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwzD4nSclN7niVbyBmkPZA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@frantic?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alex Kotliarskyi</a> on <a href="https://unsplash.com/@frantic?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>O que é, para que serve e como utilizamos dentro da LinkApi</h4><p>Antes de tudo, sabemos como é intrínseco para nós Devs o uso do git durante o desenvolvimento. Não só em projetos pessoais, de código aberto ou empresariais, mas em todo projeto que seja fomentado por várias pessoas ou comunidades.</p><p>Dado isso, é importante utilizarmos o <strong>git commit</strong> apropriadamente. Dispor de uma linguagem coerente e padronizada ajuda a todos os envolvidos no projeto a entenderem as mudanças ocorridas e quais contextos foram afetados.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*bLtPTIsKUeAQHPo2eGrKpw.png" /><figcaption>Exemplo de péssimo padrão de mensagens de commit (<a href="https://xkcd.com/1296/">xkcd</a>)</figcaption></figure><p>Na imagem acima, percebemos o quão prejudicial — a curto prazo — pode ser <em>commits </em>mal comentados, uma vez que não conseguimos entender a natureza da mudança ocorrida e o contexto que se aplica. Entretanto, a longo prazo, o efeito é ainda mais danoso, dado que a manutenibilidade do software é prejudicada devido a incoerência no escopo dessas mudanças, e como afetaram o projeto no passado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*I2Bvohrj4NQ-smOY.gif" /><figcaption>Dev ao ver commit de 3 semanas que está dando problema e escrito<strong> “some changes”</strong></figcaption></figure><p>Os <em>commits </em>são pontos na linha do tempo de um projeto. Quando documentados propriamente nos mostram quem alterou, quando, em qual contexto e qual tipo de alteração foi feita. Diante disso, vamos conhecer o <strong>Conventional Commits Pattern</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2aMLivCOl9h7NNmJp-tubA.png" /><figcaption>Conventional Commits: Uma especificação para dar um significado legível às mensagens de commit para humanos e máquinas. Disponível em: &lt;<a href="https://www.conventionalcommits.org/en/v1.0.0/">link</a>&gt;</figcaption></figure><h3>O que é ?</h3><p>O <a href="https://www.conventionalcommits.org/en/v1.0.0/"><em>Conventional Commits</em></a> é uma convenção simples de mensagens de <em>commit</em>, que segue um conjunto de regras e que ajuda os projetos a terem um histórico de <em>commit </em>explícito e bem estruturado.</p><p>Há vários benefícios (além dos já citados anteriormente) em utilizar esse tipo de convenção, como por exemplo, poder automatizar a criação de CHNGELOGs, facilitar a entrada de novos <em>Devs</em> no projeto, assim como poder gerar relatórios e conseguir entender onde está se concentrando as horas do projeto (em refatoração de código, criação de <em>features</em>, mudança de estilos, ambiente de desenvolvimento, entre outros).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*fL3z-6Ofy8-7jmVE.gif" /></figure><p>Há também quem possa estar como <a href="https://g.co/kgs/W6LKKH">Michael Scott</a> pensando algo como: “Adotando essa prática, vamos perder tempo seguindo o padrão e desestimular o tempo de mudanças rápidas no projeto”</p><p>A verdade é que adotando essa convenção nós desestimulamos a mudança desordenada, e assim, como um código bem estruturado e organizado, nós perdemos algum tempo pontualmente, mas temos um enorme ganho de tempo a longo prazo.</p><h3>Como utilizar</h3><p>As regras são muito simples, como demonstrado abaixo temos um tipo de <em>commit </em>(<em>type</em>), o escopo/contexto do <em>commit </em>(<em>scope</em>) e o assunto/mensagem do <em>commit</em> (<em>subject</em>), mas adiante irei detalhar cada um.</p><pre>!type(?scope): !subject<br>&lt;?body&gt;<br>&lt;?footer&gt;</pre><p>Dessa maneira, ! indica os atributos obrigatórios e ? indica os atributos não obrigatórios. Nesse artigo não iremos falar sobre o body e nem o footer do commit. Mas tratam-se de especificações simples, que vocês podem ver mais <a href="https://www.conventionalcommits.org/pt-br/v1.0.0-beta.4/#especifica%C3%A7%C3%A3o">aqui</a>.</p><h4>Subject: Imperativo ao invés de pretérito (modo passado)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0f5ghtG-5gTmr33W4ToQdw.png" /><figcaption>O primeiro exemplo com o subject no pretérito e o segundo com o subject no imperativo</figcaption></figure><p>Sei que pode parecer estranho ao primeiro momento escrever a mensagem no imperativo, pois a mudança implementada foi uma ação passada, mas escrevendo <em>subjects</em> utilizando o imperativo nós estamos dizendo à nossa equipe <strong>o que fará o <em>commit</em> se aplicado</strong>. No <a href="https://chris.beams.io/posts/git-commit/#imperative">artigo</a> de Chris Beams ele diz um pouco mais sobre a escolha do imperativo e traz uma grande notação, ao qual, todo <em>subject </em>deve se enquadrar:</p><blockquote>“If applied, this commit will &lt;message&gt;”</blockquote><p>Em português: “Se aplicado, esse <em>commit </em>irá &lt;mensagem&gt;”. Se pensarmos no exemplo representado acima, o resultado seria:</p><blockquote>“<strong>If applied, this commit will change the markup</strong>”, o que faz muito mais sentido do que: “If applied, this commit will changed the markup”</blockquote><h4>Type: Quais são os tipos de commit</h4><p>O <strong><em>type </em></strong><em>é</em><strong><em> </em></strong>responsável por nos dizer qual o tipo de alteração ou iteração está sendo feita, das regras da convenção, temos os seguintes tipos:</p><ul><li>test: indica qualquer tipo de criação ou alteração de códigos de teste. <strong>Exemplo:</strong> Criação de testes unitários.</li><li>feat: indica o desenvolvimento de uma nova <em>feature a</em>o projeto. <strong>Exemplo: </strong>Acréscimo de um serviço, funcionalidade, <em>endpoint</em>, etc.</li><li>refactor: usado quando houver uma refatoração de código que não tenha qualquer tipo de impacto na lógica/regras de negócio do sistema. <strong>Exemplo: </strong>Mudanças de código após um <em>code review</em></li><li>style: empregado quando há mudanças de formatação e estilo do código que <strong>não alteram</strong> o sistema de nenhuma forma. <br><strong>Exemplo: </strong>Mudar o <em>style-guide</em>, mudar de convenção <em>lint</em>, arrumar indentações, remover espaços em brancos, remover comentários, etc..</li><li>fix: utilizado quando há correção de erros que estão gerando bugs no sistema.<br><strong>Exemplo: </strong>Aplicar tratativa para uma função que não está tendo o comportamento esperado e retornando erro.</li><li>chore: indica mudanças no projeto que não afetem o sistema ou arquivos de testes. São mudanças de desenvolvimento.<br><strong>Exemplo: </strong>Mudar regras do <em>eslint</em>, adicionar <em>prettier</em>, adicionar mais extensões de arquivos ao .<em>gitignore</em></li><li>docs: usado quando há mudanças na documentação do projeto.<br><strong>Exemplo: </strong>adicionar informações na documentação da API, mudar o <em>README</em>, etc.</li><li>build: utilizada para indicar mudanças que afetam o processo de build do projeto ou dependências externas.<br><strong>Exemplo: </strong><em>Gulp</em>, adicionar/remover dependências do <em>npm</em>, etc.</li><li>perf: indica uma alteração que melhorou a performance do sistema.<br><strong>Exemplo: </strong>alterar <em>ForEach </em>por <em>while</em>, melhorar a query ao banco, etc.</li><li>ci: utilizada para mudanças nos arquivos de configuração de CI.<br><strong>Exemplo: </strong><em>Circle</em>, <em>Travis</em>, <em>BrowserStack</em>, etc.</li><li>revert: indica a reverão de um <em>commit </em>anterior.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izVKF4AT1iDtv4fJO8oWWA.png" /><figcaption>Exemplos dos tipos de commit citados anteriormente</figcaption></figure><p>Assim, conseguimos de forma simples e direta ver qual tipo de mudança está ocorrendo, melhorando bastante a visibilidade e alinhamento com a equipe.</p><p><strong>Observações</strong>:</p><ul><li>Só pode ser utilizado um <em>type </em>por <em>commit;</em></li><li>O <em>type </em>é <strong>obrigatório;</strong></li><li>Caso esteja indeciso sobre qual <em>type </em>usar, provavelmente trata-se de uma grande mudança e é possível separar esse <em>commit</em> em dois ou mais <em>commits;</em></li><li>A diferença entre build e chore pode ser um tanto quanto sutil e pode gerar confusão, por isso devemos ficar atentos quanto ao tipo correto. No caso do Node.js por exemplo, podemos pensar que quando há uma adição/alteração de certa dependência de desenvolvimento presente em devDependencies, utilizamos o chore. Já para alterações/adições de dependências comuns aos projeto, e que haja impacto direto e real sobre o sistema, utilizamos o build.</li></ul><h4>Scope: contextualizando o <em>commit</em></h4><p>Nesse ponto — e seguindo as convenções passadas — conseguimos entender o <em>tipo</em> de alteração que foi realizada no <em>commit</em> (<em>commit type</em>) e entender com clareza o que o <em>commit</em> irá trazer se aplicado (<em>commit subject</em>).</p><p>Entretanto, até aonde essa mudança pode afetar ?</p><p>Em repositórios enormes, como <a href="https://en.wikipedia.org/wiki/Monorepo"><em>monorepos</em></a>, ou projetos com várias <em>features</em> e mudanças paralelas, não fica bastante claro até onde a mudança que irá chegar pode alterar. Para isso, podemos utilizar o escopo(<em>scope</em>) do <em>commit</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZPTYtwxI-UgULgOjf8GKQ.png" /><figcaption>Exemplo de commit utilizando o scope</figcaption></figure><p>Mesmo o <em>scope </em><strong>não sendo obrigatório</strong>, ele<strong> </strong>pode ser utilizado para contextualizar o <em>commit</em> e trazer menos responsabilidade para a <em>subject</em>, uma vez que dispondo do tipo de <em>commit</em> e o contexto que foi aplicado, a mensagem deve ser o mais breve e concisa possível. <strong>Lembrando que o <em>scope </em>deve ser inserido no <em>commit </em>entre parênteses</strong>.</p><p>Além disso, no caso do <em>scope </em>é possível adicionarmos múltiplos valores, como por exemplo: Caso houvesse uma refatoração de código em um repositório com versões mobile, web e desktop. A qual afeta o contexto mobile e web, poderíamos escrever o <em>commit </em>da seguinte maneira:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1hcIpv-XNGUsdfqTjtV8A.png" /><figcaption>Dessa maneira indicamos que é um commit de refatoração que afetara os contextos mobile e web da aplicação</figcaption></figure><p><strong>Observação:</strong> Os escopos devem ser separados com / , \ ou ,.</p><h3>Como usamos na LinkApi</h3><p>Primeiramente, é importante dizer que o <em>Conventional Commit</em> e suas especificações devem ser seguidas e respeitadas. Entretanto, não é um modelo ao qual se adequa a todo tipo de projeto e empresa. Na <a href="https://www.linkapi.solutions/?gclid=CjwKCAjw_Y_8BRBiEiwA5MCBJmkhlgPllt_dANDAH_GqdTbg2qnj9hWQS1y8S6blguM7_Fp4CraISBoC8DYQAvD_BwE">LinkApi</a>, por exemplo, ao desenvolver integrações não utilizamos <a href="https://codeship.com/continuous-integration-essentials#:~:text=Continuous%20Integration%20(CI)%20is%20a,CI%20it%20is%20typically%20implied.">CI</a>. Além disso, alguns projetos por serem bastante conhecidos já possuem documentações e não é necessário reproduzi-las. Portanto os tipos de <em>commit</em>: ci ou doc não são utilizados.</p><p>Por outro lado, em nosso cotidiano haverão diversas regras de negócios implicadas à integração, e que não necessariamente gerariam uma <em>feature </em>nova, como por exemplo: um campo que deva vir em maiúsculo, ou um valor com 3 casas decimais, alguma regra de embalagem, <em>tracking </em>e etc.</p><p>Em nosso modelo de desenvolvimento, esse tipo de alteração encontra-se como uma mudança de regra de negócio, e para isso, nos criamos e utilizamos o tipo de <em>commit</em> “<strong><em>business</em></strong><em>”</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74Vfq1g4-KDkpbJfDa5r-w.png" /></figure><p>Outra regra, que utilizamos “dentro de casa” é a de definir o escopo do <em>commit</em>, de acordo com a <a href="https://www.atlassian.com/agile/scrum/sprints#:~:text=What%20are%20sprints%3F-,A%20sprint%20is%20a%20short%2C%20time%2Dboxed%20period%20when%20a,better%20software%20with%20fewer%20headaches."><strong><em>sprint</em></strong></a><strong><em> </em></strong>que trabalhamos, assim conseguimos entender o contexto que aquela mudança ocorreu com mais facilidade.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFO9815DI0h53U3-1n1RVw.png" /></figure><p>Lembrando que quando ocorre uma mudança que afetam funcionalidades de mais de uma sprint, nós adicionamos isso ao contexto também, como representado abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aj2Q-410krTt06-jGM_MGQ.png" /></figure><blockquote>Por fim, podemos dizer que o Conventional Commit pode adquirir propriedades daquele projeto, equipe ou empresa, desde que não fuja do conjunto de regras definidos pela convenção, esteja bem alinhados entre os interessados/participantes do projeto e seja bem documentado.</blockquote><h3>Bônus</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*KgWj7_xV_A7pWihm.gif" /><figcaption>Sim, você não leu errado: BÔNUS !!!</figcaption></figure><p>De certo, a curva de adoção para essa convenção pode ser demorada e até por vezes exaustiva. Para isso, vou deixar aqui recomendado uma ferramenta bastante útil para nos ajudar a adotar mais essa boa prática ao desenvolvimento de projetos:</p><h4>CommitLint</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*Zu7AyTqSODYpffLI" /><figcaption>Demonstração do commitlint (presente no <a href="https://github.com/conventional-changelog/commitlint">repositório</a>)</figcaption></figure><p>O <em>commitLint </em>fica responsável por checar se a mensagen de commit está seguindo o padrão da convenção e bloquear o envio de mudanças que não seguem o <em>conventional commit pattern</em>. Portanto, essa ferramenta “força” sua equipe a seguir o padrão estabelecido, lembrando que é possível fazer diversas customizações, como adicionar tipos, obrigar a inserir o escopo, utilizar somente snake_case/kebab-case/camelCase, entre outras diversas customizações de acordo com as necessidades do time.</p><p>Vocês podem conhecer um pouco mais da ferramenta, assim como suas configurações através <a href="https://www.youtube.com/watch?v=erInHkjxkL8">desse vídeo</a>, <a href="https://github.com/conventional-changelog/commitlint">do repositório do <em>commitlint</em></a>, <a href="https://medium.com/@larymagal/usando-commit-lint-para-gerar-releases-no-github-actions-27f4b808d52f">desse artigo</a>, entre outros.</p><h3>Conclusão</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*NbLkNkAMZKAT6j8V" /></figure><p>Obrigado a todos que leram até aqui, a intenção desse artigo foi de mostrar — para aqueles que não conheciam — uma boa forma de trabalhar em equipe, gerenciar o projeto e por fim de poder envolver-se melhor nos repositórios da comunidade (já que grande parte segue esse padrão).</p><p>Além, é claro, de poder mostrar um pouco mais sobre como trabalhamos na LinkApi.</p><p>Valeu pessoal, <strong><em>may the force be with you.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3778d1a1e657" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkapi-solutions/conventional-commits-pattern-3778d1a1e657">Conventional Commits Pattern</a> was originally published in <a href="https://medium.com/linkapi-solutions">LinkApi Solutions</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 reach Developer Experience supreme level — Part one]]></title>
            <link>https://medium.com/linkapi-solutions/how-to-reach-developer-experience-supreme-level-part-one-ed87015af29f?source=rss----ec64f022756c---4</link>
            <guid isPermaLink="false">https://medium.com/p/ed87015af29f</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[developer-relations]]></category>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dx]]></category>
            <dc:creator><![CDATA[Albert Cavalcante]]></dc:creator>
            <pubDate>Thu, 24 Sep 2020 15:27:45 GMT</pubDate>
            <atom:updated>2020-08-19T00:09:03.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*zVnWJtyGOX_kUIDm6ccCfQ.gif" /></figure><h3>How to reach Developer Experience supreme level — Part one</h3><p>Hi all, glad to be here again! I have seen many companies recently evolve their products through good DX, and I have to confess, it’s amazing! Recently, I spoke with some of my colleagues about their experiences designing products that provide good solutions for both business and technical personas. I gained interesting insight. During those conversations, I noticed that people professed difficulty measuring how great their DX is — that’s why I wrote the <a href="https://medium.com/@albertcavalcante/developer-experience-metrics-46b1d087811d"><strong>Developer Experience Metrics</strong></a>. But beyond measuring DX, people were struggling to identify the maturity levels of these professionals at their jobs. So I decided to write this article and explain my Developer Experience Maturity thesis.</p><blockquote>To begin, why is it important to map DX maturity levels?</blockquote><h3>Understanding a Developer’s Journey</h3><p>In my experience, many players tried to provide great DX with high-level actions, forgetting about the details throughout the process. For example, some API Management tool creators tried to enable great DX by giving their users a full distribution experience within their developer portals, but they forgot to really seek understanding of the beginning of the journey, the development portion… They didn’t map the entire journey, and instead, they focused on just one frame.</p><p>Don’t get me wrong, I know some products focus on a small piece of the user’s tasks for good reason, but when you work with developers you should worry about the entire experience, even when your product’s purpose is to resolve a small piece of it. Because when we talk about designing products for developers, it’s almost a rule: they will use your product with another tool. So, when I set out to identify a general developer journey I plotted the following sequence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*wALwE7oPdFtIdm7OSx5NJQ.png" /></figure><p>The idea of this article isn’t to describe the development process, but it’s important to provide a short explanation to get us on the same footing:</p><ul><li><strong>Solution Design: </strong>In this step, the developer receives the business requirements from the business personas (Product Manager, Product Owner, etc.), and with them, he designs the solution architecture. He can do it with a BPMN diagram, a mindmap, and any other tool that he feels comfortable using during this process.</li><li><strong>Development:</strong> The build phase, where the team will develop the proposed solution. Here they can use agile methodologies like Scrum, Kanban, eXtreme Programming, etc.</li><li><strong>Tests:</strong> You build it, you run it! This is Google’s mindset for their engineering teams, and I deeply believe in it and apply this to my own teams’ evolution. Basically, every developer should test their release, and not only unit tests but testing the entire client’s (end-user) experience to validate if the release will break another part of the product.</li><li><strong>Release: </strong>Let your customer feel your work, the release should be exciting for developers and customers! Here I prefer to use a cascaded release schedule; first, a smaller group of users, just because I want to understand how they will absorb the new experience, and after this validation process, I release to the larger user base.</li><li><strong>Monitoring: </strong>You build it, you run it, again! Doesn’t matter if you work with product development or professional services, you should always have a plan to monitor your releases. In every project that I worked on, I recommended my team develop custom dashboards to monitor usage. Usually, we use <a href="https://www.metabase.com/"><strong>Metabase</strong></a> as our BI tool. Why Metabase? Because it’s an open-source tool, and we love open-source. ❤</li><li><strong>Client’s insights: </strong>A well-done monitoring process gives you insights about which clients you should speak to for future information, and don’t think this is only a UX Designer or Product Manager’s responsibility! Great developers like to speak with their users because this helps them evolve the product even more.</li></ul><h3>DX Maturity Levels</h3><p>Now we can and speak about Developers Experience Maturity, and relate it to the general developer’s journey. To measure this I developed a framework with five levels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*H7sJsBY_1ghL_aUuGbrp5w.png" /></figure><h3>Suffering Because of Bad DX</h3><p>Every developer tool/service company will pass through this phase, even if DX is never important to them. This is because bad DX doesn’t impact only the user’s happiness; it will impact their sales, marketing, employee branding, etc. So these companies will be affected by their bad DX but very few of them will realize the problem’s origin.</p><h3>Understanding DX</h3><p>The small group of companies that realize the origin of their problems was DX will start to understand this subject by stumbling upon it. The product manager responsible for the product or feature will be the first warrior in this war. He will google the term, search for cases, references, etc. In my experience, I noticed this process takes at least two months. If you are at this level, I deeply recommend that you read <a href="https://medium.com/swlh/what-is-dx-developer-experience-401a0e44a9d9"><strong>What is DX</strong></a>.</p><h3>Applying DX For Your Product</h3><p>After understanding “what is DX” you will start to apply the concepts for your product. First, you’ll probably start to track your developers’ journeys; you’ll map it out, identify their needs, identify their desires, and see how your product will make their life greater.</p><p>In moments like these things get even more interesting. You start to realize that modifying your product isn’t enough to provide great DX. So you start to analyze your company, how your marketing team speaks about your product, how your sales team sells your product, how your customer success team helps your clients utilize your product.</p><p>Since this is not a matter of developing features, you will start to see that even the words you use in your product communication will be important for good developer experience. I recommend using the <em>User Journey Framework</em> to map your developer’s journey. You can find an example <a href="https://medium.com/@albertcavalcante/developer-experience-metrics-46b1d087811d"><strong>here</strong></a><strong>.</strong></p><p>This phase is really exciting, and you will need to be an excellent communicator to engage your internal stakeholders to modify your company because you will probably make changes to your organization structure — areas will be redesigned, people will be hired, a developer community will be created.</p><h3>Evangelizing DX</h3><p>Back in the days, I was responsible for creating our internal developer community, I realized that just having a great product for our customers and modifying our company internally was not sufficient to master DX for our products. So I started to look externally, to consider how our company and our team could help more developers, and I created the <a href="https://www.facebook.com/kapicommunity/"><strong>Kapi Community</strong></a><strong>.</strong></p><p>After this, I designed a career development plan for my team that helps them evolve and <a href="https://medium.com/linkapi-solutions"><strong>generate great content for the world development community</strong></a>. Currently, our content is primarily in Portuguese; we realized that Brazilian Developers require quality communities dedicated to career growth and accessible development content in their primary language.</p><p>We also strive to find great partners in our mission. Here in Brazil, we have <a href="https://rocketseat.com.br/"><strong>Rocketseat</strong></a>, a company designed by developers for developers, as well as NewSchool, a company that helps children in need better prepare themselves for the world in front of them, a future in STEM. These two companies are some of our developers’ community partners.</p><p>And to finish, I wrote this article explaining DX because I saw that many people don’t understand a simple fundamental truth: that developers deserve as great an experience as normal users, and these same people don’t understand how their product could be greater, their companies bigger, all through the simple act of making more developer-friendly tools.</p><p>The highest level of developer experience is when you start to be an active part of this battle: generating content, gathering insight, creating communities, basically being part of the process of evangelizing DX all over the world. We already have a job title for it — <strong>Developer Relations</strong>. This is one of the jobs to watch for the future; every company that respects DX will soon have this person on their team.</p><p>I’m really glad to have written this article, and even more, to say to you that this will be a starting point for a series explaining how to reach the highest level of developer experience. The series will explore each of the maturity levels, providing examples, cases, and my track record over the years working to build developer tools. I hope that you enjoyed this content, and if you want to chat about this, please, <a href="/service/mailto:albert.cavalcante@linkapi.solutions"><strong>send me an email</strong></a>.</p><p>Bye, and see you soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed87015af29f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkapi-solutions/how-to-reach-developer-experience-supreme-level-part-one-ed87015af29f">How to reach Developer Experience supreme level — Part one</a> was originally published in <a href="https://medium.com/linkapi-solutions">LinkApi Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Pattern Adapter — uma boa solução para lidar com códigos legados]]></title>
            <link>https://medium.com/linkapi-solutions/design-pattern-adapter-uma-boa-solu%C3%A7%C3%A3o-para-lidar-com-c%C3%B3digos-legados-684854671392?source=rss----ec64f022756c---4</link>
            <guid isPermaLink="false">https://medium.com/p/684854671392</guid>
            <category><![CDATA[date-fns]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[momentjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Victor de Almeida Fonseca]]></dc:creator>
            <pubDate>Tue, 22 Sep 2020 11:19:35 GMT</pubDate>
            <atom:updated>2020-09-22T13:08:36.819Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Design Pattern Adapter — uma boa solução para lidar com códigos legados</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*0FKCULCKMFtlQUnAQdOBdA.jpeg" /></figure><p>Se você é desenvolvedor JavaScript deve ter ficado surpreso com a notícia de que a tão amada biblioteca “Moment.js” não receberá mais atualizações. Com certeza a primeira coisa que você deve ter pensado é naquele seu projeto que está utilizando a biblioteca. Porém isso não é uma novidade no mundo do desenvolvimento. Na realidade bibliotecas e frameworks vem e vão. Então como podemos lidar com bibliotecas e frameworks de terceiros na nossa aplicação?</p><p>Uma excelente opção é aplicando o design pattern <strong><em>Adapter</em></strong>.</p><p><strong>O que o é Adapter?</strong></p><p>Bom o nome <strong><em>“Adapter”</em></strong> é bastante sugestivo (adaptador em português). A ideia desse design pattern é fazer com que duas interfaces/classes diferentes consigam interagir entre si ou até mesmo substituir uma à outra sem causar um efeito colateral no seu código. Para isso, inserimos uma classe <strong><em>adaptadora</em></strong> que intermediará o retorno da nova ou velha interface para o código em produção. Podemos fazer uma comparação bem prática: os adaptadores de tomada. Quando você tem uma tomada que não é compatível com o cabo de força de seu eletrônico é necessário um “<strong>adaptador”. </strong>É exatamente o mesmo propósito da <strong><em>classe adapter</em></strong> que vamos inserir no nosso código.</p><p>Então voltemos ao exemplo do Moment.js que comentamos no início e vamos utilizar o caso da depreciação da biblioteca. Tente imaginar quão problemático seria ter que instalar uma nova biblioteca e substituir todo o código legado deixado pelo Moment.js. Seria bom adaptador não é mesmo?! Nesse caso veremos na prática como podemos realizar isso</p><p><strong>Aplicando o design adapter</strong></p><p>O exemplo que vamos utilizar pode parecer bem trivial. Porém o intuito é exatamente deixa-lo bem simples para assim ficar mais fácil de assimilar-mos.</p><p>Suponhamos que na nossa aplicação existe uma classe que utilize o Moment.js para converter datas para o formato “dia-mês-ano”. Então a estrutura de nossa aplicação ficaria assim:</p><p><strong>Moment.js:</strong> classe responsável por executar a conversão de data.</p><p><strong>index.js:</strong> script para executar nossa função.</p><p>Vejamos como nosso código ficou:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12f7fdadd9341aa8820cffedbb8afe61/href">https://medium.com/media/12f7fdadd9341aa8820cffedbb8afe61/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c8a34d669062775ddaff61d5e929ac4/href">https://medium.com/media/7c8a34d669062775ddaff61d5e929ac4/href</a></iframe><p>Vamos então fazer a migração da biblioteca<strong> Moment.js.</strong> No nosso exemplo escolhemos a biblioteca <strong>date-fns.js</strong> para substitui-la. Poderíamos simplesmente reescrever a classe certo? Porém lembre que você está substituindo uma biblioteca. As probabilidades de dar alguma erro e precisarmos voltar para a biblioteca de legada são grandes. Então vamos aplicar o <strong>adapter! </strong>Começaremos escrevendo duas classes.</p><p>A primeira será nossa classe que também realizará a conversão de datas assim como a classe Moment.js: Vamos chamada de <strong>Data-fns.js</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fc3b3f65c8670eec22300abc9062809/href">https://medium.com/media/2fc3b3f65c8670eec22300abc9062809/href</a></iframe><p>Nessa classe temos dois métodos: <strong>parseISO</strong> e <strong>formatToDayMonthYear</strong>. <strong>ParseIso</strong> chama o método com o mesmo nome para transformar o input de string para formato ISO. Já a <strong>formatToDayMonthYear</strong> realiza a conversão propriamente dita.</p><p>Nossa segunda classe se chamará <strong>DataAdapter.</strong> Ela servirá de adaptador para nossa aplicação:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d919524d4f945a5a8557c43521a63f68/href">https://medium.com/media/d919524d4f945a5a8557c43521a63f68/href</a></iframe><p>Nessa classe nós criamos uma nova instância da classe <strong>DataFns </strong>dentro do constructor da classe <strong>DataAdapter.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00e56489d8f6dd3613b89d7e70fd6b2a/href">https://medium.com/media/00e56489d8f6dd3613b89d7e70fd6b2a/href</a></iframe><p>Logo em seguida encapsulamos a chamada do nosso método de nossa nova instância em <strong>this.dataApi </strong>dentro do método <strong>formatToDayMonthYear</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/317edc9a95eda2787812bde8c8ebe8f0/href">https://medium.com/media/317edc9a95eda2787812bde8c8ebe8f0/href</a></iframe><p>Agora vamos modificar nosso index.js para “plugar” nossa classe adapter no nosso script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9c22f10cfc38e7d92dc060e9fb181de/href">https://medium.com/media/a9c22f10cfc38e7d92dc060e9fb181de/href</a></iframe><p>Caso precise realizar o rollback e voltar a utilizar o Moment.js basta mudarmos a instância da nossa classe dentro da nossa classe adaptadora.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b05699502891d2bb307ee89b597c991e/href">https://medium.com/media/b05699502891d2bb307ee89b597c991e/href</a></iframe><p>Conseguiu perceber a função de adaptador de nossa classe <strong>DataAdapter?!</strong></p><p>Agora a nossa classe adapter será responsável por conectar qualquer mudança na nossa aplicação.</p><p>Nesse cenário escolhemos a modificação de uma biblioteca para mostrar como exemplo. Porém adotar esse design pattern desde o início de seu projeto para todas as bibliotecas externas pode lhe poupar muita dor de cabeça.</p><p>O código interno do nosso exemplo pode ser encontrado dentro deste repositório: <a href="https://github.com/VictorAlmeidaFonseca/adapter-design-pattern.git">https://github.com/VictorAlmeidaFonseca/adapter-design-pattern.git</a></p><p>Caso se interesse mais sobre o assunto e queira se aprofundar recomendo esse artigo: <a href="https://refactoring.guru/design-patterns/adapter">https://refactoring.guru/design-patterns/adapter</a></p><p>E ai o que achou? Comente aqui qual o design pattern que você tem utilizado para aclopar as bibliotecas externas nos eus projetos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=684854671392" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkapi-solutions/design-pattern-adapter-uma-boa-solu%C3%A7%C3%A3o-para-lidar-com-c%C3%B3digos-legados-684854671392">Design Pattern Adapter — uma boa solução para lidar com códigos legados</a> was originally published in <a href="https://medium.com/linkapi-solutions">LinkApi Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pointers in Go]]></title>
            <link>https://medium.com/linkapi-solutions/pointers-in-go-5611cb8f5d0a?source=rss----ec64f022756c---4</link>
            <guid isPermaLink="false">https://medium.com/p/5611cb8f5d0a</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineer]]></category>
            <category><![CDATA[pointers]]></category>
            <dc:creator><![CDATA[Matheus Kielkowski]]></dc:creator>
            <pubDate>Mon, 21 Sep 2020 12:29:09 GMT</pubDate>
            <atom:updated>2020-09-21T18:05:11.199Z</atom:updated>
            <content:encoded><![CDATA[<p>Nowadays, most developers don’t usually use pointers in their routine. But in this article, I will explain using the Go programming language, what are pointers, and how they can be used.</p><h3>First of all, let’s start at the beginning</h3><p>Each declared variable has space and one memory address. The majority times the addresses are represented by numbers like <strong><em>0xc000025482, </em></strong>this means that they are represented by numbers in base 16, in other words, hexadecimal numbers.</p><p>If you want to discover the memory address of a variable in Go, you just need to write the code below:</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() { <br>  var example int </pre><pre>  fmt.Println(&amp;example) <br>}</pre><p>As you see, in the variable <strong><em>example</em></strong>, we set a <strong><em>&amp;</em></strong> before print the value to the compiler get the address of it. The result will be something like <em>0xc000094010.</em></p><p>The RAM is basically a big block of sequential spaces. We declare a struct to reserved a part of the memory and each field of this struct is a sequential part of the block.</p><p>To you understand this easily, I created a struct that saves some values:</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() { <br>  var product struct { <br>     id int64 <br>     name string<br>  }</pre><pre>  fmt.Println(&amp;product.id)   <strong>// 0xc00000c0a0</strong><br>  fmt.Println(&amp;product.name) <strong>// 0xc00000c0a8</strong><br>}</pre><p>If you run this code, the compiler will print the memory address of each struct property inside the RAM.</p><h3>But, what is a pointer ?…</h3><p>The concept of pointers is simple, a pointer is a variable that has your memory address and saves another memory address.</p><p>So different from other types of variables (int32, int64, string, bool, etc), pointers save hexadecimal address numbers.</p><p>But, how I declare a pointer? Let’s see below:</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() { <br>  var age int <br>  var pointer *int </pre><pre>  fmt.Println(age)     // 0<br>  fmt.Println(pointer) // &lt;nil&gt;<br>}</pre><p>In the code above, we declare two variables, one is the <em>age</em> that saves an integer value and another is a <em>pointer</em> that saves a memory address of an integer variable.</p><p>If you run this code, the compiler will print the value of each variable declared. How we don’t assign any value to variables, the Go set them as 0 and <em>nil </em>respectively.</p><p>The value <strong><em>nil</em></strong> in Go is like <strong><em>null</em></strong> in other languages. As we see, we declare the variable but don’t point to any other variable, so the compiler set <em>nil</em> and this means at moment the pointer is not pointing to any other value.</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() { <br>  var age int <br>  var pointer *int</pre><pre>  age = 20<br>  pointer = &amp;age</pre><pre>  fmt.Println(age)     // 20<br>  fmt.Println(pointer) // 0xc00002c008<br>}</pre><p>Now we are saying to the compiler that the variable <em>pointer</em> is pointing to the variable <em>age</em>, and when the value of the pointer is printed we have the memory address of the <em>age</em> variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*I2kWrpKKwro8K1yZrCnGXQ.png" /></figure><h3>But ok, what I can do with it?</h3><p>Probably you are thinking “<em>Ok, but is it just it?</em>”, and the answer is no.</p><p>Now, as we see the pointer has access to the memory address of the variable, so is possible to have access to the value of this address.</p><p>Below I will show you how to do that in Go:</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() { <br>  var age int <br>  var pointer *int</pre><pre>  age = 20<br>  pointer = &amp;age</pre><pre>  fmt.Println(age)      <strong>// 20</strong><br>  fmt.Println(<strong>*</strong>pointer) <strong>// 20</strong><br>}</pre><p>Putting the * before the pointer, we are saying to the compiler search for the value of the memory address inside the pointer. So, we can do some interesting things with that. Let’s try to change the <em>age</em> value:</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() { <br>  var age int <br>  var pointer *int</pre><pre>  age = 20<br>  pointer = &amp;age<br>  *pointer = 25</pre><pre>  fmt.Println(age)      <strong>// 25</strong><br>  fmt.Println(<strong>*</strong>pointer) <strong>// 25</strong><br>}</pre><p>Why did it work? Basically we are saying to the compiler assign the number 25 to the value that the pointer is pointing. So now the variable <em>age</em> is equal a 25.</p><h3>How pointers can be powerful?</h3><p>Imagine that you have a list of 234.434.749.988 items and you want to remove just one item from the list.</p><p>The first thing that you can think is read item per item and when you find the item remove it. But, this is not the best solution and can make your system too slow.</p><p>Here is our system of tasks to exemplify:</p><pre>package main</pre><pre>type Task struct { <br>  title string <br>  next *Task <br>}</pre><pre>func main() { <br>  t1 := Task{title: &quot;Fix bug 1&quot;}<br>  t2 := Task{title: &quot;Fix bug 2&quot;}<br>  t3 := Task{title: &quot;Fix bug 3&quot;}</pre><pre>  t1.next = &amp;t2 <br>  t2.next = &amp;t3 </pre><pre>  list := t1</pre><pre>  fmt.Println(*list.next)       <strong>// {Fix bug 2 0xc00010c000}</strong><br>  fmt.Println(*list.next.next)  <strong>// {Fix bug 3 &lt;nil&gt;}</strong><br>}</pre><p>In this code, I created a struct called Task formed by a variable <em>title,</em> and another called <em>next</em> that points to another task.</p><p>After that, I declared three variables (<em>t1, t2, t3</em>). Each variable points to the next task and only t3 don’t because it is the last.</p><p>Finally, was declared a variable called <em>list,</em> assigned by <em>t1</em>. The struct of the list is like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*PWrW12cRB37l-4Zs5SOhWw.png" /></figure><p>Going back to our problem of removing an item from the list. By this struct, how we can remove task 2 (<em>t2</em>) without need read task per task?</p><p>What we can do to resolve this problem is very simple, we just need to point t1 to t3 and t2 to nothing. Therefore, t2 will be removed from the list because doesn’t point to any task and any task point to it.</p><p>Below I will show you how to do that:</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>type Task struct {<br> title string<br> next  *Task<br>}</pre><pre>func main() {<br> t1 := Task{title: &quot;Fix bug 1&quot;}<br> t2 := Task{title: &quot;Fix bug 2&quot;}<br> t3 := Task{title: &quot;Fix bug 3&quot;}</pre><pre> t1.next = &amp;t2<br> t2.next = &amp;t3</pre><pre> list := t1<br> fmt.Println(*list.next) // {Fix bug 2 0xc00010c000}</pre><pre><strong> t1.next = &amp;t3 <br> t2.next = nil</strong></pre><pre><strong> list = t1</strong></pre><pre><strong> fmt.Println(*list.next) // {Fix bug 3 &lt;nil&gt;}</strong><br>}</pre><p>Now the second task (<em>t2</em>) was removed and our list has just <em>t1</em> and <em>t3</em>.</p><blockquote><em>This is a very simple example. I will write an article explaining how to create a dynamic list in Go : )</em></blockquote><h3>Pass by reference and value. What is the difference?</h3><p>The concept of pass by reference and pass by value is basically in all programming languages that work with functions.</p><p>The definition of <strong>pass by reference</strong> is the fact of pass a pointer that has reference to a variable on the memory to a function. And the definition of <strong>pass by value</strong> is the fact of pass directly a variable.</p><p>Let’s see two examples of it:</p><pre><strong>// PASS BY VALUE</strong></pre><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br> var quantity int<br> fmt.Println(&amp;quantity) <strong>// 0xc00002c008</strong></pre><pre> quantity = double(quantity) <br> fmt.Println(&amp;quantity) <strong>// 0xc00002c008</strong><br>}</pre><pre>func double(quantity int) int { <br> fmt.Println(&amp;quantity) <strong>// 0xc00002c040</strong><br> <br> quantity = quantity * 2</pre><pre> return quantity<br>}</pre><p>If you run the code, the compiler will print the sequence of addresses below:</p><pre>0xc00002c008<br>0xc00002c040<br>0xc00002c008</pre><p>What we need to pay attention here, is that when we called the <em>double </em>function and pass the <em>quantity</em>, Go creates another variable that has the same value of the <em>quantity</em> on the main function.</p><p>Because the variables <em>quantity</em> inside the <em>main </em>and<em> double </em>function belong to different contexts and have different memory addresses.</p><p>Now, let’s see an example of pass by reference:</p><pre><strong>// PASS BY REFERENCE</strong></pre><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() { <br> var pointer *int <br> var quantity int <br> <br> pointer = &amp;quantity<br> fmt.Println(pointer) <strong>// 0xc00002c008</strong></pre><pre> pointer = double(pointer) <br> fmt.Println(pointer) <strong>// 0xc00002c008</strong><br>}</pre><pre>func double(value *int) *int { <br> fmt.Println(value)   <strong>// 0xc00002c008</strong><br> <br> *value = *value * 2</pre><pre> return value<br>}</pre><p>If you run the code, the compiler will print the sequence of addresses below:</p><pre>0xc00002c008<br>0xc00002c008<br>0xc00002c008</pre><p>Now all addresses are equal. Why?</p><p>Because what <em>double</em> function is receiving is a pointer to the variable <em>quantity</em> on the main function.</p><p>Go creates another variable too, but this variable is pointing to the same variable <em>quantity</em>.<em> </em>So<em> </em>the address keeps being the same and we didn’t duplicate the value of the <em>quantity</em>, saving memory space.</p><h3>Should we always use pass by reference?</h3><p>The answer to this question, as for all in computer science, is depends.</p><p>If we use pass by reference we can save more memory space than use pass by value. But what is happening with these pointers after the code was processed?</p><p>The pointers stay “loose” on the memory and we need a system called Garbage Collector to remove these pointers and free up memory space.</p><p>But the Garbage Collector requires processing time, and if we use it with a lot of frequency the system can be slow, damaging our application.</p><h3>Conclusion</h3><p>In the world of technology not exists silver bullets.</p><p>We as engineers must know how to deal with different scenarios and use the appropriate tools to do it.</p><p><strong>For those who only use a hammer, every problem is a nail.</strong></p><p>Pointers are a powerful technique to resolve some problems in our routine. So, is very interesting you understand some computer science concepts like that, to increase your vision about how to resolve a problem by the best way possible.</p><p>I hope that you had enjoyed it. Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5611cb8f5d0a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkapi-solutions/pointers-in-go-5611cb8f5d0a">Pointers in Go</a> was originally published in <a href="https://medium.com/linkapi-solutions">LinkApi Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Criptografia de dados com NodeJS — Parte 1]]></title>
            <link>https://medium.com/linkapi-solutions/criptografia-de-dados-com-nodejs-parte-1-aab4da809edc?source=rss----ec64f022756c---4</link>
            <guid isPermaLink="false">https://medium.com/p/aab4da809edc</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Victor de Almeida Fonseca]]></dc:creator>
            <pubDate>Fri, 11 Sep 2020 12:33:17 GMT</pubDate>
            <atom:updated>2020-09-10T14:59:02.624Z</atom:updated>
            <content:encoded><![CDATA[<h3>Criptografia de dados com NodeJS — Parte 1</h3><p>Uma das tarefas mais importantes de um desenvolvedor é manipular os dados da sua aplicação de maneira correta. E se tratando de dados sensíveis como número do cartão de crédito, cpf, data de nascimento e etc a responsabilidade redobra. Na verdade, com a aplicação da lei federal de proteção de dados isso passou a ser uma obrigação. Sendo assim, nesse pequeno artigo vamos tratar de como podemos assumir essa responsabilidade utilizando NodeJS e JavaScript. Lembrando que cada um conhece o seu contexto e os níveis de segurança que a sua aplicação necessita, logo a ideia desse artigo é fornecer um norte para encontrar a melhor solução.</p><p>Nessa primeira parte vamos entender um pouco de como funciona a criptografia para depois irmos para a prática.</p><p><strong>O que é hashing?</strong></p><p>Hashing é o processo de converter qualquer valor de entrada de qualquer tamanho ou tipo, para um valor de tamanho fixo contendo letras e números. Por exemplo, seria como se você pudesse converter uma página inteira de um livro para uma única sentença e ainda assim poder utilizar essa única sentença para descobrir o conteúdo inteiro da página do livro. É exatamente o que o processo de hashing faz! E ele realiza isso utilizando o que chamando de <strong><em>hash functions</em></strong>.</p><p><strong>O que são hash functions?</strong></p><p>Podemos dizer que<strong> </strong>elas são propriamente o <strong><em>algoritmo</em></strong> que realiza o cálculo matemático responsável por transformar qualquer informação recebida em um bloco fixo de letras e números (hashing) como demonstra a figura abaixo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*RWZlAmjFtHzC60SO_3GjyA.png" /><figcaption>Exemplo da excução de uma Hash Function.</figcaption></figure><p>Cada saída gerada pela hash function é única, ou seja, para cada palavra ou frase haverá apenas um único hash no final. Por exemplo, se passamos a entrada <strong><em>“nodejs” </em></strong>a saída será <strong><em>“c81e2d0e1bfbb8e44090c4fd8f8cc7c4“. </em></strong>Porém se utilizarmos <strong><em>“Nodejs”, </em></strong>iniciando com letra maiúscula o resultado é completamente diferente: <strong><em>“d9d970a1252831d8db36a3d3319a1c99”. </em></strong>Uma pequena mudança na entrada muda drasticamente a saída. <strong><em>Então cada entrada tem sua respectiva saída!</em></strong></p><p>E para realizar este cálculo podemos encontrar vários tipos de algoritmos a nossa disposição como: <em>SHA-256, MD5, BLACK3</em> e etc. (com certeza você já deve ter ouvido falar de alguns deles) A escolha do algoritmo é um fator muito importante pois só assim poderemos garantir a segurança e integridade dos nossos dados. Caso queira consultar a aplicabilidade de cada algoritmo, pode fazê-lo nesse link: <a href="https://en.wikipedia.org/wiki/Secure_Hash_Algorithms">https://en.wikipedia.org/wiki/Secure_Hash_Algorithms</a></p><p><strong>Garantindo integridade dos dados no processo de hashing</strong></p><p>Apesar de tudo o que acabamos de considerar, o processo de hashing em si não garante a integridade dos dados que criptografamos.</p><p>Veja o exemplo abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgXAIhk41xO7uwLaG_I2Kw.png" /><figcaption>Modificação de uma saída criptografada.</figcaption></figure><p>Como a figura acima demonstrou, em um ambiente não seguro é muito fácil acontecer de um código malicioso ser adicionado em uma mensagem criptografada. Assim, quando a saída chegar ao seu destino, não será mais a mensagem original e sim um código alterado que poderá afetar todo o ambiente no qual houver tentativas de descriptografa-lo e/ou manipula-lo.</p><p>Ai então entra em ação nossas as <strong><em>Keyed-Hash Message Authentication Code (HMAC) </em></strong>ou em uma tradução livre: <strong><em>Código de autenticação de mensagem hash com chave.</em></strong></p><p>Em termos simples o HMAC é nada mais que uma chave em formato hash anexada ao hash original. Quando o hash original chegar ao seu destino, para tentar manipula-lo será necessário uma chave idêntica. Assim ele saberá que tal hash original não foi manipulado. O HMAC não criptografa a mensagem. Em vez disso, a mensagem deve ser enviada juntamente com o hash HMAC. Os participantes com a chave secreta irão fazer o hash da mensagem novamente e, se for autêntico, os hashes serão correspondentes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*m_b6sGN7LkYIVIwyczrgjQ.png" /><figcaption>Adicionando HMAC a mensagem criptografada.</figcaption></figure><p>Bom até aqui aprendemos como funciona o processo de hashing e como garantir a integridade do hash criado utilizando HMACs. Poderíamos nos aprofundar muito mais. Entretanto, essa base será suficiente para podermos ir para o código na parte 2, onde vamos ver como utilizando a classe Crypto do node podemos aplicar todos esses conceitos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aab4da809edc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkapi-solutions/criptografia-de-dados-com-nodejs-parte-1-aab4da809edc">Criptografia de dados com NodeJS — Parte 1</a> was originally published in <a href="https://medium.com/linkapi-solutions">LinkApi Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[O que realmente é um algoritmo recursivo?]]></title>
            <link>https://medium.com/linkapi-solutions/o-que-realmente-%C3%A9-um-algoritmo-recursivo-f8d6c56d8483?source=rss----ec64f022756c---4</link>
            <guid isPermaLink="false">https://medium.com/p/f8d6c56d8483</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Matheus Kielkowski]]></dc:creator>
            <pubDate>Tue, 08 Sep 2020 19:48:11 GMT</pubDate>
            <atom:updated>2020-09-08T23:00:44.754Z</atom:updated>
            <content:encoded><![CDATA[<p>Indo direto ao ponto, um algoritmo recursivo, é aquele que invoca à ele mesmo durante o processo de execução. Mas, será que é só isso?</p><p>Neste artigo quero te mostrar, de uma maneira simples, como este tipo de algoritmo realmente se comporta.</p><h3><strong>O que é a recursão?</strong></h3><p>Bem, quando estamos falando de <strong>ciência da computação</strong>, a recursividade é uma sub-rotina que se invoca durante o processo de execução de um programa.</p><p>Este tipo de algoritmo pode ser extremamente poderoso em alguns cenários, mas em outros nem tanto, podendo ser considerado até ineficiente.</p><p>Um exemplo muito claro do que é a recursão, é quando estudamos na matemática o cáculo do fatorial de um número qualquer. Exemplo:</p><p>factorial(1) = 1</p><p>factorial(2) = 2 * 1</p><p>factorial(3) = 3 * 2 * 1</p><p><em>factorial(4) = 4 * 3 * 2 * 1</em></p><p>Se pararmos para analisar, a fórmula para este processo sempre será a seguinte:</p><p><strong><em>factorial(n) = n * factorial(n-1)</em></strong></p><p>Vemos que a função chama à ela mesma, mas agora passando o valor de <strong><em>n - 1</em></strong>, para poder calcular o valor do fatorial de <strong><em>n</em></strong>.</p><p>Logo, se quisessemos calcular o fatorial de 4, precisariamos antes saber o valor do fatorial de 3 e assim por diante.</p><h3><strong>Recursividade na computação</strong></h3><p>Se você já tentou desenvolver o algoritmo do cáculo do fatorial de um número em uma determinada linguagem de programação, você pode ter percebido que não necessariamente existe apenas uma maneira de desenvolver esse algoritmo.</p><p>Mas sim por dois caminhos, um de maneira recursiva e outro de maneira iterativa. Então, qual vai ser a diferença entre os dois para o computador?</p><p>Primeiro, vamos discutir como esse algoritmo se comportaria de maneira <strong>recursiva</strong>:</p><pre>int factorial (int n) {</pre><pre>  if (n == 1) return 1;</pre><pre>else<br>  return n * factorial(n-1);</pre><pre>}</pre><p>Conforme vemos acima, quando retornamos a chamada da função <strong><em>factorial(n)</em></strong>, estamos voltando para o mesmo pedaço de código.</p><p>Logo, chamamos o parâmetro <strong><em>n</em></strong> diversas vezes, mas em todas <strong><em>n</em></strong> sempre será diferente. Então teremos que manusear e separar esse parâmetro toda vez que chamarmos a função.</p><p>Assim, o que você precisa entender é que num algoritmo como este, não temos apenas um <strong><em>n </em></strong>como<strong><em> </em></strong>parâmetro sendo armazenado na memória. E para podermos manusear e separar apropriadamente, precisamos então de uma <strong>Stack</strong>.</p><p>Imagine que vamos calcular o fatorial do número 4. A primeria coisa que irá acontecer vai ser mandarmos esse algoritmo para nossa pilha.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*4b8kbxZ-TJiP91SGQnZgbQ.png" /></figure><p>Para isto funcionar corretamente e ter suas próprias variaveis locais, o que inclui todas as diferentes instâncias de <strong><em>n</em></strong>, nós mandamos outro frame para uma outra área da nossa pilha, que será a resposta do fatorial de 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*eUYaKsmZmrz3nZx3EqhQqg.png" /></figure><p>Mas o fatorial de 4 exige que tenhamos o resultado do fatorial de 3, caso contrário não é possível obter o valor de 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*fxyQ25H4amx1XwL5YdaWLQ.png" /></figure><p>Se seguirmos o mesmo processo para os demais números, ao final nossa pilha estará da sequinte maneira:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*FeSxXQ17vfGwdNmzBNb0Fw.png" /></figure><p>Agora, sabemos que o fatorial de 1 é ele mesmo, então o fatorial de 2 que estava aguardando o resultado pode prosseguir com o cáculo, retornando o valor do fatorial de 2 podemos prosseguir com o cálculo do fatorial de 3, e assim por diante, até chegarmos no programa principal com o resultado do <strong>fatorial de 4</strong>, que corresponde ao número <strong>24</strong>.</p><p>O que percebemos, é que nessa sequência de multiplas pendêcias, cada uma dessas está associada a um valor diferente de <strong><em>n</em></strong>. Então quando resolvemos o fatorial de 1, as respostas começam a ser cascatiadas para as demais funções que estavam aguardando na Stack.</p><p>O fluxo do comportamento dessa função está logo abaixo:</p><pre>(factorial 4)<br>(* 4 (factorial 3))<br>(* 4 (* 3 (factorial 2)))<br>(* 4 (* 3 (* 2 (factorial 1))))<br>(* 4 (* 3 (* 2 1)))<br>(* 4 (* 3 2))<br>(* 4 6)<br>24</pre><p>Se notarmos, podemos ver que o fluxo tem um comportamento gráfico de <em>“ida e volta”</em>, ou seja, temos as multiplas pendências e o retorno dos resultados dessas multiplas pendências.</p><p>Isto está relacionado com a necessidade de memória, pois a medida que vamos fazendo novas chamadas, e aguardamos o retorno dessas chamadas para continuar a computação, precisamos fazer empilhamentos na Stack, conforme vimos anteriormente.</p><p>Agora como fariamos esse algoritmo de maneira <strong>iterativa</strong>? Vamos ver no código abaixo:</p><pre>int factorial (int n) {</pre><pre>  int result = 1;</pre><pre>  for (int i = 1; i &lt;= n; i++) {</pre><pre>     result = i * result;</pre><pre>  }</pre><pre>}</pre><p>O que fizemos aqui foi primeiro criar uma variável que inicia com o valor de 1 (esta que representa nosso resultado final) e depois criar um loop que a cada volta nós armazenamos na nossa variável <strong><em>result</em></strong> o valor do contador multiplacado pelo valor dela mesma. Ao final do algoritmo é retornado o valor da variável <strong><em>result, </em></strong>que no caso é o nosso resultado.</p><p>Com este tipo de procedimento, nós não temos a necessidade de <em>“ir e voltar”</em>, pois não tem computação sendo executada no retorno do processo. Logo, não temos necessidade de voltar todo o empilhamento feito na Stack.</p><h3><strong>Recursão em Árvore</strong></h3><p>A recursão em árvore, é um outro tipo de shape de execução que encontramos em alguns algoritmos recursivos. Ela é muita conhecida por seu fluxo ser moldado em uma estrutura de árvore.</p><p>Para exemplificar, vamos utilizar um algoritmo que nos retorna um número que pertence à sequência de Fibonacci e está na posição correspondente ao valor do nosso parâmetro:</p><pre>int fibonacci (int n) {</pre><pre>  if (n == 0) return 0;</pre><pre>  if (n == 1) return 1;</pre><pre>  return fibonacci(n - 1) + fibonacci(n - 2);</pre><pre>}</pre><p>Se tentarmos executar este código passando o parâmetro como valor 5, a nossa função nos retornará o número 5 pois ele é o quinto número da sequência de Fibonacci <strong>(lembrando que começamos a contar do 0)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*4-O86QmbFc0IpftFGjw6fQ.png" /><figcaption>Sequência de Fibonacci</figcaption></figure><p>Logo, seu shape de execução terá o seguinte formato:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*RzSGefr1noN1huTIwLzjsg.png" /></figure><p>Por mais que isso seja interessante e nosso código no final fique enxuto e simples, uma abordagem como esta é ineficiente, pois se você reparar na imagem, verá que temos diversos galhos de execução repetidos, como por exemplo o fibonacci do número 1 (fib 1), o que acarreta um desperdício e compromete o tempo de execução do nosso algoritmo.</p><p>É importante tentarmos migrar um shape em árvore como este, para uma abordagem mais econômica. Neste caso, vamos utilizar um loop para termos um shape de execução iterativo:</p><pre>int fibonacci(int n) {       <br>   int x = 0;        <br>   int y = 1;        <br>   int res = 0; <br>        <br>   for (int i = 0; i &lt;= n; i++) {            <br>     res = x;            <br>     x = y;            <br>     y = res + y;        <br>   }<br>        <br>   return res;    <br>}</pre><p>A recursão em árvore não é sempre ruim, em alguns cenários ela é até necessária, por exemplo em file system de sistemas operacionais. Mas o interessante é <strong>como podemos prever os processos que estão sendo gerados à partir de seus procedimentos.</strong></p><h3>Conclusão</h3><p>Espero que após você ter lido este artigo eu tenha te ajudado a entender um pouco mais sobre recursividade e como ela se comporta no processo de execução de algoritmos que utilizam desse tipo de estrutura.</p><p>Lembre-se que o fato do seu código estar enxuto e simples não significa que ele está eficiente, então sempre é bom entender a complexidade dos algoritmos que você está escrevendo para não causar desperdício na hora da execução.</p><p>Obrigado! : )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8d6c56d8483" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkapi-solutions/o-que-realmente-%C3%A9-um-algoritmo-recursivo-f8d6c56d8483">O que realmente é um algoritmo recursivo?</a> was originally published in <a href="https://medium.com/linkapi-solutions">LinkApi Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy - Chega de IFs!]]></title>
            <link>https://medium.com/linkapi-solutions/strategy-chega-de-ifs-b3166ba67f20?source=rss----ec64f022756c---4</link>
            <guid isPermaLink="false">https://medium.com/p/b3166ba67f20</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[strategy]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Matheus Kielkowski]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 16:36:52 GMT</pubDate>
            <atom:updated>2020-08-31T16:21:27.239Z</atom:updated>
            <content:encoded><![CDATA[<p>Neste artigo estarei te apresentando um design pattern muito poderoso e muito fácil de se aplicar em um projeto, conhecido como Strategy.</p><p>Ele não só irá facilitar sua vida como desenvolvedor, mas também manterá seu código bem estruturado e escalável. Evitando que você tenha que fazer aquele monte de if’s no seu sistema.</p><h3><strong>Mas afinal… O que é um pattern?</strong></h3><p>Antes de tudo, se você ainda não sabe o que é ou nunca utilizou um pattern, eles são tipos de designs de código para situações que encontramos constantimente no nosso dia a dia como desenvolvedores.</p><p>Seus objetivos são manter seu sistema bem organizado e manutenível, aumentando assim a escalabilidade e facilitando a manutenção da sua aplicação.</p><p>Além disso, eles são independentes da linguagem de programação, então não importa se seu sistema está escrito em Java, C#, Javascript, etc.</p><h3><strong>Entendendo seu funcionamento</strong></h3><p>Para que você possa realmente entender o que estou falando, vou criar um cenário fictício para exemplificar seu comportamento.</p><p>Imagine que temos uma funcionalidade em uma aplicação, que calcula o valor do pedágio em uma estrada. O valor deste pedágio leva em consideração o tipo de veículo, ou seja, cada tipo de veículo (moto, carro, caminhão, etc) irá pagar uma taxa de pedágio diferente.</p><p>De primeira, podemos pensar em fazer essa atribuição ao valor do pedágio da seguinte maneira:</p><pre>function calculateTollValue(typeOfVeichule) {   <br>   if( typeOfVeichule === &quot;motorcycle&quot;){<br>    // lógica que realiza o cálculo com base no tipo de veículo<br>   }<br>   else if( typeOfVeichule === &quot;car&quot;){<br>      // logic<br>   }<br>   else if( typeOfVeichule === &quot;truck&quot;){<br>      // logic<br>   }<br>   ...<br>}</pre><p>Mas perceba quantos if’s tivemos que acrescentar ao nosso código para realizar o cálculo do pedágio pelo tipo de veículo. Digamos que agora o sistema precisará ter mais 5 maneiras diferentes de realizar o cálculo, além das que já existem, será que a melhor solução para isso seria adicionando mais condições? Eu acredito que não, e irei de mostrar agora como solucionar esse problema.</p><p>Para não precisarmos acrescentar mais condições ao nosso código, mantendo ele mais escalável, iremos aplicar o pattern Strategy que recomenda separarmos a lógica em algoritmos menores e direcionar o fluxo conforme o parâmetro informado na nossa função <strong>calculateTollValue<em>.</em></strong></p><p>Logo, iremos criar três funções de cálculo diferentes, uma para cada tipo de veículo possível, visando separar a lógica e invocar o algoritmo quando necessário.</p><p><strong>MotorCycleTollValueStrategy</strong><br>calculate()</p><p><strong>CarTollValueStrategy</strong><br>calculate()</p><p><strong>TruckTollValueStrategy</strong><br>calculate()</p><p>Essa é uma ótima abordagem caso você esteja utilizando Java ou outras linguagens onde você possa trabalhar com interfaces.</p><p>Caso você esteja trabalhando com NodeJS, existe uma maneira bem simples. Apenas vamos criar um arquivo chamado <strong>TollValueStrategy </strong>e deixar sua estrutura da seguinte maneira:</p><pre>function motorcycleTollValue(){}<br>function carTollValue(){}<br>function truckTollValue(){}</pre><pre>module.exports[&quot;motorcycle&quot;] = motorcycleTollValue;<br>module.exports[&quot;car&quot;] = carTollValue;<br>module.exports[&quot;truck&quot;] = truckTollValue;</pre><p>Assim mantemos um código fonte e três métodos, um para cada tipo de veículo, divindo a lógica em funções menores da maneira com que o pattern sugere. E o mais legal agora, é como iremos invocar o método correto, na nossa função <strong>calculateTollValue</strong>:</p><pre>function calculateTollValue(typeOfVeichule) {   <br>  require(&quot;TollValueStrategy&quot;)[typeOfVeichule]()<br>}</pre><p>Invocando desta maneira, estamos atribuindo a responsabilidade de realizar o cálculo de acordo com o tipo de veículo passado na função como parâmetro.</p><p>Como podemos ver, retiramos todos os if’s que tinhamos anteriormente no nosso código, deixando ele simples, fácil de se entender e muito mais flexível, pois caso tenhamos que adicionar mais um tipo de veículo, só precisaremos modificar o arquivo <strong>TollValueStrategy</strong>, mantendo uma fácil manutenção no nosso código.</p><h3><strong>Conclusão</strong></h3><p>Agora que você entendeu como utilizar o pattern não significa que precisa sair tirando todos os if’s do seu código. Lembre-se, <strong>complexidade desnecessária é custo.</strong></p><p>Isto é só uma maneira de facilitar a manutenção da sua aplicação e melhorar sua estruturada. Basta que você análise o cenário do seu sistema para entender se faz sentido ou não aplica-lo.</p><p>Espero que tenha gostado!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3166ba67f20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkapi-solutions/strategy-chega-de-ifs-b3166ba67f20">Strategy - Chega de IFs!</a> was originally published in <a href="https://medium.com/linkapi-solutions">LinkApi Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[O que é o problema de N + 1?]]></title>
            <link>https://medium.com/linkapi-solutions/o-que-%C3%A9-o-problema-de-n-1-24975a28dcb8?source=rss----ec64f022756c---4</link>
            <guid isPermaLink="false">https://medium.com/p/24975a28dcb8</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[engineer]]></category>
            <dc:creator><![CDATA[Matheus Kielkowski]]></dc:creator>
            <pubDate>Thu, 27 Aug 2020 11:39:26 GMT</pubDate>
            <atom:updated>2023-07-10T21:00:57.124Z</atom:updated>
            <content:encoded><![CDATA[<h3>O que é o problema N + 1?</h3><p>O problema N+1 é um anti-pattern, conhecido por ser uma maneira ineficiente de realizar consultas numa base com um número relativamente grande de dados.</p><p>Neste artigo irei explicar o comportamento deste problema, como identifica-lo e como corrigi-lo. Mantendo o desempenho da suas aplicações eficiente.</p><h3>Como se comporta?</h3><p>Vamos imaginar que temos numa base de dados duas tabelas, uma de usuários e outra de artigos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*Rfs7wLygt_Jmcg9_OlNCCw.png" /></figure><p>A tabela de usuários armazena as informações de cada usuário registrado no sistema e a tabela de artigos armazena as informações dos artigos de cada usuário. Logo temos uma relação de 1 para N, sendo o N o número de artigos que cada usuário escreveu.</p><p>Imagine que você precise desenvolver um dashboard onde será exibido dados de todos os usuários e os títulos de todos os artigos de cada um deles. O que provavelmente você pensaria em fazer de primeira seria:</p><p><strong>1°- Buscar pelas informações de todos os usuários:</strong></p><pre>SELECT ID, name, email FROM Users;</pre><p><strong>2°- Em seguida consultar o título de todos os artigos de cada usuário:</strong></p><pre>SELECT title FROM Articles WHERE user_id = id_usuario;</pre><p>Agora pense que temos 500 usuários registrados na nossa base. As consultas serão executadas da seguinte maneira:</p><pre>SELECT ID, name, email FROM Users;</pre><pre>SELECT title FROM Articles WHERE user_id = 1;<br>SELECT title FROM Articles WHERE user_id = 2;<br>SELECT title FROM Articles WHERE user_id = 3;<br>SELECT title FROM Articles WHERE user_id = 4;<br>...<br>SELECT title FROM Articles WHERE user_id = 500;</pre><p>O que podemos reparar é que no final executamos <strong>501</strong> consultas ao nosso banco de dados, por isso o nome <strong><em>N+1</em></strong>, sendo N o número de usuários.</p><p>Nesse exemplo acima temos poucas colunas nas nossas tabelas, mas muitas vezes, em sistemas empresariais de médio à grande porte, o número de colunas numa tabela pode ser bem maior. Isso faz com que o tempo que nossas consultas irão levar e o tempo de resposta da nossa aplicação aumente. O que afinal de contas, não é nada bom.</p><h3>Como identificar?</h3><p>Na grande maioria das vezes, quando temos uma consulta dentro de um loop temos o problema de N+1. Trazendo um pouco mais para o dia a dia do desenvolvedor, abaixo deixo um pseudocódigo exemplificando este cenário:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*esf6Aj77EGKFNczXmlJ4YQ.png" /></figure><p>Como podemos notar, faremos uma primeira consulta que nos trás todos os usuários. Logo após, faremos N consultas, sendo N o número de usuários e para cada iremos trazer os artigos relacionados a ele.</p><h3>Como resolver?</h3><p>Agora vem a parte boa, vamos transformar este número de <strong>501</strong> consultas<strong> para apenas 2!</strong></p><p>Primeiramente, iremos continuar fazendo a consulta que nos trás os usuários:</p><pre>SELECT ID, name, email FROM Users;</pre><p>Agora, iremos utilizar estas informações que temos para fazer a nossa segunda consulta. Nessa precisaremos antes de tudo iterar sobre nosso array de usuários para termos apenas um novo array com todos os IDs. Ficando da seguinte maneira :</p><pre>SELECT title FROM Articles WHERE user_id IN (<strong><em>array_of_users_id</em></strong>);</pre><pre><em>// SELECT title FROM Articles WHERE user_id IN (1,2,3,4,...,500);</em></pre><p>Alterando o pseudocódigo que montamos anteriormente, ele segueria a seguinte lógica:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*VYEPtkdBOmQhpFTWZ8rSPg.png" /></figure><p>Assim , o que fizemos de modificação foi apenas aproveitar os dados retornados dos usuários para criar um novo array, mas agora apenas com o ID de cada usuário, e realizar uma consulta no banco por todos os artigos que possuem relação com um dos IDs informados no operardor <strong>IN</strong>. Totalizando apenas 2 consultas feitas ao banco.</p><h3>Mas… e se usarmos JOIN?</h3><p>Se você possui experiência com SQL, perceberá que podemos ao invés de usar o operador <strong>IN</strong>, realizar um<strong> JOIN</strong> e com isso apenas precisariamos de <strong>1 consulta</strong>.</p><p>O número de consultas pode afetar no desempenho da nossa aplicação, mas isso não significa que por ser 1 consulta será mais eficiente.</p><pre>SELECT Users.ID, Users.nome, Articles.title FROM Users INNER JOIN Articles ON Articles.user_id = Users.ID;</pre><p>Por exemplo se cada usuário apenas tivesse um artigo escrito, o JOIN seria mais eficiente. Mas se cada usuário tiver em média 5 artigos, teremos muitos dados repetidos trafegando entre o banco de dados e a aplicação, o que pode consumir tempo e memória.</p><h3>Conclusão</h3><p>No final das contas, a modificação que fizemos para alterar o número de consultas na nossa base foi bem simples, mas muito poderosa.</p><p>Com ela tivemos um ganho de desempenho muito alto, deixando o tempo de resposta da nossa aplicação menor e consequentemente fazendo nosso cliente final muito mais feliz.</p><p>O objetivo desse artigo era te mostrar como boas análises feitas com calma, podem refletir de maneira significativa no comportamento do seu sistema. Espero que tenha ajudado você a refletir sobre a maneira com que anda consumindo os dados da sua base e na maneira com que projeta suas aplicações.</p><p><strong>Não seja um datilógrafo de código, mas sim um engenheiro.</strong></p><p>Espero que tenha gostado!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24975a28dcb8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkapi-solutions/o-que-%C3%A9-o-problema-de-n-1-24975a28dcb8">O que é o problema de N + 1?</a> was originally published in <a href="https://medium.com/linkapi-solutions">LinkApi Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>