<?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 Bogdan Azarić on Medium]]></title>
        <description><![CDATA[Stories by Bogdan Azarić on Medium]]></description>
        <link>https://medium.com/@cptsudoku?source=rss-15df1a5027e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rmyfeKbXbb_pQUR9QgxUKA.jpeg</url>
            <title>Stories by Bogdan Azarić on Medium</title>
            <link>https://medium.com/@cptsudoku?source=rss-15df1a5027e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:35:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cptsudoku/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[Hexagonal microservices will make you smile]]></title>
            <link>https://medium.com/@cptsudoku/hexagonal-microservices-will-make-you-smile-3850019196c1?source=rss-15df1a5027e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3850019196c1</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Bogdan Azarić]]></dc:creator>
            <pubDate>Wed, 09 May 2018 17:54:01 GMT</pubDate>
            <atom:updated>2018-05-09T17:55:05.328Z</atom:updated>
            <content:encoded><![CDATA[<p>If you rubbed the magic lamp and a genie came out granting you one wish, what would you choose? I would put on a smug look, cross my fingers, and ask for more wishes. And if that was against the law, I would go ahead and ask for more genies instead.</p><p>Now if the genie came out and told you that you had one wish about your code, what would you choose then? Would it be readable or performant? Would it be dry or loosely coupled? Personally, I would like my code to be <strong>highly testable</strong>, because if it is highly testable than it will be easy to change without breaking, and if it is easy to change then I could make it readable, performant, dry and loosely coupled. I could get more wishes for the price of one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*6ETqVdUQ7PtxGhCdqYygrA.png" /><figcaption>- Genie, give me testable code. — Really? Wouldn’t you want a life instead?</figcaption></figure><p>In <a href="https://medium.com/@cptsudoku/when-your-code-becomes-hard-to-test-d2b9cad84dcf">part 1</a> we observed how business logic leaking into infrastructure code makes your code very hard to test. In this part, we will first demonstrate, and then formalize hexagonal architecture principles which are, in my personal view, <strong>the simplest and most</strong> effective architectural pattern for making your microservices testable.</p><h3><strong>“Talk is cheap, show me the code”</strong></h3><p>Applying hexagonal architecture pattern is <strong>dead simple</strong>, but our business logic can be really sneaky in practice.<strong> </strong>If you don’t pay attention it will wiggle out of control and quietly settle into the infrastructure code making it tightly coupled to it — and then good luck kicking it out! To prevent this from happening <strong>for every line of code</strong> we need to know if it is</p><ol><li>our business logic: the behavior of our application — this makes our application a unique snowflake</li><li>our infrastructure code: the code that translates a method call to a delivery mechanism such as HTTP, middleware, database, or advanced carrier pigeons for all we care</li></ol><p>We need to take that business logic out of infrastructure classes, and we need to apply that rule <strong>consistently</strong> throughout the codebase. Sounds simple, right? There is no ‘but’ here, <strong>it is</strong> that simple. So let’s do it.</p><p>Let’s say we have a cloud file system which we can access via HTTP. The goal is to append a single entry to a log file. The log file may or may not exist, so we first better check that in order to prevent a big juicy facepalm in production. We crack our knuckles, we roll up our sleeves and before we know it there it is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d39eaabf190e286a52ca8cd616074aa/href">https://medium.com/media/0d39eaabf190e286a52ca8cd616074aa/href</a></iframe><p>Simple, clean, straightforward. And also pretty much <strong>impossible to put into a suite of integration tests</strong>. Your <em>if statement</em> is a business rule and it should not mix with infrastructure code. To test the behavior now you would have to fake an HTTP server, parse the requests, figure out what the request was all about, and after you have figured that out you would need to provide a pre-made response to test a specific behavior. Those requests are many in a world of microservices since your service is <strong>surrounded by remote calls</strong>. Let’s fix this testing pandemonium.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb79ee386290cf302b12198c2870695c/href">https://medium.com/media/bb79ee386290cf302b12198c2870695c/href</a></iframe><p>Much better now! We pulled out all of the communication code and we moved it to a class implementing <em>FileSystem</em> interface (in our case that would be called <em>FileSystemHttpClient</em>). We can exclude testing the implementations of <em>FileSystem</em> from our integrated tests and replace that dependency with a <a href="https://www.martinfowler.com/articles/mocksArentStubs.html"><strong>fake</strong></a>. The fake will implement the client interface and simulate the behavior. If we use remote filesystem in production in tests we could use local filesystem so that we don’t have to bother implementing an in-memory solution. The rest of our application will be completely unaware that we have tricked it.</p><p>We have made a business rule easy to test but before we pop the champagne, we still need to write some contract tests to see that we are actually doing a proper job of simulating the <strong>actual</strong> remote filesystem service. If we have some end-to-end tests that can cover us as well.</p><p>This solution be the remedy for the the problem when we want to have multiple implementations of our client classes. If we have a message queue client for the filesystem service, along with the HTTP client, we would have to do some copy/paste driven development and duplicate the <em>if statement</em> in the other client as well. In this scenario, the <em>if </em>statement is pulled one level above the client class so there is no duplication.</p><p>Now that we are happy with our code we should know what the heck we did here. Many readers could say that we have just practiced common sense architecture (or mere separation of concerns), but this kind specifically is called <strong>hexagonal architecture</strong>. In order to formalize this practice and not just wing it, let us delve into the theory now.</p><h3><strong>The theory now</strong></h3><p>Nobody likes the theory, however, we do need some rough guidelines until we get the intuitive sense of what our hexagons should look like. There are two main concepts that are necessary to know. First is the concept of <strong>inside and outside</strong> and the second is the concept of <strong>ports and adapters</strong>.</p><h4><strong>Inside and outside</strong></h4><p>We already know from this article that the inside is our business logic and that the outside is the infrastructure or communication code. Outside depends on the inside, and the inside does not need to know about anything on the outside. These two <strong>should not mix</strong>. By now you should have the intuitive sense in which sector each line of code belongs, so it is up to you to <strong>fortify the boundaries </strong>between the sectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5odlOfK5lnCqrZ9KPnBxA.png" /><figcaption>Domain code separated by a barbed wire and a brand new Tick Tock Croc anti-corruption layer. Original by Thomas Pierrain <a href="http://bit.ly/2HpYQZP">http://bit.ly/2HpYQZP</a></figcaption></figure><p>OK, so the moat is here, the barbed wire is here, but where is the bridge? How does the inside talk to the outside and vice versa? To facilitate the communication between the two sectors of the application we need to use <strong>ports and adapters</strong>.</p><h4><strong>Ports and adapters</strong></h4><p>“Ports and adapters” is the alternative name for the hexagonal architecture, but people rarely call it like that anymore, probably because “hexagon” sounds cool, while “ports and adapters” sounds as cool as pocket protectors.</p><p>Ports are in essence <strong>service entry points </strong>or<strong> API</strong>. In practice, they are simple Java/C# interfaces. Adapters are <strong>implementations of those ports</strong>. We can see two kinds of ports and adapters:</p><ol><li>primary port — this is the API of your service. One example would be <em>UserService</em> which is implemented by your microservice. Adapter adapting that service would be maybe <em>RestServiceAdapter</em></li><li>secondary port — this is the API of any external service your service depends on. It could <em>UserDao</em> which talks our service uses to fetch information about user or <em>Filesystem, </em>which we used as an example previously. Adapters adapting those ports would be for instance <em>HibernateUserDao</em> or <em>HttpFilesystemClient</em>.</li></ol><p>This was the bare minimum of theoretical knowledge needed create the hexagonal solutions. You are probably wondering now why should you use hexagonal architecture, and not any other architecture which offers clean separation of concerns?</p><h3><strong>What’s so different about hexagons?</strong></h3><p>If we wanted to contain business logic where it belongs, why didn’t we use traditional layered architecture? When formulating principles of hexagonal architecture, Alistair Cockburn noticed that the problem of leaky business logic as an inherent one to complex architectural styles, where it is not clear what code goes where.</p><p>If we look at some other architectural solutions we will find <strong>just about any layer you can think of</strong>. Domain layer, application services layer, domain services layer, the infrastructure layer, presentation layer, use case layer, mozzarella layer, tomato sauce layer, Parmigiano layer and most importantly <strong>bacon strips layer</strong>. Bake at 200C for 20 minutes, and “ta-da”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*kp_lR85_445fjpn_PHUm2w.jpeg" /><figcaption>As you can see from the image, layers leak. I rest my case. Original from <a href="http://bit.ly/2GRvy5k">http://bit.ly/2GRvy5k</a></figcaption></figure><p>Every additional layer adds more indirection and more complexity. In hexagonal architecture, we have only business logic and adapter code. Adapter code should not contain any logic whatsoever. And that’s about it! Therefore hexagonal architecture is really easy to comprehend, and once you fully internalize it, you will see hexagons everywhere.</p><h4><strong>When we should use hexagonal architecture</strong></h4><p>We are engineers and not car salespeople, so let’s be honest, hexagonal architecture is not a silver bullet. It has its limitations, so for instance, it will not make you stop snoring and will probably not put your kids through college. It cannot walk your dog and do your laundry. It is a <strong>design decision</strong> and it <strong>comes at a cost</strong>.</p><p>One downside is that will effectively duplicate the number of classes on your boundary. In case of MVC that would be the controller (as described in this fantastic article about <a href="http://tidyjava.com/hexagonal-architecture-powerful/"><em>Spring</em> <em>PetClinic</em></a>). If you access your persistent data using ActiveRecord pattern doing hexagonal architecture will be difficult. Actually, it does not go well with Rails at all, and for that reason will certainly make <a href="https://www.youtube.com/watch?v=z9quxZsLcfo">DHH mad</a>.</p><p>On the other hand not using hexagonal architecture will make your external dependencies hard to detach, so <strong>can we find some compromise here</strong>? Certainly! You do not have to go all the way with hexagonal architecture. You can separate those classes which you think you might swap out in production at some point, and those classes that you intend to fake in tests.</p><p>That way you get the best of both worlds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3850019196c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When your code becomes hard to test]]></title>
            <link>https://medium.com/@cptsudoku/when-your-code-becomes-hard-to-test-d2b9cad84dcf?source=rss-15df1a5027e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2b9cad84dcf</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[legacy-code]]></category>
            <dc:creator><![CDATA[Bogdan Azarić]]></dc:creator>
            <pubDate>Sun, 11 Mar 2018 20:37:33 GMT</pubDate>
            <atom:updated>2018-03-11T20:37:33.069Z</atom:updated>
            <content:encoded><![CDATA[<p>Automation is what we, software developers, do. It is the one single principle that is ingrained in our thinking. If we have to do the same thing twice — we’ll automate it. The thought of doing the same repetitive task will fill us with unease. Efficiency drives us, while repetition, overhead, boilerplate, kills our spirit. And we dread regressions.</p><p>To have any kind of confidence we need some automated tests in place, and there is no debate that the dev team has to test its code by themselves. That piece of knowledge has been creeping up on us for nearly 20 years, bit by bit. In 2018 it is almost impossible to ignore, when we see companies listing <strong>test driven codebase as one of the company perks</strong>. If, god forbid, you got the wrong idea that you will just get the code right and if, god bless, your project is successful to live long enough, you will inevitably feel the development speed going down and the rate of errors rising if your service is left unattended.</p><p>Even if you write your own tests, your QA will be an invaluable part of the team, but it would be better <strong>for them</strong> to write the infrastructure needed for reliable running of end-to-end tests. It would be better for you, <strong>the manager</strong>, as well, since the process is way more efficient than manual testing. And it would sure be better for you, <strong>the developer</strong>, if QA didn’t know what you look like.</p><p>When it comes to testing there are no two developers that will agree on the terminology. The terms that I use when talking about tests are:</p><ul><li>unit testing: testing a single class/package in isolation, with mocks around</li><li>integrated testing: the debate is raging here, and I subscribe to the definition which says that integrated tests target multiple units of code together, and mocks all external systems such as database, network, filesystem etc…</li><li>end-to-end testing: testing all application components together</li></ul><h4><strong>The one new amazing trick to complete confidence: unit tests</strong></h4><p>As with any clickbait, we tricked you here as well. You have to write not only unit tests, but to write them <strong>all</strong> if you want to have confidence in your code. Google testing pyramid (the pyramid itself was not invented by Google, but by Mike Cohn) puts the ratios of test numbers at 70/20/10 favoring unit tests, followed by integrated and ending with end-to-end tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*tteoPtCeGoBGUpvr_gKDbg.png" /></figure><p>This pyramid ratios did not come from a fortune cookie. It was, rather, the result of decades of meticulous testing and experimentation. The previous sentence, however, <strong>did</strong> come from a fortune cookie, since I did not work at Google and really could not tell. What can be sure, though, is that overreliance on integrated and end-to-end tests should be avoided, because it will deceive you and lead you astray. One notable opponent, J. B. Rainsberger, goes so far to call it a <a href="https://www.youtube.com/watch?v=VDfX44fZoMc">scam</a>. Here’s the reason why reliance of integrated and end-to-end tests cannot give you confidence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tSqe0D8Zo6S6JRdg_hURyw.png" /></figure><p>If the number of code paths in three classes is 3, 5, and 7, then the number of integrated tests needed to cover this cluster will be 3 x 5 x 7 = 115. But if we split apart this bunch and test it in isolation the number of tests will be significantly lower. Therefore, integrated tests must be the enemy, and we should avoid it like the plague. Right?</p><p>I would like to counter this point with the notion that integrated tests are, in fact, <strong>an invaluable tool in taming legacy code</strong>. Since unit tests are hard to write in case of legacy code, we should find “pinch points” (as coined by Michael Feathers), or points where we can easily isolate cluster of objects and hit that cluster with series of integrated tests until the point that we are fairly confident about the behavior of that code. This technique is called “cover and modify”.</p><p>After we have covered the cluster with integrated tests we can refactor with ease, and aim for unit test coverage. Unit and integrated tests would serve as the living documentation of our clean code. We could easily keep it clean and allow no broken windows. It would be the warm mountain lodge with a fireplace, surrounded by inhospitable wilderness populated with dragons. And from there we could cultivate the rest, bit by bit, until we reach the borders of our application. We all know that feeling of ease when working on a piece of well maintained code. And we want it back.</p><p>So what’s stopping us?</p><h4><strong>The villain</strong></h4><p>When working with microservice based architectures the biggest obstacle in our way to fully tested software is our business logic leaking into the communication code which talks to an external service such as docker, other services, database, etc. Once the business logic leaks, that piece of code becomes tightly coupled to the actual implementation. Consider the following piece of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c97be061142a785d8620e1d89816bf5/href">https://medium.com/media/8c97be061142a785d8620e1d89816bf5/href</a></iframe><p>This is obviously a simplified example of a class tasked with HTTP communication with instance pool service. Instead minding it’s own business, which is handling HTTP requests and responses, it managed to pull in a part of business logic, which says that new instance should be allocated only if there are no instances available.</p><p>If we want to have multiple clients, say a message queue client along with the HTTP client, we would have to <a href="http://www.vemcodex.com/development/2018/02/17/code-duplication.html">duplicate the logic</a> in the other class as well. And testing of that business logic becomes a real pain. In order to test a simple if statement we have to mock the HTTP client and then parse the JSON request and return a JSON response.</p><p>For a single if statement? How many if statements have leaked into your communication classes? And for how many tests? If you want to build an integrated test you could have tens of test cases which could hit the client class, if not hundreds. And for all of those cases you will have to serialize and deserialize responses.</p><p>But fear not. There exists a simple and elegant solution to sooth the pain of codebases such as this. You may have even guessed it by now. It will be explained in part 2 of this article, coming soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2b9cad84dcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>