<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Yuri Vecchi</title>
    <description>The latest articles on DEV Community by Yuri Vecchi (@yurivecchi).</description>
    <link>https://dev.to/yurivecchi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F325910%2F303189e7-ac21-4b16-81e4-e7b84281491f.jpeg</url>
      <title>DEV Community: Yuri Vecchi</title>
      <link>https://dev.to/yurivecchi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/yurivecchi"/>
    <language>en</language>
    <item>
      <title>How a Culture of Testing can assure your application's quality</title>
      <dc:creator>Yuri Vecchi</dc:creator>
      <pubDate>Mon, 06 Apr 2020 22:27:56 +0000</pubDate>
      <link>https://dev.to/yurivecchi/how-a-culture-of-testing-can-assure-your-application-s-quality-1mmc</link>
      <guid>https://dev.to/yurivecchi/how-a-culture-of-testing-can-assure-your-application-s-quality-1mmc</guid>
      <description>&lt;p&gt;How many times you needed to implement a quick fix right after doing a deploy, errors created by a programming mistake or by an unforeseen scenario, or yet a little mistake that could be caught by another programmer in a code review preventing uploading bad code to production.&lt;/p&gt;

&lt;p&gt;The culture of testing is still shortly diffused at Brazilian companies that are applying PHP language in its core business leading to a poor quality code and creating a stigma of second class programming language. However, for those with good background, is very clear that PHP language offers all necessary resources to get the job done, and in the end the main responsible for not taking advantage of fully resources are ourselves, and this can happened by unfamiliarity or little skill.&lt;/p&gt;

&lt;p&gt;More recently, the PHP language has been received tons of changes about performance and functionalities, becoming an even more friendly language to newcomers and easy to teach, keeping it as one of the preferred entry level programming languages because developers adopt it without having a solid formation by skipping very important phases to reach a monthly salary of 5 digits, and one of those important phases is simply the one that could guarantee his/her job in the end of the month: The Tests.&lt;/p&gt;

&lt;p&gt;The fact of a test being existent will not guarantee that your application will run perfectly just as planned, it is exactly the opposite, they will give you a false safety sensation in each deploy made, and the only way to mitigate the risks is by maturing the whole culture of testing of your application, what makes necessary the involvement of the whole project team and so, everybody should have a commitment with the tests.&lt;/p&gt;

&lt;p&gt;The most important element to develop this culture of testing is called collaboration, with a lot of humble among developers, by doing code reviews very well elaborated by reviewers and with great acceptance from the reviewed ones. First of all, when we implement an application we should keep in mind that it does not belong to us, but in fact it has been developed to everyone else. This kind of thinking will impact directly the way we write our code. Other important elements to be considered are in depth knowledge about SOLID, Design Patterns, Clean Code, Data Structure among others. These knowledge are truly help because they work as universal communication players for discussion and to make decisions. Remember, the reviewer commonly will not know the business rules implemented in the code, but he/she should be able to distinguish what your code is intended to do.&lt;/p&gt;

&lt;p&gt;With this in mind we have some questions that we should constantly ask to ourselves. Am I able to change my application without having a change in its behavior? Do I know which is its expected behavior? Will a new programmer understand which is the expected behavior? Fortunately we have good ways to assure those kind of behaviours by implementing tests. In most cases we can start with Exploratory Tests just from the beginning, but they must be complemented with more assertive tests such as Unit Tests followed by Integration Tests.&lt;/p&gt;

&lt;h2&gt;
  
  
  Unit Tests
&lt;/h2&gt;

&lt;p&gt;They are the minor part of your application that you can test and it is this part you are supposed to use your skills about SOLID and Clean Code, fragmenting your application in a best possible level, shortening the Ciclomatic Complexity and making its functions more deterministic. In other words, every time the application receives same entries it will produce the same results. Let's take a look in the sampling function down below, it does not return the same result making the test being impossible.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;However with a small adjustment it becomes testable and so we augmented the tests coverage.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;You probably have realised that if we do not send the timestamp as an argument, it will never be possible testing the result.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  Integration Tests
&lt;/h2&gt;

&lt;p&gt;Integration tests are commonly applied over external services, those could be an external API for collecting exchange rates or either an internal package working as subsystem for a core project at the same company, it really makes no difference from the main point of view. What really matters is the fact if your team has no access for making changes in those external services the task of creating tests for those services are much more complex to be applied because the results coming from the external services can change at anytime, and what we can do is get ready for the worst and hope for the best.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Here we have once more another non deterministic function, but this time we just cannot isolate the HTTP client because the returned result is completely out of our control.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;So in this kind of scenario what we can do is making a usage of a technique known as "Mock" which allow us to control the returned results by simulating the external behavior. That way we can safely assure those returned results, and fortunately Guzzle library already brings this functionality right out of the box.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  Code Review
&lt;/h2&gt;

&lt;p&gt;Even if your test coverage is about 100% of your code, it is a fact that you still can find bad code written or business rules not very well clarified among other singularities. For all these kind of issues there is nothing better than getting a code revision from another dev, which will have another perspective about the implemented solutions and still shield the good practices. In this process is it imperative that all team members, both reviewers and reviewed, are fully of empathy. It is healthy to understand that all members are in a situation of constant learning and, although all team members are high tech devs, none of us is God and cannot have omniscience to dictate which is wrong or right.&lt;/p&gt;

&lt;p&gt;As a reviewer the most important thing is pointing errors in a very transparent manner providing as many details as possible, with tons of patience because it is very common that a dev being reviewed thinks the only possible solution it is his solution avoiding any others suggestions.&lt;/p&gt;

&lt;p&gt;In the other hand, for the reviewed it is good to keep his/her mind opened to accept new ideas for resolving the same problem, even if this means to rewrite all the code from scratch. It is also important to take in consideration that the reviewer does not make comments or ask changes for personal reasons, but the real motivation is because both of them are the responsible for keeping the application running in a best possible way.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;At EBANX we have a very strong Testing Culture and this is taken very seriously, so we promote Clean Code sessions weekly to improve even more our skills set, we incentive code reviews by more than one reviewer and even sessions with small teams to exchange ideas about solutions already available, we have a huge unit test base running to assure our automated deploys can really work on CI mode. In every single deploy the whole base of unit tests will run to assure the changes implemented will not break code already in production. And last but not least, we value the attention and respect from all teams involved in this process.&lt;/p&gt;

&lt;p&gt;A culture of testing is much more than simply delegate the responsibility about your code to another person, to write a very well clean code, to have a 100% of test coverage or being prepared for a chaos testing and having a resilient application. Actually the testing culture works going from learning with our own mistakes up to accepting new ideas. It is about improving ourselves as devs and guarantee a nice sleeping tight night to all those that are dependent on your application running without flaws. This is just a little bit of the acquired experience from passing by years, and each one of you can identify, partially or completely, that it pays off to keep working in this amazing and dynamic profession that coding is.&lt;/p&gt;

&lt;p&gt;#TAMOJUNTO #EBANXLIFE #DEVSHIELD&lt;/p&gt;

&lt;p&gt;Contributors: &lt;a href="https://www.linkedin.com/in/joaorlima/"&gt;João Pedro L.&lt;/a&gt;, &lt;a href="https://www.linkedin.com/in/jhcarboni/"&gt;Jorge Carboni&lt;/a&gt;, &lt;a href="https://www.linkedin.com/in/leonardo-strozzi/"&gt;Leonardo Strozzi&lt;/a&gt;, &lt;a href="https://www.linkedin.com/in/lucas-maldaner-59993a90/"&gt;Lucas Maldaner&lt;/a&gt;, &lt;a href="https://www.linkedin.com/in/marcelinojaning/"&gt;Marcelino Janing&lt;/a&gt; e &lt;a href="https://www.linkedin.com/in/yurivecchi/"&gt;Yuri Vecchi&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;References:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://blog.cleancoder.com/uncle-bob/2014/11/15/WeRuleTheWorld.html"&gt;https://blog.cleancoder.com/uncle-bob/2014/11/15/WeRuleTheWorld.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Cyclomatic_complexity"&gt;https://en.wikipedia.org/wiki/Cyclomatic_complexity&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Deterministic_algorithm"&gt;https://en.wikipedia.org/wiki/Deterministic_algorithm&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://grumpy-learning.com/"&gt;https://grumpy-learning.com&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://martinfowler.com/articles/practical-test-pyramid.html"&gt;https://martinfowler.com/articles/practical-test-pyramid.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://docs.guzzlephp.org/en/stable/testing.html"&gt;http://docs.guzzlephp.org/en/stable/testing.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://phpunit.de/getting-started/phpunit-9.html"&gt;https://phpunit.de/getting-started/phpunit-9.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Chaos_engineering"&gt;https://en.wikipedia.org/wiki/Chaos_engineering&lt;/a&gt;&lt;/p&gt;

</description>
      <category>php</category>
      <category>testing</category>
      <category>culture</category>
      <category>selfimprovement</category>
    </item>
    <item>
      <title>Como uma cultura de testes garante a qualidade de sua aplicação</title>
      <dc:creator>Yuri Vecchi</dc:creator>
      <pubDate>Thu, 02 Apr 2020 04:04:14 +0000</pubDate>
      <link>https://dev.to/yurivecchi/como-uma-cultura-de-testes-garante-a-qualidade-de-sua-aplicacao-e72</link>
      <guid>https://dev.to/yurivecchi/como-uma-cultura-de-testes-garante-a-qualidade-de-sua-aplicacao-e72</guid>
      <description>&lt;p&gt;Quantas não foram as vezes que após fazer o deploy de uma alteração, uma correção teve que ser feita às pressas, seja por um erro de programação, ou um cenário que não foi previsto durante o desenvolvimento, um erro pequeno que se outro programador tivesse a oportunidade de revisar não teria ido para produção.&lt;/p&gt;

&lt;p&gt;A cultura de testes é pouco difundida nas empresas que trabalham com PHP no Brasil, levando a uma baixa qualidade de código e a estigmatização da linguagem como sendo de baixa qualidade. Porém, com a experiência, nós percebemos que a linguagem oferece os recursos necessários, e somos nós que não utilizamos todo o potencial oferecido, seja por desconhecimento ou preciosismo.&lt;/p&gt;

&lt;p&gt;O PHP sofreu várias mudanças recentemente, desde performance até funcionalidades, tornando-se uma linguagem ainda mais amigável para o aprendizado, e com isso a barreira de entrada se tornou ainda mais baixa, e como consequência temos cada vez mais desenvolvedores iniciando sem ter uma boa base de formação, pulando etapas para chegar logo aos tão sonhados cinco dígitos de salário, e uma das etapas frequentemente ignorada é justamente a habilidade que vai garantir o seu emprego no final do mês: Os Testes.&lt;/p&gt;

&lt;p&gt;Testes, simplesmente por existirem, não garantem que sua aplicação irá funcionar para sempre da maneira planejada, pelo contrário, irão dar uma falsa sensação de segurança a cada deploy realizado, e a única maneira de mitigar isso é amadurecendo toda uma cultura de testes de sua aplicação, sendo necessário que todos os desenvolvedores envolvidos no projeto estejam cientes e de acordo.&lt;/p&gt;

&lt;p&gt;O elemento mais importante ao desenvolver essa cultura é a colaboração, com muita humildade, entre os desenvolvedores, através de code reviews bem elaborados por parte do revisor e aceitação por parte do revisado. Quando desenvolvemos uma solução temos que ter em mente que ela não é feita para nós, e sim para os outros, e isso acarreta diretamente na maneira como escrevemos nossos algoritmos. Conhecimentos profundos de SOLID, Design Patterns, Estrutura de dados, entre outros, ajudam nesse processo, pois servem de linguagem comum entre as partes no momento da discussão dos caminhos escolhidos. Lembrem-se, o revisor nem sempre vai conhecer a regra de negócio implementada no seu código, mas ao ler o mesmo, ele deve conseguir saber o que está acontecendo.&lt;/p&gt;

&lt;p&gt;Com isso em mente, devemos sempre nos perguntar, eu consigo fazer uma alteração em minha aplicação sem mudar o comportamento esperado dela? Eu sei qual é o comportamento esperado dela? O próximo desenvolvedor que fizer alterações vai compreender o comportamento esperado? Felizmente temos como garantir esse comportamento através de testes, geralmente feitos de maneira manual e pessoal no começo do desenvolvimento, o Teste Exploratório, mas que logo devem ser complementados, se já não implementados desde o início do desenvolvimento, por testes mais assertivos, como os Testes Unitários seguidos pelos Testes de Integração.&lt;/p&gt;

&lt;h2&gt;
  
  
  Testes Unitários
&lt;/h2&gt;

&lt;p&gt;São a menor parte da sua aplicação que pode ser testada, e é nessa parte que entram os conhecimentos de SOLID e Código Limpo, tornando os pedaços da sua aplicação o menor possível, assim diminuindo a Complexidade Ciclomática e tornando suas funções determinísticas, ou seja, sempre que receber a mesma entrada, vai retornar a mesma saída. Tomamos como exemplo a função abaixo, embora ela respeite muitos dos princípios de código limpo, ela não nos retorna sempre o mesmo valor, tornando assim o teste impossível.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Porém com uma pequena alteração, ela se torna testável e assim aumentamos a cobertura de nossos testes.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Perceba que se não passarmos o timestamp como argumento, nunca teremos a certeza do resultado.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  Testes de Integração
&lt;/h2&gt;

&lt;p&gt;São aplicados sobre serviços externos ao algoritmo desenvolvido, seja uma API externa aonde se busca uma cotação de uma moeda, ou um pacote dentro do repositório da própria empresa, porém sem acesso para alteração por parte da sua equipe, estes testes são mais complexos de se aplicar pois o resultado pode ser alterado a qualquer momento, e nós não temos controle sobre o código externo, tudo o que podemos fazer é nos preparar para o pior e torcer pelo melhor.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Mais uma vez temos uma função não determinística, porém desta vez não conseguimos simplesmente isolar o cliente de http, pois o resultado da requisição estará completamente fora do nosso controle.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Neste momento utilizamos Mocks, simulando o resultado das chamadas, para que possamos nos assegurar do retorno para o nosso código, a biblioteca do Guzzle já traz esta funcionalidade implementada para nós.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  Code Review
&lt;/h2&gt;

&lt;p&gt;Mesmo com os testes passando e a cobertura de código de 100%, ainda podem existir problemas de código mal escrito, regras de negócio não muito claras, entre outras singularidades. Para esses casos nada melhor do que confiar a revisão de nosso código para outro desenvolvedor, com outra visão sob as soluções implementadas e que igualmente respeite as boas práticas de programação. Neste momento é muito importante termos empatia, tanto como revisor, como revisado, saber que nem todos estão no mesmo momento de aprendizado e experiência, e que embora sejamos programadores, nenhum de nós é Deus, e tem onisciência para ditar o que é certo ou errado.&lt;/p&gt;

&lt;p&gt;Como revisor é importante apontar os erros de maneira transparente e bem detalhada, sempre com paciência, pois muitas vezes o revisado pode pensar que está com a razão, e aquela solução encontrada é a única possível.&lt;/p&gt;

&lt;p&gt;Já como revisado é necessário manter a mente aberta para outras ideias para a solução daquele problema, mesmo que signifique reescrever todo código do zero. Leve em consideração que o revisor não está fazendo aquilo por motivos pessoais, e sim porque ambos são responsáveis por manter a aplicação saudável para se trabalhar.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusão
&lt;/h2&gt;

&lt;p&gt;No EBANX essa cultura de testes é levada muito a sério, com seções de clean code semanais, aonde conseguimos aprimorar mais nossas técnicas, code reviews feitos por mais de um desenvolvedor, com discussões e troca de ideias sobre as soluções implementadas, uma base extensa de testes unitários, para garantir o funcionamento da aplicação, deploys automatizados, sempre executando todos os testes para ter a certeza de que todas as alterações irão funcionar quando combinadas e o mais importante de tudo, o respeito de todos os envolvidos pelo processo.&lt;/p&gt;

&lt;p&gt;Uma cultura de testes vai muito além de delegar responsabilidades do funcionamento de seu código para outras pessoas, escrever funções impecáveis, ter 100% de cobertura de código ou estar preparado para um teste de caos e ter uma aplicação resiliente. Vai de aprender com os erros, aceitar novas ideias, evoluir como desenvolvedor e garantir uma boa noite de sono a todos os que dependem de sua aplicação rodando sem falhas. Isso é um pouco da experiência adquirida ao longo dos anos que cada um de vocês se identifica em partes ou completamente que fazem valer a pena continuar nessa profissão tão incrível e dinâmica que é a programação.&lt;/p&gt;

&lt;p&gt;#TAMOJUNTO #EBANXLIFE #DEVSHIELD&lt;/p&gt;

&lt;p&gt;Contribuidores: &lt;a href="https://www.linkedin.com/in/joaorlima/"&gt;João Pedro L.&lt;/a&gt;, &lt;a href="https://www.linkedin.com/in/jhcarboni/"&gt;Jorge Carboni&lt;/a&gt;, &lt;a href="https://www.linkedin.com/in/leonardo-strozzi/"&gt;Leonardo Strozzi&lt;/a&gt;, &lt;a href="https://www.linkedin.com/in/lucas-maldaner-59993a90/"&gt;Lucas Maldaner&lt;/a&gt;, &lt;a href="https://www.linkedin.com/in/marcelinojaning/"&gt;Marcelino Janing&lt;/a&gt; e &lt;a href="https://www.linkedin.com/in/yurivecchi/"&gt;Yuri Vecchi&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Fontes:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://blog.cleancoder.com/uncle-bob/2014/11/15/WeRuleTheWorld.html"&gt;https://blog.cleancoder.com/uncle-bob/2014/11/15/WeRuleTheWorld.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Cyclomatic_complexity"&gt;https://en.wikipedia.org/wiki/Cyclomatic_complexity&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Deterministic_algorithm"&gt;https://en.wikipedia.org/wiki/Deterministic_algorithm&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://grumpy-learning.com/"&gt;https://grumpy-learning.com&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://martinfowler.com/articles/practical-test-pyramid.html"&gt;https://martinfowler.com/articles/practical-test-pyramid.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://docs.guzzlephp.org/en/stable/testing.html"&gt;http://docs.guzzlephp.org/en/stable/testing.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://phpunit.de/getting-started/phpunit-9.html"&gt;https://phpunit.de/getting-started/phpunit-9.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Chaos_engineering"&gt;https://en.wikipedia.org/wiki/Chaos_engineering&lt;/a&gt;&lt;/p&gt;

</description>
      <category>php</category>
      <category>testing</category>
      <category>culture</category>
      <category>selfimprovement</category>
    </item>
  </channel>
</rss>
