<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lucas Schwenke on Medium]]></title>
        <description><![CDATA[Stories by Lucas Schwenke on Medium]]></description>
        <link>https://medium.com/@xuenqui?source=rss-ca67ed9b1a63------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*W4boYvlYLYNA1owjIx4STQ@2x.jpeg</url>
            <title>Stories by Lucas Schwenke on Medium</title>
            <link>https://medium.com/@xuenqui?source=rss-ca67ed9b1a63------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 23:46:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xuenqui/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SOLID — Single Responsibility Principle]]></title>
            <link>https://xuenqui.medium.com/solid-single-responsibility-principle-277a3c79a132?source=rss-ca67ed9b1a63------2</link>
            <guid isPermaLink="false">https://medium.com/p/277a3c79a132</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[single-responsibility]]></category>
            <dc:creator><![CDATA[Lucas Schwenke]]></dc:creator>
            <pubDate>Sun, 06 Feb 2022 15:21:32 GMT</pubDate>
            <atom:updated>2022-02-06T15:46:57.685Z</atom:updated>
            <content:encoded><![CDATA[<h3>SOLID — Single Responsibility Principle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y19sanwHa8GwHy_I.png" /></figure><p>Hello everyone, how are you today? In the Oriented Object world, there are many patterns and good practices to do; one of them is SOLID!</p><h4>But what is SOLID? 🤔</h4><p>SOLID is an acronym created by <a href="https://pt.wikipedia.org/wiki/Robert_Cecil_Martin">Robert C. Martin</a> (your dear Uncle Bob). Uncle Bob defined five principles:</p><ul><li><strong>S — Single Responsibility Principle</strong></li><li><strong>O — Open Closed Principle</strong></li><li><strong>L — Liskov Substitution Principle</strong></li><li><strong>I — Interface Segregation Principle</strong></li><li><strong>D — Dependency Inversion Principle</strong></li></ul><p>These principles help developers create a better, more legible, and codes cleaner. In the Oriented Object is essential to know about these principles.</p><p>This article will see the first one, the Single Responsibility Principle. The examples were written in <a href="https://kotlinlang.org/"><em>Kotlin</em></a>, but the essential idea applies to any programming language!</p><h4><strong>S — Single Responsibility Principle</strong></h4><blockquote>A class should have one and only one reason to change, meaning that a class should have only one job.</blockquote><p>According to uncle Bob, a class should have one reason to change, and only one. So the class should specialize in one specific subject and has one responsibility.</p><p>It&#39;s wrong to write &quot;God class.&quot; But what is a God class? God class is a class that has many subjects and many responsibilities. God class is hard to write tests, a coupled code, and other bad things. Avoid writing God classes, ok?</p><p>So let&#39;s check a God class example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f09f930d83969cab721f869a674eac2/href">https://medium.com/media/6f09f930d83969cab721f869a674eac2/href</a></iframe><p>Let&#39;s check this God class. We have four responsibilities for two different subjects, User and Order. This class creates a new user, updates an existing user, sends an email confirmation, and creates a new user order. Wow, many responsibilities, no?</p><p>We are violating the SRP principle, and our code is hard to write tests, is not reusable, and has a significant cohesion.</p><p>Now let&#39;s put the SRP principle in our code! The UserService will be broken into some classes; the first one is to create a new User; this class has a responsibility to create a user, just it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/317673337d603659c30d4c48e825c2aa/href">https://medium.com/media/317673337d603659c30d4c48e825c2aa/href</a></iframe><p>Is it cleaner, right? Just has one responsibility and deal with a one subject. Let&#39;s do it in the others classes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30793b7e97c865b409b3023baf608d31/href">https://medium.com/media/30793b7e97c865b409b3023baf608d31/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b56bf53d6fe32d3ba47f426652f97028/href">https://medium.com/media/b56bf53d6fe32d3ba47f426652f97028/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac44a58d37a8418128e7a03ff191acad/href">https://medium.com/media/ac44a58d37a8418128e7a03ff191acad/href</a></iframe><p>Now your God class was broken into four new classes, each one having your specific responsibility and dealing with a one subject.</p><p>Now we can reuse the classes, write tests much better, have lower cohesion, and be easier to write and understand.</p><p>We can apply the SRP in functions (methods) too! Let&#39;s see a bad example and use the principle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc6e29085aa9e3818405073ba875b385/href">https://medium.com/media/cc6e29085aa9e3818405073ba875b385/href</a></iframe><p>The function createUser has three responsibilities, so now let&#39;s refactor this function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f5b302fb071911d7151f294e11b455e/href">https://medium.com/media/3f5b302fb071911d7151f294e11b455e/href</a></iframe><p>Now each function has our responsibility! Much better, what do you think?</p><p>The SRP is the base of the other principles; we will see them in the next articles. You can see the complete code in this <a href="https://github.com/lucasschwenke/solid/tree/main/src/main/kotlin/io/github/lucasschwenke/singleresponsability">repository</a>.</p><p>I will see you in the next article!</p><p><strong>References:</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/SOLID">https://en.wikipedia.org/wiki/SOLID</a></li><li><a href="https://blog.cleancoder.com/uncle-bob/2020/10/18/Solid-Relevance.html">https://blog.cleancoder.com/uncle-bob/2020/10/18/Solid-Relevance.html</a></li><li><a href="https://medium.com/desenvolvendo-com-paixao/o-que-%C3%A9-solid-o-guia-completo-para-voc%C3%AA-entender-os-5-princ%C3%ADpios-da-poo-2b937b3fc530">https://medium.com/desenvolvendo-com-paixao/o-que-%C3%A9-solid-o-guia-completo-para-voc%C3%AA-entender-os-5-princ%C3%ADpios-da-poo-2b937b3fc530</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=277a3c79a132" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[O que é idempotência e porque devemos utilizar]]></title>
            <link>https://xuenqui.medium.com/idempot%C3%AAncia-uma-boa-pr%C3%A1tica-a-se-utilizar-em-servi%C3%A7os-rest-633c38f4d7c0?source=rss-ca67ed9b1a63------2</link>
            <guid isPermaLink="false">https://medium.com/p/633c38f4d7c0</guid>
            <category><![CDATA[safe]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[idempotent]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[idempotency]]></category>
            <dc:creator><![CDATA[Lucas Schwenke]]></dc:creator>
            <pubDate>Wed, 20 Feb 2019 01:47:36 GMT</pubDate>
            <atom:updated>2025-01-06T22:16:41.782Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmPpBbHrC6LcZMb2rW49Ow.jpeg" /></figure><p><strong>ARTIGO ATUALIZADO, LEIA EM </strong><a href="http://codigoempratica.com/2025/01/06/guia-completo-sobre-idempotencia-e-metodos-seguros-em-apis/"><strong>http://codigoempratica.com/2025/01/06/guia-completo-sobre-idempotencia-e-metodos-seguros-em-apis/</strong></a></p><p>Quero começar este artigo lhe fazendo uma pergunta, você sabe ou já ouviu falar em idempotência?</p><blockquote>Em matemática e ciência da computação, a <strong>idempotência</strong> é a propriedade que algumas operações têm de poderem ser aplicadas várias vezes sem que o valor do resultado se altere após a aplicação inicial. — Wikipedia</blockquote><p>Então um exemplo, suponha que tenho meu X valendo 0, qualquer alteração que eu fizer nele, o valor sempre continuará o inicial, no caso 0.</p><blockquote>Um método HTTP idempotente é um método HTTP que pode ser chamado muitas vezes sem resultados diferentes. Não importa se o método é chamado apenas uma vez ou dez vezes. O resultado deve ser o mesmo. Essencialmente, significa que o resultado de uma solicitação executada com sucesso é independente do número de vezes que ela é executada. Por exemplo, na aritmética, adicionar zero a um número é uma operação idempotente. — W3C</blockquote><p>Quando falamos em idempotência em API’s REST, podemos concluir que os seguintes os verbos:</p><ul><li><strong>GET</strong>, <strong>PUT</strong>, <strong>DELETE</strong>, <strong>HEAD </strong>e <strong>OPTIONS </strong>são idempotentes<strong>.</strong></li><li><strong>POST </strong>não é idempotente.</li></ul><p>Uma pequena observação aqui, gostaria de citar sobre métodos <strong>seguros</strong> e <strong>não seguros</strong>, seguros são aqueles que <strong>não alteram o estado da aplicação</strong> e não seguros que <strong>podem alterar</strong>, uma tabela para exemplificar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*mDGl28XwDXkMgJqIGDXvwA.png" /></figure><p>Por que o POST não é idempotente? Vamos lá, a principal funcionalidade de uma chamada POST é criar um recurso, então a cada requisição que se realizar, um recurso será criado e assim alterando o estado da aplicação e não mantendo o atual.</p><p>Um exemplo mais prático, suponha que eu tenha um endpoint chamado “/user” do verbo POST que recebe o seguinte payload:</p><pre>{<br>    “name”: “Lucas”,<br>    “last_name”: “Paixão”,<br>    “city”: “Araraquara”<br>}</pre><p>Cada vez que esse endpoint for chamado, irá inserir um usuário com nome Lucas, sobrenome Paixão e cidade Araraquara, assim alterando o banco de dados, inserindo um novo registro, mudando o estado da aplicação.</p><p>O GET é considerado idempotente pois ele pode retornar a mesma resposta da primeira chamada N vezes.</p><p>O PUT é um caso legal, ele altera o estado de uma aplicação certo? Agora imagina o seguinte, tenho o mesmo endpoint que citei acima, porém, com o verbo PUT, se eu alterar o campo city de “Araraquara” para “São Paulo” e enviar uma vez, será alterado meu objeto e o estado da aplicação, com um status 200, porém, se o mesmo payload for enviado novamente, a resposta será igual a da primeira chamada, com o mesmo status e body, que no caso seria:</p><pre>{<br>    “name”: “Lucas”,<br>    “last_name”: “Paixão”,<br>    “city”: “São Paulo”<br>}</pre><p>Então, vemos que o PUT é idempotente, pois, a partir da primeira chamada que eu fizer, sempre terei a mesma resposta e o estado da aplicação não será alterado.</p><p>O mesmo ocorre para o verbo DELETE, quando fizemos a primeira chamada para o endpoint “/user?name=Lucas”, será deletado o objeto e o estado da aplicação será alterado, retornando um código 204 (no-content) ou 200 (ok), porém, se eu chamar o endpoint mais uma vez terei a mesma resposta, pois, o objeto não estará mais no banco de dados, apagado fisicamente (caso de deleção lógica, a flag não muda) e o estado da aplicação será o mesmo, retornando para o cliente o mesmo código da chamada anterior.</p><p>Podemos concluir que quando disponibilizamos uma API REST, devemos nos preocupar com os serviços que irão consumir os endpoints. Muitos comentem erros e realizam chamadas duplicadas, assim podendo afetar o resultado esperado ou recebendo algum tipo de exception. Também a casos de chamadas intencionais, por exemplo, quando ocorre um timeout, muitos serviços fazem uma nova chamada para o endpoint. Com isso devemos utilizar idempotência, prevenindo alguns erros e também aplicando uma boa prática.</p><p>Referências:</p><ul><li><a href="https://cursos.alura.com.br/forum/topico-como-tratar-a-idempotencia-44666">https://cursos.alura.com.br/forum/topico-como-tratar-a-idempotencia-44666</a></li><li><a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html</a></li><li><a href="https://restfulapi.net/idempotent-rest-apis/">https://restfulapi.net/idempotent-rest-apis/</a></li><li><a href="https://pt.wikipedia.org/wiki/Idempot%C3%AAncia">https://pt.wikipedia.org/wiki/Idempot%C3%AAncia</a></li><li><a href="http://restcookbook.com/HTTP%20Methods/idempotency/">http://restcookbook.com/HTTP%20Methods/idempotency/</a></li><li><a href="https://tools.ietf.org/html/rfc7231#section-4.2">https://tools.ietf.org/html/rfc7231#section-4.2</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=633c38f4d7c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>