<?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 Arley Pádua on Medium]]></title>
        <description><![CDATA[Stories by Arley Pádua on Medium]]></description>
        <link>https://medium.com/@arleypadua?source=rss-48693b5b069c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vU71TUS7dAWVWyw8.</url>
            <title>Stories by Arley Pádua on Medium</title>
            <link>https://medium.com/@arleypadua?source=rss-48693b5b069c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:46:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arleypadua/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[Rewinding Time: A Journey to 1996]]></title>
            <link>https://arleypadua.medium.com/rewinding-time-a-journey-to-1996-7f6288870b7e?source=rss-48693b5b069c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f6288870b7e</guid>
            <category><![CDATA[windows-95]]></category>
            <category><![CDATA[nostalgia]]></category>
            <category><![CDATA[ms-dos]]></category>
            <category><![CDATA[90s]]></category>
            <dc:creator><![CDATA[Arley Pádua]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 16:15:27 GMT</pubDate>
            <atom:updated>2024-12-19T16:15:27.822Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I stumbled upon a picture of a game I used to play as a kid around 1996. That single image sparked a nostalgia-fueled mission to revive those childhood memories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xS2TkgvfJeXvDFl6_7EhA.png" /><figcaption>IBM Aptiva Kid&#39;s Room</figcaption></figure><p>I’m talking about this interactive game where you could explore the entire scene and play mini-games like concentration, tic-tac-toe, slider puzzles, and more.</p><p>The catch? This game came pre-installed on specific IBM PCs back in the day and wasn’t easily accessible elsewhere.</p><p>The journey begins with installing <a href="https://86box.net/">86Box</a>, an app that emulates older machines/architectures, so here&#39;s a list of what I needed:</p><ol><li><a href="https://86box.net/">86Box</a> installed and configured with all <a href="https://86box.readthedocs.io/en/latest/usage/roms.html">rom set</a></li><li>An image of the IBM Aptiva recovery CD-ROM (in my case I wanted for the <a href="https://archive.org/details/Aptiva2159Recovery">2159S Series</a>)</li><li>A bootable image of the <a href="https://winworldpc.com/download/417d71c2-ae18-c39a-11c3-a4e284a2c3a5">Windows 98 SE OEM CD-ROM</a>, to help us getting everything installed</li></ol><p>With all pre-requisite programs downloaded/installed, follow these stpes:</p><ul><li>Open 86Box and configure the emulated PC:</li></ul><pre>-- MACHINE --<br>Machine Type: [1996] Socket 7 (Dual Voltage)<br>Machine: [i430TX] ASUS TX97<br>CPU type: Intel Pentium<br>Frequency: 200<br>Memory: 128 MB<br><br>-- DISPLAY --<br>[ISA16] Tseng Labs ET4000/w32<br>Check IBM 8514/A Graqphics<br><br>-- INPUT DEVICES --<br>Microsoft Bus Mouse (InPort)<br><br>-- SOUND --<br>[ISA16] Sound Blaster AWE32 PnP<br><br>-- NETWORK --<br>Adapter: [PCI] Realtek RTL8029AS<br><br>-- HARD DISK --<br>Create one with at least 2GB<br>Channel 0:0<br><br>-- FLOPPY &amp; CD-ROM DRIVES --<br>Floppy: 3.5&quot; 1.44M<br>CD-ROM: ATAPI (Channel 0:1)</pre><ul><li>Load the Windows 98 SE image into the CD-ROM drive</li><li>Turn on the machine</li><li>When prompted to choose how you want to load the CD-ROM, choose to load with CD-ROM support (do not start the Windows 98 installation)</li><li>At the command prompt, type:</li></ul><pre>fdisk</pre><p><em>Follow the prompts (always choose option 1) to create a partition</em></p><ul><li>Restart the machine. Load with CD-ROM support again.</li><li>Once back at the command prompt, type:</li></ul><pre>format C:</pre><ul><li>Swap the <strong>Windows 98 SE image</strong> with the <strong>IBM Aptiva ISO image</strong> in the CD-ROM drive.</li><li>At the command prompt, type:</li></ul><pre>D:<br>cd RECOVERY<br>cd US<br>dir /w</pre><p><em>You should see files like APTIVA1.ZIP, APTIVA2.ZIP, etc.</em></p><ul><li>Extract the ZIP files to the hard drive: (C:\):</li></ul><pre>PKUNZIP.EXE -smagic -$ -d -JHSR -o D:\RECOVERY\US\APTIVA*.ZIP C:\</pre><p><em>(This might take 10–15 minutes.)</em></p><ul><li>Remove the <strong>IBM Aptiva ISO image</strong> from the CD-ROM drive and restart the machine.</li></ul><h4>Reliving the Nostalgia</h4><p>If everything went smoothly, you should see the Windows 95 logo! The machine will set up the devices/drivers, and eventually, you’ll reach the desktop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*GECiMF3cNydVJBiaGNzFHQ.png" /><figcaption>Windows 95 Desktop</figcaption></figure><p>To start the game I mentioned in the beginning, just go to:</p><blockquote>Start &gt; Programs &gt; 7th Level &gt; Kid&#39;s Rom</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*XUDbmcLvA5xuDOZPSeSw1Q.png" /></figure><p>And there you have it! Nostalgia unlocked 📺</p><h4>Troubleshooting</h4><ul><li>If you have issues opening the game due to the requirement of at least 256 colors:</li></ul><pre>Right click on the desktop &gt; Properties &gt; Settings:<br><br>- Color palette &gt; 256 Color<br>- Desktop area &gt; 800x600</pre><ul><li>If you don&#39;t see the 256 color option, make sure you have selected the &quot;Tseng Labs ET4000/w32&quot; monitor in your machine configuration and the driver is installed:</li></ul><pre>Right click on the desktop &gt; Properties &gt; Settings &gt; Advanced Properties &gt; Change<br><br>Look for the driver of the monitor &quot;Tseng Labs ET4000/W32&quot; and install it<br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f6288870b7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Perfil no GitHub e bons padrões de escrita de código]]></title>
            <link>https://arleypadua.medium.com/perfil-no-github-e-bons-padr%C3%B5es-de-escrita-de-c%C3%B3digo-28d6146d5ce0?source=rss-48693b5b069c------2</link>
            <guid isPermaLink="false">https://medium.com/p/28d6146d5ce0</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[code-style]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[ubiquitous-language]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Arley Pádua]]></dc:creator>
            <pubDate>Sat, 25 Jul 2020 14:38:35 GMT</pubDate>
            <atom:updated>2020-07-25T14:38:35.466Z</atom:updated>
            <content:encoded><![CDATA[<p>Alguns de vocês já devem saber que o GitHub lançou recentemente um tipo especial de repositórios. Se você criar um repositório que tenha o mesmo nome que a sua conta, o arquivo <em>README.md </em>desse repositório será mostrado na página do seu perfil no GitHub. Se você ainda não viu, <a href="https://github.com/arleypadua">dê uma olhada no meu perfil</a>.</p><h3>TL;DR</h3><p>Com um simples exercício ao tentar fazer um resumo de quem eu sou em forma de código, consegui notar o quão importante é escrever código que será lido por uma outra pessoa, ao invés de escrever código que máquinas vão interpretar.</p><p>Aqui está o repositório com o model que usei para me descrever: <a href="https://github.com/arleypadua/arleypadua">https://github.com/arleypadua/arleypadua</a></p><h3>Story</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rtPpEG_4aSmYHPqp.png" /></figure><p>Como eu achei a feature bem interessante, eu acabei notando que teria a capacidade de descrever um pouco sobre quem eu sou, relacionada a minha profissão e paixão. Eu comecei a pensar, ok… o que eu posso colocar aqui? Será algo chato, semelhante descrições profissionais no LinkedIn? Quem irá ler isso?</p><p>Eu escrevi algumas palavras, mas nenhuma pareceu se encaixar com o propósito da plataforma, quando então decidi escrever um resumo do meu perfil utilizando uma <strong>linguagem de programação</strong>.</p><p>Eu estabeleci algumas regras para essa brincadeira:</p><ul><li>Utilizar a linguagem que tenho mais afinidade</li><li>Tem que ser legível</li><li>Embora seja código, qualquer um tem que entender.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XdoDQheeHLwDf2zP" /></figure><p>A partir do perfil que tenho em algumas plataformas sociais por aí, rapidamente consegui criar um rascunho de como se pareceria:</p><pre><strong>Developer</strong> arley = <strong>Developer</strong><br>    .<strong>Married</strong>()<br>    .<strong>Musician</strong>(&quot;🎷&quot;, <strong>Level</strong>.Ok)<br>    .<strong>BornIn</strong>(<strong>Countries</strong>.Brazil, year: 1991)<br>    .<strong>LivesIn</strong>(<strong>Countries</strong>.Netherlands, since: 2017)<br>    .<strong>CodesIn</strong>(language =&gt; language<br>        .<strong>CSharp</strong>()<br>        .<strong>TypeScript</strong>()<br>        .<strong>JavaScript</strong>())<br>    .<strong>Interested</strong>(@in =&gt; @in<br>        .<strong>SoftwareArchitecture</strong>()<br>        .<strong>DomainDrivenDesign</strong>()<br>        .<strong>DistributedSystems</strong>()<br>        .<strong>ShareIdeas</strong>(at: &quot;https://medium.com/@arleypadua&quot;))<br>    .<strong>Found</strong>(at =&gt; at<br>        .<strong>Twitter</strong>(&quot;https://twitter.com/_arleypadua&quot;)<br>        .<strong>LinkedIn</strong>(&quot;https://www.linkedin.com/in/arleypadua/&quot;));</pre><pre>while (arley.HasLife)<br>{<br>    arley.<strong>Travel</strong>();<br>    arley.<strong>EnjoyLife</strong>();<br>    arley.<strong>Code</strong>();<br>}</pre><pre><strong><em>// todo: find out what is next 😅</em></strong></pre><p>Eu até mostrei pra minha esposa, que não tem afinidade com linguages de programação e… <strong>SUCESSO! Ela entendeu a mensagem</strong>.</p><p>Então me lembrei de uma fala interessante:</p><blockquote><em>Qualquer um pode escrever código que máquinas entendem, mas bons programadores escrevem código que humanos entendem. — Martin Fowler</em></blockquote><p>Isso se encaixa perfeitamente na vida diária de um desenvolvedor, em que máquinas sempre vão entender instruções, mas como sempre temos que adaptar os nossos códigos à realidade dos negócios que estão em constante mudança, é com bastante frequência que nos vemos indo de volta às instruções, tendo que mudá-las.</p><p>Se as instruções não estão legíveis, boa sorte ao tentar um problema e dar aos stakeholders uma mensagem clara de como está o estado atual. Por outro lado, se você tem uma base de código boa, legível, chame seu stakeholder, e converse com ele sobre o que está escrito.</p><p>O aprendizado do exercício é: se você quer se tornar um desenvolvedor melhor, pare de desenvolver código que irá simplesmente funcionar e comece a desenvolver código que tenha um real significado.</p><p>Arigo pequeno, muito tempo sem escrever por aqui, mas uma lição com algum valor.</p><p>Se quiser entrar em contato, estou disponível no Twitter <a href="https://twitter.com/_arleypadua">@_arleypadua</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28d6146d5ce0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I created my GitHub profile and how it relates to good coding standards]]></title>
            <link>https://arleypadua.medium.com/how-i-created-my-github-profile-and-how-it-relates-to-good-coding-standards-c191cb60ad6c?source=rss-48693b5b069c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c191cb60ad6c</guid>
            <category><![CDATA[ubiquitous-language]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[code-style]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Arley Pádua]]></dc:creator>
            <pubDate>Sat, 25 Jul 2020 14:15:41 GMT</pubDate>
            <atom:updated>2020-07-25T14:37:24.115Z</atom:updated>
            <content:encoded><![CDATA[<p>A few of you might already know that GitHub recently released a special type of repository. In your account, if you create a repository that matches your account name, the <em>README.md</em> file of this repository will be shown on your <a href="https://github.com/arleypadua">GitHub profile page</a>. If you haven’t seen it, <a href="https://github.com/arleypadua">check my profile</a>.</p><h3>TL;DR</h3><p>With a simple exercise of trying to describe myself in code style, showed how important it is to write code that someone else will read, instead of writing code that machines can read.</p><p>You will find the model that I used to describe myself at: <a href="https://github.com/arleypadua/arleypadua">https://github.com/arleypadua/arleypadua</a></p><h3>Story</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSN1D_F-mxwvVnxOuQUj4Q.png" /></figure><p>Since I found it quite interesting, and I suddenly gained the capacity to show a little bit about who I am, regarding my profession and passion, I started thinking, ok… what can I put in here? something a bit boring like LinkedIn profile summary? who will read it?</p><p>I wrote a couple of words, but nothing seemed to match the purpose of the platform, when I decided to <strong>code</strong> my own profile summary.</p><p>I established a couple of rules for it:</p><ul><li>Use my main programming language</li><li>Has to be easily readable</li><li>Although it is code, anyone has to read it and understand it!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KuajnI5hDPBhRMYA" /></figure><p>From the summary that I have through out a couple of social media platforms out there, I was able to draft what it would look like:</p><pre><strong>Developer</strong> arley = <strong>Developer</strong><br>    .<strong>Married</strong>()<br>    .<strong>Musician</strong>(&quot;🎷&quot;, <strong>Level</strong>.Ok)<br>    .<strong>BornIn</strong>(<strong>Countries</strong>.Brazil, year: 1991)<br>    .<strong>LivesIn</strong>(<strong>Countries</strong>.Netherlands, since: 2017)<br>    .<strong>CodesIn</strong>(language =&gt; language<br>        .<strong>CSharp</strong>()<br>        .<strong>TypeScript</strong>()<br>        .<strong>JavaScript</strong>())<br>    .<strong>Interested</strong>(@in =&gt; @in<br>        .<strong>SoftwareArchitecture</strong>()<br>        .<strong>DomainDrivenDesign</strong>()<br>        .<strong>DistributedSystems</strong>()<br>        .<strong>ShareIdeas</strong>(at: &quot;https://medium.com/@arleypadua&quot;))<br>    .<strong>Found</strong>(at =&gt; at<br>        .<strong>Twitter</strong>(&quot;https://twitter.com/_arleypadua&quot;)<br>        .<strong>LinkedIn</strong>(&quot;https://www.linkedin.com/in/arleypadua/&quot;));<br><br>while (arley.HasLife)<br>{<br>    arley.<strong>Travel</strong>();<br>    arley.<strong>EnjoyLife</strong>();<br>    arley.<strong>Code</strong>();<br>}<br><br><strong><em>// todo: find out what is next 😅</em></strong></pre><p>I even showed it to my wife, which she is not into coding at all :), and then: <strong>SUCCESS! She understood the message.</strong></p><p>This reminded me of a nice quote:</p><blockquote>Any fool can write code that a computer can understand. Good programmers write code that humans can understand. — Martin Fowler</blockquote><p>This fits a lot in a developer’s daily life, as in, machines will always understand instructions, but as we are always having to adapt business code into a reality that is always changing, it is very often that people have to refer back to the instructions, and change them.</p><p>If the instructions are non-readable, good luck on trying understand an issue and give stakeholders a clear message of what’s the current status of things. On the other hand, if you have a good, readable codebase, call your stakeholder, and talk what is written down.</p><p>The take away of this simple exercise was: If you are really looking forward to be a better developer, stop developing code that will work and start doing code that means something.</p><p>Short article, long time I don’t write something, but valuable lesson.</p><p>If you want to get in touch, I’m available on Twitter <a href="https://twitter.com/_arleypadua">@_arleypadua</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c191cb60ad6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JsonStore: Not-only SQL with SQL]]></title>
            <link>https://arleypadua.medium.com/jsonstore-not-only-sql-with-sql-54e548be7fad?source=rss-48693b5b069c------2</link>
            <guid isPermaLink="false">https://medium.com/p/54e548be7fad</guid>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[document]]></category>
            <dc:creator><![CDATA[Arley Pádua]]></dc:creator>
            <pubDate>Sat, 16 Feb 2019 18:35:03 GMT</pubDate>
            <atom:updated>2019-02-16T22:40:10.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*pzC283umjhp7UG7_.png" /></figure><p>I’m always fighting against myself when the topic is mapping domain objects correctly to a relational model. I wrote an article about it: “<a href="https://medium.com/@arleypadua/why-keeping-aggregates-with-nosql-9e1d9f9920f2">Why storing aggregates with NoSQL?</a>” with a strong opinion on this topic and I recommend the read.</p><p>Basically my opinion hasn’t changed since that post, but lately I’m using a new approach to the subject that is worth sharing.</p><p>As the title of this article says: <strong>NoSQL with SQL</strong>, I’m proposing storing domain objects as documents with SQL.</p><p>This subject isn’t something new in the market and great companies are using it, like Particular Software (creators of NServiceBus) with their <a href="https://docs.particular.net/nservicebus/sagas/">saga storage</a> or <a href="https://octopus.com/">Octopus Deploy</a> with their storage framework <a href="https://github.com/OctopusDeploy/Nevermore">Nevermore</a>.</p><p>These examples shown above are awesome and worth checking. I <a href="https://github.com/arleypadua/no-sql-with-sql">used them in the past</a> and came up with the conclusion: IMO it is somehow opinionated on your domain model and/or it can only be used within their own framework (like the saga storage from Particular).</p><h4>Introducing JsonStore</h4><p>JsonStore was born to be a lightweight C# library that offers a layer of abstraction on top of your domain objects that can translate them as Documents without interfering in your current domain model.</p><p>See the repository link: <a href="https://github.com/arleypadua/JsonStore">https://github.com/arleypadua/JsonStore</a>, please any feedback is welcome ✌</p><p>As a brief introduction on the programming model, here are a feel concepts in this library:</p><ul><li><strong>Document</strong>: Represents an identifiable document. It can be any class that will be serialized and persisted.</li><li><strong>Collection</strong>: Represents a collection of documents. You can perform actions on a collection such as: restore a document by id, change the state of a document (unmodified, changed, added or delete), and finally commit the changes present in the collection.</li><li><strong>Documents Store</strong>: This is the abstraction for a technology that stores documents. Currently only SQL Server is supported.</li><li><strong>Serializer</strong>: Implements the behavior of serializing a Document. The collection uses Json.NET as the default serializer.</li></ul><p>And bellow a dependency relationship of the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*msgeK9MaBehrL8Nsag4j0g.png" /></figure><p>In essence, the flow would be:</p><ul><li>Your application asks the document collection to add/change/remove a document.</li><li>Your application asks to commit all the changes present in the collection.</li><li>The document store gets all the documents with their changed state and persists on the database.</li></ul><p>I also created an example based on the solution of the article: “<a href="https://medium.com/@arleypadua/commands-domain-events-real-time-notification-hands-on-6694d9868056"><strong>Commands + Domain Events + Real time notification — Hands on</strong></a>”</p><p>Check it out:</p><p><a href="https://github.com/arleypadua/domain-events-signalr-jsonstore">https://github.com/arleypadua/domain-events-signalr-jsonstore</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Mo3i9dHFXolo1XIS712BA.gif" /><figcaption>Place Order &gt; Place Order &gt; New connection &gt; Place Order &gt; New connection</figcaption></figure><p>It basically persists an order whenever the user clicks on the button “Place Order” and any new connection receives all previous stored documents.</p><p>Thanks for reading 😉</p><p>Follow me on Twitter: <a href="https://twitter.com/_arleypadua">@_arleypadua</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54e548be7fad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Refactoring: Don’t underestimate it]]></title>
            <link>https://arleypadua.medium.com/refactoring-dont-underestimate-it-4192127ce40c?source=rss-48693b5b069c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4192127ce40c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[martin-fowler]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[designcode]]></category>
            <dc:creator><![CDATA[Arley Pádua]]></dc:creator>
            <pubDate>Sat, 02 Feb 2019 10:50:35 GMT</pubDate>
            <atom:updated>2019-02-02T10:50:35.198Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aESReEIHCllRmBFVW_V5lQ.png" /></figure><p>I’d like to kick off this post by saying something that I recently learned: <strong>Don’t be afraid of refactoring</strong>.</p><p>The reason I’m writing this is because I recently read Martin Fowler’s book: <strong>Refactoring — Improving the design of existing code</strong>, which I totally recommend you to read it. This changed my way of seeing this topic.</p><p>I’ll leave down below a few points that were important to me when considering the change on the way I code. It is not easy to teach yourself this, specially if you are used to code in a different way, but worth a try.</p><h4>What is refactoring and why doing so?</h4><blockquote>Refactoring is the process of changing a software system in a way that does not alter the external behavior of the code yet improves its internal structure.<br>- Martin Fowler (1999)</blockquote><p>It is a constant attempt to write code less error-prone and an improvement of the design after it has been written.</p><p>When you think of building engineers, for instance, they know far in advance how buildings need to be constructed because there are rules and laws that guide them on previewing the best resources for a specific project.</p><p>The story is different with software engineering, because business are dynamic projects that tends to change based on several factors that aren’t ruled by laws.</p><p>Given your business is always growing and changing, when you don’t apply refactoring, then your code design tends to become a <strong>hacking tool </strong>to attend the business. This will slow down you and colleagues on finding bugs, predicting effort to a new feature and eventually stop attending the business needs right on the time it requires.</p><p>On the other hand, by always applying refactoring you can get the benefit of actually read the code and understand what is happening, so your bug fix is clear or your new feature has a clearer place to be.</p><h4>Testing</h4><p>Testing will be your first ally on this subject and will increase the quality of your software.</p><p>The reason I was always afraid of refactoring is that changing existing code that already works, might lead you to create new bugs on the code. But if you have a good test suite in the first place, you will always have them watching your back. Also you spend less time debugging your software.</p><p>Having that said, first of all make sure you have tests before touching your code base for a feature or bug fix.</p><h4><strong>Apply the refactoring</strong></h4><p>There are several ways of refactoring that won’t be covered in this article, but if you basically look for <a href="https://sourcemaking.com/refactoring/smells">code smells</a> and apply some <a href="https://sourcemaking.com/refactoring/refactorings">refactoring techniques</a> you will be in a good place and helping the next developer that will touch this code.</p><p>The basic rule here would be: Always leave the campsite better than you found it before.</p><h4>Build and run your tests</h4><p>Every step of the way, make sure you build and run your tests. This way you find earlier when you made a mistake — we are humans and this is normal.</p><p>Will you find tools that really help doing this job. A good example is Visual Studio with the <a href="https://docs.microsoft.com/en-us/visualstudio/test/live-unit-testing?view=vs-2017">Live Unit Testing</a> functionality.</p><h4>Wrapping up</h4><p>If you apply the constant process of write tests, refactor, build and run, as a developer you will see an improvement on your performance, the way you code will change and you will start to think on the next developer that will eventually code on top of yours.</p><p>You will start to have questions like: If someone else <strong>look at this code</strong>, will he/she <strong>understand it</strong>? Is this name according to my <strong>domain language</strong>? Is this <strong>variable name meaningful</strong>? Is it possible to correlate the <strong>acceptance criteria </strong>by <strong>reading this code</strong>?</p><p>With this mindset, I believe this famous phrase was formed:</p><blockquote>Any fool can write code that a computer can understand. Good programmers write code that humans can understand.<br>- Martin Fowler (1999)</blockquote><p>In essence, be reasonable to the next that you will code better.</p><p>What are your experiences with it ? Do you have anything to share ? Leave a comment or find me on Twitter as <a href="https://twitter.com/_arleypadua">@_arleypadua</a>.</p><p>This article is also available in <a href="https://medium.com/@arleypadua/refactoring-n%C3%A3o-subestime-415159fa2b1c">Portuguese</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4192127ce40c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Refactoring: Não subestime]]></title>
            <link>https://arleypadua.medium.com/refactoring-n%C3%A3o-subestime-415159fa2b1c?source=rss-48693b5b069c------2</link>
            <guid isPermaLink="false">https://medium.com/p/415159fa2b1c</guid>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[designcode]]></category>
            <category><![CDATA[martin-fowler]]></category>
            <dc:creator><![CDATA[Arley Pádua]]></dc:creator>
            <pubDate>Sat, 02 Feb 2019 10:49:35 GMT</pubDate>
            <atom:updated>2019-02-02T10:50:56.834Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aESReEIHCllRmBFVW_V5lQ.png" /></figure><h3>🇧🇷 Refactoring: Não o subestime</h3><p>Eu gostaria de iniciar esse post colocando a seguinte sentença que aprendi: <strong>Não tenha medo de refatorar</strong>.</p><p>O motivo que estou escrevendo esse post é pelo fato de que recentemente li o livro do Martin Fowler: <strong>Refactoring — Improving the design of existing code</strong>. Recomendo muito pois mudou minha forma de enxergar o assunto.</p><p>Vou descrever abaixo alguns pontos que foram importante quando refleti sobre a forma como codifico. Não é fácil ter a auto-disciplina de aplicar a proposta, especialmente se a sua forma de codificar é diferente, mas vale a pena.</p><h4>O que é refactoring e porque fazê-lo?</h4><blockquote>Refactoring é o processo de mudança de software de maneira que o comportamento externo não é alterado, mas sim a sua estrutura interna. <br>- Martin Fowler (1999)</blockquote><p>É uma tentativa constante de escrever código menos propenso a erros e um aperfeiçoamento do design após sua escrita.</p><p>Quando você olha para engenheiros civis, por exemplo, eles sabem com antecedência como prédios precisam ser construídos, pois existem regras e leis que os guiam ao prever os melhores recursos para o projeto.</p><p>A história é diferente com engenharia de software, pois processos de negócio são projetos dinâmicos que tendem a mudar baseado em vários fatores que não seguem regras ou leis imutáveis.</p><p>Dado um negócio que está sempre crescendo e mudando, quando refactoring não é aplicado, então o código existente tende a se tornar uma <strong>ferramente de hacking</strong> para atender o negócio. Isso irá diminuir a sua performance e de seus colegas ao achar bugs, prever esforço necessário para uma funcionalidade e eventualmente parar de atender às necessidades do negócio em tempo hábil.</p><p>Por outro lado, ao aplicar o refactoring você ganha o benefício de ler o código e entender o que está acontecendo. Dessa forma o fix do bug se torna claro ou a funcionalidade nova tem um lugar mais claro para ser criada.</p><h4>Testes</h4><p>Os testes serão o seu primeiro aliado nesse assunto e também aumentam a qualidade do software.</p><p>O motivo pelo qual tinha medo de refatorar é que a mudança de código existente, que funciona, pode levar a novos bugs no código. Mas se você tem uma boa base de teste em primeiro lugar, eles sempre estarão lá garantindo que o resultado esperado ainda acontece. Você também gasta menos tempo <em>debugando</em> o software.</p><p>Tendo dito isso, em primeiro lugar, escreva os testes antes de mexer no código fonte ao consertar um bug ou criar uma feature.</p><h4>Refatore</h4><p>Existem várias maneiras de refatorar, que não serão descritas nesse artigo, mas se você basicamente procurar por <a href="https://sourcemaking.com/refactoring/smells">code smells</a> e aplicar algumas <a href="https://sourcemaking.com/refactoring/refactorings">técnicas de refactoring</a>, você estará em uma melhor situação e ajudará o próximo desenvolvedor que tocar nesse código.</p><p>A regra básica seria: Sempre deixe o acampamento melhor do que você encontrou.</p><h4>Compile e rode os testes</h4><p>A cada passo no processo de refactoring, faça o build e rode os testes. Dessa maneira você encontra mais cedo quando comente um erro — somos humanos e errar é normal.</p><p>Você encontrará ferramentas que realmente ajudam nesse trabalho. Um bom exemplo é o Visual Studio com a funcionalidade de <a href="https://docs.microsoft.com/en-us/visualstudio/test/live-unit-testing?view=vs-2017">Live Unit Testing</a>.</p><h4>Resumindo</h4><p>Se você aplicar o processo constante de escrever testes, refatorar, compilar e rodar os testes, como desenvolvedor você verá uma melhora na sua performance, a forma como codifica irá mudar para melhor e você irá começar a pensar no próximo desenvolvedor que tocar nesse código.</p><p>Questões em sua cabeça começarão a aparecer: Se <strong>alguém ver esse código</strong>, é possível <strong>entendê-lo</strong>? Esse nome está de acordo com a <strong>língua usada no meu domínio</strong>? O <strong>nome </strong>dessa <strong>variável tem sentido</strong>? É possível relacionar o código com os <strong>critérios de aceitação</strong> ao <strong>ler o código</strong>?</p><p>Com esse modo de pensar, eu acredito que a famosa frase foi formada:</p><blockquote>Qualquer um pode escrever código que um computador é capaz de entender. Bons programadores escrevem códigos que humanos podem entender.<br>- Martin Fowler (1999)</blockquote><p>Em essência, seja razoável e pense no próximo que você irá codificar melhor.</p><p>Quais são as suas experiências com isso? Você tem algo para compartilhar? Deixe um comentário ou me siga no Twitter <a href="https://twitter.com/_arleypadua">@_arleypadua</a>.</p><p>Este artigo também está disponível em <a href="https://medium.com/@arleypadua/refactoring-dont-underestimate-it-4192127ce40c">Inglês</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=415159fa2b1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Commands + Domain Events + Real time notification — Hands on]]></title>
            <link>https://arleypadua.medium.com/commands-domain-events-real-time-notification-hands-on-6694d9868056?source=rss-48693b5b069c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6694d9868056</guid>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[mediatr]]></category>
            <category><![CDATA[signalr]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[domain-events]]></category>
            <dc:creator><![CDATA[Arley Pádua]]></dc:creator>
            <pubDate>Sat, 29 Sep 2018 13:33:26 GMT</pubDate>
            <atom:updated>2018-09-29T13:33:26.609Z</atom:updated>
            <content:encoded><![CDATA[<p>Following my series about distributed systems, in which I start explaining about principles of <a href="https://medium.com/@arleypadua/main-principles-on-service-modelling-6e190524bd69">service design</a>, later on telling why they should be <a href="https://medium.com/@arleypadua/pizzeria-and-resilient-systems-77dd0c9ed635">resilient</a> and the need of <a href="https://medium.com/@arleypadua/domain-events-vs-integration-events-5eb29a34fdbc">domain events</a>, after some feedbacks I want to share with you guys a little bit of hands on about what I’ve been talking lately.</p><p><strong><em>Note.:</em></strong><em> At the end of the post, there is a link with the final solution.</em></p><p>To this hands on, I’ll show a system composed by:</p><ul><li>An API that accepts orders containing customer name and list of products.</li><li>A frontend used only for sending orders to the backend and receiving notifications.</li><li>A backend project, responsible to process an order and publish domain events.</li><li><a href="https://github.com/jbogard/MediatR">MediatR </a>was used as an abstraction layer for <em>commands </em>and <em>domain events</em>.</li><li>SignalR used for sending notifications to the frontend.</li></ul><p>See below an image with the concepts within this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*CG64_byH4z0cXAblmASUNA.png" /></figure><p>Starting from the API, lets create an ASP.NET Core 2.1 project and add the NuGet package: <em>MediatR.Extensions.Microsoft.DependencyInjection.</em></p><p>It will contain everything that we need to configure MediatR as our message broker.</p><p>Note that MediatR is a library that offers abstractions for sending commands and publishing events, but everything runs in memory. In a real scenario, you want to adopt a reliable system that transports these messages, as Azure Service Bys or RabbitMQ. They guarantee that you don’t loose these messages, even if one of your servers is down.</p><p>Create a controller called OrderController and add an endpoint as follows below:</p><pre>[Route(&quot;api/[controller]&quot;)]<br>public class <strong>OrdersController</strong> : <strong>Controller</strong><br>{<br>   private readonly <strong>IMediator</strong> _mediator;</pre><pre>   public OrdersController(<strong>IMediator </strong>mediator)<br>   {<br>      _mediator = mediator;<br>   }</pre><pre>   [<strong>HttpPost</strong>]<br>   public Task PostAsync([FromBody]<strong>PlaceOrderCommand </strong>order) =&gt;<br>      _mediator.Send(order);</pre><pre>}</pre><p>Note that this is a simple controller and there is nothing more than a mediator class being injected and an endpoint sending a command.</p><p>A command can never be sent in an invalid state, however, for the matter of the simplicity of this example, I’ll not implement validations. In case you want to look deep into it, see this MediatR <a href="https://github.com/jbogard/MediatR/wiki/Behaviors">wiki</a> for behaviors. With them it is possible to create an execution pipeline that runs before the command is sent and the validation can be called there.</p><p>Also the method <strong>PostAsync </strong>receives as an argument a DTO called <strong>PlaceOrderCommand</strong>, representing the action of this endpoint. See its definition:</p><pre>public class <strong>PlaceOrderCommand </strong>: <strong>IRequest</strong><br>{<br>   public string CustomerName { get; set; }<br>   public <strong>OrderLine</strong>[] OrderLines { get; set; }</pre><pre>   public class <strong>OrderLine</strong><br>   {<br>      public string ProductName { get; set; }<br>      public int Quantity { get; set; }<br>   }<br>}</pre><p>A DTO with customer name and products.</p><p>In order to send the command through MediatR, this class needs to implement the interface <em>IRequest</em>.</p><p>Until now we have an API that accepts HTTP requests and redirect them as commands to our message broker. Now we need to implement the worker responsible for processing these commands.</p><p>Now create a class called <strong>PlaceOrderRequestHandler </strong>and make it implements the interface <strong>IRequestHandler&lt;PlaceOrderCommand&gt;</strong>.</p><pre>public class <strong>PlaceOrderRequestHandler</strong> :<br>   <strong>IRequestHandler</strong>&lt;<strong>PlaceOrderCommand</strong>&gt;<br>{<br>   private readonly <strong>IMediator</strong> _mediator;<br>   public PlaceOrderRequestHandler(<strong>IMediator</strong> mediator)<br>   {<br>      _mediator = mediator;<br>   }</pre><pre>   public async Task&lt;Unit&gt; Handle(<strong>PlaceOrderCommand</strong> request,<br>      CancellationToken cancellationToken)<br>   {<br><strong>      // Manipulate your domain object<br>      // Persist it<br>      // Publish events</strong></pre><pre>      // Wait for the matter of the example<br>      await Task.Delay(2000, cancellationToken);</pre><pre><strong>      await _mediator.Publish(new OrderPlacedEvent { OrderId =<br>         Guid.NewGuid() }, cancellationToken);</strong></pre><pre>      return Unit.Value;<br>   }<br>}</pre><p>Note that the interface IRequestHandler asks for a generic meaning the type of message that this worker will handle, in our example, handle messages of type <strong>PlaceOrderCommand</strong>.</p><p>What is interesting here is that MediatR takes care of discover this class, instantiate and inject all services that it depends on. This way, our API doesn’t know any detail on who or how the message will be processed.</p><p>The Handle method will be executed as soon as MediatR identify that a command was sent. This part, usually is responsible for get the domain object, modify and publish events. Within this method there is a long process going on and at the end, the Order Placed Event is published with the order id.</p><p>Placing order is ready, but before running, we need to configure MediatR in our API. To configure it, change the method <em>ConfigureServices </em>within the class <em>Startup.cs </em>and add a line at the end of it:</p><pre>services.<strong>AddMediatR</strong>();</pre><p>Now hit Debug (F5) and see the result using Postman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0j5O-J2LKaGKD3_o73bjg.gif" /></figure><p>Back to the first image on this post, we need to implement the other way around, notifying the client that an order was created.</p><p>Lets create now:</p><ul><li>A websocket endpoint, so that clients can be able to connect and receive notifications from the server.</li><li>A worker that will listen to <strong>OrderPlacedEvent </strong>and send messages to the clients.</li></ul><p>To do that, I’m going to use ASP.NET COre SignalR. The configuration is simple: Still within the <em>Startup.cs </em>class, add a line at the end of the method <em>ConfigureServices</em>:</p><pre>services.<strong>AddSignalR</strong>();</pre><p>And at the end of the method <em>Configure </em>add the following:</p><pre>app.<strong>UseSignalR</strong>(routes =&gt;<br>{<br>      routes.<strong>MapHub</strong>&lt;<strong>OrderingEventsClientHub</strong>&gt;(&quot;/ordering-events&quot;);<br>});</pre><p>This last, configures the middleware that map the available routes to our websocket. In this example, we are using the route “<strong>/ordering-events</strong>” to the Hub “<strong>OrderingEventsClientHub</strong>”</p><p>The Hub is an abstraction of a communication channel between clients and backend. Create the class as follows:</p><pre>public class <strong>OrderingEventsClientHub </strong>: <strong>Hub </strong>{<strong> </strong>}</pre><p>Note here that it is empty, because it is representing a websocket without any methods. Its purpose is to open the window for communication between systems backend and client.</p><p>Now that we have the Hub created, we need to create the responsible for listening our order domain event and send them to the client.</p><pre>public class <strong>OrderingEventsClientDispatcher</strong> :<br>   <strong>INotificationHandler&lt;OrderPlacedEvent&gt;</strong><br>{<br>   private readonly IHubContext&lt;OrderingEventsClientHub&gt;<br>      _hubContext;</pre><pre>   public OrderingEventsClientDispatcher(<br>      <strong>IHubContext&lt;OrderingEventsClientHub&gt;</strong> hubContext)<br>   {<br>      _hubContext = hubContext;<br>   }</pre><pre>   public Task <strong>Handle</strong>(<strong>OrderPlacedEvent </strong>@event, <br>      CancellationToken cancellationToken)<br>   {<br>      return _hubContext.Clients.<strong>All</strong>.SendAsync(&quot;orderPlaced&quot;,<br>         @event, cancellationToken);<br>   }</pre><pre>}</pre><p>This class implements the interface <strong>INotificationHandler, </strong>offered by MediatR. When MediatR API recognizes that there is a new event of type <strong>OrderPlacedEvent, </strong>this class will be used and the method <strong>Handle </strong>will be executed, similar to the IRequestHandler.</p><p>On the constructor, the service <strong>IHubContext&lt;T&gt;</strong> is being injected. It is provided by SignalR and offers methods of communication.</p><p>Within the method Handle, I’m using the context to forward the event to all of our clients. Now clients will be able to listen to these events through the identifier “orderPlaced” on the first argument.</p><p><strong>Note</strong>: For the matter of this example, I’m sending the event to all clients. In a real scenario, the event would be sent only for those who are interested on it, for instance, only the user that placed the order. SignalR provides a full API that deals with such cases, by using ClaimsPrincipal available on ASP.NET.</p><p>Finishing this example, we need to create a client that is able to handle these events. Replace the file “Index.cshtml” with the following:</p><pre>@page<br>@model IndexModel<br>@{<br>   ViewData[&quot;Title&quot;] = &quot;Home page&quot;;<br>}</pre><pre>&lt;div class=&quot;row&quot;&gt;<br>   &lt;div class=&quot;col-md-12&quot;&gt;<br>      &lt;button id=&quot;placeOrder&quot; class=&quot;btn btn-info&quot;&gt;Place Order&lt;/button&gt;<br>   &lt;/div&gt;<br>&lt;/div&gt;</pre><pre>&lt;div class=&quot;row&quot;&gt;<br>   &lt;div class=&quot;col-md-12&quot;&gt;<br>      &lt;ul id=&quot;event-list&quot;&gt;&lt;/ul&gt;<br>   &lt;/div&gt;<br>&lt;/div&gt;</pre><pre>&lt;script src=&quot;~/lib/signalr/dist/browser/signalr.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;~/js/ordering.js&quot;&gt;&lt;/script&gt;</pre><p>This page contains a button, that will be used to place orders and a list used to show the events coming from the backend.</p><p>There are also 2 javascript files:</p><ul><li>“~/lib/signalr/dist/browser/signalr.js” — SignalR Client for Javascript. Can be downloaded through <a href="https://www.npmjs.com/package/@aspnet/signalr">NPM</a>.</li><li>“~/js/ordering.js” — Javascript with the code that connects to the backend.</li></ul><p>In order to see the contents of <strong>ordering.js</strong> <a href="https://github.com/arleypadua/domain-events-signalr/blob/master/src/Ordering.Api/wwwroot/js/ordering.js">click here</a>.</p><p>With all of these components, it is possible to run the project and see the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SN3SDEUd5d9qYhgv28mHLA.gif" /></figure><p>Access the <a href="https://github.com/arleypadua/domain-events-signalr">repository</a> and see the final solution.</p><p>Did you like it? No ? If you want to know more details or discuss about the solution, leave your comment below.</p><p>Follow me on Twitter <a href="http://twitter.com/_arleypadua">@_arleypadua</a>, thanks, and see you on the next one.</p><p>This article is also available in <a href="https://medium.com/@arleypadua/commands-domain-events-real-time-notification-na-pr%C3%A1tica-a925ecadd0fc">Portuguese</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6694d9868056" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Business Driven Concurrency Model]]></title>
            <link>https://arleypadua.medium.com/business-driven-concurrency-model-1ca8a5cc24dd?source=rss-48693b5b069c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ca8a5cc24dd</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[soa]]></category>
            <dc:creator><![CDATA[Arley Pádua]]></dc:creator>
            <pubDate>Sat, 29 Sep 2018 12:33:43 GMT</pubDate>
            <atom:updated>2018-09-29T12:33:43.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*-RgiOu1mTJ2mGjPAqOeyzg.jpeg" /></figure><p>Designing a multi service architecture might give you some headaches when it comes to concurrency. In this post I will describe the most famous technical concurrency models and propose a different view on them, so we can design better our systems.</p><p>Follow bellow these concurrency models, their benefits and challenges.</p><h4>Pessimist</h4><p>This concurrency model proposes that no one can change an object while it is being held by a process, meaning that all subsequent transactions will wait on the line until they get to their job.</p><p>This approach in some cases is bad because you hold your data, cannot scale, and sometimes happens that a given process decides to go on holidays while holding the line for other processes, forcing someone else manually solving the issue by killing the transaction.</p><h4>Optimistic</h4><p>This model proposes that given two or more transactions on the same object, either the first one wins or the last one wins. There is a down side on this model that in any cases somebody will lose data.</p><p>There are two strategies for the optimistic concurrency model:</p><ul><li>First one wins, meaning that the second one gets the data rejected. Unless you have a retry strategy (<a href="https://medium.com/@arleypadua/pizzeria-and-resilient-systems-77dd0c9ed635">mentioned here</a>), the second operation loose data.</li><li>Last one wins, by default the data is overwritten by the second one. This means that the first had its data lost. A difference here is that the first operation doesn’t know that the data was lost. This is problematic because you are not able to decide on what to do in such cases.</li></ul><h4>Business</h4><p>All of the above concurrency models have its own challenges, but we need a model focused on the business that deals with both worlds: optimism and pessimism.</p><p>In order to you understand this proposal, let me first show you a transaction example:</p><pre>1: Begin Transaction<br>2: Read Entity A<br>3: Read Entity B<br>4: Update Entity C with data from A and B<br>5: Commit Transaction</pre><p>Looking at this example we see that once we read data, there is no way we can guarantee, in a scalable system, that the state of C will be fully consistent with A and B, because A and B might be in a total different state that doesn’t align with C at the end of the transaction.</p><p><strong>The remaining question is</strong>: Does this inconsistency matters to the business ?</p><p>Most of the times we assume that if we put transactions all around, then everything will be consistent. This is given to the fact that as ORM’s were hugely introduced in our softwares, developers started saying:</p><blockquote>Ah! that’s fine, I don’t need to worry about the database, the ORM will take care of it for me. Let me focus on the business!</blockquote><p>Which is not absolutely true. In fact, we need to worry about the business, and if you are in a collaborative domain, where somebody can change the state of the entity that you are about to use, then you need to think in concurrency, which is part of your business and very much related to how your database works.</p><p>So, in order to have a business driven concurrency model, first rule:</p><ul><li><strong>Consciously </strong>choose your technical concurrency model (optimistic or pessimistic).</li></ul><p>But this is not enough, you still need to code in such way that you save your business from the issues that every choice might give to you.</p><p>And the way to address this issue you have to split your transaction in little pieces of transactions, doing one thing at a time with one piece of data at a time.</p><pre>1: Receive a message (command/event)<br>1: Get a Domain Object<br>2: Change the state of the Domain Object<br>3: Commit your transaction (possibly sending domain events)</pre><p>It is really <strong>important </strong>to not touch multiple domain objects, because every time you access another domain object within a single transaction, more probability to have concurrency issues is added. If you need to change more state across your domain objects, you might want to have a look at <a href="https://medium.com/@arleypadua/domain-events-vs-integration-events-5eb29a34fdbc">domain events</a>.</p><p><strong>In essence</strong>: Relationship between your domain objects, will give you concurrency issues. So, really think carefully on your service boundaries, because they will move apart unnecessary domain object relationships and by design, most of your challenges will be gone.</p><p>This approach save us in several cases, but in a higher level there is another case in which we need to think further: Sometimes the business requires that in a given process only one transaction wins, but not both. Here is an example:</p><p>In a given collaborative domain where a customer placed an order, and your business want to be proactive on shipping by having multiple shipping providers in case of delay. The following racing condition can happen:</p><pre>1: User places an order<br>2: Request shipping to provider #1<br>4: Provider #1 is taking too long, request shipping to provider #2<br>5: Provider #2 answer right away that order is shipped<br>6: Request cancel shipping to provider #1<br>7: At the same time, provider #1 answers that the order is shipped</pre><p>In this scenario you have a <strong>racing condition </strong>and both providers will delivery this order. There is no way you can run from this concurrency issue without finding a <strong>business reason </strong>and address it.</p><p>There are a few possible solutions that you might take:</p><ul><li>Deliver both and assume the loss, considering that your business wants to work proactively on shipping.</li><li>Ask the consumer to return one of the products, by giving an incentive in future purchases, reducing the costs of the issue.</li><li>And this list could go on forever…</li></ul><p>Considering the list above, you can notice that we were talking about a technical racing condition between requests, and now that we tried to find a <strong>business reason</strong>, we started talking about: <strong>returning policy</strong>. Based on this, the domain expert is able to decide what rule to follow in such scenarios.</p><p>If I’d give you a suggestion, not everything is solved by a <strong>technical decision</strong>. Sometimes you need to find a <strong>business reason </strong>for the issue and address it as part of your business.</p><p>If you are in a single user system, you don’t need to worry about it, but must scenarios, this is not the case.</p><p>Finally, <strong>don’t underestimate concurrency on you software, because there’s business hidden on it</strong>.</p><p>Follow me on Twitter <a href="https://twitter.com/_arleypadua">@_arleypadua</a>.</p><p>This article is also available in <a href="https://medium.com/@arleypadua/modelo-de-concorr%C3%AAncia-orientado-ao-neg%C3%B3cio-765834cc0712">Portuguese</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ca8a5cc24dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Modelo de Concorrência Orientado ao Negócio]]></title>
            <link>https://arleypadua.medium.com/modelo-de-concorr%C3%AAncia-orientado-ao-neg%C3%B3cio-765834cc0712?source=rss-48693b5b069c------2</link>
            <guid isPermaLink="false">https://medium.com/p/765834cc0712</guid>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[soa]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Arley Pádua]]></dc:creator>
            <pubDate>Sat, 29 Sep 2018 12:33:18 GMT</pubDate>
            <atom:updated>2018-09-29T12:34:35.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*-RgiOu1mTJ2mGjPAqOeyzg.jpeg" /></figure><p>Criar um design de software multi serviços pode te levar a algumas dores de cabeça quando pensamos em concorrência. Nesse post vou descrever os modelos técnicos de concorrência mais famosos e uma proposta diferente ao vê-los, para que possamos pensar melhor no design dos nossos sistemas.</p><p>Veja abaixo os modelos de concorrência, benefícios e desafios.</p><h4>Pessimista</h4><p>Esse modelo de concorrência propõe que ninguém pode alterar o estado de um objeto enquanto ele está sendo alterado por outro processo, significando que todas as transações subsequentes interessadas no objeto, terão que esperar sua vez na fila para fazer o que precisam.</p><p>Essa abordagem em alguns casos é ruim pois você bloqueia o dado, não pode escalar e as vezes acontece que um dado processo decide tirar férias enquanto segura a fila de processos interessados no mesmo objeto, forçando que alguém resolva o problema manualmente.</p><h4>Otimista</h4><p>Esse modelo propõe que dada duas ou mais transações em um mesmo objeto, somente uma transação ganha: ou a primeira, ou a segunda ganha. Existe um lado ruim desse modelo é que in qualquer um dos casos, um dos processos perde dado.</p><p>Existem duas estratégias para o modelo otimista:</p><ul><li>Primeira ganha, significando que o segundo tem o dado rejeitado. A menos que você tenha uma <em>retry strategy </em>(<a href="https://medium.com/@arleypadua/pizzaria-e-sistemas-resilientes-27029a277dc2">mencionada aqui</a>), a segunda operação perde dado.</li><li>Última ganha, por padrão o dado é sobrescrito pela segunda transação. Isso significa que a primeira transação tem o dado descartado. A diferença aqui é que a primeira operação não sabe que o dado foi perdido. Isso é problemático, pois você não consegue decidir o que fazer quando isso acontecer.</li></ul><h4>Negócio</h4><p>Todos os modelos acima tem seus próprios desafios, mas precisamos de um modelo focado no negócio, que pode lidar com ambos os mundos: otimista e pessimista.</p><p>Para entender a ideia proposta, veja primeiro o exemplo de uma transação abaixo:</p><pre>1: Begin Transaction<br>2: Read Entity A<br>3: Read Entity B<br>4: Update Entity C com dado de A e B<br>5: Commit Transaction</pre><p>Olhando para o exemplo vemos que uma vez que o dado é lido, não é possível garantir que o estado de C será completamente consistente com A e B, pois A e B podem ter seus estados totalmente modificados ao final da transação, não sendo mais consistente com C.</p><p><strong>A questão que fica é</strong>: Essa inconsistência é importante para o negócio ?</p><p>Na maioria das vezes assumimos que se colocarmos transações em todos os lugares, tudo será consistente. Isso se deve ao fato de que como os ORM’s se tornaram largamente utilizados nos nossos sistemas, desenvolvedores começaram a falar:</p><blockquote>Ah! Não tem problema, eu não preciso me preocupar com o banco de dados, pois o ORM cuida disso pra mim. Eu vou focar no negócio!</blockquote><p>Essa frase não é totalmente verdade. De fato, precisamos nos preocupar com o negócio, e se você está desenvolvendo um sistema em um domínio colaborativo, onde outro processo pode mudar o estado da entidade que você está para usar, então você precisa pensar em concorrência, que é parte do negócio e muito relacionado ao funcionamento do banco de dados.</p><p>Então, para ter um modelo de concorrência orientado ao negócio, a primeira regra:</p><ul><li>Faça a decisão do seu modelo de concorrência <strong>conscientemente </strong>(otimista ou pessimista)</li></ul><p>Mas o modelo de concorrência técnico não é o suficiente, você ainda tem que codificar de uma maneira que evite falhas no negócio pela sua escolha técnica.</p><p>A abordagem proposta para resolver esse problema é dividir a sua transação em pequenas partes, fazendo somente uma coisa por vez com uma porção de dado.</p><pre>1: Recebe uma mensagem (comando/evento)<br>1: Obtém o Objeto de Domínio<br>2: Altera o estado do Objeto de Domínio<br>3: Commit (possivelmente publicando Eventos de Domínio)</pre><p>É muito importante não tocar em vários objetos de domínio, porque toda vez que você acessa outro objeto de domínio na mesma transação, mais probabilidade de problemas de concorrência é adicionada. Se você precisa mudar mais estados em seus objetos de domínio, você deve olhar para os <a href="https://medium.com/@arleypadua/domain-events-vs-integration-events-980d51d4fe82">eventos de domínio</a>.</p><p><strong>Em essência</strong>: Relacionamento entre seus objeto de domínio, te dará problemas de concorrência. Então, pense com bastante cuidado nos seus <em>bounded contexts</em>,<em> </em>pois eles vão remover relacionamento de objetos de domínio desnecessários e, por design a maioria dos desafios de concorrência serão extintos.</p><p>Essa abordagem nos salva em vários casos, mas em um nível de abstração mais acima, precisamos de pensar um pouco mais adiante: As vezes o negócio requer que em um dado processo, somente uma transação ganha. Veja um exemplo abaixo:</p><p>Em um dado domínio colaborativo onde um cliente fez um pedido, e o negócio é proativo ao fazer o envio do produto tendo dois fornecedores de entrega diferentes em caso de demora. A seguinte <em>racing condition </em>pode aparecer:</p><pre>1: User faz um pedido<br>2: Solicita envio para o fornecedor #1<br>4: Fornecedor #1 demora muito, solicita envio p/ fornecedor #2<br>5: Fornecedor #2 responde na hora que foi enviado<br>6: Solicita o cancelamento para o fornecedor #1<br>7: Ao mesmo tempo, fornecedor #1 responde que o pedido foi enviado</pre><p>Nesse cenário você tem uma <strong><em>racing condition </em></strong>e ambos fornecedores vão entregar o produto. Não existe outra maneira de sair desse problem de concorrência, senão achar um <strong>motivo de negócio</strong>.</p><p>Existe uma série de soluções possíveis:</p><ul><li>Entregar ambos e assumir a perda, caso o negócio queira trabalhar dessa forma.</li><li>Pedir para o cliente o estorno de um dos produtos, dando um incentivo em compras futuras, reduzindo os custos do problema.</li><li>E essa lista poderia continuar com muitas possíveis soluções…</li></ul><p>Considerando a lista acima, você pode notar que estávamos falando sobre um problema técnico de <em>racing condition </em>entre duas solicitações, e agora tentamos achar um <strong>motivo de negócio </strong>para o problema: <strong>política de estorno</strong>. Baseado nisso, o <em>domain expert </em>é capaz de decidir em qual regra seguir nesses casos.</p><p>Se eu puder dar uma sugestão, nem tudo é resolvido por uma <strong>decisão técnica</strong>. As vezes você precisa achar um <strong>motivo de negócio</strong> para o problema e consertá-lo como parte do seu processo de negócio.</p><p>Se você está desenvolvendo um sistema de um usuário único, você não precisa se preocupar com concorrência, mas esse não é o caso da maioria.</p><p>Finalizando: <strong>Não subestime a concorrência no seu software, pois existe negócio escondido nela</strong>.</p><p>Me siga no Twitter <a href="https://twitter.com/_arleypadua">@_arleypadua</a>.</p><p>Esse artigo também está disponível em <a href="https://medium.com/@arleypadua/business-driven-concurrency-model-1ca8a5cc24dd">Inglês</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=765834cc0712" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Commands + Domain Events + Real time notification na Prática]]></title>
            <link>https://arleypadua.medium.com/commands-domain-events-real-time-notification-na-pr%C3%A1tica-a925ecadd0fc?source=rss-48693b5b069c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a925ecadd0fc</guid>
            <category><![CDATA[mediatr]]></category>
            <category><![CDATA[signalr]]></category>
            <category><![CDATA[domain-events]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[cqrs]]></category>
            <dc:creator><![CDATA[Arley Pádua]]></dc:creator>
            <pubDate>Sun, 23 Sep 2018 20:56:21 GMT</pubDate>
            <atom:updated>2018-09-29T13:33:39.946Z</atom:updated>
            <content:encoded><![CDATA[<p>Seguindo a minha série de posts sobre sistemas distribuídos em que começo explicando os <a href="https://medium.com/@arleypadua/principais-princ%C3%ADpios-na-modelagem-de-servi%C3%A7os-a810ba2efe7f">princípios na modelagem de serviços</a>, também explicando o porquê eles devem ser <a href="https://medium.com/@arleypadua/pizzaria-e-sistemas-resilientes-27029a277dc2">resilientes</a> e a importância da implementação de <a href="https://medium.com/@arleypadua/domain-events-vs-integration-events-980d51d4fe82">domain events</a>, após alguns <em>feedbacks </em>do pessoal resolvi compartilhar um pouco de prática associada aos conceitos mencionados nos <em>posts</em>.</p><p><strong><em>Obs.:</em></strong><em> No final do post, há um link com a solução completa.</em></p><p>Para esse post prático, vou demonstrar um sistema muito simples composto de:</p><ul><li>Uma API que aceita pedidos contendo nome do cliente e lista de itens de um pedido.</li><li>Um frontend simples usado somente para o envio de pedidos e receber notificações do backend.</li><li>Um projeto de backend, responsável por processar o pedido e publicar domain events.</li><li>Para a abstração de <em>commands </em>e <em>domain events </em>vou usar a biblioteca <a href="https://github.com/jbogard/MediatR">MediatR</a>, muito fácil e intuitiva para o exemplo.</li><li>Para o envio de notificações para o frontend, vou usar SignalR, uma vez que ele oferece uma maneira fácil de trabalhar com websockets.</li></ul><p>Veja na imagem abaixo os conceitos abordados nesse exemplo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*CG64_byH4z0cXAblmASUNA.png" /></figure><p>Começando a partir da API, crie um projeto com ASP.NET Core 2.1 e adicione o NuGet package: <em>MediatR.Extensions.Microsoft.DependencyInjection.</em></p><p>Ele conterá tudo que é necessário para configurar o MediatR como nosso message broker.</p><p>É importante observar que o MediatR é uma biblioteca que oferece abstrações de envio de comandos e publicação de eventos, porém tudo roda em memória. Em um caso real, você deve adotar um sistema de transporte de mensagens, como Azure Service Bus ou RabbitMQ. Eles garantem que as mensagens não se percam, mesmo que seu servidor caia.</p><p>Crie uma controller chamada OrderController e adicione um endpoint conforme abaixo:</p><pre>[Route(&quot;api/[controller]&quot;)]<br>public class <strong>OrdersController</strong> : <strong>Controller</strong><br>{<br>   private readonly <strong>IMediator</strong> _mediator;</pre><pre>   public OrdersController(<strong>IMediator </strong>mediator)<br>   {<br>      _mediator = mediator;<br>   }</pre><pre>   [<strong>HttpPost</strong>]<br>   public Task PostAsync([FromBody]<strong>PlaceOrderCommand </strong>order) =&gt;<br>      _mediator.Send(order);</pre><pre>}</pre><p>Veja que não há muito segredo aqui e nossa controller está bem simples.</p><p>Um comando nunca deve ser enviado sem estar válido, porém, para fins de simplicidade do exemplo, não vou implementar as validações. Caso queira olhar mais a fundo, veja o <a href="https://github.com/jbogard/MediatR/wiki/Behaviors">wiki</a> do MediatR para behaviors. Com eles é possível criar um pipeline de execução antes que o comando seja enviado e implementar sua validação lá.</p><p>Note que o método <strong>PostAsync </strong>recebe como parâmetro uma DTO chamada de <strong>PlaceOrderCommand</strong>, representando a ação do endpoint. Veja a sua definição:</p><pre>public class <strong>PlaceOrderCommand </strong>: <strong>IRequest</strong><br>{<br>   public string CustomerName { get; set; }<br>   public <strong>OrderLine</strong>[] OrderLines { get; set; }</pre><pre>   public class <strong>OrderLine</strong><br>   {<br>      public string ProductName { get; set; }<br>      public int Quantity { get; set; }<br>   }<br>}</pre><p>Um simples DTO contendo o nome do cliente e os produtos requisitados.</p><p>Note que para que seja possível enviar o comando através da API do MediatR, é necessário implementar a interface <em>IRequest.</em></p><p>Até agora temos uma API que aceita requisições HTTP e redireciona as requisições como comandos para o nosso message broker. Agora precisamos implementar o worker responsável por processar essas mensagens.</p><p>Para isso, crie uma classe chamada <strong>PlaceOrderRequestHandler </strong>implementando a interface <strong>IRequestHandler&lt;PlaceOrderCommand&gt;</strong>.</p><pre>public class <strong>PlaceOrderRequestHandler</strong> :<br>   <strong>IRequestHandler</strong>&lt;<strong>PlaceOrderCommand</strong>&gt;<br>{<br>   private readonly <strong>IMediator</strong> _mediator;<br>   public PlaceOrderRequestHandler(<strong>IMediator</strong> mediator)<br>   {<br>      _mediator = mediator;<br>   }</pre><pre>   public async Task&lt;Unit&gt; Handle(<strong>PlaceOrderCommand</strong> request,<br>      CancellationToken cancellationToken)<br>   {<br><strong>      // Manipulate your domain object<br>      // Persist it<br>      // Publish events</strong></pre><pre>      // Wait for the matter of the example<br>      await Task.Delay(2000, cancellationToken);</pre><pre>      <strong>await _mediator.Publish(new OrderPlacedEvent { OrderId =<br>         Guid.NewGuid() }, cancellationToken);</strong></pre><pre>      return Unit.Value;<br>   }<br>}</pre><p>Veja que a interface IRequestHandler, pede um tipo genérico significando que tipo de mensagem esse worker vai processar, no nosso caso processar mensagens do tipo <strong>PlaceOrderCommand</strong>.</p><p>O interessante é que o MediatR será o responsável por descobrir essa classe, instanciar e cuidar da injeção de dependência. Fazendo com que a nossa API não precise conhecer nenhum detalhe de quem vai processar o comando.</p><p>O método Handle será executado assim que o MediatR identificar um comando. Essa parte, geralmente é responsável por recuperar o agregado/entidade do domínio, modificá-lo e publicar eventos.</p><p>No método <em>Handle </em>um processo longo de criação do pedido e o evento de pedido criado (<strong><em>OrderPlacedEvent</em></strong>) é publicado contendo o ID do pedido.</p><p>Nossa parte de realizar pedido está pronta, mas antes de rodar, precisamos configurar o MediatR na nossa aplicação. Para isso vá até o método <em>ConfigureServices </em>da classe <em>Startup.cs </em>e adicione na última linha o seguinte:</p><pre>services.<strong>AddMediatR</strong>();</pre><p>Agora faça o debug do projeto e veja o resultado chamando a API com o Postman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0j5O-J2LKaGKD3_o73bjg.gif" /></figure><p>Voltando à primeira imagem do post, precisamos implementar o caminho de volta e notificar o cliente que um pedido foi criado.</p><p>Para isso precisamos criar:</p><ul><li>Um endpoint de websocket, para que clientes possam se conectar e receber mensagens do servidor</li><li>Um worker que ficará escutando o evento <strong><em>OrderPlacedEvent </em></strong>e enviando mensagens para os clientes.</li></ul><p>Para criar o websocket, vamos utilizar o ASP.NET Core SignalR. A configuração é bem simples: ainda na classe <em>Startup.cs, </em>adicione o seguinte no final do método <em>ConfigureServices</em>:</p><pre>services.<strong>AddSignalR</strong>();</pre><p>E no final do método <em>Configure </em>adicione o seguinte:</p><pre>app.<strong>UseSignalR</strong>(routes =&gt;<br>{<br>      routes.<strong>MapHub</strong>&lt;<strong>OrderingEventsClientHub</strong>&gt;(&quot;/ordering-events&quot;);<br>});</pre><p>Esse último, configura o middleware responsável por mapear as rotas disponíveis para o nosso websocket. Para o nosso exemplo, só estamos configurando a rota “<strong>/ordering-events</strong>” para o Hub “<strong>OrderingEventsClientHub</strong>”.</p><p>O Hub é uma representação no <strong>SignalR</strong> do canal de comunicação entre os clients e o backend, para isso, crie a classe OrderingEventsClientHub:</p><pre>public class <strong>OrderingEventsClientHub </strong>: <strong>Hub </strong>{<strong> </strong>}</pre><p>Perceba que ela está vazia, pois ela está representando somente um websocket sem nenhum método definido. Sua única função é abrir uma porta de comunicação entre o backend e o client.</p><p>Tendo criado o Hub, precisamos de criar o responsável por escutar os eventos de pedido criado e enviá-los ao client.</p><pre>public class <strong>OrderingEventsClientDispatcher</strong> :<br>   <strong>INotificationHandler&lt;OrderPlacedEvent&gt;</strong><br>{<br>   private readonly IHubContext&lt;OrderingEventsClientHub&gt;<br>      _hubContext;</pre><pre>   public OrderingEventsClientDispatcher(<br>      <strong>IHubContext&lt;OrderingEventsClientHub&gt;</strong> hubContext)<br>   {<br>      _hubContext = hubContext;<br>   }</pre><pre>   public Task <strong>Handle</strong>(<strong>OrderPlacedEvent </strong>@event, <br>      CancellationToken cancellationToken)<br>   {<br>      return _hubContext.Clients.<strong>All</strong>.SendAsync(&quot;orderPlaced&quot;,<br>         @event, cancellationToken);<br>   }</pre><pre>}</pre><p>Essa classe implementa a interface <strong>INotificationHandler</strong>, fornecida pelo MediatR. Quando o MediatR reconhecer que um evento <strong>OrderPlacedEvent </strong>foi publicado, essa classe será usada e o método <strong>Handle </strong>será executada.</p><p>No construtor da classe, o serviço <strong>IHubContext&lt;T&gt; </strong>é injetado. Ele é um serviço fornecido pelo SignalR e fornece métodos de comunicação do backend para os clients.</p><p>Note que no método Handle, estou usando o contexto para redirecionar o evento para todos os clientes.</p><p>Os clientes poderão escutar esse evento através do identificador “orderPlaced” passado como primeiro parâmetro.</p><p><strong>Obs.: </strong>Para fins de simplicidade do exemplo, estou enviando o evento para todos os clientes. Em um cenário real, o evento deveria ser enviado apenas para clients que estão interessados nesse evento, como por exemplo, algum usuário em específico. O SignalR fornece uma API bem coerente para usuários através do ClaimsPrincipal usado no ASP.NET.</p><p>Para finalizar o exemplo, precisamos criar um cliente que possa consumir esses eventos, para isso, substitua a página “Index.cshtml” pelo seguinte:</p><pre>@page<br>@model IndexModel<br>@{<br>   ViewData[&quot;Title&quot;] = &quot;Home page&quot;;<br>}</pre><pre>&lt;div class=&quot;row&quot;&gt;<br>   &lt;div class=&quot;col-md-12&quot;&gt;<br>      &lt;button id=&quot;placeOrder&quot; class=&quot;btn btn-info&quot;&gt;Place Order&lt;/button&gt;<br>   &lt;/div&gt;<br>&lt;/div&gt;</pre><pre>&lt;div class=&quot;row&quot;&gt;<br>   &lt;div class=&quot;col-md-12&quot;&gt;<br>      &lt;ul id=&quot;event-list&quot;&gt;&lt;/ul&gt;<br>   &lt;/div&gt;<br>&lt;/div&gt;</pre><pre>&lt;script src=&quot;~/lib/signalr/dist/browser/signalr.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;~/js/ordering.js&quot;&gt;&lt;/script&gt;</pre><p>Essa página bem simples contém um botão, que será utilizado para criar pedidos e uma lista de eventos que usamos para mostrar o progresso das requisições/eventos vindos do backend.</p><p>Também há dois javascripts:</p><ul><li>“~/lib/signalr/dist/browser/signalr.js” — Cliente para SignalR em Javascript. Pode ser obtido através do node package: <a href="https://www.npmjs.com/package/@aspnet/signalr">https://www.npmjs.com/package/@aspnet/signalr</a></li><li>“~/js/ordering.js” — Javascript contendo a lógica necessária para conectar ao backend.</li></ul><p><a href="https://github.com/arleypadua/domain-events-signalr/blob/master/src/Ordering.Api/wwwroot/js/ordering.js">Clique aqui</a> para ver o conteúdo do script <strong>ordering.js</strong>.</p><p>Com todos esses componentes, é possível fazer o debug do projeto e ver o resultado final, Confira:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SN3SDEUd5d9qYhgv28mHLA.gif" /></figure><p>Acesse o <a href="https://github.com/arleypadua/domain-events-signalr">repositório</a> do projeto e veja a solução completa.</p><p>Gostou ? Não gostou ? Se quiser saber de mais detalhes ou discutir, deixe nos comentários.</p><p>Me acompanhe no Twitter <a href="http://twitter.com/_arleypadua">@_arleypadua</a>, obrigado, até a próxima.</p><p>Esse artigo também está disponível em <a href="https://medium.com/@arleypadua/commands-domain-events-real-time-notification-hands-on-6694d9868056">Inglês</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a925ecadd0fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>