<?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 Matheus Hofstede on Medium]]></title>
        <description><![CDATA[Stories by Matheus Hofstede on Medium]]></description>
        <link>https://medium.com/@hofstede-matheus?source=rss-d7090ee45416------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wRhjQb4odSsy8EwZD1knfw.jpeg</url>
            <title>Stories by Matheus Hofstede on Medium</title>
            <link>https://medium.com/@hofstede-matheus?source=rss-d7090ee45416------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:44:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hofstede-matheus/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[Seamless and Streamlined Deployment with Google Cloud + Firebase]]></title>
            <link>https://hofstede-matheus.medium.com/seamless-and-streamlined-deployment-with-google-cloud-firebase-420a0d06a1b?source=rss-d7090ee45416------2</link>
            <guid isPermaLink="false">https://medium.com/p/420a0d06a1b</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Matheus Hofstede]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 15:01:50 GMT</pubDate>
            <atom:updated>2023-08-22T15:01:50.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3bsKmac75hnRgvYZ.jpg" /></figure><p>Whether for POCs, college assignments, or recruitment process challenges, giving the user the possibility to use the application is essential. With this post, I bring a simple and robust way to deploy your projects.<br>This walkthrough is programming language/framework agnostic, as soon as the backend runs on a TCP port and the frontend generates static files.</p><h3>Backend</h3><p>For the backend, we&#39;ll use <a href="https://cloud.google.com/run?hl=pt-br">Cloud Run</a> to run Docker containers in a certain port and Javascript/Node.js.</p><p>We will use the &quot;<a href="https://cloud.google.com/run/docs/deploying-source-code">Deploy from source code</a>&quot; option, where a Dockerfile is not really necessary, but in this guide, we will use one for more control over the container.</p><p>Docker is a containerization platform that helps ship applications in a consistent way regardless of the environment.</p><p>A <a href="https://docs.docker.com/engine/reference/builder/">Dockerfile</a> is a recipe that Docker will follow to build an application image. Next, I’ll build one step by step:</p><p>You will need a Docker image for the language/framework you are using, find it on <a href="https://hub.docker.com/">Dockerhub</a> and insert it in FROM step. Always try to use official images and specific versions.</p><p><a href="https://hub.docker.com/_/node">Node.js / Javascript</a></p><p><a href="https://hub.docker.com/_/python">Python</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7746126442a6021437bfc911e8202a3/href">https://medium.com/media/b7746126442a6021437bfc911e8202a3/href</a></iframe><p>Define the location where the application will run and copy the dependency file.<br>For Javascript, it is a package.json<br>For Python, it is a requirements.txt</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/757baa4831685b759fb2e702fad968d5/href">https://medium.com/media/757baa4831685b759fb2e702fad968d5/href</a></iframe><p>Install dependencies as usual.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6e4dd100e9289ab63e99c40c08a03bb/href">https://medium.com/media/c6e4dd100e9289ab63e99c40c08a03bb/href</a></iframe><p>Copy the source code.<br>Note that two COPY commands were run: One for the dependencies and another for the source code.</p><p>The advantage of installing dependencies in a separate step is that since each line of the Dockerfile is a layer, Docker will cache the layers that haven’t changed. <br>An example is if only the source code changes, lines 4 and 6 will benefit from the cache and dependencies would not be installed again.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b92c4692365db70e5c4899ffa41e200f/href">https://medium.com/media/b92c4692365db70e5c4899ffa41e200f/href</a></iframe><p>Finally, expose the port your application will use and set the CMD command.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/948a6dde588e71ae853c6bfb19003d27/href">https://medium.com/media/948a6dde588e71ae853c6bfb19003d27/href</a></iframe><p>Above is the result of the recipe needed to run the application’s container.</p><p>Create a <a href="https://cloud.google.com/resource-manager/docs/creating-managing-projects">new project</a>.</p><p><a href="https://cloud.google.com/billing/docs/how-to/verify-billing-enabled#console">Make sure that billing is enabled for your Google Cloud project</a>.</p><p><a href="http://console.cloud.google.com/apis/library/run.googleapis.com">Enable the Cloud Run Admin API</a>.</p><p><a href="https://cloud.google.com/sdk/docs/">Install and initialize</a> the gcloud CLI.</p><p>Or follow <a href="https://cloud.google.com/run/docs/setup">this guide</a>.</p><p>To build and deploy the container on Cloud Run, use it in the root of your backend project, where the Dockerfile is located:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b341d9079ff4d9a0ba2a8178aa14d6b5/href">https://medium.com/media/b341d9079ff4d9a0ba2a8178aa14d6b5/href</a></iframe><p>Where <em>cloudrunapp</em> is the name you want to give the service.</p><p>Don’t forget to enable the <a href="https://console.cloud.google.com/apis/library/run.googleapis.com?hl=pt-br">Cloud Run API and a billing</a> account for this project.</p><p>If prompted, select a region and allow “unauthenticated invocations”</p><p>If you need to add <a href="https://cloud.google.com/run/docs/configuring/services/environment-variables#console">environment variables</a>, click “Edit and Deploy New Revision”. In the “Container” tab, scroll down to “Environment variables” and add the necessary ones.<br>This should be ok for tiny projects, but if you need more security, please use <a href="https://cloud.google.com/run/docs/configuring/services/secrets">Secret Manager</a>.</p><p>Your application should be available at the indicated link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*534jfklWGKp8Frto72A-qw.png" /></figure><h3>Frontend</h3><p>For the frontend, we’ll use Firebase Hosting to serve static files.</p><p>Create a <a href="https://console.firebase.google.com/u/0/">Firebase</a> project in the console.</p><p>In this example, we’ll initialize a <a href="https://vitejs.dev/guide/">Vite</a> project, build it, and serve it from Firebase Hosting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/057abd42f1f39c57df4ff2ae12f1a6f8/href">https://medium.com/media/057abd42f1f39c57df4ff2ae12f1a6f8/href</a></iframe><p>The <em>dist</em> folder will be created.</p><p>Install firebase-tools, login and start a Firebase project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3e5ce99bd108399f435ce3ecd08f0f6/href">https://medium.com/media/e3e5ce99bd108399f435ce3ecd08f0f6/href</a></iframe><p>Follow this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7834c4e9986c75b7880926814d2793c3/href">https://medium.com/media/7834c4e9986c75b7880926814d2793c3/href</a></iframe><p>And finally deploy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e85d75365a0613e4c53cf5315ea3cc4d/href">https://medium.com/media/e85d75365a0613e4c53cf5315ea3cc4d/href</a></iframe><p>Your application will be served on the indicated link and even the <a href="https://firebase.google.com/docs/hosting/custom-domain">custom domain</a> can be configured easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMpfLTSgLfw2vY_IWOCw-Q.png" /></figure><p>Github repo with code:</p><p><a href="https://github.com/hofstede-matheus/deploy-gcp-tutorial">https://github.com/hofstede-matheus/deploy-gcp-tutorial</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=420a0d06a1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilizando OKR para planejamento pessoal]]></title>
            <link>https://hofstede-matheus.medium.com/utilizando-okr-para-planejamento-pessoal-75e61f989b2d?source=rss-d7090ee45416------2</link>
            <guid isPermaLink="false">https://medium.com/p/75e61f989b2d</guid>
            <category><![CDATA[planejamento]]></category>
            <category><![CDATA[okr]]></category>
            <category><![CDATA[goals]]></category>
            <category><![CDATA[metas-pessoais]]></category>
            <category><![CDATA[2023]]></category>
            <dc:creator><![CDATA[Matheus Hofstede]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 17:40:07 GMT</pubDate>
            <atom:updated>2023-01-09T18:37:42.903Z</atom:updated>
            <content:encoded><![CDATA[<p>Percebi que um artigo que fiz em 2020 sobre esse tema vem recebendo uma quantidade visualizações atípicas: cerca de 300 no mês de dezembro e quase 500 nos últimos 2 meses. Dois anos depois, mais maduro e vivido, faço essa segunda versão para ajudar quem precisa se planejar nesse momento.</p><p>Antes de tudo, queria deixar alguns fatos sobre planejamento:</p><ol><li>Planejamento de final de ano só é uma convenção. Seja no final ou metade do ano, o importante é ter um.</li><li>Tudo bem não &quot;tickar&quot; tudo e o OKR entende isso. Mais adiante explico porque 70% é &quot;ok&quot;.</li><li>&quot;Pivotar&quot; é parte do OKR. Se o que foi definido não fizer sentido, nada impede começar o planejamento do zero em qualquer momento do ano.</li></ol><p>Utilizar conceitos de administração aplicados à minha vida pessoal não é algo novo pra mim e com OKR não é diferente: apesar de ser mais usado em empresas, conceitos se encaixam bem na vida pessoal.</p><p>A metodologia OKR sugere clareza na definição das metas e um planejamento menos espaçado, em ciclos de 3 meses. Afinal, nesse peíodo de tempo, muita coisa pode mudar.</p><p>No OKR temos 3 dimensões:</p><h4>Objetivos</h4><p>Dão uma perspectiva de estratégia e indicam claramente <strong>onde você quer chegar</strong>.</p><h4>Resultados chaves (Key-results)</h4><p>São metas mensuráveis que indicam <strong>o quão perto</strong> você está de alcançar o objetivo.</p><h4>Iniciativas</h4><p>Ações físicas que <strong>devem ser tomadas</strong> para alcançar o objetivo. Normalmente envolvem rotina ou ações únicas que convergem para o resultado desejado.</p><h4>Segue um exemplo:</h4><blockquote><strong>Objetivo</strong>: Comprar o celular x à vista</blockquote><blockquote><strong>Resultado chave 1</strong>: Reduzir gastos fixos em 20%, em relação aos meses passados</blockquote><blockquote><strong>Resultado chave 2</strong>: Poupar e investir (em renda fixa) R$ 200 por mês</blockquote><blockquote><strong>Iniciativas</strong>: Cortar assinatura de streaming que não é tanto usada; Trocar para um plano de internet mais barato; Pedir delivery apenas nos finais de semana; Pesquisar investimentos de renda fixa mais rentáveis que 100% do CDI.</blockquote><p>Nem todos objetivos podem ser realizados em 3 meses, por isso existem duas cadências de OKRs:</p><h4>Táticos</h4><p>OKRs de curto prazo e guiadores, que pode ser alcançados em 3–4 meses. Normalmente convergem para os OKRs estratégicos.</p><h4>Estratégicos</h4><p>OKRs de médio-longo prazo e motivacionais, que podem ser alcançados em 1–2 anos. Tendem a ser mais flexíveis por causa da dificuldade humana em planejar em longo prazo.</p><h3>Como chegar aos objetivos?</h3><p>Para chegar nos meus objetivos estratégicos, costumo a separar em 3 etapas:</p><h4>Autoconhecimento</h4><p>É um momento de descoberta pessoal e esclarecimento de suas valores.<br>Utilize ferramentas como análise <strong>SWOT</strong> (matriz FOFA) e a <strong>Roda da Vida</strong> para levantar pontos que precisam ser melhorados.</p><h4>Brainstorm</h4><p>Depois do momento de descoberta, reflita sobre objetivos e coisas que são relevantes de investir. Ainda não é o momento de descartar possibilidades.</p><h4>Priorização</h4><p>É fisicamente impossível fazer tudo que veio nos passos anteriores, então a hora de priorizar o que mais faz sentido naquele seu momento.</p><p>Para chegar nos meus objetivos táticos, eu repito os passos de <strong>Brainstorm</strong> e <strong>Priorização</strong> com um ciclo de 3 meses em mente.</p><h3>Quando mudar de estratégia?</h3><p>Talvez os objetivos táticos não foram os melhores para levar até os estratégicos e, no final de cada ciclo, é o momento de avaliar isso.</p><p>Se os estratégicos não fizerem mais sentido, o correto é passar novamente nos passos de <strong>Autoconhecimento</strong>, <strong>Brainstorm</strong> e <strong>Priorização </strong>para gerar algo mais coerente.</p><h3>Sobre resultados no OKRs</h3><p>Na metodologia, é considerado &quot;ok&quot; atingir 70% dos seus resultados, mas o ideal não deixa de ser 100%.</p><p>Quando aplicado no contexto empresarial, metas tendem a ser altamente ambiciosas para esses 70% já serem algo relevante, porém eu sinceramente não recomendo definir metas tão ambiciosas na sua vida pessoal e gerar frustração e ansiedade.</p><p>Resultado é mais válido que bater números.</p><p>Também sabemos que medir cansa, e minha sugestão é utilizar estratégias pra ajudar nisso:<br>Caixinhas e aportes automáticos podem ajudar a ter mais disciplina.<br>O aplicativo que você é obrigado a usar na hora de treinar pode contar os dias pra você.<br>Acoplar novos hábitos à rotinas que você já iria fazer (trabalho e/ou estudos) ajudam.</p><p>Dito isso, espero que o uso dessa do OKR no planejamento pessoal ajude a realizar seus objetivos em 2023.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75e61f989b2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proxy Pattern in a Clean Architecture context: A decoupled Cache implementation proposal with…]]></title>
            <link>https://levelup.gitconnected.com/proxy-pattern-in-a-clean-architecture-context-a-decoupled-cache-implementation-proposal-with-ff0bb5f96161?source=rss-d7090ee45416------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff0bb5f96161</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Matheus Hofstede]]></dc:creator>
            <pubDate>Sat, 22 Oct 2022 22:16:27 GMT</pubDate>
            <atom:updated>2022-11-01T02:40:44.288Z</atom:updated>
            <content:encoded><![CDATA[<h3>Proxy Pattern in a Clean Architecture context: A decoupled Cache implementation proposal with NodeJS and TypeScript</h3><p>The “Proxy” design pattern is a structural pattern that allows an object to be replaced by another that intermediates the original one. An example is a Cache, which temporarily stores data to avoid access to a costly resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*uDrHTUBGj4yNWerl9yiWZA.png" /><figcaption><a href="https://refactoring.guru/design-patterns/proxy">https://refactoring.guru/design-patterns/proxy</a></figcaption></figure><p>In this post, I propose an elegant and decoupled way to solve this problem in the context of Clean Architecture.<br>This post builds on my <a href="https://hofstede-matheus.medium.com/achieve-dependency-inversion-with-nodejs-typescript-and-tsyringe-8b956bc3254c">last post</a>, which still respects the principles of dependency inversion.</p><p>Highlights are:</p><ul><li><strong><em>Proxies</em></strong> implement the same interface as any <strong><em>Repository</em></strong>, so <strong><em>Usecases</em></strong> don’t know (and shouldn’t need to) that they are working with a proxy.</li><li>Few boilerplate in proxy implementations.</li><li>Extensible through <strong><em>Proxy</em></strong> and <strong><em>Cacheable</em></strong> interfaces</li></ul><p>First of all, we must implement two interfaces:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4967ada8885fe8543aff9dfe5edaf4a/href">https://medium.com/media/d4967ada8885fe8543aff9dfe5edaf4a/href</a></iframe><p><strong><em>Cacheable</em></strong> defines the shape in which the object to be cached will be wrapped. <br><strong><em>value</em></strong> represents the data itself, <br><strong><em>expiresAt</em></strong> represents when the object will expire.</p><p><strong><em>Proxy</em></strong> defines the contract that a proxy must follow. <br><strong><em>TTL</em></strong> is generic to ease the extensibility of a proxy. <br>Since our <strong><em>Proxy</em></strong> will be an <strong><em>InMemmoryCacheProxy</em></strong>, its implementation can be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f483505e7bdf4d38545db22f51f4ba88/href">https://medium.com/media/f483505e7bdf4d38545db22f51f4ba88/href</a></iframe><p>In this implementation, we defined that the Generic <strong>TTL</strong> is a number and the <strong><em>ExpireCondition</em></strong> is of type Date. In this specific proxy implementation, we want it to expire over time.</p><p>Note that in this particular implementation, the cache is stored in memory and managed via <strong><em>DI</em></strong>. Still, it could be, for example, stored in <strong><em>Redis (RedisCacheProxy)</em></strong>, as long as the <strong><em>Proxy</em></strong> interface is respected.</p><p>Also, notice that the <strong><em>proxy()</em></strong> function receives a function as a parameter. In the implementation, we use that function name to inject the <strong><em>Cacheable </em></strong>object and call it when the cache expires<em>.</em></p><p>Last but not least, I created a function to make it easier to differentiate a <strong><em>Proxy</em></strong> token from a <strong><em>Proxee</em></strong> token.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/051b01913054f67e98acef14217f9ac1/href">https://medium.com/media/051b01913054f67e98acef14217f9ac1/href</a></iframe><p>As I said before, whoever is calling does not know that they are calling a <strong><em>Proxy</em></strong> because the contract is the same as for any repository:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43ed16720dba4eb492e212a487ae2772/href">https://medium.com/media/43ed16720dba4eb492e212a487ae2772/href</a></iframe><p>Followed by a proxy implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26f63c6e1ec1ad177160c1f1db68f69c/href">https://medium.com/media/26f63c6e1ec1ad177160c1f1db68f69c/href</a></iframe><p>The only difference is that it receives the original repository in the constructor to point to the actual source.</p><p>With the entire implementation located in <strong><em>CacheProxy</em></strong>, we could reuse code and simplify the <strong><em>Proxy</em></strong> implementation.</p><p>In our container, we must register the <strong><em>Proxy</em></strong>, the <strong><em>Proxee</em></strong> (actual repository), and the function to be <strong><em>Cacheable</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ce2b0441b89efbe05d19debee3130ba/href">https://medium.com/media/0ce2b0441b89efbe05d19debee3130ba/href</a></iframe><p>In this way, our <strong><em>GetCatsUseCase </em></strong>doesn&#39;t even get modified, as it is still using a <strong><em>CatsRepository</em></strong>.</p><p>As a running example, I created a test suite using <strong><em>jest</em></strong>. First, we need to configure the test container:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ee822fa7cada916b57115bf82f57de8/href">https://medium.com/media/8ee822fa7cada916b57115bf82f57de8/href</a></iframe><p>And here are the tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80757980f71397d2084b0c3263ad5966/href">https://medium.com/media/80757980f71397d2084b0c3263ad5966/href</a></iframe><p>In the first test, we check if the real repository is being called since it was initialized as <strong><em>undefined</em></strong> and <strong><em>expiresAt</em></strong> as <strong><em>new Date()</em></strong>.</p><p>In the second one, we simulated a change in the original repository. However, as the object has not expired in the cache, it still should return the following:</p><pre>[<br>  { name: &#39;cat1&#39;, breedName: &#39;Persa&#39; },<br>  { name: &#39;cat2&#39;, breedName: &#39;Sphynx&#39; }<br>]</pre><p>In the last one, we simulate a delay long enough to cause the cache to expire so that the data is taken from the original repository:</p><pre>[<br>  { name: &#39;cat3&#39;, breedName: &#39;Persa&#39; }, <br>  { name: &#39;cat4&#39;, breedName: &#39;Sphynx&#39; }<br>]</pre><p>To see it live, run:</p><pre>yarn test</pre><p>This simple example shows how to implement Cache with Clean Architecture with NodeJS in the backend. Still, the main idea is applicable in a frontend or mobile, even with different programming languages, if it supports OOP.</p><p>The complete code is located in this <a href="https://github.com/hofstede-matheus/proxy-pattern-cache">repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff0bb5f96161" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/proxy-pattern-in-a-clean-architecture-context-a-decoupled-cache-implementation-proposal-with-ff0bb5f96161">Proxy Pattern in a Clean Architecture context: A decoupled Cache implementation proposal with…</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Achieve dependency inversion with NodeJs, Typescript, and tsyringe]]></title>
            <link>https://hofstede-matheus.medium.com/achieve-dependency-inversion-with-nodejs-typescript-and-tsyringe-8b956bc3254c?source=rss-d7090ee45416------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b956bc3254c</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Matheus Hofstede]]></dc:creator>
            <pubDate>Thu, 29 Sep 2022 21:39:28 GMT</pubDate>
            <atom:updated>2022-09-29T21:39:28.541Z</atom:updated>
            <content:encoded><![CDATA[<h3>Achieve dependency inversion with NodeJS, Typescript, and tsyringe</h3><p>Dependency inversion is one of the 5 SOLID principles and, in my opinion, one of the most important as it allows decoupling modules through abstractions instead of using concrete implementations.</p><p>Remember that you <strong>don’t</strong> need to use a dependency injection tool to achieve the dependency inversion principle, although a DI library like tsyringe makes it easier by delegating the injection to an external module/container.</p><p>At various times in my career, I came across projects in js/ts that used a DI library, and although a repository/service was being injected, the injection was provided by the class name (and not by an abstraction).</p><pre>container.register(InMemmoryCatsRepository, InMemmoryCatsRepository)</pre><pre>...<br>export class GetCatsUseCase implements UseCase {</pre><pre>@inject(InMemmoryCatsRepository) private catsRepository: CatsRepository<br>...<br>}</pre><p>Injecting <strong><em>InMemmoryCatsRepository</em></strong> (a class) breaks the idea of dependency inversion as the <strong><em>usecase</em></strong> layer gets to know the implementation, thus depending directly on it.</p><p>Instead of using a class like before, let’s use a <a href="https://github.com/microsoft/tsyringe#injection-token">token</a>, which can be a class, a string, or a symbol.</p><pre>type InjectionToken&lt;T = any&gt; =<br>  | constructor&lt;T&gt;<br>  | DelayedConstructor&lt;T&gt;<br>  | string<br>  | symbol;</pre><p>To show that, I will use a project that uses dependency injection manually and implement it correctly with <strong><em>tsyringe</em></strong>.</p><h4>Application Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYL1z_wYLv4vRBixvbddFg.jpeg" /></figure><h4>Folder schema</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*82smxmzKF6x79u73AUqcdA.jpeg" /></figure><p>Starting from the point where the dependencies are injected manually (via instance), let’s focus on the part where the dependency inversion makes the most sense: in the <strong><em>usecase</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/289bf3e23626a68e4a017d7307b13ca3/href">https://medium.com/media/289bf3e23626a68e4a017d7307b13ca3/href</a></iframe><p>And dependencies are resolved in index.ts</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8439257c1ffa288715f874b8e5fc11a1/href">https://medium.com/media/8439257c1ffa288715f874b8e5fc11a1/href</a></iframe><p><a href="https://github.com/hofstede-matheus/di-node-ts-tsyringe/tree/e253e139de28b4ecac2c59e2b83e8ccc29480f23">See this commit</a></p><p>At this point, we have the benefit that the <strong><em>usecase</em></strong> constructor receives an interface, and that&#39;s great. But we can do even better by injecting the dependencies using a dependency injection tool.</p><p>Let&#39;s follow with using <strong><em>tsyringe</em></strong>.</p><p>I&#39;m not going to show how to install and configure <strong><em>tsyringe</em></strong>, as it is well documented in the <a href="https://github.com/microsoft/tsyringe#installation">official docs</a>.</p><p>Let&#39;s start by creating a container to register the dependencies in <strong><em>src/di/container.ts</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9e9202fbd9a3a2b367c11dac886c814/href">https://medium.com/media/e9e9202fbd9a3a2b367c11dac886c814/href</a></iframe><p>Now all dependencies are registered in one single place, and we can control and register each instance depending on the environment (e.g., injecting a FakeRepository in a test environment)</p><p>Let&#39;s annotate the usecase with <strong><em>@injectable</em></strong>, and inject the repository with <strong><em>@inject. </em></strong>The repository also needs to be annotated with <strong><em>@injectable.</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b0a1a26e777a8df63931c7e1bb6cf5a/href">https://medium.com/media/4b0a1a26e777a8df63931c7e1bb6cf5a/href</a></iframe><p><a href="https://github.com/hofstede-matheus/di-node-ts-tsyringe/tree/6c10ab38bab1536d209b5e6b25ba6ea23e3c5033">See this commit</a>.</p><p>Although the code above works, we just created a dependency between <strong><em>GetCatsUseCase</em></strong> and <strong><em>InMemmoryCatsRepository. </em></strong>In other words, an inner layer (application) depends on an implementation detail, the infra layer (database).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B41naoYE859GrlXU.png" /><figcaption><a href="https://www.dandoescode.com/blog/clean-architecture-an-introduction/">https://www.dandoescode.com/blog/clean-architecture-an-introduction/</a></figcaption></figure><p>Let&#39;s solve this issue.</p><p>First, we must attach a token with the repository (abstraction). I choose to use a Symbol as they are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol">immutable and unique</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f5eb45a3191afc4022effa65cbf512f/href">https://medium.com/media/2f5eb45a3191afc4022effa65cbf512f/href</a></iframe><p>And the repository can be registered as a Singleton, so the instance is shared between all the application lifetime:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8264c9bb96fe059d1dc8f8162c8c70b9/href">https://medium.com/media/8264c9bb96fe059d1dc8f8162c8c70b9/href</a></iframe><p>And now, our <strong><em>usecase</em></strong> does not know (and it doesn&#39;t need to) the concrete repository implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fec6396eade2d0d4ec565d59942da542/href">https://medium.com/media/fec6396eade2d0d4ec565d59942da542/href</a></iframe><p><a href="https://github.com/hofstede-matheus/di-node-ts-tsyringe/commit/2864e0d714406be415ca8b52570fa9ce386f0ce1">See this commit</a>.</p><p>The implementation of that Repository can be like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0e40343b4c6e67e2851ca1dbd50848b/href">https://medium.com/media/a0e40343b4c6e67e2851ca1dbd50848b/href</a></iframe><p>And changing the Repository Data Source is as easy as:</p><ol><li>Implementing a new repository:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/918c61f7be82d0bb6692a1e639d1112d/href">https://medium.com/media/918c61f7be82d0bb6692a1e639d1112d/href</a></iframe><p>2. And registering it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bf48fde38d97a8cef8ddb3f0e4a2f5c/href">https://medium.com/media/1bf48fde38d97a8cef8ddb3f0e4a2f5c/href</a></iframe><p><a href="https://github.com/hofstede-matheus/di-node-ts-tsyringe/tree/a5a6ae025973dd8d5119d62c403907d270bd8f84">Check this commit</a>.</p><p>The application works in the same way, but now we are fully respecting the <em>dependency inversion</em> <em>principle</em>, and in addition, respecting the <em>open-closed principle </em>as a Repository is open for extension but closed for modification.</p><p>This tiny example can be extended at various levels and be applied to more significant projects, with the benefit of having much more maintainable applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b956bc3254c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making my homepage score 95+ on PageSpeed Insights]]></title>
            <link>https://hofstede-matheus.medium.com/making-my-homepage-score-95-on-pagespeed-insights-648e08a534c1?source=rss-d7090ee45416------2</link>
            <guid isPermaLink="false">https://medium.com/p/648e08a534c1</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[page-speed]]></category>
            <dc:creator><![CDATA[Matheus Hofstede]]></dc:creator>
            <pubDate>Sat, 24 Apr 2021 02:05:38 GMT</pubDate>
            <atom:updated>2021-04-24T02:07:52.613Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*kSphKAtQ-0PyoCgq.jpg" /></figure><p>Taking advantage that today I had a holiday, I did some upgrades on my personal website, linking 2 projects to my portfolio. So, I tested some changes to see if I could get a higher score on PageSpeed Insights.</p><p>I’m going to tell how I turned my personal website from 87–96 to a 95–99 score on PageSpeed Insights.</p><h3>Preload CSS</h3><p>I use Roboto font from Google Fonts, so my first try was preloading Google Fonts, not blocking the page rendering. So my page loads, and until the CSS is not downloaded, it will fall back to Times New Roman font. <br>So:</p><pre>&lt;link href=”https://fonts.googleapis.com/css2?family=Roboto:wght@500&amp;display=swap&quot; rel=”stylesheet”&gt;</pre><p>Turns into:</p><pre>&lt;link <br>rel=”preload” <br>as=”style” <br>href=”<a href="https://fonts.googleapis.com/css2?family=Roboto:wght@500&amp;display=swap">https://fonts.googleapis.com/css2?family=Roboto:wght@500&amp;display=swap</a>&quot;<br>onload=”this.rel=’stylesheet’”&gt;</pre><p>Don’t preload your critical CSS — ones crucial to your website structure, like loading animations, fade-in animations, flexbox structure, etc. Doing so lowers your <a href="https://web.dev/cls/?utm_source=lighthouse&amp;utm_medium=unknown">Cumulative Layout Shift</a> and makes a better UX.</p><h3><strong>Serve all static files on your server</strong></h3><p>CDNs are good, but hosting files on your server is even better. It is a good idea to download fonts, CSS, Javascript, images, and any other static file to your own server. Each request creates an overhead in terms of execution time and traffic.<br>This includes looking inside external CSS and modifying it to only use internal files.<br>I downloaded the G<a href="https://fonts.googleapis.com/css2?family=Roboto:wght@500&amp;display=swap">oogle Fonts CSS</a> and modified it to use:</p><pre>src: url(https://medium.com/KFOlCnqEu92Fr1MmEU9fCBc4EsA.woff2) format(“woff2”);</pre><p>instead of:</p><pre>src: url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmEU9fCRc4EsA.woff2) format(&#39;woff2&#39;);</pre><h3>Using responsive images</h3><p>Desktops have bigger screens and faster internet connection than mobile phones. So makes no sense to serve the same images used by desktops on phones.<br>Using <strong>srcset</strong>attribute on images define the image it should be using on different screen widths.</p><pre>&lt;img srcset=” url size, url size, url size “ src=”default url” &gt;</pre><h3>Minify static files</h3><p>To keep it simple, I did not minified static files. But it is a great idea to reduce file sizes, removing unnecessary characters.</p><h3>Compress images</h3><p>Using formats like <strong>JPEG 2000, JPEG XR e WebP </strong>make image sizes smaller, thus it makes requests take less time. <br>These formats don&#39;t accept transparency, but a simple hack is to manually paint the transparent background if the background behind your image never changes.</p><p>My website is indeed minimalist, not having so much content and almost no Javascript, except for google tag manager scripts.<br>But using these simple technics, your website could score green on PageSpeed Insights, therefore making your SEO better. I really hope these tips help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=648e08a534c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve code quality with ktlint, detekt, and git hooks]]></title>
            <link>https://hofstede-matheus.medium.com/improve-code-quality-with-ktlint-detekt-and-git-hooks-d173722594e4?source=rss-d7090ee45416------2</link>
            <guid isPermaLink="false">https://medium.com/p/d173722594e4</guid>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[ktlint]]></category>
            <category><![CDATA[detekt]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Matheus Hofstede]]></dc:creator>
            <pubDate>Sun, 20 Dec 2020 18:47:55 GMT</pubDate>
            <atom:updated>2020-12-20T18:47:55.059Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*R-bzIx8jUphGYWEJ.png" /></figure><p>Code quality nowadays is not only a paper of QA professionals and the <strong>code</strong> <strong>review</strong> step is not the moment to point out code style/code smells issues. That job is a job that can perfectly be done by machines, and I’m going to show how to set up a simple but effective process to improve the code of your Android or Kotlin based projects.</p><h3>ktlint</h3><p>ktlint defines itself as:</p><blockquote>An anti-bikeshedding Kotlin linter with built-in formatter</blockquote><p>A lint is is a tool that analyzes source code to flag programming errors, bugs, and stylistic errors. So ktlint does that job with Kotlin programming language.<br>The official lib is called <a href="https://github.com/pinterest/ktlint">ktlint</a> but we are going to another lib that conveniently creates Gradle tasks that runs ktlint to check or format your code, <a href="https://github.com/jlleitschuh/ktlint-gradle">ktlint-gradle</a>. Lets code!</p><p>Create a new Android (or kotlin only)project and ktlint-gradle to your top-level project build.gradle file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef5dd524ad059aaadea3d9e964165f4c/href">https://medium.com/media/ef5dd524ad059aaadea3d9e964165f4c/href</a></iframe><p>Use the <a href="https://github.com/JLLeitschuh/ktlint-gradle/releases">latest stable release</a> of ktlint-gradle</p><p>And within <em>allprojects</em> section, apply the ktlint-gradle plugin to be able to use ktlint tasks through all your other modules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7b7ac900b34784536c79540d46be714/href">https://medium.com/media/e7b7ac900b34784536c79540d46be714/href</a></iframe><p>Now sync your project. Opening the Gradle section of Android Studio (shift, shift and search for “Gradle”), you will see new tasks available in the verification and formating folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*kDYvtguaK1HfBCzmnoXEsQ.png" /><figcaption>new tasks</figcaption></figure><p>To run the ktlintCheck open a new terminal window run:</p><pre>./gradlew ktlintCheck</pre><p>You will get errors that can and cannot be automatically fixed.<br>For those who can be, run:</p><pre>./gradlew ktlintFormat</pre><p>Then correct any errors that cannot be automatically fixed (eg. wildcard import). And run:</p><pre>./gradlew ktlintCheck</pre><p>And it will pass with no errors.</p><h3>detekt</h3><p>ktlint is focused on code formatting, whereas detekt is about code analysis, including code complexity, code smells, etc)<br>Both can be run together with no conflicts. Let&#39;s add detekt.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bd79f8b01bdb54e97d1e4a088a5d9fb/href">https://medium.com/media/9bd79f8b01bdb54e97d1e4a088a5d9fb/href</a></iframe><p>and configure the plugin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34d8b7db157031ea37b2fd744f313760/href">https://medium.com/media/34d8b7db157031ea37b2fd744f313760/href</a></iframe><p>Run the task <strong>DetektGenerateConfig </strong>to create a file in /config/detekt/detekt.yml that holds the standard rules.</p><p>You can edit the configuration file to match the rigor that you need. Read the <a href="https://arturbosch.github.io/detekt/style.html">documentation</a> to find what each rule means.</p><h3>Git Hooks</h3><p>Git hooks (not Github hooks) are scripts that fire when something occurs, like a push or a commit.<br>Let&#39;s create a git hook to check lint errors and code smells on commit.</p><p>.git/hooks/pre-commit</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/046cbf158049f0266123efc03b5f9d4f/href">https://medium.com/media/046cbf158049f0266123efc03b5f9d4f/href</a></iframe><p>And make it executable, otherwise, the hook is going to be ignored:</p><pre>chmod a+x .git/hooks/pre-commit</pre><p>Making a pre-commit hook instead of a pre-push hook or even wait for the CI to point the lint error is a more clever approach because it will reduce the number of commits needed for a feature or a fix to be done.</p><h3>TODO</h3><ul><li><em>Add semantic commit checking in the pre-commit hook</em></li></ul><p>Based on:</p><p><a href="https://youtu.be/YmZIkUGnCco">https://youtu.be/YmZIkUGnCco</a></p><p><a href="https://www.youtube.com/watch?v=eysVDO2_X0s">https://www.youtube.com/watch?v=eysVDO2_X0s</a></p><p><a href="https://www.youtube.com/watch?v=b-AWsOmszWk">https://www.youtube.com/watch?v=b-AWsOmszWk</a></p><p><a href="https://proandroiddev.com/ooga-chaka-git-hooks-to-enforce-code-quality-11ce8d0d23cb">https://proandroiddev.com/ooga-chaka-git-hooks-to-enforce-code-quality-11ce8d0d23cb</a></p><p><a href="https://arctouch.com/blog/static-analysis-ktlint-detekt">https://arctouch.com/blog/static-analysis-ktlint-detekt</a>/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d173722594e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android “res” folder on Flutter]]></title>
            <link>https://hofstede-matheus.medium.com/android-res-folder-on-flutter-1e6f7ca6f9c7?source=rss-d7090ee45416------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e6f7ca6f9c7</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Matheus Hofstede]]></dc:creator>
            <pubDate>Sat, 21 Nov 2020 00:53:31 GMT</pubDate>
            <atom:updated>2020-11-21T00:53:31.856Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2fqHoEnz4IY_kfI5xcOW4w.png" /></figure><p>The Android Framework is a feature-rich ecosystem with many conventions. As an Android developer migrating to Flutter, which has somehow a loose framework, I missed the troubleshooter “res” folder. So I created a similar structure to use statically defined resources like strings, colors, themes, and images.<br>Nothing more than expected from a strongly typed language fanboy and productivity lover.<br>So instead of using:</p><pre>Color(0xFF787790)<br>// or<br>AssetImage(&#39;path/to/image&#39;)<br>// use<br>colors.primary<br>// or<br>images.appIcon</pre><p>Check out the <a href="https://github.com/hofstede-matheus/flutter-res-folder">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e6f7ca6f9c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Cloud Pub Sub on Android with MVVM]]></title>
            <link>https://hofstede-matheus.medium.com/google-cloud-pub-sub-on-android-with-mvvm-c30d90b1fc68?source=rss-d7090ee45416------2</link>
            <guid isPermaLink="false">https://medium.com/p/c30d90b1fc68</guid>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Matheus Hofstede]]></dc:creator>
            <pubDate>Thu, 30 Apr 2020 23:19:40 GMT</pubDate>
            <atom:updated>2020-05-01T16:47:55.401Z</atom:updated>
            <content:encoded><![CDATA[<p>As a demand for a project of my work I had to study Pub Sub architecture to implement an app with real time data. I’ve used as a example a internal project that was already running Pub Sub. Because there is not much content on the web on how to use Pub Sub on Android, I’ve decided to explain how I did it.</p><h3>Prologue</h3><p>First of all you need to sign up for a free Google Cloud Platform account and enroll to a free trial at <a href="https://cloud.google.com/free">https://cloud.google.com/free</a></p><p>Now follow this <a href="https://www.youtube.com/watch?v=f5DOsB7Nlw0&amp;list=PLIivdWyY5sqKwVLe4BLJ-vlh9r9zCdOse">video tutorial</a> up to step 2 to create everything you need. In the end you should have 4 things:<br>- gcloud project name (mine is <strong><em>wired-record-275613</em></strong>)<br>- topic name (mine is <strong><em>topic</em></strong>)<br>- subscription name (mine is <strong><em>subscription</em></strong>)<br>- the <strong><em>.json</em></strong> file with the credentials</p><h3>On Android</h3><p>Let’s start with the gradle file (app), put these dependencies that we will use in the project.</p><pre>implementation &#39;androidx.recyclerview:recyclerview:1.1.0&#39;<br>implementation &#39;com.google.android.material:material:1.1.0&#39;<br><br>implementation &#39;androidx.lifecycle:lifecycle-runtime-ktx:2.3.0-alpha01&#39;<br><br>implementation &#39;com.github.blocoio:faker:1.2.8&#39;<br><br>implementation (&#39;com.google.cloud:google-cloud-pubsub:1.105.0&#39;) <strong>{<br>    </strong>exclude group: &#39;org.apache.httpcomponents&#39;<br><strong>}<br></strong>implementation &#39;io.grpc:grpc-okhttp:1.28.0&#39;</pre><p>You will notice that you will get an error when you build the project, something about META-INF and Dex, so put this under <strong><em>buildTypes</em></strong></p><pre>packagingOptions <strong>{<br>    </strong>exclude &#39;META-INF/INDEX.LIST&#39;<br><strong>}</strong></pre><p>And inside <strong><em>defaultConfig</em></strong></p><pre>multiDexEnabled true</pre><p>Then rename the .json file downloaded from Cloud Platform to credentials.json and move it to res/raw/</p><p>Also don’t forget to give internet permissions to the app</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;</pre><p>I’ve used MVVM architecture with Repository in this project having “Depend on an abstraction and not an implementation”, the Dependency inversion principle mindset. So the ViewModel will depend on an interface (abstraction), and it doesn’t matter where the data comes from. This makes testing and future changes much easier, in case I start using REST, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*4N6nlk4FXvo1YMaXoRu7IQ.png" /><figcaption>Project structure</figcaption></figure><p>Here are the implementation of the main Pub Sub features, <strong><em>subscribe()</em></strong>, <strong><em>publish()</em></strong> and <strong><em>receiveMessage()</em></strong></p><pre>override fun subscribe(subscription: String) {<br>    GlobalScope.launch(Dispatchers.IO) <strong>{<br>        </strong>try {<br>            val subscriptionName = ProjectSubscriptionName.of(projectName, subscription)<br><br>            subscriber = Subscriber.newBuilder(subscriptionName, this@GoogleCloudPubSubDataSource)<br>                .setCredentialsProvider <strong>{ </strong>credentials <strong>}<br>                </strong>.build()<br>            subscriber?.startAsync()?.awaitRunning()<br>            subscriber?.awaitTerminated()<br>        } catch (t: Throwable) {<br>            Log.i(&quot;PUBSUB&quot;, t.message ?: &quot;Something went wrong&quot;)<br>        }<br>    <strong>}<br></strong>}</pre><pre>override fun publish(topicName: String, message: String) {<br>    var publisher: Publisher? = null<br>    try {<br>        val projectTopicName = ProjectTopicName.of(projectName, topicName);<br>        publisher = Publisher.newBuilder(projectTopicName).setCredentialsProvider(<br>            FixedCredentialsProvider.create(credentials)).build()<br>        val data = ByteString.copyFromUtf8(message)<br>        val pubsubMessage = PubsubMessage.newBuilder().setData(data).build()<br>        val messageIdFuture: ApiFuture&lt;String&gt; = publisher.publish(pubsubMessage)<br><br>        ApiFutures.addCallback(<br>            messageIdFuture,<br>            object : ApiFutureCallback&lt;String&gt; {<br>                override fun onSuccess(messageId: String) {<br>                    <em>println</em>(&quot;published with message id: $messageId&quot;)<br>                }<br>                override fun onFailure(t: Throwable) {<br>                    <em>println</em>(&quot;failed to publish: $t&quot;)<br>                }<br>            },<br>            MoreExecutors.directExecutor()<br>        )<br>    } finally {<br>        if (publisher != null) {<br>            publisher.shutdown();<br>            publisher.awaitTermination(1, TimeUnit.MINUTES);<br>        }<br>    }<br>}</pre><pre>override fun receiveMessage(message: PubsubMessage, consumer: AckReplyConsumer) {<br>    Log.i(&quot;PUBSUB&quot;, message.<em>data</em>.toStringUtf8())<br>    consumer.ack()<br>    pubSubMessages.add(gson.fromJson(message.<em>data</em>.toStringUtf8(), Message::class.<em>java</em>))<br>    viewModel.updateCodeArrayList(pubSubMessages)<br>}</pre><p>I’m not going to paste the code here, Github himself does it very well, I just wanted to leave an explanation of what’s going on behind the scenes.<br>When I click on the FAB, I call the ViewModel’s <strong><em>sendMessage()</em></strong> method with a random name and message. ViewModel calls <strong><em>sendMessage()</em></strong> that was injected from MainActivity and it publishes the message. Now everyone who subscribed to this topic subscription will receive the message, and as the app itself has subscribed in MainActivity, it receives the message, updates ViewModel’s LiveData and populates RecyclerView.</p><p>Do not worry on things running on the main thread and the adapter being recreated every time a new data arrives, what I really wanted to show is Pub Sub on Android with a fully reactive architecture.</p><h3>Useful things</h3><p>Complete code:<br><a href="https://github.com/hofstede-matheus/PubSubAndroidExample">https://github.com/hofstede-matheus/PubSubAndroidExample</a><br>A nice playlist from Google explaining Pub Sub using Cloud Plataform<br><a href="https://www.youtube.com/playlist?list=PLIivdWyY5sqKwVLe4BLJ-vlh9r9zCdOse">https://www.youtube.com/playlist?list=PLIivdWyY5sqKwVLe4BLJ-vlh9r9zCdOse</a><br>A nice vide explaining the concept behind Pub Sub:<br><a href="https://www.youtube.com/watch?v=O1PgqUqZKTA">https://www.youtube.com/watch?v=O1PgqUqZKTA</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c30d90b1fc68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[O que uma transferência interbancária (ou a falta dela) tem a ver com o Antifrágil]]></title>
            <link>https://hofstede-matheus.medium.com/o-que-uma-transfer%C3%AAncia-interbanc%C3%A1ria-ou-a-falta-dela-tem-a-ver-com-o-antifr%C3%A1gil-e40d3a832ca4?source=rss-d7090ee45416------2</link>
            <guid isPermaLink="false">https://medium.com/p/e40d3a832ca4</guid>
            <category><![CDATA[nassim-nicholas-taleb]]></category>
            <category><![CDATA[investimento]]></category>
            <category><![CDATA[antifrágil]]></category>
            <dc:creator><![CDATA[Matheus Hofstede]]></dc:creator>
            <pubDate>Sat, 25 Apr 2020 03:22:29 GMT</pubDate>
            <atom:updated>2020-04-25T03:22:29.715Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://revistapegn.globo.com/Startups/noticia/2020/04/exclusivo-startup-de-educacao-medica-sanar-recebe-aporte-de-r-60-milhoes.html">Startup de educação médica Sanar recebe aporte de R$ 60 milhões</a></p><p>Me deparei com essa notícia em um grupo do Whatsapp, e a primeira coisa que me veio na cabeça foi “nossa, a Sanar é a materialização do Antifrágil”. Já tive em alguns momentos contatos com ela, até por que ela é composta praticamente toda pelo MEJ, e por ter um amigaço, que posso até chamar de conselheiro, que fez parte dela.</p><p>Apesar de ter trocentos artigos na internet explicando o conceito, é uma coisa que adoro e sempre que acho uma oportunidade de explicar, eu faço com um sorriso besta.</p><p>Normalmente quando você pergunta qual é o contrário de frágil, a primeira coisa que vem na cabeça da pessoa é robusto ou resiliente. Por exemplo: se um copo de vidro cair no chão, ele quebra por que é frágil. Mas se ele fosse o contrário de frágil ele resistiria a queda ou <strong>ficaria mais forte</strong> com a queda? Segundo Taleb, autor do livro Antifrágil, o contrário de frágil é justamente essa, característica das coisas que se beneficiam com o caos.</p><p>Voltando a Sanar, o caos é a crise e se a SanarFlix já era útil quando o mundo estava sem quarentena, agora é mais útil ainda.</p><p>Uma vez minha psicóloga me perguntou quais eram as minhas maiores qualidades. Não passou nem um segundo e eu, com um sorriso no rosto, falei que uma delas é ser antifrágil, e expliquei a ela, talvez com mais empolgação do que deveria, esse conceito.</p><p>Eu lembro exatamente de quando eu comecei a investir. Fiz uma conta na Easynvest e na época, para não pagar TED e comer 10% do meu rendimento, eu fazia a grade odisseia de ir na boca do caixa, depositar em uma conta de serviços essenciais no Bradesco, esperar um dia, fazer uma transferência interbancária para Easy e assim investir sem dar um centavo pro banco.<br>Até que chegou um belo dia que a Easynvest anunciou que não iria aceitar mais transferência entre contas do Bradesco, e eu vi sendo inviável investir no Tesouro, um <strong>caos</strong> total. Foi ai que procurei a internet inteira, e talvez a Deep Web para achar uma maneira de fazer uma TED de graça e achei o Inter, que não só tinha TEDs gratuitas, como eu poderia transferir sem sair de casa.<br>Eu saí de me deslocar, esperar 1 dia útil para poder investir, para investir instantaneamente sem sair de casa. Talvez naquela época eu não percebi, mas a partir desse pequeno caos, eu acabei melhorando o processo como um todo.</p><p>Nesse momento do Covid-19, eu me vi antifrágil novamente. Para contextualizar sou desenvolvedor Android na Cubos Tecnologia, e devido ao impacto da quarentena alguns projetos precisaram diminuir a equipe e algumas pessoas foram realocadas em outros projetos. Por uma oportunidade eu fui realocado para uma vaga de Backend. Imaginando uma realidade paralela que não tivessem mais projetos na Cubos com vagas para Dev Android, provavelmente eu estaria fora. Nesse momento senti que fui antifrágil e com esse caos, me sinto preparado para assumir uma vaga de back.</p><p>Segundo Taleb, para um sistema ser considerado antifrágil, as suas partes frágeis tem que ser mitigadas, então é sempre bom ter em mente o que pode te tirar do jogo e trabalhar nessas fragilidades.</p><p>É uma coisa muito bonita de se ver como os conceitos propostos por Taleb transbordam a área de economia, e fico sempre fazendo esses paralelos com outras áreas da vida.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e40d3a832ca4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Não é só pelo dinheiro… e nunca foi]]></title>
            <link>https://hofstede-matheus.medium.com/n%C3%A3o-%C3%A9-s%C3%B3-pelo-dinheiro-e-nunca-foi-a157580ffe6b?source=rss-d7090ee45416------2</link>
            <guid isPermaLink="false">https://medium.com/p/a157580ffe6b</guid>
            <category><![CDATA[finanças]]></category>
            <category><![CDATA[investimento]]></category>
            <category><![CDATA[dinheiro]]></category>
            <dc:creator><![CDATA[Matheus Hofstede]]></dc:creator>
            <pubDate>Thu, 12 Mar 2020 02:23:32 GMT</pubDate>
            <atom:updated>2020-03-13T16:39:38.034Z</atom:updated>
            <content:encoded><![CDATA[<p>Um fenômeno interessante que acontece nos relacionamentos (pelo menos os que já passei em outros relacionamentos) é uma espécie de crossing-over (sim, aquele que você aprendeu em biologia no ensino médio) dos hábitos e conhecimento do casal.</p><p>No meu relacionamento anterior eu era uma pessoa extremante workaholic, enquanto minha ex era uma pessoa que meditava, e fazia outras coisas de pessoas Zen. Durante o relacionamento eu percebi que fui me tornando menos viciado no trabalho (de um jeito positivo) enquanto ela se interessou e começou a investir.</p><p>No meu relacionamento atual está acontecendo algo parecido. Talvez pelo exemplo e admiração, minha namorada está voluntariamente interessada no mundo das finanças. Apesar do pai dela estar de uma certa maneira desmotivando ela a investir e afirmar que “só vale a pena se tiver 10 mil conto” e seu irmão estar falando pra ela comprar ações (estamos em 11/03/2020, em plena crise global do petróleo e o Covid-19 sendo considerado pandemia), eu usei meus melhores argumentos pra convecê-la a começar a investir pelo tesouro direto, seguem eles:</p><h3>Lembra da fórmula de juros compostos?</h3><p>Na fórmula dos juros compostos, o tempo está na potência. Ou seja ao aumentar o tempo, os juros aumentam também <strong>exponencialmente</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*9PS-yL1TcUjXpZUt.gif" /></figure><p>Segue um exemplo do <a href="https://www.clubedospoupadores.com/investimentos/poder-tempo-investimentos.html">poder do tempo nos investimentos</a></p><h3>Quando você começa a caminhar, o caminho aparece</h3><p>Lá nos meus 18 anos eu fiz uma revolução na minha vida: Eu quebrei meu porquinho de dinheiro. Naquele momento eu já entendia o que era inflação e que meus 30 reais estavam se desvalorizando se eu deixasse parado. Resolvi juntar eles com uma parte da minha mesada e um dinheiro que conseguia vendendo coisas na internet pra investir no tesouro SELIC. O processo era o seguinte:<br>Eu juntava minhas economias do mês, e ia depositar aquelas notas e moedas na boca do caixa do Bradesco, pra depositar numa conta de serviços essenciais, que briguei com meu gerente pra exercer meu direito de ter uma, esperar 1 dia útil pra cair na conta e eu fazer uma transferência interbancária pra a Easyinvest.<br>Em torno de 60–80 reais era pouco? Dava trabalho e demorava pra depositar esse dinheiro? Sim e sim. Mas eu sabia exatamente o que eu estava fazendo.<br>E colocando metas de comprar pelo menos um título por mês, e fui criando um hábito daquele clichê maravilhoso de “me pagar primeiro”.<br>Afinal, quebrar meu porquinho foi um <strong>símbolo</strong>, foi a manifestação física de ser protagonista a partir dali.</p><h3>Engane seu cérebro</h3><p>Entre deixar seu dinheiro no Nubank, rendendo 100% do CDI e no tesouro SELIC (em uma corretora), que para simplificar rende também 100% do CDI, os dois a 80km/h, qual é o melhor?<br>Na minha humilde opinião, no tesouro SELIC é a melhor opção. E não estou falando de rentabilidade, ou de IOF, estou querendo exemplificar que somos humanos, ou seja, quando naquele momento você quer muito comprar uma coisa, e tem aquele dinheiro livre em sua conta, é muito mais simples utilizarmos esse dinheiro do que termos um certo “trabalho” com o que está na corretora, pois precisaríamos esperar o D+1 de liquidação do título e transferi-lo, para só então começarmos a utilizar.<br>Só esse resistência a mais já te dá tempo de pensar se realmente vale a pena de se afastar do seu sonho pra reagir esse impulso.</p><h3>Não é só pelo dinheiro… e nunca foi</h3><p>No livro Me Poupe! da Nathalia Arcuri ela contou o momento que ela pôde comprar a parte da casa á vista no momento do divórcio do marido, e segundo ela, foi nesse momento que passou na cabeça dela que X mulheres morrem de vítimas de violência doméstica todos os dias e a maioria desses casos é por causa da dependência financeira do marido. E estava claro que fazer o trabalho que ela faz é contribuir no empoderamento feminino e a abaixar essa métrica.</p><p>Por minha namorada ser mulher, eu incentivo a contribuir positivamente na <a href="http://www.tesouro.fazenda.gov.br/-/participacao-feminina-no-tesouro-direto-atinge-novo-recorde">estatística</a> de mulheres investidoras e vejo meu papel como incentivar ela nesse processo de ser dona do próprio destino e ser mais um mulherão da porra que ela é.</p><p>Ninguém investe só por investir, por trás de todo investimento há uma meta, um sonho, uma geladeira, uma viagem, um carro zero ou a independência financeira pra ser conquistado lá na frente. <br>É a sensação de poder comprar uma coisa e mesmo assim não comprar, porque seus objetivos com aquele dinheiro estão claros.<br>É uma base sólida que possibilita a ajudar outras pessoas sem ter que tirar da carne e a fazer investimentos de conhecimento com a consciência tranquila.</p><p>Tentei explicar pra ela que investir também envolve coisas intangíveis como a liberdade e é muito mais complexo que ter um pouquinho mais de dinheiro depois de algum tempo. Isso é tudo pessoal!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a157580ffe6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>