<?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 erik dreyer on Medium]]></title>
        <description><![CDATA[Stories by erik dreyer on Medium]]></description>
        <link>https://medium.com/@erikdreyer?source=rss-1a1e3c14962d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZE1b-fH2slF_s6y_8d2dgg.jpeg</url>
            <title>Stories by erik dreyer on Medium</title>
            <link>https://medium.com/@erikdreyer?source=rss-1a1e3c14962d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:56:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erikdreyer/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[Prefer Typesafe Error Handling to Exceptions in kotlin]]></title>
            <link>https://erikdreyer.medium.com/prefer-typesafe-error-handling-to-exceptions-in-kotlin-f3aa282aef98?source=rss-1a1e3c14962d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3aa282aef98</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[error-handling-techniques]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[erik dreyer]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 14:41:17 GMT</pubDate>
            <atom:updated>2025-10-20T10:03:31.566Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prefer Typesafe Error Handling to Exceptions in Kotlin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94VfSrPb7meRtYodM2B8dA.jpeg" /></figure><h3>Why?</h3><p>Even in these modern times where AI is writing more and more code for us, I believe it remains important for humans to have a solid understanding of various principles and philosophies that drive the choices we make when crafting software.</p><p>Throughout my career, I’ve had a passion for writing/crafting software that’s easy to reason about, maintain, and augment with new capabilities for/by other engineers on my various teams. Our technology choices can assist us, or even hinder us, in this effort.</p><p>Here, we are going to look at one specific aspect of software engineering that is often an afterthought in our domain designs, <strong>error handling</strong>. Far too often, we write our happy path code, then afterwards tack on some try..catch blocks. A consequence of this is that error handling is somewhat haphazard and often clumsy or worse, incorrect.</p><p>I’m going to lay out another approach to error handling that I believe requires us to consider failure modes earlier in the software writing process. This approach also uses the compiler to “prove” your error handling is correct and even future proofs your code from errant refactoring efforts.</p><p>I’ll demonstrate how we can benefit from these additional protections without sacrificing the seeming simplicity of exception-based mechanisms.</p><p>I’ll be using kotlin as language of choice since it has the feature set required to enable these techniques. I’m not aware of any other language that has these capabilities. Feel free to let me know in the comment section if I’m incorrect.</p><h3>What’s wrong with Exceptions?</h3><p>Some languages support the notion of a <a href="https://www.geeksforgeeks.org/goto-statement-in-programming/">‘goto’ statement</a> (e.g. c, c++). More modern languages have essentially done away with this capability as it’s generally regarded as a ‘<a href="https://stackoverflow.com/questions/3517726/what-is-wrong-with-using-goto">bad idea’</a>. However, this concept still exists in the form of thrown exceptions. When an exception is thrown, control flow generally jumps up the call stack to a point where it’s caught. IF it’s caught.</p><p>When done properly, exception handling is a powerful mechanism to handle failure in an application. I’d assert that the knowledge of how to do proper error handling comes with the experience of dealing with NOT doing exception handling properly.</p><p>I’ll briefly list the issues I’ve seen with exception handling.</p><ul><li>They tend to be an afterthought. Engineers write the happy paths, then bolt on error handling at the end. It’s almost like they are thinking, “I don’t know what to do here, so… THROW”. Let someone else figure out what to do with this problem. Of course, it’s not always like this, but it often is. <strong>The primary issue here is that error handling is not treated as a first class concern </strong>of the design.</li><li>Nothing enforces that exceptions are caught. This can bite you when you’re refactoring. If you move a method that throws out of the current call stack, it may no longer be caught by an existing try..catch. The exception may not be caught at all! Case in point:</li></ul><pre>class ExceptionHandling {<br>  // Before Refactor<br>  fun originalMethod() {<br>    try {<br>      firstMethod() // This will lead to an exception being thrown<br>    } catch (e: Exception) {<br>      println(&quot;Exception caught in originalMethod&quot;)<br>    }<br>  }<br>  <br>  private fun firstMethod() {<br>    secondMethod()<br>  }<br>  <br>  private fun secondMethod() {<br>    // caught by originalMethod<br>    throw RuntimeException(&quot;Error in deep method call&quot;)<br>  }<br>}<br><br></pre><p>Now look what happens during an errant refactor. It’s obvious here in this trivial example, but in complex codebases, this can be a true vulnerability. It’s the sort of thing that may not show up in tests, unless you have integration tests that test for this specific issue in the entire code path. Often this sort of hidden logic bug doesn’t manifest until shows up until it’s in production.</p><pre>class RefactoredExceptionHandling {<br>    fun refactoredMethod() {<br>        try {<br>            firstMethod() // No longer throws an exception<br>        } catch (e: Exception) {<br>            println(&quot;Exception caught in refactoredMethod&quot;)<br>        }<br>    }<br><br>    private fun firstMethod() {<br>        // secondMethod was moved out of call stack<br>    }<br>    <br>    companion object {<br>        fun utilityMethod() {<br>            // oops, never caught? ¯\_(ツ)_/¯ <br>            throw RuntimeException(&quot;Error in refactored method call&quot;)<br>        }<br>    }<br>}</pre><ul><li>Exceptions rarely show up in method signatures. See ExceptionHandling.secondMethod() above. If you are writing code that calls this method, you have to open the method and read the source code to see if it throws. It’s worse if you are trying to use ExceptionHandling.firstMethod()because that method itself doesn’t throw. You now have to navigate all the code it calls as well to see if those throw. If you don’t know your codebase, or the libraries you are using, you may miss the fact that you need to wrap calls to those methods in try..catch. In the JDK itself, the signature of String.charAt() (see below), is an example that exemplifies this. It throws a IndexOutOfBoundsException but you’d never know that unless you read the javadoc, or the source code. Not wrapping this in try..catch could be a bug in your code.</li></ul><pre>class String {<br>  // ...<br>  <br>  // example of common JDK method that doesn&#39;t declare thrown exceptions<br>  public char charAt(int index) { /* ... */ }<br><br>  // ...<br>}</pre><ul><li>The code can be hard to test. Sure, you can prove a throwing method works perfectly well. But say you have a program made up of 10 methods. Every one of them throws for one reason or another. Unit tests prove they work flawlessly. Now combine those methods into a program. Each unique combination will dictate a different set of exception handling capabilities. It is incumbent on the engineer to understand what these are because, and this is the important bit, <strong>the compiler will not tell them. </strong>It becomes much harder to prove correctness in such an application. Now try dealing with new requirements that requires some refactoring and/or introduces new failure modes. Tread carefully my friends.</li></ul><h3>What to do instead?</h3><p>I’m going to leverage a few specific features of kotlin that when combined will give us the same semantics as exception-based error handling, but also addressing the issues outlined above.</p><p>Specifically, what I mean by that is, just like exceptions, an error may occur deep in a call stack and we can still easily put the error handling higher up in the call stack. The big difference here is that the error handling is compile-time enforced.</p><p>If you refactor your code as in the example above, you will get immediate compile-time feedback that a possible error escaped it’s error handling block.</p><p>The features of kotlin that we’re going to use are:</p><ul><li>Algebraic data types (ADTs) to catalog the finite failure modes a method has</li><li>Exhaustive pattern matching to future proof our code against future updates to the logic or structure</li><li><a href="https://arrow-kt.io/">Arrow’s</a> Either and Raise types and associated either{}DSL as the mechanism by which we defer error handling</li><li>Using a new kotlin feature called “<a href="https://github.com/Kotlin/KEEP/blob/context-parameters/proposals/context-parameters.md">context parameters</a>” introduced as an experimental feature in kotlin 2.1.20</li></ul><h3>The mechanics of how this works</h3><p>I’m going to first show you the mechanics of how to use this alternative approach to exception-based error handling. Then after that we’ll discuss the consequences.</p><p>Make sure you’re using kotlin 2.1.20 and the latest version of IntelliJ (20205.1) for this to work.</p><p>Enable context parameters in your gradle file with the following:</p><pre>tasks.withType&lt;org.jetbrains.kotlin.gradle.tasks.KotlinCompile&gt; {<br>  compilerOptions {<br>    freeCompilerArgs.addAll(listOf(&quot;-Xcontext-parameters&quot;))<br>  }<br>}</pre><p>The following trivial example uses the base minimum of code required to demonstrate the mechanics of how this works.</p><p>The following bridge functions are required for now. Context parameters are brand new. The libraries haven’t had a chance to catch up yet. I’m certain a future version of <a href="https://arrow-kt.io/">Arrow</a> will provide these for us.</p><pre>// First, these bridge functions are currently required, but are temporary.<br>// A future version of Arrow will include these for you<br><br>context(r: Raise&lt;Err&gt;)<br>inline fun &lt;Err&gt; raise(err: Err): Nothing = r.raise(err)<br><br>context(r: Raise&lt;Err&gt;)<br>inline fun &lt;Err&gt; ensure(condition: Boolean, err: () -&gt; Err): Unit = <br>  r.ensure(condition, err)<br><br>context(r: Raise&lt;Err&gt;)<br>inline fun &lt;A, Err&gt; ensureNotNull(value: A?, err: () -&gt; Err): A <br>  = r.ensureNotNull(value, err)<br><br>context(r: Raise&lt;Err&gt;)<br>inline fun &lt;Err, A&gt; Either&lt;Err, A&gt;.bind(): A = <br>  with(r) { bind() }</pre><p>OK, with that out of the way, here’s our business logic example. In brief, we call a busines method from main() that has two layers</p><pre>// Here we catalog the failure modes of our business logic as<br>// an algebraic data type<br>sealed interface ExecutionError<br>data class ErrorParent(val message: String) : ExecutionError<br>data class ErrorChild(val message: String) : ExecutionError<br><br>fun main() {<br>  val result: Either&lt;ExecutionError, Int&gt; = either { // 1<br><br>    // either{} provides us a Raise&lt;ExecutionError&gt; context...<br>    val that: Raise&lt;ExecutionError&gt; = this // 2<br><br>    // which is required to invoke this method<br>    doWorkParent(12) <br>  }<br>}<br><br>context(_: Raise&lt;ExecutionError&gt;) // 3<br>fun doWorkParent(n: Int): Int {<br>  ensure (childResult % 2 == 0) // 4<br>    { ErrorParent(&quot;n is not divisible by 2&quot;) }<br>  <br>  val childResult: Int = doWorkChild(n)<br>  return childResult<br>}<br><br>context(_: Raise&lt;ExecutionError&gt;) // 3<br>fun doWorkChild(n: Int): Int {<br>  ensure (n % 4 == 0) // 4<br>    { ErrorChild(&quot;n is not divisible by 4&quot;) }<br>  <br>  // explicitly short circuit the method here<br>  raise(ErrorChild(&quot;bad stuff happened&quot;)) // 5<br>  <br>  return n<br>}</pre><p>Here’s what to focus on in the above code sample:</p><ul><li>For (1) — The use of either {} here is analogous to the use of try..catch. Use this DSL in the same way and in the same places you would typically catch exceptions.</li><li>Notice the that the type of result is Either&lt;ExecutionError, Int. If you’re unfamiliar, Either is a discriminated union type. It is broken out into Left and Right states. It’s either in a Left state, or a Right state, but not both. Either is right-biased. By convention the happy path goes on the Right side. The error state goes on the Left.</li><li>In our example the Left side is ExecutionError which is just a normal class. You could use Exception classes here, but you may find you have more utility when just using normal classes. In our example, it’s an algebraic structure with a limited set of specialized subtypes.</li><li>For (2) — Inside of the either {} block, this is of type Raise&lt;ExecutionError&gt;. The either DSL provides this to you as a receiver type for the methods made available to you by that DSL. The reason this is important is that this becomes the context required to execute our business methods (see next bullet)</li><li>For (3) — We have two methods marked with context(_: Raise&lt;ExecutionError&gt;). This is one way to use the new experimental <a href="https://github.com/Kotlin/KEEP/blob/context-parameters/proposals/context-parameters.md">context parameters</a> feature. What this says is that the methods marked with this context cannot be invoked unless that context exists. That context is provided to us automatically by using the either{} DSL. See marker (2) in the code example. If you try to invoke such a method, you get a compiler error.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCm-Gz4KsYVUftIukwyZwQ.png" /><figcaption>You get a compiler error if you attempt to invoke a method without it’s required context</figcaption></figure><ul><li>For (4) — We’re using the ensure() method provided by the either{} DSL. This method (along with a number of other DSL methods) is only available within the either {} block. If the provided boolean expression is false, the associated error ( ErrorParent / ErrorChild ) is immediately raised (analogous to throw) and the method short circuits immediately.</li><li>For (5) — You can also just explicitly raise an error as well. This is analogous to throwing an exception.</li></ul><h3>Why is this better than exceptions?</h3><p>Let me start by saying that even though we’re using a functional approach to error handling here, we have similar semantics to exception-based approaches in that an error may be raised (think “thrown”) deep in the call stack, but handled higher up in the stack. So, from a convenience standpoint, it’s the same.</p><p>Notice that in our business logic methods that require the Raise context, we have basically written happy path logic with happy path return types. The error handling is “baked in”. Kotlin does a great job of providing powerful capabilities while staying out of your way. There is nearly zero boilerplate code here. And yet there is no magic happening here. The code is still explicit. The context() directive is a clear signal to code authors about what is happening here.</p><p>Here are the clear advantages over using exceptions:</p><ul><li>You pretty much have to handle the error. It’s compile time enforced. You cannot not handle it. Well, there is one exception. If you throw away or ignore the return value of the either {} block then the error can go unhandled. Even so, this technique is compile-time protected from unsafe refactors.</li><li>If you refactor the code so that a method that raises an error is no longer in the method call hierarchy, the compiler will complain immediately. That is, if a context() function is moved out of the codepath that provides that context, it’s a compiler error.</li><li>One consequence of this approach is that the engineer must consider the failure modes of software up front. That is, they must catalog the business errors that may occur and create error hierarchies that make sense for their use cases. This is a “good thing”®. You should be considering failure modes earlier in your process. You will find it can impact the structure of your code.</li><li>Another consequence is that the context() tends to be somewhat viral when used for error handling. You have to add the context to all meethods in the call hierarchy down to the lowest level that may raise an error. Some may argue that’s a negative consequence. I’d argue it’s actually a guardrail that protects you. In my experience this makes the code much easier to reason about. You have clear signal at all levels of the call chain that the method can fail and how specifically it can fail. This is a huge advantage over exception based code that is silent in this way. In fact, you should consider the context() params as part of the method signature.</li><li>A corollary to the previous point is that you always know how the code can fail. Unlike the String.charAt(n) example of how exception handling can contain hidden traps, there is no guessing as to how your methods can fail.</li></ul><h3>A few more examples to help illustrate the value</h3><p>Sometimes, code at a low level can raise low level errors. Your code at higher levels will want to translate lower level errors to higher level.</p><p><strong>How to translate low level errors to higher level errors:</strong></p><pre>import arrow.core.raise.Raise<br>import arrow.core.raise.either<br><br>class HighLevelError(val message: String)<br>class LowLevelError(val message: String)<br><br>// High level business fn<br>context(r: Raise&lt;HighLevelError&gt;)<br>fun highLevelWork() {<br>  // translate from a lower level error to a higher one<br>  either { lowLevelWork() }<br>    .onLeft { lle -&gt; <br>      r.raise(HighLevelError(&quot;High level error. lle.message=${lle.message}&quot;))<br>    }<br><br>// Low Level business fn<br>context(r: Raise&lt;LowLevelError&gt;)<br>fun lowLevelWork() {<br>  r.raise(LowLevelError(&quot;Low level error&quot;))<br>}</pre><p>What about exhaustive pattern matching (EPM) when handling the error? Exhaustive pattern matching protects you against changes to the failure modes. If at some point in the future, you add a new failure mode, you’ll get immediate compile time feedback at all locations where you may have to handle that new failure mode.</p><p>Here’s one way to handle the current set of errors:</p><pre>sealed interface ProcessingError<br>class NotFoundError(val message: String) : ProcessingError<br>class InvalidStateError(val message: String) : ProcessingError<br><br>// if we uncomment this class the &#39;when()&#39; will fail to compile<br>// with an error indicating you haven&#39;t handled this case.<br>// class NewError(val message: String) : ProcessingError<br><br>fun main() {<br>  val result = either { processSomething() }<br>    .onLeft { err -&gt;<br>      when (err) {<br>        is NotFoundError -&gt; println(&quot;Not found error: ${err.message}&quot;)<br>        is InvalidStateError -&gt; println(&quot;Invalid state error: ${err.message}&quot;)<br>        // do NOT add an &#39;else -&gt;` block! It kills exhaustive checking.<br>      }<br>    }<br>}<br><br>context(r: Raise&lt;ProcessingError&gt;)<br>fun processSomething(): String {<br>  r.raise(InvalidStateError(&quot;Something is invalid&quot;))<br>  return &quot;Success&quot;<br>}</pre><p><strong>Hint: Do Not Add an </strong><strong>else -&gt; Condition To Your When Expressions When Using Enums or Sealed Types. </strong>Doing so will kill the EPM protections the compiler gives you. You want to have these protections for future proofing your code. If the compiler can signal to you that you broke something, then you don’t need a unit test. You don’t have to wait for a run time error. You know Right Now.</p><p>I may add more examples, based on questions in the comments.</p><h3><strong>In Summary</strong></h3><p>The techniques outlined above have the same semantics of exception-based error handling, but with added compile time protections that you’ve handled your errors properly.</p><p>The use of context params, along with other kotlin features, makes this fairly trivial to use.</p><p>Your code is future proofed from new/changed requirements, or from errant refactorings. You get instant compile-time feedback when you break the error handling.</p><p>The compile-time protections you get from doing this are worth their weight in gold. Every error you move from run time to compile time is one less unit test you have to write. You cannot overstate the importance of being able to test your business invariants at compile time. (There are additional ways to do this to validate your domain, but that’s the subject of another article to come some day).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3aa282aef98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modular Architecture for Monoliths]]></title>
            <link>https://erikdreyer.medium.com/modular-architecture-for-monoliths-156368d9653c?source=rss-1a1e3c14962d------2</link>
            <guid isPermaLink="false">https://medium.com/p/156368d9653c</guid>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[erik dreyer]]></dc:creator>
            <pubDate>Sun, 27 Mar 2022 16:32:03 GMT</pubDate>
            <atom:updated>2024-04-19T13:44:45.423Z</atom:updated>
            <content:encoded><![CDATA[<h4>For teams not ready for microservices</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5FGhg75nRALbAOne" /><figcaption>Photo by <a href="https://unsplash.com/@teckhonc?utm_source=medium&amp;utm_medium=referral">T.H. Chia</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ul><li><a href="https://erikdreyer.medium.com/modular-architecture-for-monoliths-156368d9653c">Part 1: Motivation and Architecture Overview</a></li><li>Part 2: Modulith Details (coming soon)</li></ul><h3><strong>Why?</strong></h3><p>Writing high quality server-side software applications that stand the test of time is a hard problem. Over time, applications become increasingly complex and suffer from a variety of problems, some of which are outlined below.</p><p>As illustrated in Figure 1, there are a bevy of concerns, across multiple dimensions that software engineers must be mindful of at all times.</p><p>High quality software addresses most, if not all, of these. A good software architecture will either solve these concerns, make it difficult to violate them, or at the very least guide the software engineer to produce high quality software.</p><figure><img alt="Figure 1: Dimensions of Software Product Quality" src="https://cdn-images-1.medium.com/max/1024/1*op93VBhap0x8KyH3mx9Zug.png" /><figcaption>Figure 1: Dimensions of Software Product Quality</figcaption></figure><h3>Credit Where Credit is due</h3><p>The ideas contained here are influenced by a variety of sources. A few of those stand out above the rest and deserve to be highlighted here. For further reading I highly recommend the following:</p><ul><li><a href="https://reflectoring.io/book/">Get Your Hands Dirty on Clean Architecture</a> — A great introduction to hexagonal architectures (also called “ports and adapters”) for Spring Boot applications written in Java.</li><li><a href="https://fsharpforfunandprofit.com/books/">Domain Modeling Made Functional</a> — Although this book targets F#, the concepts apply to many other modern languages, including Kotlin. This is by far the best introductory book for functional programming and functional domain modeling that I’ve come across and I highly recommend it to everyone.</li><li><a href="https://github.com/ddd-by-examples/library">https://github.com/ddd-by-examples/library</a> — This application influenced two big decisions in this project. The first being that each bounded context is contained in its own Spring context. The second idea is that persistence operations are modeled as event handlers. More on both of these below.</li></ul><p>If I’ve missed something/someone, contact me. I’m happy to give credit.</p><h3>Some Problems With Traditional Layered Architectures</h3><p>Traditionally, Spring Boot applications use a layered architecture that looks something like Figure 2. Requests into the application typically plunge through the layers and out again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*pK7Q5JpBLN6cw_ChrF497A.png" /><figcaption>Figure 2 — Typical “Pancake” layer architecture of Spring Boot apps</figcaption></figure><p>Nothing is inherently wrong with this, but a layered architecture has too many open flanks that allow bad habits to creep in and make the software increasingly harder to modify over time.</p><p>Here are just some of the problems that arise:</p><p><strong>It promotes DB-driven design:</strong></p><ul><li>By its very definition, the foundation of a traditional layered architecture is the database.</li><li>This creates a strong coupling between the persistence layer, the domain layer, and often the web layer as well.</li><li>The persistence code is virtually fused into the domain code, thus it’s hard to change one without the other. That’s the opposite of being flexible and keeping options open.</li></ul><p><strong>It’s prone to shortcuts:</strong></p><ul><li>The only global rule is that from a certain layer, we can only access components in the same layer or a layer below.</li><li>if we need access to a certain component in a layer above ours, we can just push the component down a layer and we’re allowed to access it. Problem solved? Over time, the persistence layer will grow fat as we push components down through the layers.</li></ul><p><strong>It grows hard to test</strong></p><ul><li>A common evolution within a layered architecture is that layers are being skipped. We access the persistence layer directly from the web layer.</li><li>We’re implementing domain logic in the web layer, even if it’s only manipulating a single field. What if the use case expands in the future?</li><li>In the tests of our web layer, we not only have to mock away the domain layer, but also the persistence layer.</li></ul><p><strong>It hides the use cases</strong></p><ul><li>In a layered architecture it easily happens that domain logic is scattered throughout the layers.</li><li>A layered architecture does not impose rules on the “width” of domain services. Over time, this often leads to very broad services that serve multiple use cases.</li><li>A broad service often has MANY dependencies on other Spring beans from the context, at varying layers.</li><li>A broad service is also often used by many components in the web layer.</li><li>The end result is <a href="https://en.wikipedia.org/wiki/Big_ball_of_mud">“The Big Ball of Mud”</a>.</li></ul><p><strong>It makes parallel work difficult</strong></p><ul><li>Working on different use cases will cause the same service to be edited in parallel which leads to merge conflicts and potentially regressions.</li></ul><h3>The Modulith Architecture</h3><p><strong>Modulith: </strong>A modular monolith, where a module is loosely defined as a self-contained, independent, and functionally complete software bundle that covers an area of concern for the business. A module has a well defined public interface.</p><p>The remainder of this article refers to this basic application that can serve as the basis for any new application: <a href="https://github.com/edreyer/modulith">https://github.com/edreyer/modulith</a></p><p>The architecture of this project, although still a Spring Boot application, takes a different approach. None of the individual ideas implemented in this project are new, but the way in which these ideas are combined into a single architecture is new.</p><p>The following concepts dovetail together in an elegant way, working in concert to provide for a powerful system architecture. Here is a high level overview of each of the major design elements of this architecture:</p><p><a href="https://kotlinlang.org/docs/home.html"><strong>Kotlin</strong></a></p><ul><li>The use of kotlin was a strategic choice. This language provides a number of capabilities not available to Java without which this architecture would not be possible.</li><li>Specifically, the features of kotlin that are heavily leveraged: <strong>Coroutines</strong>, <strong>Algebraic Data Types</strong>, and support for <strong>Functional Programming.</strong></li></ul><p><a href="https://en.wikipedia.org/wiki/Domain-driven_design"><strong>Domain Driven Design (DDD)</strong></a></p><ul><li>Not limited to just a set of human processes for requirements discovery, the output of those processes translates directly into the design of the domain of the system</li><li>In modulith, each <a href="https://martinfowler.com/bliki/BoundedContext.html">Bounded Context</a> is isolated at compile time by packing them in maven artifacts.</li><li>In addition to this, each Bounded Context is isolated at runtime as well. Each runs in its own Spring Application Context.</li></ul><p><a href="https://alistair.cockburn.us/hexagonal-architecture/"><strong>Hexagonal Architecture</strong></a></p><ul><li>Also knows as a Ports and Adapters architecture</li><li>An alternative to the 3-layer pancake architecture, this inverts the dependencies so that the domain of the application sits at the center, and depends on nothing.</li><li>More on this below.</li></ul><p><a href="https://itnext.io/an-introduction-to-algebraic-data-types-9429e49eac27"><strong>Algebraic Data Types (ADTs)</strong></a></p><ul><li>An alternative to the traditional use of Object Oriented (OO) techniques to model a domain.</li><li>The power of ADTs is that they allow you to move business invariants from runtime checks to the type system, the effect of which is to move runtime errors to compile time errors. A huge win.</li><li>They also inherently provide state machines for each domain in your system</li><li>These are enabled by kotlin natively, along with exhaustive pattern matching and destructuring</li><li>Inherently immutable, making it easier to use in multi-threaded contexts</li></ul><p><a href="https://alvinalexander.com/scala/fp-book/benefits-of-functional-programming/"><strong>Functional Programming (FP)</strong></a></p><ul><li>Follow the link for a brief outline of the benefits</li><li>This project introduces the concept of a Workflow. This is a generalized form of what you might call a &quot;Use Case&quot;. There is a 1:1 relationship between each API (e.g. Controller method) and a Workflow.</li><li>Every Workflow is kicked off with either a Command or Query (see: CQRS), and results in an Event.</li><li>Workflow never throws exceptions. Instead, the result of the workflow execution is contained in a discriminated union type containing either the desired Event output, or an Error type.</li><li>FP concepts extend beyond just the Workflow concept, and are embodied throughout.</li></ul><p><a href="https://blog.allegro.tech/2020/02/webflux-and-coroutines.html"><strong>Asynchronous / Non-blocking</strong></a></p><ul><li>This project makes use of <a href="https://kotlinlang.org/docs/coroutines-guide.html">Kotlin Coroutines</a>.</li><li>A given server can handle a much higher request volume because requests aren’t bound to threads, as they are in traditional servers.</li><li>Coroutine support is weaved throughout such that every operation that’s performed, from each web request down to each database call are all performed using non-blocking operations.</li><li>Coroutines are a mechanism that makes parallel programming easy, even fun. In Java, you are forced to use primitives (e.g. Thread) that are exceedingly hard to get correct.</li></ul><p><a href="https://martinfowler.com/bliki/CQRS.html"><strong>Command Query Responsibility Segregation (CQRS)</strong></a></p><ul><li>Inspired by: <a href="https://medium.com/swlh/cqrs-and-application-pipelines-in-kotlin-441d8f7fe427">https://medium.com/swlh/cqrs-and-application-pipelines-in-kotlin-441d8f7fe427</a></li><li>By separating out how Queries (reading data) of the system are performed from the Commands (writing data), we can optimize for each independently.</li><li>This mechanism also provides the mechanism for how a workflow in one Bounded Context can communicate with another Bounded Context.</li></ul><p><a href="https://en.wikipedia.org/wiki/Event-driven_architecture"><strong>Event Driven</strong></a></p><ul><li>Direct relation to DDD, which defines a system by its Events.</li><li>Events generated by each workflow, are published using Spring’s event system.</li><li>As an example, domain objects are packaged in events, and sent to the event system. Event listeners in the database Adapters translated these into DB Entities for storage. The logic that persists the system state changes is decoupled from the business logic that generated those changes. This reduces a rather large class of bugs.</li></ul><h3><strong>modulith Architecture Diagram</strong></h3><p>In the next installment, I’ll document the major components of this architecture and the decisions that motivated those design decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Pj9J89sCtCyuTqB2djNh-Q.png" /><figcaption>Figure 3 — Architecture diagram for “modulith”</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=156368d9653c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>