<?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 Gara Mohamed on Medium]]></title>
        <description><![CDATA[Stories by Gara Mohamed on Medium]]></description>
        <link>https://medium.com/@gara.mohamed?source=rss-22ede26bdbb3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QQM_tcYvC5kLy4KksIEOsQ.jpeg</url>
            <title>Stories by Gara Mohamed on Medium</title>
            <link>https://medium.com/@gara.mohamed?source=rss-22ede26bdbb3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:16:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gara.mohamed/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[Design Patterns in the Generative AI Era]]></title>
            <link>https://medium.com/@gara.mohamed/design-patterns-in-the-generative-ai-era-23ef03e4089f?source=rss-22ede26bdbb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/23ef03e4089f</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Gara Mohamed]]></dc:creator>
            <pubDate>Mon, 22 Sep 2025 08:02:01 GMT</pubDate>
            <atom:updated>2025-09-22T08:02:01.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAnLrdqhVzjQlQa5eM13Rw.png" /><figcaption>Generated by ChatGPT</figcaption></figure><p>Over the past decades, design patterns have been a cornerstone in the toolkit of professional developers. More recently, generative AI has emerged as a new pillar, reshaping the way developers approach problem-solving and software creation.</p><p>In this post, we explore the role that design patterns can play when working with LLMs and AI agents.</p><h4>The Importance of Design Patterns</h4><p>When design patterns appeared in software development, they weren’t just clever solutions — they were a sign of maturity, borrowing deep insights from Christopher Alexander’s work in building architecture.</p><p>Every design patterns catalog serves two primary purposes:</p><ul><li>Provide a shared language for experienced developers</li><li>Offer a solid foundation for beginners to understand design concepts</li></ul><p>Design patterns are brain-friendly. Back in 1946, Dutch psychologist Adriaan de Groot discovered that chess grandmasters could recall complex board positions almost instantly. The secret? They didn’t have photographic memories — they recognized familiar patterns, a cognitive process called “chunking.”</p><p>Despite these advantages, their importance, and extensive research, design patterns still have limited automation and lack widely adopted tooling. Generative AI, however, has the potential to change this landscape.</p><h4>The Evolution of Design Pattern Usage</h4><p>Generative AI is reshaping the software industry faster than ever. Design patterns, once primarily a tool for human communication, are now finding new applications in prompt engineering and within IDE-based AI agents.</p><p>Here’s what that looks like in practice:</p><ul><li>You can feed a codebase to an LLM and let it spot which patterns are in play.</li><li>Instead of long-winded instructions, you can simply use the pattern’s name as shorthand.</li><li>Ask an AI agent to explain some code, and it can frame the answer using familiar patterns — in my experience this is very helpful when reverse-engineering a codebase.</li><li>Suggested refactoring by Agents can be described using a pattern name.</li><li>Even generated documentation and comments can become clearer when patterns provide the shared language.</li><li>IDE refactoring tools can go far beyond the basics when supercharged with AI and design pattern knowledge.</li></ul><p>So Generative AI, from prompts to refactoring, is reinventing Design Pattern usage.</p><h4>Conclusion</h4><p>The evolution of design pattern usage highlights their enduring value in software development. With Generative AI accelerating change, the question is isn’t whether patterns remain relevant, but how they will adapt and shape the future of development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23ef03e4089f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prevent UI damage from Disabled Fields]]></title>
            <link>https://medium.com/design-bootcamp/prevent-ui-damage-from-disabled-fields-12a9b5a84c13?source=rss-22ede26bdbb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/12a9b5a84c13</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ux]]></category>
            <dc:creator><![CDATA[Gara Mohamed]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 19:30:37 GMT</pubDate>
            <atom:updated>2025-09-15T13:51:00.681Z</atom:updated>
            <content:encoded><![CDATA[<p>This post highlights a common mistake I’ve seen in almost every enterprise Web Application I’ve worked on: the incorrect use of the disabled attribute. Misusing it can lead to poor user interfaces and unintended behavior in forms.</p><p>The post begins with a review of the disabled attribute, followed by an analysis of issues caused by its misuse. It concludes with a recommended solution and best practices.</p><p>It also goes over the Angular Form API and Material Design 3, and wraps up with my personal pick.</p><blockquote>This post was reviewed and polished with the help of ChatGPT to improve the English — even this sentence.</blockquote><h4>The disabled state</h4><p>The HTML attribute is <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/disabled"><em>introduced as following</em></a>:</p><blockquote>The Boolean <strong>disabled</strong> attribute, when present, makes the element <strong>not mutable, focusable, or even submitted with the form</strong>. The user can neither edit nor focus ]on the control, nor its form control descendants.</blockquote><p>The Angular FormControl API, for its part, define <a href="https://angular.dev/api/forms/FormControl#disabled">the disabled property</a> as:</p><blockquote>A control is disabled when its status is DISABLED.</blockquote><blockquote>Disabled controls are <strong>exempt from validation checks</strong> and are <strong>not included in the aggregate value of their ancestor controls</strong>.</blockquote><p>According to Material Design 3, a disabled form field should look like the fourth state:</p><figure><img alt="Material Form Field states" src="https://cdn-images-1.medium.com/max/1024/1*Lo7pQhfOpHyvzapmlQhzig.png" /><figcaption>Material Form Field states</figcaption></figure><p>After looking at how fields are disabled in both APIs and UIs, let’s explore what a disabled input means and what can go wrong.</p><h4>The disabled state as a pattern</h4><p>Before we get into the disabled field anti-pattern, let’s start by clarifying when the disabled state is a good choice.</p><blockquote>A field should be disabled <strong>when its value isn’t meaningful or relevant</strong>.</blockquote><p>If a value doesn’t apply to an input in the current form state, the input should be disabled.</p><h4>The disabled state as an anti-pattern</h4><p>Like any API, the disabled state can be misused. A common UI anti-pattern I’ve frequently observed is using the disabled attribute to implement a read-only form field. This is generally a bad choice for two main reasons:</p><ul><li><strong>It offers a worse user experience.</strong> Disabled fields are harder to read than normal ones, which makes the form less accessible and less user-friendly. Here’s an example:</li><li><strong>It can introduce bugs.</strong> For example, when using Angular’s Form API, if you try to access the value of a FormGroup, the values of disabled FormControls will not be included in the request that will be sent to the backend server. To work around this, developers often rely on Angular’s getRawValue() method.</li></ul><p>Now that we’ve covered the UI/UX and dev problems, let’s jump to a recommended alternative.</p><h4>The read-only field pattern</h4><p>The HTML specification allows to define <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/readonly">a </a><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/readonly">readonly attribute</a> on many types of input elements. The difference between the attributes disabled and readonly is the following:</p><blockquote>The difference between <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/disabled">disabled</a> and readonly is that read-only controls can still function and are still focusable, whereas disabled controls can not receive focus and are not submitted with the form and generally do not function as controls until they are enabled.</blockquote><p>The Material Design 3 define the read-only state as following:</p><blockquote>Read-only text fields display pre-filled text that the user cannot edit. A read-only text field is styled the same as a regular text field and is clearly labeled as read-only.</blockquote><figure><img alt="Material Design Read-only state" src="https://cdn-images-1.medium.com/max/1024/1*WWBMKKKP03_p4HQIIZ1pzw.png" /><figcaption>Material Design Read-only state</figcaption></figure><h4>My choices</h4><p>My preferred implementation of the disabled and read-only states is <strong>a variation of the Material Design approach</strong>. Here are my choices:</p><ul><li><strong>Disabled form fields:</strong> They should visually follow the MD3 disabled style, but if necessary, include a hint (e.g., a tooltip or helper text) to explain why the field is disabled. The hint shouldn’t be grayed out.</li><li><strong>Read-only form fields: </strong>These should be styled like regular text fields but with a distinct container outline (e.g., grayed out). Read-only fields should have a clear visual indication — users shouldn’t have to read the hint text to realize the input is read-only. The hint is added only if the read-only status is dynamic.</li></ul><figure><img alt="Form Field States" src="https://cdn-images-1.medium.com/max/1024/1*YSlj69ah1w2E187U4rc4lg.png" /><figcaption>Form Field States</figcaption></figure><h4>Implementation details</h4><p>There are many implementation details we could discuss, but that’s beyond the scope of this post. I’ll therefore limit this section to two points:</p><ul><li><strong>Angular </strong><strong>FormControl</strong> — FormControl does not have a built-in readonly state; only disabled is defined. This may change: the new experimental, signal-based Forms API now exposes FieldState.readonly.</li><li><strong>Angular Material</strong> — Angular Material does not fully follow Material Design 3 in this regard: the readonly state is not implemented according to the specification. While the style can be customized, the default implementation is not ideal.</li></ul><h4>Conclusion</h4><p>This post explored the usage of disabled and readonly states to build user interfaces that enhance the user experience.</p><p><em>Quick rule of thumb:</em></p><p>If an input doesn’t make sense → disable it. If it makes sense but shouldn’t be edited → make it readonly. Handle these states wisely because good UX depends on correct input states.</p><p><em>Possible extensions for future posts:</em></p><ul><li><strong>UI vs. API:</strong> We mixed UI and API usage issues here; splitting them into two dedicated posts could make the discussion clearer and more adapted to the different profils in a product team.</li><li><strong>Beyond visuals:</strong> This post focused on the visual aspect of inputs, but their behavior deserves a deeper dive.</li><li><strong>Alternatives:</strong> Hiding a field is another option, though usually not a good one.</li><li><strong>Validation:</strong> Should readonly fields be validated? This is an open question worth exploring.</li><li><strong>Form layout:</strong> Using disabled and readonly states can help manage space in complex forms.</li><li><strong>Framework specifics:</strong> More implementation details in Angular and Angular Material could be discussed.</li></ul><p>We’ll pause here for today that is enough to use the disabled form attribute like a Pro.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12a9b5a84c13" width="1" height="1" alt=""><hr><p><a href="https://medium.com/design-bootcamp/prevent-ui-damage-from-disabled-fields-12a9b5a84c13">Prevent UI damage from Disabled Fields</a> was originally published in <a href="https://medium.com/design-bootcamp">Bootcamp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain Driven Design in Action: A Cohesive Mechanism From the Trenches]]></title>
            <link>https://medium.com/better-programming/ddd-in-action-a-cohesive-mechanism-from-trenches-c697d738c968?source=rss-22ede26bdbb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c697d738c968</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gara Mohamed]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 07:39:05 GMT</pubDate>
            <atom:updated>2023-03-29T12:06:38.009Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quantity over date range example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DPItOiWR0ICUWhr6" /><figcaption>Photo by <a href="https://unsplash.com/@esteejanssens?utm_source=medium&amp;utm_medium=referral">Estée Janssens</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>I joined a team working on a cornerstone product a few years ago. The mission was similar to the Kitchen Nightmares television series. There were problems everywhere. To improve the situation, it was necessary to approach the software engineering state of the art gradually. Since the product was rich in business rules, I promoted the DDD mindset and toolset from the beginning of our journey.</p><p>We successfully used many DDD patterns and principles in our domain model implementation. In this article, I will present an example of a cohesive mechanism that allowed us to tackle the complexity of our product.</p><p>Before jumping to the first section of this article, I want to emphasize that I adopted the following rules in the rest of this article:</p><ul><li>The business problem is simplified to expose only the part that is related to this post</li><li>We aim to present the high-level API without the implementation details.</li><li>The presented code will be Kotlin snippets.</li></ul><p>Let’s begin our journey by exposing the domain problem.</p><h4>Business domain</h4><p><a href="https://documents.acer.europa.eu/en/Gas/Framework%20guidelines_and_network%20codes/Pages/Gas-Capycity-Allocation-Mechanisms.aspx">In the gas transport and gas trading across the EU industry</a>, a customer can allocate a gas capacity on a time slot. For example, a customer can allocate a throughput of 1000 kWh from 01/01/2024 to 31/12/2024.</p><p>Let’s define this concept in our ubiquitous language using the term Customer Allocated Capacity. The allocation has many properties, such as customer contract and network point. But in this article, the more interesting properties are:</p><ul><li>Allocation Time Slot</li><li>Allocated Throughout</li></ul><p>One of the complex use cases in this domain is assigning allocated capacity between two customers (<a href="https://www.prisma-capacity.eu/gtcs">article 33</a>). One customer can allocate capacity and then transfer it to another one. This operation is complex because the transfer can be just for a sub-period and can impact many allocated capacities.</p><p>The following diagram depicts a simplified view of the use case using the Event Storming notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4E8Bext4xhRY09f39DvqwQ.png" /></figure><p>The apply assignment strategy is the algorithm discussed in this article. Let’s start by describing the different domain modelling techniques we have used to collaborate with the domain experts.</p><h4>Domain modeling</h4><p>The Event Storming notation is a high-level modelling technique. It’s not very well adapted to model the details of the expected solution. A better complementary notation is the tabular representation of the Gherkin language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GYpsY9uUVcKVz4bjiSW53Q.png" /></figure><p>Even Gherkin was a good collaboration tool for other types of problems; it wasn’t the best one for this case. We preferred to adopt a more visual notation that simplifies conversations. So, I defined a simple visual language with an anonymous period and a given quantity over each period. Let’s see the above example with this notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71e3U7rh1BQPemEau19eZw.png" /></figure><p>So, we adopted a semi-formal syntax to sketch a useful model in discussion with our domain experts. The notation focuses only on the complex part of the domain problem.</p><blockquote>The tabular Gherkin notation and excel file was used to collaborate on hourly capacities.</blockquote><p>After defining a shared model, the next step is model implementation.</p><h4>The testing strategy</h4><p>The model implementation was fully guided by behavioural tests. I used the classical Outside-In double-loop workflow. I started every test iteration with a Gherkin scenario describing the required behaviour using a gradually complex concrete example. Then I tried to pass the test. When things got complicated and unmanageable with only high-level tests, I added more low-level tests to master the complexity. This approach allows me to identify the origin of red tests quickly.</p><p>In addition to JUnit, we used Gherkin/Cucumber as a testing tool which has many pros:</p><ul><li>Gherkin can also be used as a collaboration tool</li><li>The different scenarios are defined with the UL</li><li>The different scenarios are a living documentation</li><li>It is easy to add scenarios by any person on the team</li><li>Bugs are quickly fixed if we have the failing scenario</li></ul><p>But Gherkin/Cucumber also has many cons:</p><ul><li>We should write the Glue code. Without a well-established strategy, the glue code becomes a real mess.</li><li>Lack of advanced support in IDE editor. But this is not a problem for multi-caret editing Guru.</li><li>Limited scalability in the case of a combinatorial explosion of test cases. Our product manager’s creativity allowed us to enumerate cases using Excel files much better.</li></ul><blockquote>To handle the complexity in the glue code, we defined a set of rules and patterns that make the code predictable and easy to write and understand. This can be the subject of a separate post.</blockquote><p>Let’s now talk about the implementation design.</p><h3>The Implementation Strategy</h3><p>In the first iterations, usually, I don’t try to design the details behind the API. I let the design emerge as I add enough examples. At some point, when I started to confront arithmetic operations in the assignment algorithm, I had at least two design alternatives.</p><h4>First design solution</h4><p>The first solution is to make the code more specific and define operations in the domain entity:</p><pre>val customerAllocations = customerAllocation.apply(assignement)</pre><p>and/or domain service:</p><pre>val customerAllocations = service.applyAssignement(customerAllocations, assignement)</pre><p>The arithmetics operation are expressed using the CustomerAllocatedCapacity entity:</p><pre>interface CustomerAllocatedCapacity {<br><br>  val id: CustomerAllocatedCapacityId<br>  val allocationStartInstant: Instant<br>  val allocationEndInstant: Instant<br>  val quantity: EnergyQuantity<br><br>  fun add(other: CustomerAllocatedCapacity): CustomerAllocatedCapacity<br><br>  fun subtract(other: CustomerAllocatedCapacity): CustomerAllocatedCapacity<br>}<br><br>fun sumOf(<br>  first: CustomerAllocatedCapacity,<br>  second: CustomerAllocatedCapacity<br>): List&lt;CustomerAllocatedCapacity&gt; {<br>  ...<br>}</pre><p>With this solution, there is no generic code, and the interfaces are more explicit. But the fields used in domain entities are implicit, and the code is more difficult to understand because the math will be intertwined with the domain object operations. Worse than that, summing allocated capacities is not a domain concept.</p><h4><strong><em>Second design solution</em></strong></h4><p>The second alternative was to extract the specialized math in a separate module. All operations on a quantity over a date range are handled by a new central explicit concept: the QuantityOverDateRange value object.</p><pre>interface QuantityOverDateRange {<br>  val dateRange: DateRange<br>  val quantity: Quantity<br>  val groupId: String?<br>}</pre><p>So, to do computation on the date range and quantity of a domain entity, we should:</p><ul><li>Convert CustomerAllocatedCapacity entity to an QuantityOverDateRange value object</li><li>Do computation using QuantityOverDateRange objects</li><li>Create new entities from the resulting QuantityOverDateRange objects</li></ul><p>For example, the domain entity becomes:</p><pre>class CustomerAllocatedCapacity(<br>  val id: CustomerAllocatedCapacityId,<br>  val allocationStartInstant: Instant,<br>  val allocationEndInstant: Instant,<br>  val quantity: EnergyQuantity<br>) {<br><br>  val allocationPeriod<br>    get () = DateRange(allocationStartInstant, allocationEndInstant)<br><br>  fun asQuantityOverDateRange() = QuantityOverDateRange(allocationPeriod, quantity.inKwhj25(), id)<br>}</pre><p>By isolating the Math logic and making it independent of our domain entities, the code becomes more generic, but it is also more explicit and clear. And this is exactly what Eric Evans recommends in the blue book:</p><blockquote>You may see a part of the model that can be viewed as specialized math; separate that.</blockquote><p>The whole solution is based on four layers. The 🔵 are homemade, and the 🟢 is a third-party class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44FaCDllpi3nMSxnYM_Qfg.png" /></figure><p>The upper layer is the CustomerAllocatedCapacity domain model. The domain model uses the generic domain model QuantityOverDateRange. The DateRange value object is implemented based on Guava Range generic type.</p><blockquote>Using a third-party library to implement a domain model was the subject of The mythical “only Java” heuristic section in <a href="https://medium.com/@gara.mohamed/lombok-a-ddd-friendly-java-tool-a4925a502bf0#6dc4">my previous article</a>.</blockquote><p>The QuantityOverDateRange main properties are date range, quantity, and group id (a correlation id between different instances).</p><pre>interface QuantityOverDateRange {<br><br>  val dateRange: DateRange<br>  val quantity: Quantity<br>  val groupId: String?<br><br>  fun subtract(subtrahend: QuantityOverDateRange): SubtractionResult<br><br>  fun add(value: QuantityOverDateRange): List&lt;QuantityOverDateRange&gt;<br>}</pre><p>The main operations are: subtract and add. The SubtractionResult contains information about the remaining ranges and changes. They are both used to create customer-allocated capacities after applying the assignment algorithm.</p><pre>data class SubtractionResult(<br>  val remainingRanges: List&lt;QuantityOverDateRange&gt;,<br>  val changes: List&lt;Change&gt;,<br>) {}</pre><p>Besides the main operation in the QuantityOverDateRange, there are many others that are used for different use cases. The following code gives us an idea of the QuantityOverDateRange API.</p><pre>interface QuantityOverDateRange {<br><br>  val dateRange: DateRange<br>  val quantity: Quantity<br>  val groupId: String?<br>  <br>  fun startBefore(period: DateRange): Boolean<br>  <br>  fun endAfter(period: DateRange): Boolean<br>  <br>  fun withDateRange(dateRange: DateRange): QuantityOverDateRange<br><br>  fun add(value: QuantityOverDateRange): List&lt;QuantityOverDateRange&gt;<br><br>  fun subtract(subtrahend: QuantityOverDateRange): SubtractionResult<br><br>  fun subtract(subtrahends: List&lt;QuantityOverDateRange&gt;): SubtractionResult<br>  <br>  fun subtractQuantity(subtrahend: QuantityOverDateRange): QuantitySubtractionResult<br>  <br>  fun hasMoreQuantityThan(other: QuantityOverDateRange): Boolean<br>  <br>  fun periodIntersectionWith(other: QuantityOverDateRange): DateRange<br><br>  fun hasSamePeriodAndQuantityAs(other: QuantityOverDateRange): Boolean<br><br>  fun hasSamePeriodAs(other: QuantityOverDateRange): Boolean<br><br>  fun hasIntersectionWith(other: QuantityOverDateRange): Boolean<br><br>  fun hasNoIntersectionWith(other: QuantityOverDateRange): Boolean<br>}</pre><p>The entry point to the customer-allocated capacity assignment is QuantityOverDateRangeList. The role of this value object is to encapsulate an ordered list of QuantityOverDateRange and allows us to subtract a QuantityOverDateRange according to the defined order.</p><pre>interface QuantityOverDateRangeList {<br><br>  val listOrderedByPriority: List&lt;QuantityOverDateRange&gt;<br><br>  fun subtract(subtrahend: QuantityOverDateRange): SubtractionResult<br><br>  fun haveAtLeast(quantityOverDateRange: QuantityOverDateRange): Boolean<br><br>  fun haveGapDuring(LocalDateRange period): Boolean<br><br>  fun haveInnerGapsDuring(period: DateRange): Boolean<br><br>  fun doNotEnclose(dateRange: DateRange): Boolean<br>  <br>  fun dateRngesExtremum(): DateRange<br>  <br>  fun dateRanges(): List&lt;DateRange&gt;<br>}</pre><p>So, to implement the assignment algorithm in the domain model, we create a QuantityOverDateRangeList encapsulating the list of CustomerAllocatedCapacity to be impacted as a list of QuantityOverDateRange. Then we call the subtract operation with the Assignment entity as a parameter. Finally, we transform SubtractionResult to the resulting CustomerAllocatedCapacity list.</p><p>Before summarizing, I want to mention another complex operation in our cohesive mechanism. It’s the sum of a QuantityOverDateRange list. This operation wasn’t used in the assignment use case but was added later for another business use case.</p><pre>fun sum(values: List&lt;QuantityOverDateRange&gt;): List&lt;QuantityOverDateRange&gt; {<br>  // ...<br>}</pre><p>The QuantityOverDateRange value object wasn’t extracted for the sake of reuse. The original goal was to make the assignment tackle the complexity of the assignment algorithm. But, the created cohesive mechanism had more feature envy. Having an existing model for QuantityOverDateRange simplified the implementation of the following features.</p><p>To summarize the previous code, the QuantityOverDateRange contains the following four operations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uM4BxW2dcxTCubQ3AiKFMA.jpeg" /></figure><p>The QuantityOverDateRangeList contains a single operation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2X9fCjSss60TERbXIQJk4A.jpeg" /></figure><p>Implementing such a cohesive mechanism wasn’t possible without the presence of skilled and motivated developers who embody the common sense of the Domain-Driven mindset.</p><p>In addition to pair and mob/ensemble programming, trying all kinds of waste avoidance and technical excellence adoption, the team had a dose of passion. Let’s look at an example.</p><h4>The motivated team</h4><p>When our solution was stable, in the middle of a conversation, I talked about the possibility of defining an executable visual DSL for our scenario language. A highly skilled and motivated developer implemented the idea. He refined the syntax of our language to be formal, then he implemented the interpreter. He gave us a demo. It was amazing to write an abstract test with just enough data to test the risky, complex part of the application. The only real limitation of this POC was the absence of automatic formatting.</p><pre>                                   (id  , contrat                , parent)<br>  [-----------100------------]     (ca1 , customer1              ,       )<br>  [-------100---------]            (ca2 , customer1              ,       )<br><br>  [--------200--------]            (cc , customer1 =&gt; customer2,       )<br><br>                                   (id  , contrat                , parent)<br>  [--------100--------]            (   , customer2               , ca1   )<br>  [--------100--------]            (   , customer2.              , ca2   )<br>                       [-100-]     (   , customer1               , ca1   )</pre><p>The syntax is composed of three vertical blocks separated by empty lines. They are the Given/When/Then blocks. Horizontally, there are two sections: the left side is the quantity over date ranges, and the right side is the other properties. The first line contains property names. The following lines, each one defines an instance of a CustomerAllocatedCapacity in the Given and Then blocks. The When block contains an Assignment entity.</p><h3>Conclusion</h3><p>Layers and abstractions are powerful design primitives that DDD uses to define patterns that allow us to tackle the complexity at the heart of software. This article discussed a concrete example of a DDD cohesive mechanism used to define an abstraction that makes the code more human-friendly.</p><p>Implementing such patterns requires team maturity, but it is essential to manage the scaled complexity in strategic enterprise products. In such context, the eXtreme Programming, DDD, BDD, and TDD principles, practices, and patterns are not optional.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c697d738c968" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/ddd-in-action-a-cohesive-mechanism-from-trenches-c697d738c968">Domain Driven Design in Action: A Cohesive Mechanism From the Trenches</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[Lombok: a DDD-friendly Java tool]]></title>
            <link>https://medium.com/@gara.mohamed/lombok-a-ddd-friendly-java-tool-a4925a502bf0?source=rss-22ede26bdbb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4925a502bf0</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Gara Mohamed]]></dc:creator>
            <pubDate>Mon, 09 May 2022 11:05:56 GMT</pubDate>
            <atom:updated>2022-05-27T07:58:10.936Z</atom:updated>
            <content:encoded><![CDATA[<p>Evaluating Lombok from a DDD perspective</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BFQWwV-Z5Xc8GXQ-" /><figcaption>Photo by <a href="https://unsplash.com/@mtsjrdl?utm_source=medium&amp;utm_medium=referral">Mathis Jrdl</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>DDD is a holistic approach to tackling complexity in the heart of software. It takes care of both the strategic and the tactical aspects of software solutions and IT organizations. This post is limited to the tactical scope: <em>we try to evaluate a tool from a DDD viewpoint</em>. <strong>The real goal of the analysis is not the tool itself but the DDD mindset.</strong></p><p>Lombok is a java tool that is largely used. Its pros and cons were well discussed in many articles and Stack Overflow answers. In this post, we evaluate Lombok from a DDD perspective. The analysis is based mainly on my understanding of:</p><ul><li>Eric’s book which I read two times (the first time was five years ago)</li><li>And some of his talks at DDD conferences (such as DDD Europe)</li></ul><p>Let’s first start with a brief history of the java language and a description of the problem resolved by Lombok.</p><h4>Java power and limitation</h4><p>My journey with Java started eighteen years ago on a text-based IDE called <a href="https://archive.org/details/tucows_296665_JPad_Pro">JPadPro</a>. It was a big step forward in developing GUI applications after my first screens with other platforms. It was easy to write small desktop applications with Swing. As a software engineering student, I enjoyed writing my first Java classes.</p><p>Since that time, the JDK has kept growing in popularity and maturity. The language, API, and the platform have evolved during the last twenty years and the ecosystem has become quite large and mature. All this stuff kept attracting me more and more.</p><p>But after all that time, some limitations of the Java native platform are not totally tackled by the JDK: the language is verbose when dealing with some repetitive tasks such as declaring constructor, properties, equals, hashCode, simple builders.</p><p>As a lazy programmer who hates redundant dummy tasks and likes to do more challenging ones, I suffered from this verbosity when working on real-world professional applications. Let’s illustrate the problem with a concrete simple example.</p><p>In the following listing we declare a class for defining a Person:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af3a585dc6a6013ab1b7c22180d34a9f/href">https://medium.com/media/af3a585dc6a6013ab1b7c22180d34a9f/href</a></iframe><p>This is a class with three fields with default access visibility. We should now add the following idiomatic stuff:</p><ul><li>constructor</li><li>properties</li><li>equals and hashCode methods</li><li>toString method</li><li>Builder class</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e8a687d6ba895502c92e5e04469061a/href">https://medium.com/media/2e8a687d6ba895502c92e5e04469061a/href</a></iframe><p>This is a code for an immutable class. If we add the setters we can have almost 100 lines of code. We can extract the Builder class to a separate file to reduce the verbosity but the problem still exists.</p><p>Writing this verbose code has two major drawbacks in terms of developer experience:</p><ul><li>This is an example with three properties. For a real-world entity with twenty or even more fields, the situation becomes worse.</li><li>It is hard to maintain this logic. If we add a property we must update all methods which is an error-prone task.</li></ul><p>The code can be generated by the IDE. This is true when the class is created for the first time. But when we change attributes we should launch the generation action for each part of the code.</p><p>There is also another cost: we should read all this dummy code which is visual pollution and it’s hard to analyze by the human brain.</p><p>Let’s now look at Lombok and see how it tries to resolve the problem.</p><h4>What is Lombok?</h4><p>Lombok <strong><em>can be seen</em></strong> as an extension of the Java compiler. It uses the Annotation Processing Tool to <em>“generate”</em> code in the compilation phase. The main value of Lombok is to reduce the class declaration verbosity by removing the boilerplate code and using a declarative approach based on annotations. When we use Lombok in our example it becomes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6d86e8c36a418612891cc233beb4ccb/href">https://medium.com/media/c6d86e8c36a418612891cc233beb4ccb/href</a></iframe><p>So, the idea is to make some aspects of Java programs more declarative. If all or the majority of the class member are exposed as object properties then Lombok can be a good tool to use.</p><p>Lombok offers many features that do not all have the same level of maturity. <strong>In this post we limit Lombok to his main annotations subset:</strong></p><ul><li>Value</li><li>Builder</li><li>With</li><li>EqualsAndHashcode</li></ul><p>With this quick Lombok reminder/presentation, let’s jump now to the DDD side.</p><h4>What is Domain Driven Design?</h4><p>DDD is an approach that emerged to tackle the complexity in the heart of software applications. It defines principles, patterns, and practices from the high-level organizational, social and political aspects to the low-level lines of code.</p><p>DDD states that when the complexity is in the business logic, then we should isolate this logic in a domain model layer. This layer should be dedicated to expressing the model and be free from GUI, DB, and HTTP clients logic. The model isolation is an important principle and it deserved a full chapter in the DDD blue book.</p><p>DDD is based on the agile (as defined by the manifesto) and Lean Software Development mindsets. The DDD doesn’t try to reinvent the wheel it’s partially a brilliant collection of the good principles and practices that emerged in the industry.</p><h4>What is the relation between Lombok and DDD?</h4><p>DDD is a holistic approach that covers high-level strategic topics as well as low-level tactical topics. The main idea of the tactical part is to express the model in the software solution.</p><p>When talking about implementing the model, the blue book discussed four main subjects:</p><ul><li>An architectural style that helps to isolate the domain model</li><li>A catalog of useful design patterns to express the model</li><li>The supple design</li><li>The tools that we use to build a software</li></ul><p>Even if DDD is tool agnostic, it promotes some criteria for selecting tools. In many chapters, the blue book talked about programming languages (general-purpose, 4GL, DSL, etc…), frameworks, and databases. I think that one of the best paragraphs that explain the DDD mindset about tools is the following:</p><blockquote>Architectural frameworks and other tools will continue to evolve. Newer frameworks will automate or prefabricate more and more of the technical aspects of an application. If this is done right, application developers will increasingly concentrate their time on modeling the core business problems, greatly improving productivity and quality. But as we move in this direction, we must guard against our enthusiasm for technical solutions; elaborate frameworks can also straitjacket application developers.</blockquote><p>So, DDD is not against tools but it prefers ones that help us to focus mainly on business problems. Our model should be:</p><ul><li>Isolated from the external world and also from technical aspects</li><li>Easy to define with a declarative style</li></ul><p>Let’s take another excerpt from the book talking about tools but this time from the Value Object chapter:</p><blockquote>Immutability of an attribute or an object can be declared in some languages and environments but not in others. <strong>Such features help communicate the design decision</strong>, but they are not essential. Many of the distinctions we are making in the model cannot be explicitly declared in the implementation with most current tools and programming languages. You can’t declare ENTITIES, for example, and then have an identity operation automatically enforced. But the lack of direct language support for a conceptual distinction does not mean that the distinction is not useful. <strong>It just means that more discipline is needed to maintain the rules that will be only implicit in the implementation</strong>. This can be reinforced with naming conventions, selective documentation, and <em>lots of discussion</em>.</blockquote><p>This paragraph has a direct relationship with the tool selected in this article. Lombok allows to declaratively define an immutable object without the Java boilerplate code. Lombok also makes declaring entity identity more declarative.</p><p><strong>This post is at the same level as the DDD book discussions of the various tools used to implement the domain model</strong>. I hope that the two previous blue book citations are enough as examples to illustrate the link between tools and DDD in general. But, before we go forward, I would like to point out that the Domain-Specific Languages section in chapter 10 exposes the pros and cons of DSLs which can be compared to our discussion of Lombok&#39;s pros and cons at the end of this article.</p><p>Let’s now discuss Lombok features from a DDD perspective. Our first evaluation of Lombok will be from the XP perspective.</p><h4>eXtreme Programming</h4><p>Simplicity is one of the values of eXtreme Programming. It’s usually applied to the design but should also be applied to the tools used to implement it. It’s clear that listing 2 introduces an accidental complexity in the codebase which has no relationship with the problem being resolved. So, the Lombok version helps to achieve the required simplicity and remove the accidental complexity.</p><p>The XP philosophy is to use the easy design solution and then refactor if the constraints change. This applies well to the use of tools and Lombok is a decision that can be easily reversed.</p><h4>Lean software development</h4><p>From a Lean point of view, writing boilerplate, redundant and dummy code is a waste that should be eliminated. The developer should fully put his energy on the domain problem and the listing 2 approach hijack the developer’s focus from the domain (or at least reduce his efficiency).</p><p>By its declarative strategy, Lombok helps us to:</p><ul><li>focus more on the domain model</li><li>eliminate accidental complexity</li><li>eliminate waste</li></ul><p>All these points enhance the developer’s experience. And the better the developer&#39;s experience the bigger his impact on the product.</p><blockquote>One of the basic craft rule that I learned ten years ago is: Every thing that can be automated should be automated.</blockquote><h4><strong>Rich domain model pattern</strong></h4><p>The DDD promoted the rich domain model pattern. Listing 2 code is not a scalable approach to use when adopting this pattern because domain entities will contain complex behavior and all the dummy code that we add interwind with the rich behavior and makes the navigation in the codebase painful.</p><p>So, Lombok helps to keep only the rich domain behavior in entities and value objects.</p><blockquote>Usually getter/setter are considered as a DDD anti-pattern. But exposing domain entities state using properties can be a good solution if the rich domain model pattern is respected.</blockquote><h4><strong>The mythical “only Java” heuristic</strong></h4><p>Using only Java to implement the domain layer is a heuristic that I saw in a few blog posts but It doesn’t exist in the reference DDD books (at least to my knowledge). And it’s a heuristic that conflicts with the DDD mindset. To see why let’s remind ourselves what the blue book said about the goal of isolating the domain model:</p><blockquote>Concentrate all the code related to the domain model in one layer and isolate it from the user interface, application, and infrastructure code. <strong>The domain objects, free of the responsibility of displaying themselves, storing themselves, managing application tasks, and so forth, can be focused on expressing the domain model.</strong> This allows a model to evolve to be rich enough and clear enough to capture essential business knowledge and put it to work.</blockquote><p>The goal of isolating the model is <strong>to be focused on expressing the domain model. </strong>Everything that is not directly related to this responsibility should be avoided. And any tool that simplifies the writing, reading, and navigating in the model is considered DDD-friendly at least from this perspective.</p><p>In the Generic Subdomains chapter, It was stated explicitly that DDD is not about reinventing the wheel even for the domain model:</p><blockquote>Don’t feel compelled to implement all aspects of a published model, if you can identify a simplified subset that is self-consistent and satisfies your needs. But in cases where there is a well-traveled and well-documented — or better yet, formalized — model available, it makes no sense to reinvent the wheel. <strong>DDD is not about reinventing the wheel.</strong></blockquote><p>So, if we can reuse a well-established model to design our abstract domain model, then why we can’t do the same thing when implementing this model in our code. <strong>DDD is not a justification to use poor solutions or reinvent the wheel.</strong></p><p>In my experience, using a third-party library in the domain layer is an interesting choice when implementing a cohesive mechanism. I’m writing a dedicated post about a real cohesive mechanism example. I will publish the article as soon as possible.</p><p>Let’s now look at two examples that I usually use when engaged in discussion about the Java Only rule:</p><ul><li>In 2012, to represent date and time in a Java application, we had at least two choices: either we use the JDK native API or we use a third-party library such as Joda time. The Java date and time API before 2014 was a poor one. If we followed the Java-only heuristic we will use a bad API. A heuristic that promotes using bad API isn’t a good one. And the history of the Joda time library confirms this because the actual Joda time API is now part of the JDK.</li><li>The Java API doesn’t contain a concept to model a range. So, we can use a third-party library such as Guava with its Range type or we can choose to create one from scratch so the domain layer is independent of external libraries. We can do that if it’s justified but the justification can’t be: “this is the DDD” because the DDD is not about reinventing the wheel.</li></ul><p>From a DDD point of view, using a third-party module in the domain layer is forbidden for two reasons:</p><ul><li>The module contains infrastructural stuff that couples the model to external systems.</li><li>The selected module does not help to express the domain model very well.</li></ul><p>So, if the third-party module respects the two constraints, from a DDD point of view, it can be used in the model. But, the third-party module adoption should be evaluated from other perspectives. For example, we can ask the question: why did we choose the Java platform to develop the application. Maybe, the module should respect the same choice criteria.</p><h4>Lombok: the false problem</h4><p>Lombok is using APT to hack the compiler. To add a feature, it should be implemented for the different versions of the compiler. Sure, this is not ideal but this is a problem for the maintainers of the project, not the users. From a user perspective what accounts is:</p><ul><li>How easy to use</li><li>How active the project</li><li>The release roadmap</li></ul><p>So, talking about the internal implementation to justify the use or not of Lombok is not a very wise argument. From a user perspective, Lombok suffers from another type of limitation.</p><h4>Lombok: the real problem</h4><p>The real problem of Lombok is usually the tooling. The first problem is that we need to install a plugin in our IDE. The second problem which is worse is that the plugin has a different release cycle than Lombok. These are the real practical disadvantages of Lombok.</p><p>There is another problem that is more controllable: Lombok is an additional tool to master. But, the team is autonomous to solve this problem. It doesn’t depend on a third-party entity to solve the learning problem.</p><h3>Alternatives</h3><p>The JVM languages such as Kotlin are a good alternative to resolve the Java language verbosity. Almost all Lombok&#39;s main features are tackled by Kotlin. From a DDD point of view, Kotlin is a good language for implementing Domain Model on the JVM.</p><p>The recent versions of Java are also a good alternative. Some interesting features, such as records, were added to the language. But, they are still limited compared to Lombok and Kotlin.</p><h4>Conclusion</h4><p>DDD is not about making perfect solutions. The first DDD rule for the domain model design is that: <strong>a good design is imperfect</strong> and we should stop being perfectionists.</p><p>DDD is mainly about understanding the business problem by communicating with domain experts to construct a shared understanding based on a domain model. The domain model should be implemented using patterns and tools. Any tool that makes the model expressive and pure is a DDD-friendly tool. But, DDD-friendliness is not the only criteria to use when selecting our toolbox. It’s the main one but it’s not the single one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4925a502bf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hexagonal Architecture’s Common Misconceptions]]></title>
            <link>https://medium.com/@gara.mohamed/hexagonal-architectures-common-misconceptions-9aa2380c13c0?source=rss-22ede26bdbb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aa2380c13c0</guid>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Gara Mohamed]]></dc:creator>
            <pubDate>Sun, 07 Jun 2020 20:55:42 GMT</pubDate>
            <atom:updated>2023-02-22T18:20:59.983Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gyN7PvaY9w-8eRHs" /><figcaption>Photo by <a href="https://unsplash.com/@tzenwahon?utm_source=medium&amp;utm_medium=referral">James Hon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>The hexagonal architecture is simple, elegant, and beautiful. It’s also a well-defined architecture. Alistair Cockburn published at least two articles describing it. However, even in 2020, we still read on some famous blog posts (which appear in the first positions in Google search result) a false description and a bad implementation of this stylish architecture.</p><p>The goal of this post is to briefly point some misconceptions that I found on some frequently visited blog posts. This is not an introduction to the basics of this architecture. We don’t present examples and pedagogical content. So before reading it’s a prerequisite to already know the basics. There are already excellent articles describing the architecture. There is no need to reinvent the wheel.</p><p>So, let’s begin with a succinct reminder of Hexagonal architecture’s keywords.</p><h4>The building blocks reminder</h4><p>The Hexagonal Architecture (also named Ports and Adapters) defines two zones: the inside of the Hexagon and its outside. The communication between the two worlds is done via a defined set of ports. The ports are defined inside the hexagon and in the outside, we define ports’ adapters.</p><p>The hexagon contains two parts which present some symmetries and asymmetries: the left and the right sides.</p><p>So let’s start with the first misconception.</p><h4>What is the Inside of the Hexagon?</h4><p>The first big misconception is that the hexagon is the domain. No doubt, the domain is at the heart of the architecture but the hexagon contains both the application and the domain logic. So saying that inside is the domain and the outside is application do not match with the original definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*Mn8jZDh18tYEYtAa.gif" /><figcaption>Alistair Cockburn’s original picture defined in <a href="https://alistair.cockburn.us/hexagonal-architecture/">this link</a></figcaption></figure><p>The goal of the Hexagon is to encapsulate the part that is independent of external peers. The application layer should be reused between several adapters of the same port. For example, if we have two adapters (REST and SOAP) for a single port, the application logic should not be duplicated in the two corresponding adapters. It should reside inside the Hexagon. And this is the essence of <a href="https://martinfowler.com/eaaCatalog/serviceLayer.html">the Service Layer pattern</a>.</p><p>So we can say that the left side of the hexagon is the application of the service layer pattern (see <em>Use Cases And The Application Boundary</em> section).</p><p>Some people declare that the Hexagon should be the domain and not the application. This reminds me of Martin Fowler’s tweet about Continous Integration:</p><h3></h3><p></p><p>By definition, the Hexagon is the application. You can’t change a definition of a well defined and documented concept. If you want to do that you have to create a variant of the architecture and give it another name.</p><p>The next misconception is about the right side of the Hexagon.</p><h4>How to implement the right side?</h4><p>The Hexagonal architecture is simple but some implementation deviates from this fundamental characteristic when implementing<strong> the right side adapters</strong>. So, instead of just implementing the interface defined in the domain layer, the implemented adapter will delegate to another object having the same level of abstraction and even the same signature. This implementation becomes has the same complexity as a GoF adapter but without having its advantages. To be more precise, I’ve seen this problem in implementations of Repositories based on Spring Data. In the last section, we’ll discuss a little more the GOF Adapter pattern in the Hexagon Architecture.</p><p>Next, we discuss a misconception about ports.</p><h4>Ports are interfaces?</h4><p>Often, we describe the ports as interfaces (in Java sens). But, this is not a precise statement. There is an asymmetry between the right and left side ports. The right side port should be defined using an interface. But, for the left side, it’s not recommended to define the port as an interface if it’s <a href="https://martinfowler.com/bliki/HeaderInterface.html">a header interface</a> and not <a href="https://martinfowler.com/bliki/RoleInterface.html">a role interface</a>. In his sample code, Alistair didn’t use an interface for the left side port example (even if in his poetry example, he used an interface).</p><p>Our last point will be the use of the GOF adapter pattern.</p><h4>What about the adapters?</h4><p>In the original article, Alistair noted that the GoF Adapter Pattern is related to the architecture. But, this doesn’t mean that all the adapters of the ports are GoF adapters. Only the primary adapters implement the GoF pattern. The secondary adapters are not always an implementation of the GoF one even if they are named with the same name.</p><h4>Conclusion</h4><p>Even there are errors in many articles describing the Hexagonal Architecture, there are also excellent articles. One of my favorite articles is <a href="https://jmgarridopaz.github.io/content/hexagonalarchitecture.html#tc5">this one</a>. But, the reference stays Alistair’s <a href="https://alistair.cockburn.us/hexagonal-architecture/">posts</a>. We should read them before any other ones.</p><p>Finally, if we read in a post that the hexagon contains the business logic, the inner of the hexagon is the domain or the outside is the application, we should move to another post :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aa2380c13c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Please, don’t use a Design Pattern’s name]]></title>
            <link>https://medium.com/@gara.mohamed/please-dont-use-a-design-pattern-s-name-636f335ee213?source=rss-22ede26bdbb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/636f335ee213</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Gara Mohamed]]></dc:creator>
            <pubDate>Sun, 19 Apr 2020 22:37:39 GMT</pubDate>
            <atom:updated>2020-04-19T22:37:39.302Z</atom:updated>
            <content:encoded><![CDATA[<p>in its linguistic meaning</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SKdXE3quqBmlyCB9" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Each engineering discipline defines its own terms and Jargon. This terminology is established over time by pioneers and experts and is generally promoted by their published books and articles (nowadays conferences and talks participate too).</p><p>After many years of building software systems, the industry started to promote the definition of a single term to define a high-level solution and choose Design Pattern as a meta-term to designate these terms. As stated in GoF: “Design patterns capture solutions that have developed and evolved over time” [GoF-p10]. Many authors published their defined design patterns in catalogs and some even developed a pattern language. One big advantage of design patterns is to simplify communication between engineers. We need just one or two words to express a complex design solution that needs many sentences and diagrams to be explained. So, they are a powerful communication tool.</p><p>This article is about using design pattern’s name in a type name. So, we start with good usage and then we move to the bad part.</p><h3>Naming Patterns</h3><p>In <a href="https://martinfowler.com/articles/refactoring-external-service.html">this</a> article, Martin Fowler says: “I sometimes hear people say that you shouldn’t put pattern names into your code, but I don’t agree. Often pattern names help to communicate roles different elements play, so it’s silly to spurn the opportunity.” So, suffixing a type with a design pattern name or a member in a design pattern is a best practice that helps the code reader to understand as quickly as possible the details of the design. If we prefer to not use the pattern name in the source code or we can’t do it, we should at least manifest it in the source code documentation.</p><p>Once, I implemented a dynamic query with Method Object but I think that suffixing the class name with Method Object is not an elegant naming choice. I prefer to suffix the class name with Query. So, I just added a sentence in the Java Doc that makes it explicit that the class is a Method Object.</p><p>As detailed in the Clean Code book in the 2nd chapter, a type name should be searchable, intention revealing, pronounceable, etc... But, it would also be a good thing if it has<strong> a design revealing name</strong>.</p><h3>Naming Anti-Patterns</h3><p>But can we reverse the power of design pattern names against us? Yes, we can. <strong>There are at least two cases in which a pattern name become misleading:</strong></p><ul><li>First, when we use a pattern name in its linguistic meaning. For example, it’s a bad idea to use the word Bridge to indicate that a type relies two parts. Bridge is a well-defined design pattern by the Gang of Four book to “Decouple an abstraction from its implementation so that the two can vary independently.” [GoF-p20]. So, if we don’t have an abstraction and an implementation that varies independently, the Bridge name will be misleading for developers who know the pattern.</li><li>Second, when we use the wrong pattern name. For example, it’s confounding to “Define an interface for creating an object, but let subclasses decide which class to instantiate.” [GoF-p20] and name it with a Builder suffix. Linguistically, it may be a builder but technically it’s a wrong and ambiguous name.</li></ul><p>The side effect of these two situations is time waste and slowing down the developers. So, before using a pattern name or inventing our own pattern name we should take a look at the well-established references about design patterns. This makes our code well crafted and creates trust in our code.</p><h3>Conclusion</h3><p>Design patterns names are here to make the communication more effective. So, we should fully exploit this powerful tool to avoid confusion and ambiguity. And, it’s a pity to make design pattern name a misleading tool for developers. <strong>So we should avoid using a Design Pattern name in its linguistic meaning in our source code.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=636f335ee213" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java idioms of the Mapper Pattern]]></title>
            <link>https://medium.com/@gara.mohamed/java-idioms-of-the-mapper-pattern-f7527827ac98?source=rss-22ede26bdbb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7527827ac98</guid>
            <dc:creator><![CDATA[Gara Mohamed]]></dc:creator>
            <pubDate>Sun, 29 Mar 2020 22:09:01 GMT</pubDate>
            <atom:updated>2020-04-07T19:27:05.438Z</atom:updated>
            <content:encoded><![CDATA[<p>using static method, MapStruct, Function, DSL and DTO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cbNCowhEKliZRZTm" /><figcaption>Photo by <a href="https://unsplash.com/@les_photos_de_raph?utm_source=medium&amp;utm_medium=referral">Raphaël Biscaldi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Mapping and mappers are everywhere in Java world. There are patterns, tools and API. Martin Fowler defined a mapper <a href="https://martinfowler.com/eaaCatalog/mapper.html">pattern</a> in his book PoEAA. There many tools to create mapper/converter between beans/DTO/entities such as <a href="https://mapstruct.org/">MapStruct</a>. The Stream class uses a mapper as a callback to <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#map-java.util.function.Function-">the map method</a>.</p><p>In this article, we will see many Java idioms to implement a mapping between two objects. To illustrate the different techniques, we use an anti-corruption layer example. But, the same techniques apply to other cases such as REST endpoints.</p><h4>Use case</h4><p>Let’s assume that we have an application that needs to access an external REST API. The client-side code is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*qqVz201s0ng-5ZuiwgQR3Q.png" /><figcaption>REST Client Interface</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*hsbe_fjS76dme9ZhjtoASQ.png" /><figcaption>Source Model</figcaption></figure><p>The two methods return the same type, but one returns a List and the other a simple type.</p><p>The domain code doesn’t access to this API. The REST client is instead encapsulated in an anti-corruption layer that converts the external model to an internal one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*NINQyagmSMrvAKvCq__GkQ.png" /><figcaption>Target model</figcaption></figure><p>The tests for the ACL (anti-corruption layer) is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*vlaaiVZSPtU6dmACX9el1g.png" /></figure><p>Each version will inherit from this base class to test the implementation. The following Gateway code is the common part between all the variants:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*x3Ew9tZvf8fW-JUYK4Mlvg.png" /></figure><p>Let’s now deep dive into the details of the Gateway implementations using a mapper function/method/object.</p><h4>Mapper as a static method</h4><p>A good mapper is a pure function that gets an input and creates an output from it without side effects and for the same input, we always get the same output. In Java, it’s a good practice to mark a pure function as static even if they are private. This will make explicit that the method is independent of any instance even it doesn’t guarantee that it’s a pure function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*tY5vP3_CNnTIknAoU0AtbA.png" /></figure><p>The mapping is done using two overloaded pure functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*Bo6MydQIJrFBUHTMiqVyLA.png" /></figure><p>The methods can also be named <strong>customerFrom(buyer)</strong> and <strong>customersFrom(buyers)</strong>.</p><p>This is a good option if we don’t mock the mapper. Generally, it’s not recommended to mock pure functions unless we consider the mapper as a role.</p><p>This approach has few limitations:</p><ul><li>We repeat the same code to map collections. To respect the DRY principile we can define a method: static &lt;S, T&gt; List&lt;T&gt; map(List&lt;S&gt; source, SimpleMapper::map);</li><li>It’s not an elegant solution when used in a stream pipeline: list.stream().map(SimpleMapper::toCustomer). It’s more beautiful to write: <strong>list.stream().map(toCustomer). We can write the following: </strong>list.stream().map(buyer -&gt; toCustomer(buyer)), but it’s more verbose.</li><li>It doesn’t work well if our map method isn’t pure (For example, if we access to now()).</li></ul><h4>Generated Mapper</h4><p>Tools like Mapstruct allows to create a mapper as an interface and generate implementation during the compilation phase. In some cases, this is a powerful approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*SH7Wqs6lL0T0vKyFlAprcQ.png" /></figure><p>The mapper interface is elegant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*MgeCRpclLPQ9M6TWlOKE1A.png" /></figure><p>This approach has also a few limitations:</p><ul><li>If the structure of the two classes is different, we should install a plugin to have autocompletion and refactoring features. The code can also be more verbose than the handwritten one.</li><li>Each time, we should define a method for collection mapping.</li><li>can’t be referenced fluently in map function.</li></ul><h4>Mapper as a Function</h4><p>This version tries to circumvent the limitation of the previous technique using the Java 8 Function interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*qrTbTdk1iStFrYuGvL4SGw.png" /></figure><p>The mapper is handwritten. It’s more explicit and less verbose when mapping a different structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*HltQ8hCeuVwGNTMMPxNw6Q.png" /></figure><p>The Mapper interface extends the Function interface and defines a default method to map list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*1DK8ocnY3l2FXj2hWZJzUA.png" /></figure><p>The limitation of this approach:</p><ul><li>The mapper should implement the Mapper interface.</li><li>The mapping of a similar structure is verbose.</li><li>The API is not so fluent: we call a function as an object. To avoid this problem we can create an alias to this method.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*nt3_IpulyRBgtGttEBkNwQ.png" /></figure><h4>Mapper as a Generated Function</h4><p>This variant is a combination of the two previous. We use a generated mapper that implements the Mapper interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*1Qi2f8r9IFCG3TpsK3tMhw.png" /></figure><p>The mapper is a MapStruct interface that extends the BaseMapper interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*DCOT8EPfYs9qnzY4uzROvg.png" /></figure><p>We called the interface BaseMapper to avoid conflict with Mapper annotation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*nBmx6Y-mLnb3_u1aazIFBg.png" /></figure><p>This solution has the same properties as the previous one, but the mapping of a similar structure becomes automatic.</p><h4>Mapper as an object-oriented DSL</h4><p>This version is one of the two best fluent API for the mapper. The DSL is implemented using the methods chaining.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*c2ESh419Y72whiB32rfsSg.png" /></figure><p>The map is a static overloaded method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*XfzAYtFPRKWTZI2VYvErTg.png" /></figure><p>The main advantages of this approach are the fluent API and the auto-completion (compared to the next version). The main disadvantage is verbosity.</p><h4>Mapper as a functional DSL</h4><p>Except for the first version (mapper as a static method), all the others are object-oriented or hybrid solutions. In the rest of this post, we will show more functional and fluent API.</p><p>The following version creates a micro-DSL for mapper based on function callback. The mapping is expressed in the natural language style. If we remove the parentheses, the map function call becomes “<strong>map buyer to customer”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*-lOGwnU39UFnQzsYFo4Cow.png" /></figure><p>Instead of creating the Function using a static method, we can do it with a static field. In this case, we use the point-free functional notation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*YWijIxlMFA_cDicuPtIe7Q.png" /></figure><p>The micro-DSL is defined using static methods. Each method takes as second argument a lambda:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*rQXL6eCwLoNp5LAO8oiMJA.png" /></figure><p>This is a nice DSL oriented solution. But it’s more verbose than some of the other mapper variants. In the first functional DSL version, we create the mapper using a higher-order function. And we should define two functions one for <strong>toCustomer</strong> and the other for <strong>toCustomers</strong>. Compared to the OO DSL mapper, we lose the auto-completion.</p><h4>DTO as Mapper</h4><p>The previous versions are based on static methods and dedicated mapper classes. In this variant, we present a different approach. The role of a mapper is played by the source object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*_B4crzg6BGP-_12RPej9iQ.png" /></figure><p>The DTO object becomes the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*dRmH_gtPAGFKhmq8UsMGQA.png" /></figure><p>The second variant of this approach is when the target object contains the mapping logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*g7zko2NdhvgW78GclfQaFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*1vWfEzcrbo8UryZ7kkvWQw.png" /></figure><p>We can also use a static factory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*xQeCZmWkVqWlSPBHuXL_ew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*0wrE_FcDmYoH-bYU9XGpmQ.png" /></figure><p>A third alternative is to do the mapping inside the getters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*9TK4Df2ZmxyvPisKppuDQA.png" /></figure><p>The advantage of the DTO as a mapper is the code simplicity. There are fewer classes and the API is fluent.</p><p>The disadvantages are the eventual violation of the single responsibility principle, the redundant code when mapping collections and the limited scalability when mapping complex objects. The DTO can be part of a third-party library or a generated code so we can’t adopt this strategy in this case.</p><h4>Conclusion</h4><p>Choosing a technique among the previous ones <em>can be</em> a matter of taste.</p><ul><li>If you are a fan of the clean code you will choose the beautiful, elegant and fluent API.</li><li>If you are a fan of the object-oriented style, you will choose one of the object-oriented variants.</li><li>If you are a fan of the functional style, you will choose one of the functional variants.</li><li>If you prioritize the simplicity and like to make trade-offs, you can choose the DTO variant and eventually sacrifice the SRP.</li></ul><p>But, I think that there are some criteria that can make the choice more objective:</p><ul><li>First, if a good part of the mapping is between the same or similar structure, it’s a good choice to use a generative approach.</li><li>Second, if you map many collections, you should choose an approach that respects the DRY principle.</li><li>Third, if you have a complex mapping, you choose a scalable approach (for example use a dedicated class to each mapping).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7527827ac98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Break a Cyclic Dependency between ES6 modules]]></title>
            <link>https://medium.com/angular-in-depth/how-to-break-a-cyclic-dependency-between-es6-modules-fd8ede198596?source=rss-22ede26bdbb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd8ede198596</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gara Mohamed]]></dc:creator>
            <pubDate>Wed, 10 Apr 2019 20:34:57 GMT</pubDate>
            <atom:updated>2020-04-29T21:12:37.571Z</atom:updated>
            <content:encoded><![CDATA[<p>Based on Typescript examples</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WAPNJCjMBrJPTbM5" /><figcaption>Photo by <a href="https://unsplash.com/@tine999?utm_source=medium&amp;utm_medium=referral">Tine Ivanič</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*YUZgX2IGGWHgb6H6.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><h3>Introduction</h3><p>One of the rare books fully dedicated to modularity patterns is <a href="https://www.oreilly.com/library/view/java-application-architecture/9780132874779/">Java Application Architecture: <strong>Modularity Patterns with Examples</strong> Using OSGi</a> written by <em>Kirk Knoernschild</em>. Among the important sections in this book is the chapter <strong>Acyclic Relationships</strong> which explains three techniques to break cyclic dependencies to make the dependency structure a <strong>Directed Acyclic Graph</strong> (DAG) as required by the <a href="https://en.wikipedia.org/wiki/Acyclic_dependencies_principle"><strong>Acyclic Dependencies Principle</strong> (<strong>ADP</strong>)</a>.</p><p>In this article, we apply these three techniques to ES6 modules. So, let’s start by introducing the example on which we will carry out the techniques.</p><h3>Cyclic Dependency Example</h3><p>In this section, we present the starting code that will be refactored in the following sections. There are <strong>two cycle types </strong>between modules: <strong>direct</strong> and <strong>indirect</strong>. Our example shows just the first type. The source code of the different versions is available <a href="https://stackblitz.com/edit/the-techniques-to-break-a-cyclic-dependency-between-es6-modules">here</a>.</p><p>In our original codebase, we have two modules:</p><ul><li>An order module containing an Order class</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/920b387a35ba779881dfcc705a062e63/href">https://medium.com/media/920b387a35ba779881dfcc705a062e63/href</a></iframe><ul><li>A customer module containing a Customer class</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1d71b58afd09d59be99bbb30e8cb2ad/href">https://medium.com/media/a1d71b58afd09d59be99bbb30e8cb2ad/href</a></iframe><p>In the two modules, we have two root concepts:</p><ul><li><em>Customer</em></li><li><em>Order</em></li></ul><p>and we have two behaviors associated with them:</p><ul><li><em>calculate customer discount based on customer orders.</em></li><li><em>calculate order discount based on customer discount.</em></li></ul><p>The two modules customer.ts and order.ts depend on each other. So, the dependency graph is a cyclic one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*lnfeT65hdo3hgyuXeA-LnA.png" /><figcaption>Cyclic dependency</figcaption></figure><p>Let’s break this cycle.</p><h3>Breaking Cyclic Dependency Techniques</h3><p>The most important techniques to break dependency cycles are:</p><ul><li>Dependency Inversion (aka. Callback)</li><li>Escalation</li><li>Demotion</li></ul><p>In this section, we cover the three techniques and also a more basic one: Merging. After that, we will try to draw a classification tree of all the strategies.</p><h4>Dependency Inversion (aka <strong>Callback</strong>)</h4><p>To remove the cycle using DI, we remove one direction of the two dependencies and harden the other one. To do that we should use an abstraction: in the order module, we add the <strong>DiscountCalculator</strong><em> </em>interface<em>.</em> Thus, the Order class depends on this new type and the order module no longer depends on the customer module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36fb33c38151c3c27db9f9657e4b9683/href">https://medium.com/media/36fb33c38151c3c27db9f9657e4b9683/href</a></iframe><p>The customer class is still responsible for calculating the discount, but this time it implements this behavior as a DiscountCalculator class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c02ac2fde2b3d9bc50cd47df3142cc7c/href">https://medium.com/media/c02ac2fde2b3d9bc50cd47df3142cc7c/href</a></iframe><p>The dependency graph becomes now a DAG:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*3idNXa2IAGCb1AbaP8vrOA.png" /></figure><p>The dependency is now unidirectional and the cycle is removed.</p><h4>Escalation</h4><p>With the first technique, to remove the cycle we just edited the dependencies of a single module. In the next two techniques (escalation and demotion), we will delegate the discount calculation to a new module and we will introduce two more dependencies to/from the new module.</p><p>The customer calculates the discount based on its orders.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b11a4f3a0d967d5df109811a53db66c/href">https://medium.com/media/5b11a4f3a0d967d5df109811a53db66c/href</a></iframe><p>And the Order just stores the raw amount. It’s no longer responsible for calculating its discounted amount.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db1862d8b115231c80e37573e4da1788/href">https://medium.com/media/db1862d8b115231c80e37573e4da1788/href</a></iframe><p>It’s now the role of the OrderDiscounter to calculate the discounted amount.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/604381a9d1ccc31e51c0f2bf051606bb/href">https://medium.com/media/604381a9d1ccc31e51c0f2bf051606bb/href</a></iframe><p>The new dependency graph becomes the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*LkmFtSMKBMz_G9rj2cjscQ.png" /><figcaption>Escalation</figcaption></figure><p>The dependency graph becomes also a DAG, but with a new module and two new arrows.</p><h4>Demotion</h4><p>As the escalation, to break the cycle demotion add a new module but with two ingoing dependencies. The new module contains the new class OrderDiscount:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e43085bb856a47301ce89aac6753553f/href">https://medium.com/media/e43085bb856a47301ce89aac6753553f/href</a></iframe><p>The Order class uses the OrderDiscount to calculate its discountedAmount:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/063de419b2081fc489b8d47edb847052/href">https://medium.com/media/063de419b2081fc489b8d47edb847052/href</a></iframe><p>The customer is responsible for creating the OrderDiscount instance that will be passed to the Order.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7135cf35db63b105038d7f1369be4ad/href">https://medium.com/media/c7135cf35db63b105038d7f1369be4ad/href</a></iframe><p>The new dependency graph becomes the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*qA0TTCXLx03z-WUEgNi9lw.png" /><figcaption>Demotion</figcaption></figure><p>Like the escalation graph, the demotion’s dependency graph becomes also a DAG with a new module and two new arrows. But, this time the direction of the arrow is inverted.</p><h4>Merge modules</h4><p>The other way to break the dependency cycle in our example is to merge the two modules in a single one. This is a simple strategy but it is not the best one when the cohesion between the two modules is low.</p><p>We should also note that by merging our two modules we remove the cycle at the modules level but it stays present at the classes level. If we want to break the cycle at the classes level we can use the same techniques.</p><h4>Taxonomy</h4><p>After showing the cyclic dependency breaking strategies, let’s draw a taxonomy diagram as a summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*v2vlwIAeHXutG0wZveR7bw.png" /></figure><p>Expect the remove the two modules strategy, we already discussed the other strategies. So, we don’t repeat our self and we go straight to the conclusion.</p><h3>Conclusion</h3><p>In his book, Kirk Knoernschild carried the patterns from the C++ to the Java world. In this post, we’ve tried to do the same thing by promoting the terminology to the Javascript and Typescript world. The Java world is more mature and rich than the front-end ecosystem. So, it should be more and more inspired by the backend experience.</p><p>Before we finish this article, I would like to note two things:</p><ul><li>We presented each technique in the context of breaking a direct cycle but they can also be used to break indirect cycles.</li><li>Dependency cycle isn’t absolute evil. For example, in some cases, the cycle is allowed if it is local to a layer. But, the cycle shouldn’t exist between release units.</li></ul><p>Finally, you can find Kirk’s code that inspired this post on his GitHub <a href="https://github.com/pragkirk/poma/tree/master/acyclicrelationships">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd8ede198596" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/how-to-break-a-cyclic-dependency-between-es6-modules-fd8ede198596">How to Break a Cyclic Dependency between ES6 modules</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain-Driven Design: The Identifier Type Pattern]]></title>
            <link>https://medium.com/@gara.mohamed/domain-driven-design-the-identifier-type-pattern-d86fd3c128b3?source=rss-22ede26bdbb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d86fd3c128b3</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Gara Mohamed]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 13:04:03 GMT</pubDate>
            <atom:updated>2019-03-27T21:38:55.816Z</atom:updated>
            <content:encoded><![CDATA[<p>A Typescript version</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k7n8CDCWms2eFVXn" /><figcaption>Photo by <a href="https://unsplash.com/@victordax?utm_source=medium&amp;utm_medium=referral">Victor Dementiev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>The key difference between an <strong>Entity</strong> and a <strong>Value Object</strong> is the identity. Entities contains an intrinsic identifier but Value Objects<strong> </strong>have no identity.</p><p>An entity’s identifier can be described using one of the following techniques:</p><ul><li>Primitive type</li><li>Special type defined as a value object or an alias type</li></ul><p>The Domain-Driven Design mindset has largely promoted the second technique. So, let’s see some of its advantages.</p><h3>Primitive Identifier vs. Type Identifier</h3><p>Before speaking of the advantages of a dedicated id type, we first introduce the codebase that will be used in our analysis. Our example is very straightforward. We have two modules:</p><ul><li>A customer module containing a Customer class.</li><li>An order module containing an Order class with a refrence to a customer.</li></ul><h4>Version 1</h4><p>In the first version, we use a string as the customer id type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d6048e262209417eb5fe3cf6423cea9/href">https://medium.com/media/7d6048e262209417eb5fe3cf6423cea9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e22ce80568619b45805c48a52fbdfd2a/href">https://medium.com/media/e22ce80568619b45805c48a52fbdfd2a/href</a></iframe><h4>Version 2</h4><p>In the second version, we use an alias type CustomerId as the customer id type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/451ee60a5772c2a6862cf1fb81d4e0cf/href">https://medium.com/media/451ee60a5772c2a6862cf1fb81d4e0cf/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e98a787af6afdfad5d69abe1b7d2460a/href">https://medium.com/media/e98a787af6afdfad5d69abe1b7d2460a/href</a></iframe><p>After, introducing our example, let’s start analyzing it.</p><h3>Why we prefer the dedicated type pattern?</h3><p>In this section, we will try to enumerate some advantages of creating a special type for entities identifiers.</p><h4>Avoid the classic bug</h4><p>In the first version, we spot <strong>the primitive obsession code smell</strong>. This code smell favors the occurance of the following classic bug.</p><p>Suppose that we have this function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54e181dfe2cc7d1354525874413bad37/href">https://medium.com/media/54e181dfe2cc7d1354525874413bad37/href</a></iframe><p>If we do the following mistake (we inverse the parameters order), the compiler would not help us and the problem will be unremarked at compile time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bb83b7fbda3723ba51e3b529226d306/href">https://medium.com/media/5bb83b7fbda3723ba51e3b529226d306/href</a></iframe><h4>Allow function/method overloading</h4><p>In this section, we will try to use the previous function <em>findOrdersBy</em> with a single parameter. So, if we want to find orders for a customer using a primitive id, we should define the following method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6eb4c2611b47d759f561be9ead9e371/href">https://medium.com/media/a6eb4c2611b47d759f561be9ead9e371/href</a></iframe><p>Now, if we want to overload the method to fetch orders by creator, we can’t do it as the type of the customerId and creatorId have the same type. We have two options: we either use two different functions (findOrdersByCustomer and findOrdersByCreator) or use overloads:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4402fd2af021efa532efbc8fc59c06a/href">https://medium.com/media/c4402fd2af021efa532efbc8fc59c06a/href</a></iframe><p>So, the special id type allow to write a less verbose and elegant code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a8e32560aebcf4436a124526cf73734/href">https://medium.com/media/4a8e32560aebcf4436a124526cf73734/href</a></iframe><h4>Make logical dependencies physical</h4><p>In the first version, the order class has a customerId. The customer has also the same information. So, there is a logical relationship between the customer and order classes but the two classes are statically independent.</p><p>In his famous book <strong>Clean Code</strong>, <strong>Uncle Bob</strong> states that:</p><blockquote>If one module depends upon another, that dependency should be physical, not just logical.</blockquote><p>Our second version materializes the logical dependency by creating a physical one. So, if we change the type of the customer id, the compiler will stop us if we forget to change the customerId type in the Order class. However, in the first version, we didn’t have this security.</p><h4>Validate id</h4><p>When using a value object, we can be sure that the id value is valid by adding a guard condition in the constructor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0dd623a2b9d341c3b13d4f82868247b/href">https://medium.com/media/d0dd623a2b9d341c3b13d4f82868247b/href</a></iframe><p>Using this approach, we are sure that all the id instances are valid.</p><h4>Integrate applications</h4><p>Generally, an entreprise application doesn’t live isolited from other applications. So, the same Entity can transite between the different applications. Sometimes the same entity identifier has a different format and representation in the different applications.</p><p>For example, our application can communicate with two other applications A and B:</p><ul><li>In our application, the customer id is stored as a string.</li><li>In A, the id is stored as a number.</li><li>In B, the id is stored as a string of 15 digits with leading zeros.</li></ul><p>Using a value object, we can control the format conversion in a single place independently of the number of occurence of the customer id in the integration APIs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74564da97dc29e8d9ba427f3e09dfd0e/href">https://medium.com/media/74564da97dc29e8d9ba427f3e09dfd0e/href</a></iframe><p>If the application A or B change its customer id representation, we will have a single place to edit in our code.</p><h3>Conclusion</h3><p>I’ve seen this pattern more in the Java world but less in the Typescript one. So, I’ve wrote this article to promote this pattern in the front-end projects.</p><p>As we have seen this pattern has many advantages. Its main disadvantage is that we have to make a navigation to access to the raw value, but this is not a real problem as we don’t need to do it if we use only the value wrapper.</p><h4>My other front-end articles:</h4><ul><li><a href="https://medium.com/@gara.mohamed/angular-vs-react-part-0-component-creation-evolution-and-refactoring-perspective-c2c6b6471828">Angular vs. React (Part 0): component creation, evolution and refactoring perspective</a></li><li><a href="https://blog.angularindepth.com/does-angular-applications-become-stable-after-a-single-change-detection-cycle-40b99efa9510">Do Angular applications become stable after a single change detection cycle?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d86fd3c128b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular vs. React (Part 2): component wrapping and delegation]]></title>
            <link>https://medium.com/@gara.mohamed/angular-vs-react-part-2-component-wrapping-and-delegation-e91c707b382c?source=rss-22ede26bdbb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e91c707b382c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Gara Mohamed]]></dc:creator>
            <pubDate>Mon, 29 Oct 2018 08:25:26 GMT</pubDate>
            <atom:updated>2018-10-29T09:34:49.202Z</atom:updated>
            <content:encoded><![CDATA[<p>Comparing React and Angular component wrapping capability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sTAHw7hl2Jsf_v0W" /><figcaption>“plate of vegetable salads” by <a href="https://unsplash.com/@_ahungryblonde_?utm_source=medium&amp;utm_medium=referral">Sara Dubler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>In <a href="https://medium.com/@gara.mohamed/angular-vs-react-part-1-style-abstraction-and-encapsulation-f55b336e0eaa">the first article</a> of this series, we talked about wrapping styles in components. In this second article, we continue our journey with the wrapping technique, but this time we talk about wrapping a component in an other one and establishing a delegation relationship between the two components. This will add more challenges.</p><p>The source code of the examples of the whole series is available <a href="https://github.com/mohamed-gara/angular-vs-react">here</a>.</p><p>The full introduction to the series is <a href="https://link.medium.com/lhmmEXfriR">here</a>.</p><p>Let’s start by revisiting the advantages of wrapping, but this time for components.</p><h4>Why we need component wrapping?</h4><p>In a real application containing hundreds or thousands of components, it’s a best practice to:</p><ul><li>Encapsulate the redundant code in reusable components.</li><li>Wrap third party components in custom components.</li></ul><p>This will provide at least the following qualities:</p><ul><li>Ensure coherence between different parts of the application.</li><li>Simplify development and avoid copy/past.</li><li>Reduce the bundle size by removing duplication and reducing code size.</li><li>Decouple the application from third party components and make it more easy to switch from one component to an other one.</li></ul><p>Let’s jump to the case study.</p><h4>Case study</h4><p>Our case study is simple but illustrative. Our goal is to show the following content:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*wIzgUUOsVnWT8HIL73V-2g.png" /><figcaption>two bootstrap progress bars</figcaption></figure><p>We have two progress bars representing the progress level of two projects. The bars are bootstrap progress component and each one is preceded by a label describing the value.</p><p>So, let’s start with implementing the Angular version.</p><h4>Angular implementation</h4><p>In our first Angular version, we use the <a href="https://ng-bootstrap.github.io/#/components/progressbar">ng-bootstrap progress bar</a> component directly in our code. The code showing the two progress bars is the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96c65c022e85b31d9e6ae282dbce6a22/href">https://medium.com/media/96c65c022e85b31d9e6ae282dbce6a22/href</a></iframe><p>The code is verbose, redundant and high coupled to the ng-bootstrap component. So, we will solve these problems by creating a component that wrap the the redundant html elements and delegate to the ngb-progressbar component.</p><p>The template of the refactored version is the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6782fb928d52fe3b828ebb7c98919c6/href">https://medium.com/media/f6782fb928d52fe3b828ebb7c98919c6/href</a></iframe><p>The template is now less verbose and more simple to change. The application bundle will be smaller and the application style will be consistent. So, the result is so good, but let’s dive in the implementation details of the app-progress-bar component.</p><p>To make our app-progress-bar component as generic as the ngb-progressbar component and to expose all the latest potential to the former users, we should do two things:</p><ul><li>First, we should copy all the inputs and outputs defined in <a href="https://github.com/ng-bootstrap/ng-bootstrap/blob/aca4cbe16f20c4f381464029d37759f9850bf24b/src/progressbar/progressbar.ts#L21">ngb-progressbar component class</a> into app-progress-bar component class. We should also take back any <strong>default value</strong>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d5eca7dfedb0214802af6ced13896df/href">https://medium.com/media/1d5eca7dfedb0214802af6ced13896df/href</a></iframe><ul><li>Then, in the template, we should delegate each input from <strong>app-progress-bar</strong> to <strong>ngb-progressbar</strong>, and emit each output from <strong>ngb-progressbar</strong> to <strong>app-progress-bar</strong>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d475fc85161070d62e35fe220296a4c1/href">https://medium.com/media/d475fc85161070d62e35fe220296a4c1/href</a></iframe><p>As we see, the delegation is too easy to do and can be automated for all the inputs except one. In the case of the max input, if we write <strong>[max]=”max”</strong>, the result will be the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*iBOlSUd5paJPVOuB5zpTqg.png" /><figcaption>The progress bars don’t show the colored bar</figcaption></figure><p>If the user of the <strong>app-progress-bar</strong> don’t define a value for the max input, we will pass undefined to the <strong>ngb-progressbar</strong> max input which will erase the default value and rise the bug. So, to resolve the problem, we should define a default max value.</p><p>In our case, we haven’t an output on the ng-bootstrap component, but if one day we will have a <em>valueChange</em> output:</p><ul><li>First, we should declare an output in <strong>app-progress-bar</strong> component class:</li></ul><p><em>@Output() valueChange = new EventEmitter&lt;number&gt;();</em></p><ul><li>Second, in the template, we should emit the value like this</li></ul><p><em>&lt;ngb-progressbar</em><strong><em> </em></strong><em>(valueChange)=”valueChange.emit($event)” …&gt;</em></p><blockquote>Note: In this post, we only compare the delegation mechanisms that exist in both Angular and React. However, there are other types of delegation between components that exist only in Angular (e.g.: delegation between components associated to a FormControl). In this article, we ignore them as they are relatively complex and hey need an article in its own right.</blockquote><p>Now, we will repeat the same thing but in a React application.</p><h4>React implementation</h4><p>Our journey with the React will be shorter than the Angular one. In the previous section we’ve detailed all the required steps to implement our wrapping component. So, in this section we will quickly show the equivalent code for each step with a brief description.</p><p>As with the first Angular version, to implement our case study, we start by using <a href="http://reactstrap.github.io/components/progress/">the reactstrap progress bar component</a> directly in our code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/109f7b6f284c861fcff8a3b2fde635f3/href">https://medium.com/media/109f7b6f284c861fcff8a3b2fde635f3/href</a></iframe><p>In the refactored version, the div bloc of each progress bar will be replaced by an instance of our <strong>LabeledProgress</strong> new component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6314cc4f5f267bba9fb243882dfbaf4b/href">https://medium.com/media/6314cc4f5f267bba9fb243882dfbaf4b/href</a></iframe><p>The <strong>LabeledProgress</strong> is a simple functional component wrapping the <strong>reactstrap</strong> <strong>Progress</strong> component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ff2cdeff86b0e21cf204bc14c40e259/href">https://medium.com/media/9ff2cdeff86b0e21cf204bc14c40e259/href</a></iframe><p>As shown above, to pass the props from the wrapper component to the wrapped component, we use two magic operators:</p><ul><li>First, we use the rest operator to extract the props to delegate to the inner component.</li><li>Second, we use the spread operator to pass the extracted props to the inner component.</li></ul><p>That’s all. We don’t have to worry about the default values because if the user of the outer component don’t specify a property value, we will not pass an undefined to the inner component. So, we will not accidentally override the default values.</p><p>The last thing to do, is to define the propTypes for our LabeledProgress component :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/515f101685fca395eca4f3207f78c888/href">https://medium.com/media/515f101685fca395eca4f3207f78c888/href</a></iframe><p>Using the spread operator, the Progress propTypes are reused in the definition of the LabeledProgress propTypes.</p><p>All rights. We can now make our conclusion by comparing the two results.</p><h4>Conclusion</h4><p>Wrapping components and establishing a delegation relationship between a wrapper/outer/parent and a wrapped/inner/child component can be done in both Angular and React. However, the implementation details vary between the two component engines.</p><p><strong>Angular</strong>:</p><ul><li>We should write <strong>a specific code</strong> but we can <strong>automate its generation</strong> using a dedicated tool.</li><li>We are forced to <strong>duplicate</strong> the inner component code into the outer component code.</li><li>We should be very careful with <strong>the default values</strong> passed to the wrapped component inputs.</li><li>When the wrapped component change its inputs and/or its outputs we should <strong>manually update</strong> the wrapper component.</li></ul><p><strong>React:</strong></p><ul><li>We use <strong>a generic code</strong> to wire the two components.</li><li>We don’t have to write a specific code to connect both of them.</li><li>As <strong>the views</strong> are written using the <strong>JSX</strong>, they are <strong>inherently dynamic</strong>.</li><li>When the wrapped component change its inputs and/or its outputs, the wrapper component isn’t impacted. Thereby,<strong> </strong>the component will be open to extension and closed to modification — <strong>The Open Closed SOLID Principle</strong>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e91c707b382c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>