<?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 Jonas Tulstrup on Medium]]></title>
        <description><![CDATA[Stories by Jonas Tulstrup on Medium]]></description>
        <link>https://medium.com/@jonastulstrup?source=rss-175522a2102a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EM8hDEg15-1kD1GlxwOsSg.jpeg</url>
            <title>Stories by Jonas Tulstrup on Medium</title>
            <link>https://medium.com/@jonastulstrup?source=rss-175522a2102a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 01:18:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jonastulstrup/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[The Decorator Pattern, Why We Stopped Using It, and the Alternative]]></title>
            <link>https://medium.com/better-programming/the-decorator-pattern-why-i-stopped-using-it-and-the-alternative-2ae447f9de08?source=rss-175522a2102a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ae447f9de08</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jonas Tulstrup]]></dc:creator>
            <pubDate>Tue, 08 Mar 2022 15:03:22 GMT</pubDate>
            <atom:updated>2022-03-08T15:52:08.960Z</atom:updated>
            <content:encoded><![CDATA[<h4>Issues arising from the decorator pattern and how to avoid them</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NmqtNU1Q23pc-xe542dwwA.png" /><figcaption>Simplified decorator pattern. Image Source: Author.</figcaption></figure><p>The decorator pattern is a well-known and widely used programming design pattern. At first glance, the pattern seems to fit multiple software development principles and best practices, however, after years of using the pattern, we have noticed some serious issues. This post describes some of the pitfalls associated with the decorator pattern, which ultimately made us avoid the pattern altogether.</p><h3>The Decorator Pattern</h3><p>The decorator pattern is a well-known structural design pattern that allows for extending existing classes with additional functionality without touching the original implementation.</p><p>Essentially, the pattern takes a component that we want to extend, say with retry logic, and creates a new component wrapping the original one. All calls to the new component are forwarded to the wrapped component, with some additional logic done either before or after. The two components should implement the same interface allowing the decorator to be injected and used in place of the original component.</p><p>The Gist below shows a simplified usage of the decorator pattern. Here, looking up a username is decorated with a policy retrying 10 times. The UsernameLookupRetryDecorator can now be used instead of the UsernameLookup as they implement the same interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/604559c5af752360ef0810529944c86a/href">https://medium.com/media/604559c5af752360ef0810529944c86a/href</a></iframe><h3>Benefits of the Decorator Pattern</h3><p>Typical reasons for applying the decorator pattern are adhering to the famous <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">Single Responsibility Principle</a> and the <a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle">Open-Closed Principle</a>.</p><p>The common perception of these principles dictates that a single class should do just one small thing. The decorator pattern enables this as part of the logic, such as retrying or logging, can be placed in a separate class decorating the original one and thereby separating the concerns.</p><p>The open-closed principle encourages extension over modification which is exactly what the decorator pattern does — if you realize that your existing component needs additional logic, the decorator pattern allows you to add this without modifying the original class in any way.</p><h3>Why We Stopped Using the Decorator Pattern</h3><p>Despite the aforementioned benefits of the decorator pattern, we mostly stopped using the pattern altogether. As it turns out, the benefits of the decorator pattern are also what create serious pitfalls.</p><p>The decorator is added without modifying the original component or even the places where the component is used. This also means that it is not immediately clear when later looking at the existing code that it is in fact being decorated with additional logic behind the scenes. The logic contained in decorators is essentially hidden. This causes serious pitfalls.</p><p>In the past years, we have seen this create problems in various ways. The worst cases have caused production issues due to critical logic from a decorator being overlooked and left out when a component was refactored. The opposite thing has also happened multiple times — people adding logic directly to a component, which was already present in a decorator.</p><p>Someone could stumble upon the UsernameLookup component from the Gist above, realize that it has no retry logic, and add this directly to the class as seen below. Once deployed to production, the component would retry 100 times instead of the expected 10. 10 times in the component itself, multiplied by the 10 retries that were already there in the hidden decorator logic.</p><p>The less serious downside of the pattern is that code is simply less readable and harder to comprehend when closely related logic gets spread to different classes. This is especially the case when these classes are then composed together behind the scenes, as they are with the decorator pattern.</p><h3>The Alternative to the Decorator Pattern</h3><p>Most of the time, the uses of the decorator pattern can simply be removed. Instead of putting logging, retry, or whatever other logic you need into a decorator, simply place it directly in the original component. The Single Responsibility Principle does not have to be interpreted at such a granular level and modifying a component instead of extending it rarely has any negative implications in practice. At the same time, the number of files and classes required is reduced significantly which helps keep the code concise and easy to understand.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35c6f476bf6a8f08285f5d16be828e7b/href">https://medium.com/media/35c6f476bf6a8f08285f5d16be828e7b/href</a></iframe><p>If you really want to separate a piece of the logic into its own class, either for separation of concerns or to avoid duplicating the logic if multiple components need it — consider injecting this class into the original component instead of decorating it. This way, it is clear and visible when looking at the original component what is going on.</p><p>The decorator pattern can of course provide enough value in certain cases to outweigh the risks and downsides. The important point here is simply to consider if it is actually worth it. If you choose to use the pattern, consider adding tests that cover the <a href="https://betterprogramming.pub/quit-unit-testing-classes-and-use-a-behavior-oriented-approach-306a667f9a31">intended behavior end-to-end</a>. Unit tests that cover individual classes in isolation will not be enough to discover missing or duplicate logic like described in this article.</p><p>I hope you enjoyed reading this post and that it made you rethink the implications that arise from using the popular decorator pattern. This post is part of a series on simplifying the way software is written. Check out the initial post, describing the overall thoughts and how we removed 80% of our code:</p><p><a href="https://betterprogramming.pub/avoiding-premature-software-abstractions-8ba2e990930a">Avoiding Premature Software Abstractions</a></p><pre><strong>Want to Connect?</strong></pre><pre><a href="https://jonastulstrup.medium.com/subscribe">Join my email list for more simplified software insights!</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ae447f9de08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/the-decorator-pattern-why-i-stopped-using-it-and-the-alternative-2ae447f9de08">The Decorator Pattern, Why We Stopped Using It, and the Alternative</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why We Quit Unit Testing Classes to Focus On a Behavioral Approach]]></title>
            <link>https://medium.com/better-programming/quit-unit-testing-classes-and-use-a-behavior-oriented-approach-306a667f9a31?source=rss-175522a2102a------2</link>
            <guid isPermaLink="false">https://medium.com/p/306a667f9a31</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jonas Tulstrup]]></dc:creator>
            <pubDate>Wed, 08 Dec 2021 17:12:29 GMT</pubDate>
            <atom:updated>2021-12-09T07:18:46.539Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why you should consider avoiding class-level tests, in favor of a behavior-oriented approach</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNG3GqMvrRJXHimXeF1hlg.jpeg" /><figcaption>Testing behavior of the entire system rather than each class in isolation. Image Source: Author.</figcaption></figure><p>I recently <a href="https://betterprogramming.pub/avoiding-premature-software-abstractions-8ba2e990930a">wrote a post explaining</a> how we removed 80% of our code by avoiding premature software abstractions and how that greatly improved development efficiency and reduced errors.</p><p>One point that I largely left out of that post, was our decision to completely stop writing unit tests for individual classes. I am not saying that you have to pick only one type of test for your system, but simply that the type of tests that focus on individual classes in isolation has multiple issues which made us avoid those completely. In this post, I will cover our reasoning behind this choice, as well as our alternative approach, based on the following main issues with class-level testing.</p><ol><li>Class tests make changes painful</li><li>Class tests don’t validate actual behavior</li><li>Class tests are hard to understand</li></ol><p>Let’s dive into each of these in more detail.</p><h3>1. Class Tests Make Changes Painful</h3><p>Unit testing on a class level locks down every class in our codebase to work in a specific way and to use other classes in a specific way. Even though class-level unit tests should not test the implementation of the class, the class itself, including its methods and interface, acts as an implementation detail in the perspective of the system as a whole.</p><p>This becomes an issue when making changes to our code as every small modification will break tests. Since typical changes to a codebase affect multiple classes, we will most often have to update tests for every single class that we touched. Not only that, we might additionally need to update other tests that are mocking any of the changed classes. This becomes tedious and adds an extra barrier to changing even the slightest detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NET9pvbTRZjw9EoEliJqA.jpeg" /><figcaption>Typical changes cause multiple tests to break. Image Source: Author.</figcaption></figure><p>Even when we are only modifying internal implementation details our tests will break and need updating. Say we want to refactor one class into two so we can reuse part of the logic elsewhere. This will immediately break the tests, requiring us to remove and update test cases for the original class as well as create a new set of test cases for the added class. And we didn’t even change any external behavior of the system.</p><p>Instead, we would prefer tests to break only when external behavior changes. This would make us free to do any internal refactorings of our codebase without a single change to our tests. Additionally, we would prefer changes to multiple classes within the same flow — such as an endpoint of a microservice — to only require updating a single set of tests, instead of one for every touched class.</p><h3>2. Class Tests Don’t Validate Actual Behavior</h3><p>Class-level testing focus on individual classes in isolation. As a result, we are testing implementation details rather than the behavior of our code as a whole. A major downside is that whenever a test fails, it doesn’t tell us anything about whether the external behavior of our code has changed or not, as the tests might have simply failed due to a changed implementation detail.</p><p>It is even a problem when all tests continue to be green after a change — typically indicating to developers that everything is good, and safe to deploy. However, this is often not the case for this type of test as we rely on mocking other classes. Every time a class is mocked, an assumption is made of how that class works, which quickly becomes out of date when the class itself changes and we forget to update the mocks.</p><p>For example, say that class A handles when class B returns result X, tested by mocking B to act this way<strong>.</strong> If we, later on, change class B<strong> </strong>to start also returning result Y in some scenarios, then even though A does not handle this new case, all of its tests would still be green as every mock of B<strong> </strong>are still set to always return X. Unless developers remember class A when changing B we will have breaking code with all-green tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mwl_R65lzx2gfoQxcdCn-w.jpeg" /><figcaption>Class tests rely on assumptions that quickly get outdated. Image source: Author.</figcaption></figure><p>This means that even when class tests continue being green after a change, we cannot be sure that the code as a whole actually behaves correctly. Instead of this, we would prefer tests passing or failing to be tied only to the external behavior of our codebase. If tests fail, behavior has changed, and if they pass, then the code behaves the same.</p><h3>3. Class Tests Are Hard To Understand</h3><p>We just covered that testing classes in isolation do not say much about the external behavior of our code. As a result of this, to really know if a flow is working after making changes, we need to understand each and every class involved in the flow and if their corresponding tests are covering all the required cases and all possible outcomes from the classes that they mock.</p><p>We then have to piece this together in our minds to conclude whether the individual classes will jointly result in the correct external behavior of the flow. This is both hard and error-prone, especially when the change is made by somebody who does not know every corner of the codebase by heart.</p><p>It is further complicated by the fact that class testing, due to its focus on implementation details, results in many tests breaking often, and for many different reasons. This entails that developers constantly need to update tests, each time requiring a full understanding of the classes involved in the flow, their tests, and how they might affect each other differently after the change.</p><p>Let’s have a look at the example below showing four classes using each other as illustrated by the arrows.</p><p>If class D changes, not only would we have to understand and update the tests for D, we would also need to understand its impact on all classes depending on D and their corresponding tests.</p><p>In this example, that would be classes B and C. Additionally, as B<strong> </strong>might behave differently due to D changing, we also need to understand A and the tests of that class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZTlXjpITOwpAXUYq_Jkkg.jpeg" /><figcaption>Inferring behavior from class tests is complex. Image source: Author.</figcaption></figure><p>Even though understanding a single class test might not be difficult, it becomes quite complex when we need to infer any kind of external behavior from these tests.</p><p>Instead, we would prefer that a single test case alone would be enough to infer some part of the actual external behavior of our codebase.</p><h3>The Alternative To Unit Testing Classes</h3><p>We made a choice to avoid class-level unit testing entirely, and because of that, we naturally needed an alternative approach to automated testing. We are primarily applying these concepts for testing individual microservices, but they can also be applied to many other types of systems, such as native and web apps or even libraries.</p><h4>Concept</h4><p>What we ended up with relies on the basic concept of treating our running system as a black box focusing only on external behavior. This means that we, as part of our tests, start up the system and execute each test on it while it is running. We aim at treating it as much as a black box as possible since this automatically makes the tests independent of implementation details and focused on behavior. Essentially, instead of unit testing classes, we are treating our entire system, a microservice for example, as the unit or system under test.</p><p>This has become our most granular type of test and is still only focused on the behavior of a single system or codebase. Additional types of tests might be required to ensure correct behavior end-to-end across multiple systems. However, I will not cover these in this post.</p><h4>Mocking external dependencies</h4><p>When treating our system as a black box, we no longer want to mock, stub, double, or fake any internal parts of the codebase, as the tests should not be concerned with those.</p><p>We do want to mock external dependencies though, as this allows us to test our system in isolation. The definition of what is and isn’t external will vary from project to project according to what makes sense.</p><p>For example, when testing our microservices, databases are treated as internal and are thus not mocked. Time is treated as an external component and is mocked, and so is HTTP communication between the system and other external systems. In cases where our microservice uses a message queue, it can be both.</p><p>Messages that are both published and consumed by the microservice itself will not be mocked, however, when publishing or receiving any messages to or from other systems, those will be mocked and treated as external. This is visualized in the illustration below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fagTJltvf9bxBRyxgAgXPQ.jpeg" /><figcaption>Internal vs External. Image Source: Author.</figcaption></figure><h4>Arranging test data</h4><p>When treating the running system as a black box, we want to arrange test data and provide input exactly like how it would happen when running in a real environment.</p><p>For a microservice, this could be through invoking the endpoints that it exposes, or publishing messages on an external queue that the service consumes.</p><p>For a frontend, this could be by actually pressing buttons and navigating the user interface similar to what a user would do.</p><p>Using this approach we ensure that all tests are based on real application states exactly as they would appear in production. Additionally, as everything is invoked through allowed input to the system, we will never be spending time testing cases that cannot happen in reality, which is an added benefit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnxBrcF_2kwNJU9Mm0egzA.jpeg" /><figcaption>Arranging test data by invoking externally exposed endpoints. Image Source: Author.</figcaption></figure><p>To make tests easy to write and maintain, creating reusable methods for arranging commonly used test data is often well worth it. An example could be arranging users in a database. Instead of making the HTTP request for creating users in every single test, move it to a reusable method that each test case can invoke.</p><h4>Asserting the outcome</h4><p>With test data arranged we are ready to execute an action on our system and assert the outcome. As we are still treating our system as a black box, we aim for asserting only the external outcomes that our action caused.</p><p>Examples of external outcomes could be the HTTP response in case our action was an HTTP request. Additionally, external outcomes could also be outgoing HTTP calls made by the system and messages published on an external message queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZfTnuoUHCWBMPoHXQs1g8Q.jpeg" /><figcaption>Asserting external outcomes of the action. Checkmarks represent points of assertion. Image Source: Author.</figcaption></figure><p>When setting up mocks for asserting the correct external behavior of our system, consider using mocks in <a href="https://stackoverflow.com/questions/3134108/what-are-strict-and-non-strict-mocks">strict mode</a>. They should be strict in the sense that they cause tests to fail whenever invoked with any input they were not specifically set up to handle. This will ensure not only that our system does the right things, but also that no unexpected behavior is happening. We do not want to make HTTP calls and send messages to other systems when we shouldn’t.</p><h4>Execution time</h4><p>When switching out classical class-level unit tests with behavioral system tests, we need to ensure that our tests are still executing quickly. This is one of the benefits of class-level unit tests, as they are not dependent on anything except the class itself which <em>usually</em> makes them extremely fast. When tests suddenly involve both HTTP calls and database queries, this becomes harder.</p><p>The solution for getting around this will vary depending on the technology you are using. In our concrete case, using the <a href="https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0">ASP.NET TestServer</a> was enough to make HTTP calls fast, and substituting our database for an in-memory variant while running tests locally helped with query speeds.</p><p>Before a pull request can be merged though, all tests are run with a real database as the in-memory variant will never behave exactly the same. It is important to find a good balance between execution time and using as-real-as-possible internal dependencies.</p><h3>Conclusion</h3><p>That’s it, we have now gotten rid of class-level unit tests altogether. Our new approach focuses entirely on behavior, and as a result of this, when tests are passing, we know that the same cases will also work for an actual user of the system.</p><p>We no longer need to update tests every time implementations details change, making us free to do any internal refactorings seamlessly.</p><p>Lastly, there is no longer any need for having to piece together multiple different classes and tests inside the minds of developers to infer behavior — reading a single isolated test case is now enough to understand and verify how the system behaves.</p><p>I would love to hear about your experiences with behavioral tests in the comments section! What types of testing are you favoring, and why?</p><pre><strong>Want to Connect With the Author?</strong></pre><pre><a href="https://jonastulstrup.medium.com/subscribe">Join my email list for more helpful insights on simplified software!</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=306a667f9a31" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/quit-unit-testing-classes-and-use-a-behavior-oriented-approach-306a667f9a31">Why We Quit Unit Testing Classes to Focus On a Behavioral Approach</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding Premature Software Abstractions]]></title>
            <link>https://medium.com/better-programming/avoiding-premature-software-abstractions-8ba2e990930a?source=rss-175522a2102a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba2e990930a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jonas Tulstrup]]></dc:creator>
            <pubDate>Mon, 15 Nov 2021 15:02:46 GMT</pubDate>
            <atom:updated>2021-12-08T18:49:45.745Z</atom:updated>
            <content:encoded><![CDATA[<h4>How we removed 80% of our code — improving development speed and reducing errors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qciKoNh03-nCQN3VV9Xxqw.jpeg" /><figcaption>Files required before and after removing premature abstractions. Based on a real example endpoint updating a piece of data. Each post-it represents a file. Image credit: Author.</figcaption></figure><p>Software developers love abstractions<strong>.</strong> Abstractions are great and absolute key for efficient development. Writing software using solely 1’s and 0’s would be quite the chore after all. The problem comes when abstractions are introduced prematurely, i.e., before they are solving a real non-theoretical problem. Adding abstractions always comes at the cost of complexity and, when done excessively, starts slowing down the speed of development and the ability for people to easily comprehend the codebase.</p><blockquote>All problems in computer science can be solved by another layer of abstraction… Except for the problem of too many layers of abstraction. — Butler Lampson</blockquote><p>This post illustrates how avoiding common abstractions can lead to a much cleaner codebase with massively reduced complexity as well as increased readability and maintainability. The post is based on a transformation in the way I, and the rest of our team, build microservices now compared to previously. For us, this has reduced the size of a regular feature, such as a new microservice endpoint for updating or reading data, from a total of approximately <strong>25 files</strong> down to<strong> </strong>just <strong>5,</strong> that’s an <strong>80% reduction</strong> with the majority of code simply having been deleted, all while simultaneously improving code readability.</p><p>The points discussed are grounded in principles like <a href="https://en.wikipedia.org/wiki/KISS_principle">Keep it Simple, Stupid</a> (KISS) and <a href="https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it">You Aren’t Gonna Need It</a> (YAGNI), meaning that we want to keep abstractions to a minimum and only introduce complexity when it provides a significant and real benefit. The points will apply to most kinds of software engineering.</p><h3>Common Premature Abstractions</h3><p>Let’s look at some concrete cases of premature abstractions that tend to occur often in practice. These are all based on real examples found in our own codebases.</p><ol><li>Responsibilities are abstracted too granularly</li><li>Design patterns are used without real benefit</li><li>Performance is optimized prematurely</li><li>Low coupling is introduced everywhere</li></ol><p>Let’s take a closer look at each of these individually.</p><h4>1. Responsibilities are abstracted too granularly</h4><p>One root cause of a complex codebase is responsibilities being split at a way too granular level. This could be the abstraction of a database query into a dedicated repository class, an HTTP call abstracted away into a service class, or some fully internal piece of logic moved to a separate component.</p><p>This is typically done to satisfy the highly popular SOLID principle of single responsibility — <em>each class should only have one reason to change, or, they should only have one job. </em>If we split every tiny piece of logic into a separate class then everything has super clear-cut responsibilities, only does one job, and thus only has one reason to change. Great right? The problem is that all these small pieces are typically still tightly coupled and highly dependent on each other. If any communication between the pieces changes, often that will have a cascading effect requiring changes in many of these pieces. So they might each only have one reason to change, but that does no good if a single change often requires making changes in many of the pieces, making changing the code a pain.</p><p>Additionally, there are often no real practical advantages to having classes that change for one reason only. As a matter of fact, making changes in classes that do more than one thing often provides a lot more context for the developer which makes understanding the change and its impact on surrounding code much easier.</p><p>So when should we split responsibilities then? A common and very valid case is when the logic needs to be used in more than one place. If the exact same HTTP call or database query is needed in multiple locations in the code, duplicating the logic will often reduce the maintainability. In such a case moving it to a shared and reusable component will likely be a good idea. The key is to not do this before it is required. Another valid case is when the logic is very complex and impacts the readability of the surrounding code negatively. If a piece of the logic takes up 300 lines of code this might be the case, whereas doing it for only a few lines will probably end up just hurting readability and making navigating the code harder. Remember that splitting responsibilities always adds more structural complexity to the code.</p><p>Below you see how changing our view on class responsibilities impacts the original architecture shown at the top of the post. On the left, we place logic from a service class directly into the command handler which needs the logic of the service. On the right, we move a database query in a repository class directly into the event handler that needs it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HqlDbUhdRcsHAJrxGABoLQ.jpeg" /><figcaption>On the left, we place logic from a Service class directly into the Command Handler needing it. On the right, we move a database query to a Repository directly into the Event Handler that needs it. Image credit: Author.</figcaption></figure><h4>2. Design patterns used without real benefit</h4><p>Introducing various programming design patterns before their benefit is really needed is another common pitfall. Design patterns are great at solving specific problems in a codebase, and under certain circumstances can reduce overall complexity. That said, almost all of them come with the downside of added structural complexity and reduced coherence of the code.</p><p>A good example of this is the <a href="https://en.wikipedia.org/wiki/Decorator_pattern">Decorator Pattern</a>. The decorator pattern is often used for adding additional functionality on top of an existing component. This could be a component making an HTTP request, to which we want to add a retry mechanism. Without changing the original component, we can add a new component wrapping the original one with the retry logic added on top. By implementing the same interface it can be substituted for the original component directly in the code or through dependency injection.</p><p>At first, this seems like a great idea. We don’t have to change any existing code, we can test each of them in isolation and each piece is easy to understand when looked at individually. The massive downside comes from the fact that we again lose coherence. When a developer, later on, looks at the original component or the code using the component, it will not be immediately clear what will happen when the code is executed as there is more logic added on top “behind the scenes”. I have seen real cases of retries being added directly to a class only to later find out that it was already decorated with retry logic ending up in a multiplication of retries when deployed. Cases like these only really happen when it is not immediately clear how the code behaves.</p><p>Another pattern used extensively is the <a href="https://en.wikipedia.org/wiki/Command_pattern">Command</a> and <a href="https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">Publish-Subscribe Pattern</a>. Here a class, instead of handling a request directly, abstract it into a command to be handled elsewhere. An example could be an API controller mapping HTTP requests into commands, and publishing them to be handled by an appropriate handler that is subscribing to this specific command. This provides loosely coupled and clear-cut segregation between the part of the code that receives and interprets requests and the part that knows how to handle the requests. There exist legitimate use-cases of this pattern, but it is healthy to question yourself whether it, in practice, is just a useless layer of mapping. A layer of mapping that furthermore makes it harder to follow the execution path of the program as the publisher, per pub-sub definition, does not know where the command ends up being handled.</p><p>These are just a couple of examples of design patterns that are often used prematurely. The same thing can be said for almost any pattern out there. They all have downsides to them, so only bring a pattern to use when the benefits are needed and outweigh the cons. Below you again see the impact on our original architecture from removing unnecessary design patterns. On the left, we remove the Decorator pattern and on the right, the entire command flow including a publish/subscribe mechanism is removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXIxLvA6Y8MOvpDWAe8-9g.jpeg" /><figcaption>Removing prematurely introduced design patterns. Decorator pattern removed on the left. Command and Publish/Subscribe pattern removed on the right. Image credit: Author.</figcaption></figure><h4>3. Performance optimized prematurely</h4><p>Building software that performs well is crucial, and often the most efficient solution to a problem is the cleanest and simple. At other times, though, this is not quite the case. Here the cost of optimizing must be held against the real practical benefit that we expect to gain. Costs to take into consideration would be time spent analyzing, implementing, and maintaining the optimization as well as the potential decrease in code readability from using a more complex approach to achieve efficiency. Do not sacrifice code readability for unnecessary efficiency, and remember that the cost of a developer&#39;s time often far exceeds the potential gain from saving computational resources by micro-optimizing code.</p><blockquote><em>Premature optimization is the root of all evil — </em>Donald Knuth</blockquote><p>Optimizations can also be done at an architectural level. One example is the <a href="https://martinfowler.com/bliki/CQRS.html">Command Query Responsibility Segregation (CQRS)</a> pattern. CQRS essentially implies that you have two separate data models, one for updating data and one for reading data, splitting your application into a read and write side. This allows optimizing one side for efficient reads and the other for efficient writes as well as scaling one side more than the other in case your application is particularly read-heavy or write-heavy.</p><p>The huge downside of this pattern is the fact that a whole separate data model needs to be built and maintained resulting in a massive development overhead. If the performance is needed, this tradeoff might be just fine, but even for applications used by millions of people, I rarely see the added read or write efficiency providing any measurable benefit. A more sensible approach would be to use a single model for both reads and writes and only create optimized read models for the few individual cases where it is known for a fact the simple approach will not perform adequately.</p><p>Below you see an illustration of the read side being removed from our example flow. Instead of subsequent queries reading from the dedicated Read Model table, they would read directly from the Event Source which in our example is where the data is originally written to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r9jEdadT7eCE4wLfQ0xeXw.jpeg" /><figcaption>Removing the entire dedicated read-side of the application to instead use the same model for both reading and writing. Image credit: Author.</figcaption></figure><h4>4. Low coupling introduced everywhere</h4><p>A codebase with low coupling is one where each part is as independent as possible from the other parts. Low coupling makes changes to one part cause only minimal impact to other parts and makes swapping out a part of the code easier as they depend on each other only in the most minimal way. Good examples of this are external libraries or modules that are used by multiple different codebases. We don’t want changes to the functionality of a library to affect the codebases using it more than what is absolutely required, and it is beneficial to be able to swap out this library for a different one in case the need arises.</p><p>A typical way of achieving low coupling is by following the <em>Dependency Inversion</em> and <em>Open/Closed</em> SOLID principles saying that entities should depend on abstractions rather than concrete implementations while being open for extension and closed for modification. In practice, this is often done by abstracting classes behind interfaces and having others depend on those interfaces rather than the concrete classes.</p><p>The problem comes when the interpretation of these principles results in low coupling being introduced everywhere, even among individual classes within the same isolated feature, such as an API endpoint of a microservice or a screen in a frontend. This can often be seen by interfaces being introduced extensively for every single class that exposes any kind of logic used by other classes inside the given feature.</p><p>An isolated feature does not need low coupling and interfaces between the elements inside it. The reason is that this low coupling comes at a cost. Low coupling, and interfaces specifically, make the code less coherent and harder to navigate as you do not directly know what concrete code will be executed. Instead, you first need to check which implementations exist of the interface and then figure out which one is actually used at runtime. Additionally, an interface is yet another file that needs to be added to your project and held up to date whenever the signature of the concrete implementation change.</p><p>Interfaces solve tons of problems, introduce them whenever they are needed to solve a real practical problem, and not any earlier than that just to achieve unnecessary low coupling. Typically, this would be when you need to be able to swap the implementation, or when creating external libraries used by others without access to modifying the library codebase. Also, if you are merely using interfaces to allow mocking in tests, seriously consider switching to a mocking library that allows mocking concrete classes to avoid the overhead.</p><p>Below this is visualized by removing two interfaces, letting the event handler and command handler have direct references to concrete implementations of the repository and service class respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ml03Z0007Onng-ERwFoC0A.jpeg" /><figcaption>Removing interfaces that are not needed. Interface for a repository on the left, and the interface for a service class on the right. Image credit: Author.</figcaption></figure><h4>Bonus tip for the adventurous</h4><p>If you are feeling particularly adventurous, you can go the extra mile and move separate classes into the same file. If the classes are closely related, co-dependent, and often change together, this can improve both maintainability and the context readily available when making changes. That said, be prepared to move the class to its own file if it should happen to grow significantly in size — we don’t want to end up hurting the readability.</p><p>The important thing here is that code that changes together is located as close together as possible, to make those changes seamless. It typically happens more often that a change will impact multiple classes because they are within the same feature, rather than because they are of a specific type. This is essentially favoring a <a href="https://jimmybogard.com/vertical-slice-architecture/">Vertical Slice Architecture</a> over the more classical Onion Architecture, as typical changes are vertical in nature rather than horizontal. Grouping classes in folders based on the feature they are related to rather than their type goes a long way here.</p><p>In our example architecture, this is seen by classes for the request and responses being placed directly in the same file as the controller who takes the request as input and provides the response as output. This is a good example of very closely related classes that often change together. When placed in the same file, you immediately get the full overview of the feature without needing to jump between files. An important note here is that we only have one endpoint per controller. Thus, each file only cares about that single feature and nothing else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-xCIWBbuKRonrWwIAaOYQ.jpeg" /><figcaption>Merging closely related classes, such as the request, response, and controller. This file will handle everything for a single endpoint. In other words, only one endpoint per controller class. Image credit: Author.</figcaption></figure><h4>Refactor when the need arises</h4><p>Now that we are no longer doing premature abstractions, it is important to consider refactoring as a natural part of making changes. If a piece of logic is suddenly needed in more than one place, then now is the time to abstract it to a separate reusable component. If we suddenly need to swap implementations, then now is the time to add an interface. Avoiding premature abstractions does not mean that abstractions will never be introduced, just that we will introduce them ad hoc when a real need arises. It is by no means an excuse for writing sloppy spaghetti code.</p><p>With all these improvements though, doing refactorings and moving pieces around should become a breeze. One pain point which is still present when refactoring often is having dedicated unit tests for every single class where all its dependencies are mocked. This type of automated testing locks down each class to behave and communicate with other classes in a very specific way as you are essentially testing the implementation of the codebase rather than the behavior. This means that whenever a class changes its unit tests, and often other tests mocking that class, needs to be updated. This is not nice when the change is a purely structural refactoring, such as moving some piece of logic to a reusable component, where the external behavior of your codebase does not change.</p><p>For this reason, we have dropped this kind of unit testing entirely and opted for a completely different approach to automated testing. This allows us to make all kinds of internal refactorings quickly without having to update a single test. But that’s a whole other topic for a separate post, <a href="https://betterprogramming.pub/quit-unit-testing-classes-and-use-a-behavior-oriented-approach-306a667f9a31">which you can find here</a>.</p><p>Applying the above principles to our original architecture results in the improved design shown below — all by removing premature abstractions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8S1bJJH8UvnjWD88MVkFnw.jpeg" /><figcaption>Improved architecture as a result of removing premature abstractions. Image credit: Author.</figcaption></figure><h3>Conclusion</h3><p>We have taken a look at 4 common types of premature abstractions often seen in codebases resulting in unnecessary complexity. All have very valid reasons for being used, but the problem arises when they are introduced prematurely and provide no real benefit in practice. There exist many more examples similar to the ones listed in this post. The key takeaway is to change your mindset to always look harshly at each part of your code. Every time you consider introducing yet another abstraction really ask yourself, and your colleagues, if it will actually provide the value that you are looking for, or if it could simply be left out without any issues. Adding complexity just for theoretical reasons like “to separate concerns” and “to not depend on concrete implementations”, is simply not good enough. There should always be concrete, practical, real-world benefits every time new complexity is added.</p><p><strong>Now, take a look at your codebases.</strong> Do they also have premature abstractions that you could remove? A good codebase makes it super quick and easy to make simple changes and refactorings. Check your recent pull requests and compare the size of the changes with what was achieved by them.</p><p>I would be happy to hear if these ideas and principles have changed the way you build software and your experience from doing so.</p><h3><a href="https://jonastulstrup.medium.com/subscribe">Join my email list for more helpful insights on simplified software!</a></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba2e990930a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/avoiding-premature-software-abstractions-8ba2e990930a">Avoiding Premature Software Abstractions</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>