<?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 Aleksei  Safonov on Medium]]></title>
        <description><![CDATA[Stories by Aleksei  Safonov on Medium]]></description>
        <link>https://medium.com/@safonovb2c?source=rss-7ad784fd0620------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Nk-3_p-i9X-ZAEWXgvhHEw.jpeg</url>
            <title>Stories by Aleksei  Safonov on Medium</title>
            <link>https://medium.com/@safonovb2c?source=rss-7ad784fd0620------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 05:29:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@safonovb2c/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[Understanding GRASP]]></title>
            <link>https://medium.com/@safonovb2c/understanding-grasp-16d4f01fb78c?source=rss-7ad784fd0620------2</link>
            <guid isPermaLink="false">https://medium.com/p/16d4f01fb78c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[grasp]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Aleksei  Safonov]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 20:08:15 GMT</pubDate>
            <atom:updated>2024-08-06T20:32:12.219Z</atom:updated>
            <content:encoded><![CDATA[<p>This series of articles introduces General Responsibility Assignment Software Patterns (GRASP) and explores their relationship with other important design concepts, such as SOLID, Domain-Driven Design, and other object-oriented software design principles.</p><h4>What is GRASP?</h4><p>GRASP is a set of software design principles that helps <em>distribute responsibilities among objects</em> in object-oriented systems. The core idea is to <em>allocate responsibilities between components</em> in a way that makes system easily maintainable, extensible, and modifiable, while also making the application code more understandable. GRASP principles are especially useful when designing systems with a large number of components.</p><p>A <em>component </em>in this context is any part of the system that performs a specific function or provides a particular service. Components can represent various levels of abstraction, including classes, objects, libraries, modules, microservices, and other structural elements.</p><p>In programming, <em>responsibility </em>is expressed as the duty to perform a specific actions or to store data and to be “<em>the single source of truth</em>”. It is necessary to separate behavior (actions) — doing something itself, creating an object, processing data, performing calculations — and data (knowledge) — public object data, references to related objects, etc. Let’s consider an example:</p><pre>public class Customer implements Entity, AggregateRoot {<br><br>    private final UUID id; // Knowledge<br>    private final String email; // Knowledge<br>    private final String name; // Knowledge<br>    private final List&lt;Order&gt; orders; // Knowledge<br><br>    // Behavior<br>    public DomainEvent addOrder(Order order) {<br>        // Responsibilities - initiating <br>        // and coordinating actions with child objects<br>        // validation logic<br>        this.orders.add(order);<br>        return new OrderAddedEvent(order);<br>    }<br><br>    // Behavior<br>    public DomainEvent removeOrder(UUID orderId) {<br>        Order order = this.orders.stream()<br>            .filter(x -&gt; x.getId().equals(orderId))<br>            .findFirst()<br>            .orElse(null);<br><br>        // Responsibilities - initiating <br>        // and coordinating actions with child objects<br>        if (order != null) {<br>            order.remove();<br>            return new OrderRemovedEvent(order);<br>        }<br>    }<br><br>    // Behavior<br>    public double getOrdersTotal() {<br>        return this.orders.stream()<br>                  .mapToDouble(Order::getValue)<br>                  .sum();<br>    }<br>}</pre><p>Responsibilities of the Customer:</p><ul><li>Store knowledge about itself (id, email, name, orders)</li><li>Act as the single source of truth for its data about the Customer domain.</li><li>Initiate and coordinate actions like adding or removing Orders.</li><li>Validate data and actions within the domain (e.g., check if order exists before removing)</li><li>Perform calculations, such as computing the total value of all orders.</li></ul><h4>GRASP in System Design</h4><p>GRASP principles are also invaluable for distributing responsibilities effectively at a high level within a system. Applying these principles leads reduced coupling between components and more efficient system architecture. Ultimately, GRASP helps to build systems that can evolve with changing requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8LlC1BQjQ5OlfiE36c5nPg.png" /></figure><p>Arrows indicate the interaction patterns, showing how the Customer class interacts with domain events and the uniqueness checker, coordinating actions related to orders.</p><ul><li><strong>Customer</strong>: Responsible for initiating and coordinating actions with other objects.</li><li><strong>Order</strong>: Represents the orders managed by the customer.</li><li><strong>Domain Events</strong>: (CustomerRegisteredEvent and OrderAddedEvent) are triggered by actions within the system.</li><li><strong>ICustomerUniquenessChecker</strong>: Ensures that a customer is unique.</li></ul><p>GRASP includes the following principles:</p><ul><li><a href="https://medium.com/@safonovb2c/low-coupling-in-software-design-1818bb93e14f">Low Coupling</a></li><li><a href="https://medium.com/@safonovb2c/high-cohesion-in-software-design-685784471c39">High Cohesion</a></li><li><a href="https://medium.com/@safonovb2c/indirection-in-software-design-aba4fe3782b2">Indirection</a></li><li><a href="https://medium.com/@safonovb2c/protected-variations-in-software-design-04e9fb65ddba">Protected Variations</a></li><li><a href="https://medium.com/@safonovb2c/information-expert-in-software-design-13d39feae314">Information Expert</a></li><li><a href="https://medium.com/@safonovb2c/creator-principle-in-software-design-d8b4ee652244">Creator</a></li><li><a href="https://medium.com/@safonovb2c/controller-principle-in-software-design-928ce73d5e91">Controller</a></li><li><a href="https://medium.com/@safonovb2c/polymorphism-in-software-design-1237b16a3088">Polymorphism</a></li><li><a href="https://medium.com/@safonovb2c/pure-fabrication-in-software-design-bd4c7ce34bf7">Pure Fabrication</a></li></ul><p>Think of GRASP as a skilled craftsperson’s toolbox. The tools themselves can’t build a house, but they provide resources to construct it efficiently and with high quality. Adapting GRASP principles doesn’t automatically makes everything “SOLID” but it serves as a powerful tool to simplify the process.</p><p>All principles are interconnected and support each other. For a deeper dive into each principle explore the linked articles in the provided list.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16d4f01fb78c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pure Fabrication in Software Design]]></title>
            <link>https://medium.com/@safonovb2c/pure-fabrication-in-software-design-bd4c7ce34bf7?source=rss-7ad784fd0620------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd4c7ce34bf7</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[grasp]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Aleksei  Safonov]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 20:05:05 GMT</pubDate>
            <atom:updated>2024-08-06T20:16:38.318Z</atom:updated>
            <content:encoded><![CDATA[<h4>Pure Fiction</h4><p>Previous article: <a href="https://medium.com/@safonovb2c/polymorphism-in-software-design-1237b16a3088">Polymorphism</a> <em>← </em>|| → First article: <a href="https://medium.com/@safonovb2c/understanding-grasp-16d4f01fb78c">Understanding GRASP</a></p><p><strong>Pure Fabrication </strong>refers to a component that supports high-level design decisions, but has no connection to the problem domain.</p><p>R<em>esponsibility </em>of such element<em> </em>is to manage technical aspects of the application or serve as a connecting element between other components. By isolating and encapsulating elements that don’t naturally belong with the core business logic, Pure Fabrication helps maintain a <strong>clean separation</strong> between different parts of the system.</p><p><strong>Software design patterns</strong> often focus on creating abstractions rather than mirroring real-world entities. Let’s explore some common examples:</p><ul><li><strong>Facade</strong>: The Facade pattern simplifies interactions with complex subsystems by providing a unified interface. This can be seen as a form of Pure Fabrication because it doesn’t directly represent any specific domain object but instead acts as a layer that abstracts the complexities of the underlying systems.</li><li><strong>Builder</strong>: Is not a natural representation of the domain but is used to construct complex objects step by step.</li><li><strong>Proxy</strong>: Acts as a middleman between a client and a target object. It does not represent any concept in the problem domain but instead manages access to the real object.</li><li><strong>Repository:</strong> Abstracts data access, providing a cleaner interface for data operations without exposing details of data storage. It serves as a mediator that encapsulates data storage details</li></ul><p>In <strong>Domain-Driven Design</strong>, Pure Fabrication involves creating utility or infrastructure components. These components are typically designed to enhance interactions between system elements or to support non-functional requirements like security and logging.</p><p>Let’s consider an example: a library management system. A proper use of Pure Fabrication might involve creating a DatabaseManagerclass to handle low-level database interactions (like querying, updating, etc.), thus keeping these responsibilities outside of domain.</p><h4>Misuse of Pure Fabrication</h4><p>Imagine that your colleague had created a class called BookPrinter with a method printBookDetails(Book book). The logic inside printBookDetails does not just print the details. It also includes complex calculations, formatting rules, and logic to retrieve additional data from the database.</p><pre>// Domain entity<br>public class Book {<br>   private String title;<br>   private String author;<br>   private int yearPublished;<br>   // Some domain logic <br>}<br><br>// Pure Fabrication for printing logic<br>public class BookPrinter {<br><br>    private DatabaseManager dataBaseManager;<br><br>    public String printBookDetails(Book book) {<br>       // Business logic <br>       double price = calculatePrice(book);<br>       // Data retrieval <br>       String additionalData = fetchAdditionalData(book);<br>       return formatDetails(book, price, additionalData); <br>   }<br><br>    private double calculatePrice(Book book) {<br>       // Complex price calculation logic <br>       return 13.37;<br>     }<br>  <br>    private String formatDetails(Book book, double price, String data) {<br>       return book.toString() + &quot;price &quot; + price + &quot; info &quot; + data;<br>    }<br>  <br>    private String fetchAdditionalData(Book book) {<br>       // Simulate database retrieval <br>       return dataBaseManager.getAdditionalData(book);<br>    }<br>}</pre><p>The implementation above raises several concerns:</p><ul><li>The BookPrinter class has taken <strong>more responsibilities than just printing </strong>details. It performs calculations and data retrieval, which should be handled elsewhere.</li><li>The BookPrinter class depends on various other components, including database access. This creates unnecessary coupling across different layers of the system.</li></ul><h4>The Solution</h4><p>In some cases, it might make sense to put certain logic within the domain class itself, especially if it is directly related to the internal properties of the class. However, if the logic involves multiple responsibilities, like handling business rules and external interactions (e.g., database access), it can lead to a bloated domain class. Let&#39;s consider a balanced approach to determine what belongs in the Book class and what should be handled by an application service class.</p><pre>// Domain entity<br>public class Book {<br>    private String title;<br>    private String author;<br>    private int yearPublished;<br>    private BigDecimal price;<br>    // Some domain logic<br><br>    public double calculatePrice(Book book) {<br>        // Business logic for price calculation<br>        return price;<br>    }<br>}<br><br>// Application Logic<br>public class BookService {<br>    private DatabaseManager dataBaseManager;<br><br>    public String fetchAdditionalData(Book book) {<br>        // Simulate database retrieval from multiple sources<br>        var info = dataBaseManager.getAdditionalData(book);<br>        return dataBaseManager.getMoreAdditionalData(book) + info;<br>    }<br>}<br><br>// Pure Fabrication for printing<br>public class BookPrinter {<br>    private final BookService bookService;<br><br>    public String formatDetails(Book book) {<br>        var data = bookService.fetchAdditionalData(book);<br>        return book.toString() + &quot; price &quot; + book.getPrice() + &quot; info &quot; + data;<br>    }<br>}</pre><ul><li><strong>Domain Entity</strong>: The Book class now handles its intrinsic properties and business logic, such as calculating the price.</li><li><strong>Application Logic</strong>: The BookService class is responsible for data retrieval and other external interactions, such as database access.</li><li><strong>Pure Fabrication</strong>: The BookPrinter class now focuses solely on formatting and printing book details, using results from other classes without incorporating their responsibilities.</li></ul><p>As a result BookPrinter class is focused solely on formatting and printing book details. A different class (BookService) handles data retrieval prossess, while domain logic resides in the domain (e.g., Book).</p><h4>Points to consider</h4><ul><li>Extracting focused functionality into Pure Fabrication classes helps break down monolithic classes into smaller, more manageable units. Each Pure Fabrication implementation should assume <strong>a single, well-defined responsibility</strong>.</li><li>Leverage Pure Fabrication to allow for adding new features without modifying existing code.</li><li>Use specialized classes to <strong>avoid situations where subclasses violate expected behavior</strong> of their base classes.</li><li>Instead of burdening clients with large interfaces containing methods they don’t use, <strong>tailor interfaces to specific needs</strong>.</li></ul><p>Congratulations on making it this far! Now, armed with these principles and with a touch of common sense, you’re ready to build robust and maintainable systems.</p><p>Happy coding!</p><p>See a <a href="https://medium.com/@safonovb2c/understanding-grasp-16d4f01fb78c">full list of GRASP principles here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd4c7ce34bf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polymorphism in Software Design]]></title>
            <link>https://medium.com/@safonovb2c/polymorphism-in-software-design-1237b16a3088?source=rss-7ad784fd0620------2</link>
            <guid isPermaLink="false">https://medium.com/p/1237b16a3088</guid>
            <category><![CDATA[grasp]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Aleksei  Safonov]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 20:02:48 GMT</pubDate>
            <atom:updated>2024-08-06T20:44:22.949Z</atom:updated>
            <content:encoded><![CDATA[<h4>Is subtitle is a type of Title?</h4><p>Previous article: <a href="https://medium.com/@safonovb2c/controller-principle-in-software-design-928ce73d5e91">Controller</a> <em>← </em>|| → Next article: <a href="https://medium.com/@safonovb2c/pure-fabrication-in-software-design-bd4c7ce34bf7">Pure Fabrication</a></p><p><strong>Polymorphism</strong> is a fundamental concept that allows different objects of the same type be treated as objects of a common superclass.</p><p><em>Responsibility </em>of polymorphic component is to provide a way to perform a single action in different ways, allowing different objects to respond to the same message or method call.</p><p><strong>Advantages of using Polymorphism:</strong></p><ul><li>New objects simply need to follow the same contract. Client code can interact with an interface rather than a concrete implementation, making it easier to change or extend the system.</li><li>By using polymorphism, you can handle variations in behavior through different implementations of a common interface rather than modifying existing code.</li><li>Polymorphism can replace complex conditional logic. Instead of having multiple “if” statements to handle different types or behaviors, polymorphism allows different classes to implement the required behavior, and the use them based on the context.</li></ul><p>Polymorphism serves as a powerful tool for managing dependencies within a system. It enforces <strong>Low Coupling </strong>and a cleaner <strong>Separation of Concerns</strong> between components. For instance, an abstract class could provide a basic behavior for a particular task, while its subclasses handle the specific details.</p><p>Many <strong>software design patterns</strong> use Polymorphism as their basis:</p><ul><li><strong>Strategy</strong>: Polymorphism allows to use different strategies of the same type, changing them dynamically.</li><li><strong>Command</strong>: Turns actions into objects, making them parameterizable. Polymorphism allows command objects to implement a common interface and substitute for each other depending on the context.</li><li><strong>Template Method</strong>: Defines the skeleton of an algorithm, leaving some steps for implementation in subclasses. Then subclasses can implement these steps differently.</li></ul><p>In <strong>Domain-Driven Design</strong>, polymorphism is applied similarly to any other object-oriented approach: to implement class hierarchies, grouping objects with common properties and behavior.</p><p>For example, different types of transportation can be asked to “move,” and they will perform the action, each in its own unique way.</p><pre>// Transport<br>public interface Transport {<br>    void move();<br>}<br><br>public class Truck implements Transport {<br>    @Override<br>    public void move() {<br>        // Truck movement implementation<br>    }<br>}<br><br>public class Bicycle implements Transport {<br>    @Override<br>    public void move() {<br>        // Bicycle movement implementation<br>    }<br>}</pre><h4>Misuse of Polymorphism Principle</h4><p>Consider we add a new method loadCargo to Transport, which is not appropriate for all types of transport.</p><pre>// Transport<br>public interface Transport {<br>    // Misplaced method, not all transport types can load cargo<br>    void loadCargo(); <br>}<br><br>public class Truck implements Transport {<br>    //...<br>    @Override<br>    public void loadCargo() {<br>        // Truck-specific cargo loading implementation<br>    }<br>}<br><br>public class Bicycle implements Transport {<br>   // ...<br>    @Override<br>    public void loadCargo() {<br>        // Bicycles don&#39;t load cargo, irrelevant implementation<br>        throw new UnsupportedOperationException(&quot;Bicycles can&#39;t load cargo.&quot;);<br>    }<br>}</pre><p>In this design Bicycle is forced to implement the loadCargo method, even though it does not make sense to do so. This leads to unnecessary and confusing implementations.</p><h4>The Solution</h4><p>To resolve this issue, we can redesign the interface structure. By using multiple interfaces, we can <strong>Separate the Concerns</strong> of different transport types:</p><pre>// Transport<br>public interface Transport {<br>    void move();<br>}<br><br>// CargoTransport<br>public interface CargoLoader {<br>    void loadCargo();<br>}<br><br>public class Truck implements Transport, CargoLoader {<br>    @Override<br>    public void move() {<br>        // Truck movement implementation<br>    }<br><br>    @Override<br>    public void loadCargo() {<br>        // Truck-specific cargo loading implementation<br>    }<br>}<br><br>public class Bicycle implements Transport {<br>    @Override<br>    public void move() {<br>        // Bicycle movement implementation<br>    }<br>}<br><br>class Driver {<br>    void dirve(Transport transport) {<br>        // Work with transport <br>        transport.move();<br>    }<br>}<br><br>class Warehouse {<br>    void load(CargoLoader cargoLoader) {<br>        // Load the cargo<br>        cargoLoader.loadCargo();<br>    }<br>}</pre><p>Each class now has a <strong>Single Responsibility</strong>. Truck and Bicycle classes focus solely on their respective behaviors. Adding CargoLoader didn&#39;t alter existing Car and<strong> </strong>Bicycle<strong> </strong>implementations.</p><p>By splitting the Transport interface into Transport and CargoLoader, we <strong>ensure that classes implement methods relevant only to their functionality</strong>. Driver class depends on the Transport, while the Warehouse class depends on the CargoTransport.</p><h4>Points to Consider</h4><ul><li>Focus on defining clear interface contracts that represent expected common behavior.</li><li>Use polymorphism to reduce coupling between components.</li><li>Consider using composition when it provides a more flexible solution. This can be especially helpful when dealing with complex relationships between classes.</li><li>Think about how changes to one interface or implementation of polymorphic methods will affect other parts of the system. Will it require widespread code changes? Can you mitigate these impacts with careful design?</li><li>Don’t Overcomplicate. Polymorphism is a powerful tool, but it’s not always necessary. Sometimes, a simpler approach using conditional logic or other techniques might be more appropriate.</li></ul><p>Whats next?</p><p><em>Continue reading</em>: <a href="https://medium.com/@safonovb2c/pure-fabrication-in-software-design-bd4c7ce34bf7">Pure Fabrication in Software Design</a></p><p>See a <a href="https://medium.com/@safonovb2c/understanding-grasp-16d4f01fb78c">full list of GRASP principles here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1237b16a3088" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Controller Principle in Software Design]]></title>
            <link>https://medium.com/@safonovb2c/controller-principle-in-software-design-928ce73d5e91?source=rss-7ad784fd0620------2</link>
            <guid isPermaLink="false">https://medium.com/p/928ce73d5e91</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[grasp]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Aleksei  Safonov]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 20:00:15 GMT</pubDate>
            <atom:updated>2024-08-06T20:43:09.830Z</atom:updated>
            <content:encoded><![CDATA[<h4>Who is in charge?</h4><p><em>Previous article</em>: <a href="https://medium.com/@safonovb2c/creator-principle-in-software-design-d8b4ee652244">Creator</a> <em>← </em>|| → <em>Next article</em>: <a href="https://medium.com/@safonovb2c/polymorphism-in-software-design-1237b16a3088">Polymorphism</a></p><p><strong>Controller</strong> Principle states that a distinct component should be <em>responsible </em>for orchestrating the actions of other components within a system. It should handle requests and events and delegate tasks to the appropriate objects.</p><p>Controllers are particularly useful in complex systems where multiple objects need to interact. By centralizing the coordination logic, Controller <strong>helps to reduce coupling</strong><em> </em>between components.</p><p>Several <strong>software design patterns </strong>that leverage the Controller principle:</p><ul><li><strong>MVC:</strong> The Controller manages user input, updates the Model (data), and selects the appropriate View (presentation).</li><li><strong>Observer:</strong> The subject acts as a controller, notifying observers of changes without knowing their implementations.</li><li><strong>Chain of Responsibility:</strong> A controller-like mechanism delegates requests through a chain of handlers.</li><li><strong>Facade:</strong> A simplified interface that acts as a controller, managing interactions with complex underlying components.</li></ul><p>In <strong>Domain-Driven Design</strong>, the role of the Controller is to manage the flow of operations in application.</p><ul><li><strong>Application Coordination</strong>: Controller handles user input and maps it to domain operations, coordinates tasks, managing the sequence of interactions, ensuring that the domain logic remains decoupled from the UI and infrastructure logic.</li><li><strong>Transaction Management</strong>: Controllers often manage transactions, ensuring that multiple operations are executed within a single transactional context.</li><li><strong>Security and Validation</strong>: The Controller can enforce security policies and perform initial validation of input data before calling business logic.</li></ul><h4>Misuse of Controller</h4><p>To better understand the importance of adhering to <strong>SOLID </strong>principles when designing controllers, let’s look at an example that violates these principles and discuss how to refactor it.</p><pre>public class OrderService {<br><br>    private final DirectDataBaseAccess dataBaseAccess;<br>    <br>    // The controller should not handle business logic<br>    public void createOrder(String customerId, String productId, int quantity) {<br>        // Domain validations should not be here<br>        if (quantity &lt;= 0) {<br>            throw new IllegalArgumentException(&quot;Quantity must be greater than zero.&quot;);<br>        }<br>        <br>        Order order = new Order(customerId, productId, quantity);<br>        // Controller should not handle persistence<br>        double pricePerUnit = dataBaseAccess.getProductPrice(productId)<br>        // This business logic should not be here      <br>        double totalPrice = quantity * pricePerUnit;<br>        order.setTotalPrice(totalPrice);<br>        // Controller should not handle persistence<br>        dataBaseAccess.save(order); <br>    }<br>}</pre><ul><li>OrderService has <em>multiple responsibilities</em>: Validation, Business logic (calculating total price) and Persistence (accessing database).</li><li>If we need to add a new type of Order or a new validation rule, we would have to modify the existing class.</li><li>The OrderService class directly depends on DirectDataBaseAccess, which is likely a concrete implementation that directly access a database. As a result, the business logic within OrderService is dependent on the details of how data is stored and retrieved.</li></ul><h4><strong>The Solution</strong></h4><p>To correctly use the Controller Principle, OrderController should delegate business logic and persistence to appropriate components:</p><pre><br>// Service layer only coordinates business logic and persistence<br>public class OrderService {<br><br>    private OrderRepository orderRepository;<br>    private ProductRepository productRepository<br><br>    public void createOrder(String customerId, Long productId, int quantity) {<br>        var price = productRepository.getById(productId);<br>        var order = new Order(customerId, productId, quantity,price);<br>        orderRepository.save(order);<br>    }<br>}<br><br>// Repository layer to handle persistence<br>public class OrderRepository {<br>    public void save(Order order);<br>}<br><br>// Repository layer to handle persistence<br>public class ProductRepository {<br>    public void getById(Long productId);<br>}<br><br>// Domain class<br>public class Order {<br>    // Omit feilds for brievety<br><br>    public Order(String customerName, String productName, <br>                 BigDecimal quantity, BigDecimal price) {<br>        // Domain validation<br>        if (quantity &lt;= 0 || price &lt;= 0) {<br>            throw new IllegalArgumentException(&quot;Quantity must be greater than zero.&quot;);<br>        }<br>        this.customerName = customerName;<br>        this.productName = productName;<br>        this.quantity = quantity;<br>        this.price= price;<br>    }<br><br>    // Business logic moved to the domain class<br>    public double calculateTotalPrice() {<br>        return this.quantity * pricePerUnit;<br>    }<br>}</pre><p>Now, the responsibilities are separated into different classes and each class has only <strong>Single Responsibility</strong> and also respecting <strong>Open/Closed Principle</strong>.</p><ul><li><strong>OrderService</strong>: Coordinates business logic and persistence by delegating to the OrderRepository and ProductRepository.</li><li><strong>OrderRepository</strong>: Handles the persistence of orders.</li><li><strong>ProductRepository</strong>: Handles retrieval of product information, such as price.</li><li><strong>Order</strong>: Encapsulates domain logic, including validations and calculation of the total price.</li></ul><h4>Points to consider</h4><ul><li><strong>U</strong>se Controllers as Orchestration Points. Controllers should coordinate the actions of other components (like services, repositories) but should not contain complex logic themselves. Delegate complex operations to dedicated service classes.</li><li>Use controllers to introduce an additional layer of abstraction between different parts of your application. This can help reduce coupling and improve maintainability.</li><li>Decompose Complex Controllers<strong>.</strong> If a controller starts to become too large or handles too many responsibilities, consider breaking it down into smaller, more focused components.</li><li>Ensure that each controller class handles only one aspect of the application’s functionality.</li><li>Leverage dependency injection to provide controllers with the necessary dependencies.</li><li>Design controllers in a way that they can be extended to support new functionality without modifying existing code. Use interfaces, abstract classes, or dependency injection to achieve this.</li></ul><p>Whats next?</p><p><em>Continue reading</em>: <a href="https://medium.com/@safonovb2c/polymorphism-in-software-design-1237b16a3088">Polymorphism in Software Design</a></p><p>See a <a href="https://medium.com/@safonovb2c/understanding-grasp-16d4f01fb78c">full list of GRASP principles here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=928ce73d5e91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creator Principle in Software Design]]></title>
            <link>https://medium.com/@safonovb2c/creator-principle-in-software-design-d8b4ee652244?source=rss-7ad784fd0620------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8b4ee652244</guid>
            <category><![CDATA[grasp]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Aleksei  Safonov]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 19:51:21 GMT</pubDate>
            <atom:updated>2024-08-06T20:15:19.815Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building with confidence</h4><p>Previous article: <a href="https://medium.com/@safonovb2c/information-expert-in-software-design-13d39feae314">Information Expert</a> <em>← </em>|| → Next article: <a href="https://medium.com/@safonovb2c/controller-principle-in-software-design-928ce73d5e91">Controller</a></p><p><strong>Creator Principle</strong> states that object A should be <em>responsible </em>for creating object B if A contains or aggregates B or has a single responsibility focused on the creation of objects B, and has the all necessary information to create B. Creator should ensure that the object is created in a valid state and its invariants are upheld.</p><p>Creator principle is commonly used in many <strong>software design patterns</strong>:</p><ul><li><strong>Factory Method</strong>: Defines an interface for creating an object but leaves the decision of which specific class to instantiate to subclasses, delegating the responsibility for creating instances to them.</li><li><strong>Builder</strong>: Allows for the step-by-step construction of complex objects.</li><li><strong>Prototype</strong>: Defines an interface for creating an object by copying an existing object (prototype). This approach is useful when the structure of the object is complex enough to require a reusable functionality.</li><li><strong>Singleton</strong>: Ensures that a class has only one instance and provides a global point of access to that instance.</li><li><strong>Object Pool</strong>: Pre-creates and stores a set of objects in a pool to avoid the overhead of creating and destroying objects at runtime.</li></ul><p>In <strong>Domain-Driven Design</strong> it is common that aggregates are responsible for the creation of child objects. Object creation patterns help to <strong>Separate Responsibilities</strong> for creating objects from application and business logic.</p><p>For example an aggregate, named Order, which encapsulates core business logic of processing an order.</p><pre>// Entity Product<br>public class Product {<br>    private final String name;<br>    private final BigDecimal price;<br>}<br><br>// Aggregate Order<br>public class Order {<br><br>    private UUID orderId;<br>    private List&lt;Product&gt; products;<br><br>    public void addProduct(String productName, BigDecimal productPrice) {<br>        var product = new Product(productName, productPrice);<br>        products.add(product);<br>    }<br>}<br><br>// Example usage<br>public class OrderUseCase {<br><br>    private final OrderRepository orderRepository;<br><br>    public Order createOrder(List&lt;ProductsDto&gt; productsDto) {<br>        // Create an order and add products with their prices<br>        var order = new Order();<br>        productsDto.forEach(p -&gt; order.addProduct(p.getName(), p.getPrice()));<br>        // Save to the database<br>        Order savedOrder = orderService.save(order);<br>        return savedOrder;<br>    }<br>}</pre><p>In this example, the addProduct method in the Order class allows adding products with their names and prices, and Order acts as a Creator of Product entities.</p><h3>Misuse of the Creator Principle</h3><p>Misuse of the Creator principle occurs when a object A creates objects B that it should not be <em>responsible </em>for, leading to poor cohesion, high coupling, and violating the <strong>Single Responsibility Principle</strong>.</p><p>Imagine that Order now needs to maintain a relationship with a Customer.</p><pre>// Entity Product<br>public class Product {<br>    private String name;<br>    private BigDecimal price;<br>}<br><br>// Aggregate Order<br>public class Order {<br>    private UUID orderId;<br>    private Customer customer;<br>    private List&lt;Product&gt; products;<br><br>    public Order(String customerName) {<br>        // Omit validation logic<br>        this.orderId = UUID.randomUUID();<br>        this.customer = createCustomer(customerName);<br>        this.products = new ArrayList&lt;&gt;();<br>    }<br><br>    private Customer createCustomer(String customerName) {<br>        // Omit complex and creation validation logic<br>        return new Customer(customerName);<br>    }<br><br>    public void addProduct(String productName, BigDecimal productPrice) {<br>        Product product = new Product(productName, productPrice);<br>        products.add(product);<br>    }<br>}<br><br>// Example usage<br>public class OrderUseCase {<br>    private final OrderRepository orderRepository;<br><br>    public Order createOrder(String customerName, List&lt;ProductsDto&gt; productsDto) {<br>        // Create an order and add products with their prices<br>        var order = new Order(customerName);<br>        productsDto.forEach(p -&gt; order.addProduct(p.getName(), p.getPrice()));<br>        // Save to the database<br>        Order savedOrder = orderService.save(order);<br>        return savedOrder;<br>    }<br>}</pre><p>By making Order class responsible for creating Customer objects, Order start to depend on the details of the Customer class. Any changes to customer creation logic, such as new validation rules or additional fields, would require changes in Order class and its methods. This means the Order class would had<em> </em><strong>more than one reason to change</strong>.</p><p>The primary responsibility of the Order is to handle order-related activities. This includes managing the list of products, calculating total price, handling order status, and so on. Managing customer information is not a part of its responsibilities.</p><p>The Customer is responsible for managing customer-related activities, such as holding customer information and validations, which can be part of a separate system.</p><p>Order class should <strong>depend on an abstraction</strong> (e.g., a Customer object passed to it), not on the details of how the customer is created.</p><pre>// Aggregate Order<br>public class Order {<br>    private UUID orderId;<br>    // Still needs a reference <br>    private Customer customer;<br>    private List&lt;Product&gt; products;<br><br>    public Order(Customer customer) {<br>        // Omit validation logic<br>        this.orderId = UUID.randomUUID();<br>        this.customer = customer;<br>        this.products = new ArrayList&lt;&gt;();<br>    }<br><br>    public void addProduct(Product product) {<br>        // Omit validation logic<br>        products.add(product);<br>    }<br>}<br><br>// Service class to create orders<br>public class OrderService {<br>    private final OrderRepository orderRepository;<br><br>    public Order createOrder(Customer customer, List&lt;Product&gt; products) {<br>        var order = new Order(customer);<br>        for (Product product : products) {<br>            order.addProduct(product);<br>        }<br>        return orderRepository.save(order);<br>    }<br>}<br><br>// Example of usage<br>public class OrderUseCase {<br>    private final OrderService orderService;<br>    // Assume a service to handle customers<br>    private final CustomerService customerService; <br><br>    public Order createOrder(String customerName, List&lt;ProductDto&gt; productsDto) {<br>        // Create or get existing(!) customer<br>        val customer = customerService.provideCustomer(customerName);<br><br>        // Convert ProductDto to Product<br>        val products = productsDto.stream()<br>            .map(dto -&gt; new Product(dto.getName(), dto.getPrice()))<br>            .collect(Collectors.toList());<br><br>        // Create an order<br>        return orderService.createOrder(customer, products);<br>    }<br>}</pre><p>By encapsulation creation of Customer objects, Order became <strong>open for extension but closed for modification </strong>and any changes to Customer creation logic can be introduced without modifying the Order class.</p><h4>Points to consider</h4><ul><li>If objects don’t have significant variability or complexity (e.g., simple data objects), sometimes, using straightforward constructors can be more practical and easier to understand. Over-engineering with factories or builders may lead to confusion rather than clarity.</li><li>In performance-critical applications, if object creation is a frequent operation and involves complex logic, the additional layers could lead to performance bottlenecks. Direct instantiation may be preferred for efficiency.</li><li>Creator principle can sometimes lead to inflexibility if not implemented carefully. For example, if a class is responsible for creating objects of a specific type, it might become challenging to modify or extend that functionality later without altering the original class.</li><li>If the creation logic is tightly coupled with the business logic, it may complicate unit testing. Mocking or stubbing dependencies can become more difficult if object creation is centralized in a creator class.</li></ul><p>Whats next?</p><p><em>Continue reading</em>: <a href="https://medium.com/@safonovb2c/controller-principle-in-software-design-928ce73d5e91">Controller Principle in Software Design</a></p><p>See a <a href="https://medium.com/@safonovb2c/understanding-grasp-16d4f01fb78c">full list of GRASP principles here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8b4ee652244" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Information Expert in Software Design]]></title>
            <link>https://medium.com/@safonovb2c/information-expert-in-software-design-13d39feae314?source=rss-7ad784fd0620------2</link>
            <guid isPermaLink="false">https://medium.com/p/13d39feae314</guid>
            <category><![CDATA[grasp]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-design]]></category>
            <dc:creator><![CDATA[Aleksei  Safonov]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 19:46:58 GMT</pubDate>
            <atom:updated>2024-08-06T20:14:24.505Z</atom:updated>
            <content:encoded><![CDATA[<h4>Knowledge is power</h4><p>Previous article: <a href="https://medium.com/@safonovb2c/protected-variations-in-software-design-04e9fb65ddba">Protected Variations</a> <em>← </em>|| → Next article: <a href="https://medium.com/@safonovb2c/creator-principle-in-software-design-d8b4ee652244">Creator</a></p><p><strong>Information Expert</strong> <strong>Principle </strong>states that a task should be assigned to the component that has the necessary information to accomplish it. This helps to determine which component should be responsible for a specific tasks.</p><p><em>Responsibility </em>of Information Expert is to encapsulate knowledge within itself and act as a <strong>single source of truth </strong>for its functionality.</p><p>Some related <strong>software design patterns</strong> include:</p><ul><li><strong>Facade</strong>: Acts as an “expert” that “knows ”all the necessary interactions.</li><li><strong>Proxy</strong>: A Proxy manages access to a real object. It can decide when and how to provide access to the real object based on certain conditions.</li><li><strong>Composite</strong>: When components can be combined into a tree structure, Composite pattern provides a unified interface for all components, regardless of their complexity. The component with the most information (in this case, structural information) handles operations.</li></ul><p>In <strong>Domain Driven Design</strong>, aggregates serve as entry points for performing operations, upholding invariants and changes of the state their child objects. The Information Expert principle helps to identify which component should be responsible for “knowledge” and business rules.</p><p>Consider an Order class that encapsulates and shipping tariff details. Each item carries a weight, impacting the overall cost of the order based on the cumulative cargo weight. In this scenario, the Order has <strong>single responsibility -</strong>it serves as an Information Expert, containing all the data needed to execute relevant business logic.</p><pre>// item<br>public class Item   {<br><br>    private final BigDecimal weight;<br><br>    public BigDecimal getWeight() {<br>        return weight;<br>    }<br>}<br><br>public class Order {<br><br>    private final List&lt;Item&gt; items;<br>    private final Tariff tariff;<br><br>    public BigDecimal getTotalPrice() {<br>        // Assume the cost depends on the total weight of the items<br>        // and the order tariff multiplier<br>        return items.stream()<br>                .map(item-&gt; item<br>                      .getWeight()<br>                      .multiply(tariff.getMultiplier()))<br>                .reduce(BigDecimal.ZERO, BigDecimal::add);<br>    }<br>}</pre><p>A holiday sale has been announced, requiring a discount to be applied. In this context, the Order does not have enough information to handle seasonal discounts, so the calculation has been extracted into new functionality. The Order simply provides the necessary product information. By leveraging the <strong>Open/Closed Principle</strong>, this allows to add new pricing strategies without changing the existing code in Order or altering the base price calculation logic in the PriceCalculator.</p><pre>public interface PriceCalculationStrategy {<br>    BigDecimal calculatePrice(Order order);<br>}<br><br>public class DefaultPriceCalculationStrategy implements PriceCalculationStrategy {<br>    @Override<br>    public BigDecimal calculatePrice(Order order) {<br>        return order.getTotalPrice();<br>    }<br>}<br><br>public class SpecialOfferPriceCalculationStrategy implements PriceCalculationStrategy {<br>    @Override<br>    public BigDecimal calculatePrice(Order order) {<br>        // Special offer discount<br>        return order.getTotalPrice().multiply(new BigDecimal(&quot;0.9&quot;)); // 10% discount!<br>    }<br>}</pre><p>PriceCalculator acts as the Information Expert, deciding when and which discounts to apply, using the Strategy pattern to calculate the product price:</p><pre>public class PriceCalculator {<br><br>    private Map&lt;SaleType, PriceCalculationStrategy&gt; calculationStrategies;<br><br>    public BigDecimal calculatePrice(Order order, SaleType saleType) {<br>        PriceCalculationStrategy strategy = calculationStrategies.get(saleType);<br>        return strategy.calculatePrice(order);<br>    }<br>}</pre><h4>Misuse of Information Expert</h4><p>There are two possible outcomes:</p><ul><li>“God Class” anti-pattern, similar to High Cohesion situation, where one class takes on too many responsibilities.</li><li>System becomes so fractured that it is impossible to define the responsibility or even the purpose of any component.</li></ul><p><em>To fully leverage Information Expert principle a developer need to become a Domain Expert himself.</em></p><p>Strong domain knowledge, team collaboration, and applying Domain-Driven Design<strong> </strong>best practices is a powerful approach to properly utilize Information Expert Principle<strong>.</strong></p><p>By using Domain-Driven Design, developers can create a shared understanding of the domain between the development team and the business stakeholders, which is essential for designing a system that meets the business needs. Domain-Driven Design also provides a set of tools and techniques, such as domain modeling, model distillation and ubiquitous language, that help developers to create a robust and maintainable system.</p><p>Whats next?</p><p><em>Continue reading</em>: <a href="https://medium.com/@safonovb2c/creator-principle-in-software-design-d8b4ee652244">Creator Principle in Software Design</a></p><p>See a <a href="https://medium.com/@safonovb2c/understanding-grasp-16d4f01fb78c">full list of GRASP principles here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13d39feae314" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protected Variations in Software Design]]></title>
            <link>https://medium.com/@safonovb2c/protected-variations-in-software-design-04e9fb65ddba?source=rss-7ad784fd0620------2</link>
            <guid isPermaLink="false">https://medium.com/p/04e9fb65ddba</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[grasp]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Aleksei  Safonov]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 19:42:56 GMT</pubDate>
            <atom:updated>2024-08-06T20:12:38.113Z</atom:updated>
            <content:encoded><![CDATA[<h4>Say “NO” to cascade changes</h4><p>Previous article: <a href="https://medium.com/@safonovb2c/indirection-in-software-design-aba4fe3782b2">Indirection</a> <em>← </em>|| → Next article: <a href="https://medium.com/@safonovb2c/information-expert-in-software-design-13d39feae314">Information Expert</a></p><p><strong>Protected Variations Principle</strong> aims to identify potential points of instability or change within a system and design its components to be resilient to these variations.</p><p><em>Responsibility </em>of a component designed with Protected Variations is to encapsulate functionality that is expected to change frequently (the variations) and offer a stable interfaces to interact with it.</p><p>A good example of Protected Variations is message exchange in microservices architecture. A stable contract is established between services, where the producer is responsible for correctness of forming and sending the data. Producer can change its logic, implementation, database strategy, and data handling as long as it adheres to the contract. This ensures that other services remain unaware of these changes and are protected from them.</p><p>The most common software design patterns that utilize Protected Variations share a key trait: they define an contract, with concrete classes implementing this contract. Dependent components then use the interface without needing to know the internal implementation.</p><p>Several <strong>software design patterns</strong> utilize Protected Variations, including:</p><ul><li><strong>Adapter</strong>: This pattern allows incompatible interfaces to work together by wrapping an existing class with a new interface.</li><li><strong>Facade</strong>: This pattern provides a simplified interface to a complex subsystem, shielding clients from changes in the subsystem’s internal implementation.</li><li><strong>Bridge</strong>: This pattern separates an abstraction from its implementation so that both can vary independently, protecting against changes in both: the abstraction and the implementation.</li></ul><p><strong>Domain Driven Design and Protected Variations</strong></p><p>In <strong>Domain Driven Design</strong>, a bounded context defines a clear boundary within which a particular domain model is applicable and acts as a variation point. Protected Variations help to encapsulate changes within these bounded contexts, allowing changes in one context without affecting others.</p><ul><li><strong>Domain events </strong>can serve as a mechanism of communication between different domains. By handling changes through events, the domain model remains stable and protected from direct modifications.</li><li><strong>Repositories and domain services</strong> provide stable interfaces for interacting with the domain model. By using Protected Variations, these interfaces shield the core domain logic from changes in data storage or external services.</li><li>Certain elements like external systems or integration points are encapsulated using <strong>Anti-Corruption Layers </strong>and serves as Protected Variations mechanism.</li></ul><h4>Misuse of Protected Variations</h4><p>Consider a back-end application using a simple MVC architecture with presentation, application, and infrastructure layers. In this setup, the application layer is intended to serve as a barrier between presentation and infrastructure, adhering to the Protected Variation Principle.</p><pre>// Request DTOs from the front-end part of the system<br>public class OrderRequestDto {<br>    // fields and getters/setters<br>}<br><br>// Presentation layer<br>@RestController<br>public class OrderController {<br><br>    private final OrderUseCase orderUseCase;<br><br>    @PostMapping(&quot;/order&quot;)<br>    public Order getOrder(@RequestBody OrderRequestDto orderRequest) {<br>        return orderUseCase.getOrder(orderRequest);<br>    }<br>}<br><br>// Application layer (Service and Port)<br>public interface OrderUseCase {<br>    Order getOrder(OrderRequestDto orderRequest); <br>}<br><br>@Service<br>public class OrderUseCaseImpl implements OrderUseCase {<br><br>    private OrderRepositoryPort orderRepositoryPort;<br><br>    @Override<br>    public Order getOrder(OrderRequestDto orderRequest) {<br>        return orderRepositoryPort.findByFilter(orderRequest)<br>           .orElseThrow(() -&gt; new OrderNotFoundException(orderRequest.getId()));<br>    }<br>}<br><br>// Domain model<br>@Entity<br>public class Order {<br>  // fields and domain logic<br>}<br><br>// Infrastructure layer (Repository and Adapter)<br>public interface OrderDatabasePort {<br>    Optional&lt;Order&gt; findByFilter(OrderRequestDto orderRequest); <br>}<br><br>@Repository<br>public class OrderDatabaseAdapter implements OrderDatabasePort {<br><br>    private final JpaOrderRepository jpaOrderRepository;<br><br>    @Override<br>    public Optional&lt;Order&gt; findByFilter(OrderRequestDto orderRequest) {<br>        return jpaOrderRepository.findByFilter(orderRequest);<br>    }<br>}<br><br>// JPA Repository<br>interface JpaOrderRepository extends JpaRepository&lt;Order, Long&gt; {<br>    // complex search operation with multiple params in where <br>    Optional&lt;Order&gt; findByFilter(OrderRequestDto orderRequest);<br>}</pre><p>At first glance, the code appears to be well-structured, with each layer relying on the abstractions of the other layers and looks “SOLID enough”. However, it violates Protected Variations Principle in a subtle yet significant way.</p><h4>The Problem</h4><p>The main issue lies in the pervasive use of OrderRequestDto and Order throughout all layers. OrderRequestDto, which originates from the front-end, is tightly coupled to the internal layers of back-end application, including the domain and persistence logic. This means that any change in the front-end&#39;s data structure (e.g., adding or removing a field in OrderRequestDto) will ripple through multiple layers, necessitating modifications in the domain entities, database queries, and core application logic.</p><p>The domain and infrastructure layers should be agnostic of the specific format of requests originating from external sources. Using OrderRequestDto directly exposes the details of the front-end&#39;s data structure to these layers, breaking encapsulation and making them vulnerable to changes in the presentation layer.</p><p>Furthermore, if changes are made to the Order entity, it not only affects the back-end application but also impacts the front-end team. Order has become a contract between the front-end and back-end, complicating coordination between the teams.</p><h4>The Solution</h4><p>To resolve the issue and make the application layer work as intended, there is a simple and straightforward solution: each interface should has it’s own contract.</p><pre>// Request DTO from front-end <br>public class OrderRequestDto {<br>    // fields and getters/setters<br>}<br><br>// Response DTO to front-end <br>public class OrderResponseDto {<br>    // fields and getters/setters<br>}<br><br>// Mapping logic<br>public class OrderRequestConverter {<br><br>    public OrderUseCaseFilterDto toUseCaseFilterDto(OrderRequestDto orderRequestDto) {<br>       // Mapping from front-end request to application contract<br>       return new OrderUseCaseFilterDto();<br>    }<br><br>    public OrderResponseDto toResponse(OrderUseCaseResponseDto responseDto) {<br>       // Mapping from application response to frontend contract<br>       return new OrderResponseDto();<br>    }<br>}<br><br>// Presentation layer <br>@RestController<br>public class OrderController {<br><br>    private final OrderUseCase orderUseCase;<br>    private final OrderRequestConverter orderConverter;<br><br>    @PostMapping(&quot;/order&quot;)<br>    public OrderResponseDto getOrder(@RequestBody OrderRequestDto orderRequestDto) {<br>        val filter = orderConverter.toUseCaseFilterDto(orderRequestDto);<br>        val result = orderUseCase.getOrder(filter);<br>        return orderConverter.toResponse(result);<br>    }<br>}<br><br>// Application layer (Service and Port)<br>// Serves as a request contract with application layer<br>public class OrderUseCaseFilterDto {<br>    // fields and getters/setters<br>}<br><br>// Serves as a response contract with application layer<br>public class OrderUseCaseResponseDto {<br>    // fields and getters/setters<br>}<br><br>// Mapping logic<br>public class OrderUseCaseConverter {<br><br>    public ComplexFilter toDataBaseFilter(OrderUseCaseFilterDto filterDto) {<br>       // Mapping from application filter to database filter<br>       return new ComplexFilter();<br>    }<br><br>    public OrderUseCaseResponseDto toOrderUseCaseResponseDto(Order order) {<br>       // Mapping from domain model to application response contract<br>       return new OrderUseCaseResponseDto();<br>    }<br>}<br><br>// Contract for Use Case logic<br>public interface OrderUseCase {<br>    OrderUseCaseResponseDto getOrder(OrderUseCaseFilterDto filterDto); <br>}<br><br>// Implementation of Use Case logic<br>public class OrderUseCaseImpl implements OrderUseCase {<br><br>    private final OrderRepositoryPort orderRepository;<br>    private final OrderUseCaseConverter orderUseCaseConverter;<br><br>    @Override<br>    public OrderUseCaseResponseDto getOrder(OrderUseCaseFilterDto filterDto) {<br>        val jpaFilter = orderUseCaseConverter.toDataBaseFilter(filterDto);<br><br>        val order = orderRepository.findByFilter(jpaFilter)<br>           .orElseThrow(() -&gt; new OrderNotFoundException(filterDto.getId()));<br><br>        return orderUseCaseConverter.toOrderUseCaseResponseDto(order);<br>    }<br>}<br><br>// Infrastructure layer (Repository and Adapter)<br><br>// Filter for database request<br>public class ComplexFilter {<br>    // fields and getters/setters<br>}<br><br>// Port to Infrastructure with a contract - find Order entity<br>public interface OrderRepositoryPort {<br>    Optional&lt;Order&gt; findByFilter(ComplexFilter filter); <br>}<br><br>// Implementation of Infrastructure logic for database access<br>public class OrderDatabaseAdapter implements OrderRepositoryPort {<br><br>    private final JpaOrderRepository jpaOrderRepository;<br><br>    @Override<br>    public Optional&lt;Order&gt; findByFilter(ComplexFilter filter) {<br>        return jpaOrderRepository.findByFilter(filter);<br>    }<br>}<br><br>public interface JpaOrderRepository extends JpaRepository&lt;Order, Long&gt; {<br>    // complex search operation with multiple params in where <br>    Optional&lt;Order&gt; findByFilter(ComplexFilter filter);<br>}</pre><p>After refactoring, application layer serves as an Anti-Corruption Layer between the infrastructure and presentation layers, shielding them from changes in each other. The Order class can be modified freely, and infrastructure code does not affect presentation contracts, thereby not impacting the front-end team.</p><p>This approach not only adheres to <strong>SOLID </strong>principles but also enhances the overall maintainability of the system.</p><ul><li>Each class has a <strong>Single Responsibility</strong>. For example, OrderRequestConverter is solely responsible for converting between DTOs and application-specific data structures. The OrderController handles HTTP requests and uses the converter for data transformation.</li><li>The system is <strong>open for extension but closed for modification</strong>. New features or changes can be added by extending existing components without modifying them. For instance, to add a feature that downloads order information as XML, only new controller and a converter are needed to be add:</li></ul><pre>// Mapping logic<br>public class OrderXmlRequestConverter {<br>     <br>    public OrderUseCaseFilterDto toUseCaseFilterDto(OrderXmlRequestDto orderRequestDto) {<br>       // Mapping from front-end request to application contract<br>       return new OrderUseCaseFilterDto();<br>    }<br><br>    public OrderResponseDto toResponse(OrderUseCaseResponseDto responseDto) {<br>       // Mapping from application response to frontend contract<br>       return new OrderXmlResponseDto();<br>    }<br>}<br><br>// Presentation layer<br>@RestController<br>public class OrderController {<br><br>    private final OrderXmlRequestConverter orderXmlConverter;<br>    private final OrderUseCase orderUseCase;<br><br>    @GetMapping(&quot;/order/xml&quot;)<br>    public OrderXmlResponseDto getOrderAsXml(@RequestBody OrderXmlRequestDto orderRequestDto) {<br>        OrderUseCaseFilterDto filter = orderConverter.toUseCaseFilterDto(orderRequestDto);<br>        OrderUseCaseResponseDto result = orderUseCase.getOrder(filter);<br>        return orderXmlConverter.toXmlResponse(result);<br>    }<br>}</pre><ul><li>By using interfaces with separate DTO (contract), we ensure that <strong>client code is not forced to depend on the abstractions it does not use</strong>.</li></ul><h4>Points to consider</h4><ul><li>Identify components that are expected to change frequently and establish stable interfaces and contracts between components to protect them against changes.</li><li>Ensure that changes to one component do not break other components by thorough testing and validation.</li><li>Avoid tight coupling between components, as it can lead to a ripple effect of changes throughout the system.</li><li>Use Anti-Corruption layers to isolate the system from external changes.</li></ul><p>Whats next?</p><p><em>Continue reading</em>: <a href="https://medium.com/@safonovb2c/information-expert-in-software-design-13d39feae314">Information Expert in Software Design</a></p><p>See a <a href="https://medium.com/@safonovb2c/understanding-grasp-16d4f01fb78c">full list of GRASP principles here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04e9fb65ddba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Indirection in Software Design]]></title>
            <link>https://medium.com/@safonovb2c/indirection-in-software-design-aba4fe3782b2?source=rss-7ad784fd0620------2</link>
            <guid isPermaLink="false">https://medium.com/p/aba4fe3782b2</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[grasp]]></category>
            <category><![CDATA[software-design]]></category>
            <dc:creator><![CDATA[Aleksei  Safonov]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 19:35:20 GMT</pubDate>
            <atom:updated>2024-08-06T20:11:23.799Z</atom:updated>
            <content:encoded><![CDATA[<h4>KISS or not to KISS</h4><p>Previous article: <a href="https://medium.com/@safonovb2c/high-cohesion-in-software-design-685784471c39">High Cohesion</a> <em>← </em>|| → Next article: <a href="https://medium.com/@safonovb2c/protected-variations-in-software-design-04e9fb65ddba">Protected Variations</a></p><p><strong>Indirection </strong>is a design principle that suggests using intermediate objects or high-level abstractions to reduce coupling between components in a system. The <em>responsibility </em>of such intermediate objects is to manage dependencies between components, providing a stable interface that shields them from changes.</p><p>Let’s look at some examples of <strong>software design patterns</strong> utilizing Indirection:</p><ul><li><strong>Decorator</strong>: Indirection is achieved by adding additional functionality to an object without changing its structure.</li><li><strong>State</strong>: Indirection occurs through representing an object in various states and delegating the responsibility for the object’s behavior to the current state.</li><li><strong>Mediator</strong>: Indirection is achieved by centralized control over multiple objects, avoiding direct connections between them.</li></ul><p>In <strong>Domain-Driven Design</strong>, Indirection manifests in separating domain from infrastructure and presentation layers, connecting application into a cohesive mechanism through abstractions.</p><p>Consider an example - online store with operations for placing an order. Indirection is expressed through a OrderUseCase which serves as an intermediate layer between incoming requests and domain logic.</p><pre>// Domain service for placing an order<br>public interface OrderDomainService {<br>    void placeOrder(Order order);<br>}<br><br>// Contract for working with the application <br>public interface OrderUseCase {<br>    void placeOrder(UseCaseOrderDto orderDto);<br>}<br><br>// Use case implementation<br>public class OrderUseCaseImpl implements OrderUseCase {<br><br>    private OrderDomainService orderService;<br>    private OrderUsecaseConverter convertor;<br><br>    public void placeOrder(UseCaseOrderDto orderDto) {<br>        // Map DTO to domain entity<br>        var order = convertor.convert(orderDto);<br>        // Call domain service to place the order<br>        orderService.placeOrder(order);<br>    }<br>}<br><br>// Presentation layer adapter<br>public class OrderController {<br><br>    private final OrderUseCase orderUseCase;<br>    private final OrderRequestConverter orderRequestConverter;<br><br>    public void handleOrderRequest(RequestDto requestDto) {<br>        // Adapt interaction with the API<br>        var orderDto = orderRequestConverter.convert(requestDto);<br>        orderUseCase.placeOrder(orderDto);<br>    }<br>}</pre><h4>Misuse of Indirection</h4><p>When applying Indirection principle, it is crucial to balance it with its counterpart, KISS (“Keep It Simple, Stupid”), to avoid unnecessary complexity.</p><p>Several signs indicate that indirection is being overused:</p><ul><li>Developers struggle to understand interactions between components due to excessive abstraction levels.</li><li>Project has too many intermediate objects or layers that seem unjustified and hinder code comprehension.</li><li>Introducing intermediate layers or objects complicates the program structure without clear benefits in flexibility or dependency management.</li><li>Adding intermediate layers negatively impacts system performance.</li><li>Intermediate layers make debugging and testing more difficult, increasing development effort.</li></ul><p>Let’s look at the example.</p><pre>// Action class<br>public class Action {<br>    public boolean doAction() {<br>        // Action logic<br>    }<br>}<br><br>// Task class<br>public class Task {<br>    private Action action;<br><br>    public boolean performAction() {<br>        return action.doAction();<br>    }<br>}<br><br>// TaskAction class<br>public class TaskAction {<br>    public boolean performTaskAction(Task task) {<br>        task.performAction();<br>    }<br>}<br><br>// TaskManager class<br>public class TaskManager {<br>    // Result of Action is lost here<br>    public void processTasks(List&lt;TaskAction&gt; taskActions) {<br>        for (TaskAction taskAction : taskActions) {<br>            taskAction.performTaskAction();<br>        }<br>    }<br>}<br><br>// TaskProcessor class<br>public class TaskProcessor {<br>    private TaskManager taskManager;<br><br>    public void processTasks(List&lt;TaskAction&gt; taskActions) {<br>        taskManager.processTasks(taskActions);<br>    }<br>}</pre><ul><li>Action and Task essentially represent the same idea of performing an action and could be combined into one class.</li><li>TaskAction simply delegates the task&#39;s action without adding any functional value.</li><li>TaskManager provides &quot;bulk&quot; task execution, but it doesn&#39;t add any useful functionality. The same result could be achieved by iterating through the list of tasks without it. Moreover, the result of Action is lost in this stage.</li><li>TaskProcessor delegates working with the task list to TaskManager, and they could be combined into one class since they perform the same job.</li></ul><h4>The Solution</h4><p>Sometimes, straightforward design is a simple and more effective solution.</p><pre>// Combined Action and Task class<br>public class Task {<br>    TaskResult performAction() <br>}<br><br>public class ComplicatedTaskImpl implements Task {<br><br>    public TaskResult performAction() {<br>        // Action logic<br>    }<br>}<br><br>// Simplified TaskProcessor class<br>public class TaskProcessor {<br><br>    public List&lt;TaskResult&gt; processTasks(List&lt;Task&gt; tasks) {<br>        returntasks.stream()<br>           .map(task -&gt; task.performAction())<br>           .collect(Collectors.toList());<br>    }<br>}</pre><ul><li>Action and Task are merged into a single Task class, giving it a clear, <strong>single responsibility.</strong></li><li>New design is <strong>open for extension</strong>. Different types of tasks can be easily added by implementing Task interface without modifying existing code.</li><li>By removing unnecessary abstractions, the <strong>interface becomes more focused</strong> and relevant.</li><li>Refactored code <strong>reduces unnecessary dependencies</strong> between classes.</li></ul><p>Code has become better after refactoring. It adheres more closely to <strong>SOLID </strong>principles, reduces unnecessary complexity.</p><h4>Points to consider</h4><ul><li>Ensure you clearly understand why you need to use Indirection. The goal is to reduce coupling. Try to find balance and avoid adding unnecessary layers that complicate your design without providing benefits.</li><li>Design intermediate objects with clear, well-defined interfaces that provide a stable contract between components.</li><li>If you find that indirection is causing more harm than good, simplify your design. Merge redundant classes and remove unnecessary abstractions.</li><li>Remember about potential performance impacts and monitor it. Excessive indirection can introduce overhead, so always measure and evaluate performance implications.</li><li>Provide “clean and clear” documentation for the use of abstractions in your system to help other developers understand the design choices and the roles of various intermediate objects.</li></ul><p>Whats next?</p><p><em>Continue reading</em>: <a href="https://medium.com/@safonovb2c/protected-variations-in-software-design-04e9fb65ddba">Protected Variations in Software Design</a></p><p>See a <a href="https://medium.com/@safonovb2c/understanding-grasp-16d4f01fb78c">full list of GRASP principles here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aba4fe3782b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High Cohesion in Software Design]]></title>
            <link>https://medium.com/@safonovb2c/high-cohesion-in-software-design-685784471c39?source=rss-7ad784fd0620------2</link>
            <guid isPermaLink="false">https://medium.com/p/685784471c39</guid>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[grasp]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Aleksei  Safonov]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 19:25:44 GMT</pubDate>
            <atom:updated>2024-08-06T20:11:33.505Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is Cohesion?</h4><p>Previous article: <a href="https://medium.com/@safonovb2c/low-coupling-in-software-design-1818bb93e14f">Low Coupling</a> <em>← </em>|| → Next article: <a href="https://medium.com/@safonovb2c/indirection-in-software-design-aba4fe3782b2">Indirection</a></p><p>Cohesion refers to the degree of consistency and connectivity between elements within a component. The more elements are logically related and affect each other, the higher the cohesion.</p><p><strong>High Cohesion</strong> principle suggests that parts of a component should be logically related and focused on achieving a single common goal. <em>Responsibility </em>of High Cohesion is to ensure those parts are well-organized, self-contained and have clear separation of concerns.</p><p><strong>Advantages of using High Cohesion Principle</strong></p><ul><li>Components are easier to understand and maintain because their elements are logically connected and perform related tasks.</li><li>Reduces the likelihood of errors when changing code, as changes typically affect only closely related elements.</li><li>Components with High Cohesion are easier to test in isolation, as they have a well-defined scope.</li><li>Cohesive modules are often more reusable because they encapsulate a specific functionality that can be applied in different contexts.</li></ul><p>In<strong> Domain-Driven Design</strong>, High Cohesion is essential for building coherent domain models:</p><ul><li><strong>Aggregates:</strong> A unified invariant and common transactional boundaries create strong connections between objects within the aggregate. This centralizes domain logic and make it easier to modify.</li><li><strong>Business Services:</strong> High cohesion within a business service helps define its responsibilities and ensures logical integrity within the system.</li><li><strong>Bounded Contexts</strong>: Defined boundaries of entities and their relationships, ensuring consistency and integrity of abstractions and representations within the context.</li></ul><p>Consider an example from an online store application.</p><pre>public class OrderProcessorUseCase {<br>    private OrderValidator orderValidator;<br><br>    public void processOrder(Order order) {<br>        if (orderValidator.validateOrder(order)) {<br>            // Order processing logic<br>        }<br>    }<br>}<br><br>class OrderValidator {<br>    boolean validateOrder(Order order) {<br>        // Validation logic<br>        log.info(&quot;Validating order #&quot; + order.getId());<br>        return /* validation result */;<br>    }<br>}</pre><p>OrderProcessorUseCase is responsible for processing orders, while OrderValidator handles order validation. Each class performs a specific task, but they are highly cohesive as order validation is essential within the context of order processing.</p><h4>Misuse of High Cohesion</h4><p>However, misapplying this principle can result in the “God Object” antipattern, where a single class ends up taking on too many responsibilities, becoming overly complex and difficult to manage.</p><pre>public class Order {<br>    private List&lt;Item&gt; items;<br>    private Customer customer;<br>    private PaymentDetails paymentDetails;<br>    private ShippingDetails shippingDetails;<br><br>    public void addItem(Item item) {<br>        // Add item to the order<br>    }<br><br>    public void removeItem(Item item) {<br>        // Remove item from the order<br>    }<br><br>    public void calculateTotal() {<br>        // Calculate the total cost of the order<br>    }<br><br>    public void processPayment() {<br>        // Process payment for the order<br>    }<br><br>    public void sendConfirmationEmail() {<br>        // Send confirmation email to the customer<br>    }<br><br>    public void generateInvoice() {<br>        // Generate an invoice for the order<br>    }<br><br>    public void handleCustomerSupportIssue() {<br>        // Handle customer support related to the order<br>    }<br>}</pre><ul><li>The Order has too many responsibilities<em> </em>and therefore many reasons to change, making it difficult to maintain.</li><li>Order forces clients to depend on a large functionality with many methods, most of which they might not need.</li><li>Any change might affect other functionalities, making changes risky and error-prone.</li><li>Unit testing becomes challenging as the class has multiple responsibilities, requiring comprehensive test coverage.</li><li>As the system grows, more functionalities will be added to the Order class, making the issue even worse.</li></ul><h4>The Solution</h4><p>Refactoring Order into smaller, more cohesive classes based on <strong>SOLID </strong>principles offers an effective solution to this problem. This approach not only enhances cohesion within each class but also creates a highly cohesive component dedicated to manage Order domain logic.</p><pre>public class Order {<br>    private List&lt;Item&gt; items;<br>    private Customer customer;<br><br>    public void addItem(Item item) {<br>        // Add item to the order<br>    }<br><br>    public void removeItem(Item item) {<br>        // Remove item from the order<br>    }<br><br>    public double calculateTotal() {<br>        // Calculate the total cost of the order<br>        return items.stream().mapToDouble(Item::getPrice).sum();<br>    }<br>}<br><br>public class ShippingService {<br>    public void shipOrder(Order order, ShippingDetails shippingDetails) {<br>        // Ship the order<br>    }<br>}<br><br>public class EmailService {<br>    public void sendConfirmationEmail(Order order) {<br>        // Send confirmation email to the customer<br>    }<br>}<br><br>public class InvoiceGenerator {<br>    public void generateInvoice(Order order) {<br>        // Generate an invoice for the order<br>    }<br>}<br><br>public class CustomerSupportService {<br>    public void handleCustomerSupportIssue(Order order) {<br>        // Handle customer support related to the order<br>    }<br>}</pre><ul><li>Each responsibility is moved into its own class (Order, ShippingService, EmailService, InvoiceGenerator, CustomerSupportService) and <strong>each of them have only one reason to change and single responsibility</strong>.</li><li>After refactoring, Order domain and application logic is <strong>open for extension but closed for modification</strong>. New functionalities can be added by creating new classes or extending existing ones without modifying the existing Order class or other service classes. For example, a new PaymentService class could be added without changing the Order class.</li><li>Smaller, focused classes enable easier implementation of interfaces (if needed) and following the <strong>Liskov Substitution Principle</strong>.</li><li>By breaking down Order into smaller abstractions, <strong>each client can depend only on the interfaces (methods) they actually use.</strong> For example, a class that only needs to send emails will depend on EmailService, not on the entire Order class.</li><li>The refactored design can introduce abstractions (interfaces) for each service and <strong>components can depend on low-level components, and both depend on abstractions</strong>. This allows for easier swapping of implementations (for example, different email services) without changing the dependent classes.</li></ul><p>Whats next?</p><p><em>Continue reading</em>: <a href="https://medium.com/@safonovb2c/indirection-in-software-design-aba4fe3782b2">Indirection in Software Design</a></p><p>See a <a href="https://medium.com/@safonovb2c/understanding-grasp-16d4f01fb78c">full list of GRASP principles here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=685784471c39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Low Coupling in Software Design]]></title>
            <link>https://medium.com/@safonovb2c/low-coupling-in-software-design-1818bb93e14f?source=rss-7ad784fd0620------2</link>
            <guid isPermaLink="false">https://medium.com/p/1818bb93e14f</guid>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[grasp]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Aleksei  Safonov]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 19:18:48 GMT</pubDate>
            <atom:updated>2024-08-06T20:33:58.534Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>What is Coupling?</strong></h4><p><em>First article</em>: <a href="https://medium.com/@safonovb2c/understanding-grasp-16d4f01fb78c">Understanding GRASP</a> <em>← </em>|| → <em>Next article</em>: <a href="https://medium.com/@safonovb2c/high-cohesion-in-software-design-685784471c39">High Cohesion</a></p><p>Coupling refers to the degree of interdependence between components. The higher the coupling, the more components affect each other, and the more one component depends on changes in another.</p><p><strong>Low Coupling Principle</strong> advocates minimizing dependencies between system components, ensuring that each component is self-sufficient and functions as a ‘black box’;</p><p>A good example of following Low Coupling as <em>responsibility</em> of an interface to represent a contract of a component as a whole. All other components should rely solely on the interface and not depend on the component’s internal implementation or structure.</p><p><strong>Advantages of using Low Coupling:</strong></p><ul><li>Organizing code into independent modules or components, each performing specific functions, simplifies maintenance and code reuse.</li><li>Low coupling reduces the likelihood of errors, as changes in one component do not affect operation of others.</li><li>Components can be tested independently, and changes in one component rarely cause errors in others, simplifying error detection and resolution.</li><li>Reducing dependencies between components, allowing them to be replaced or scaled independently. For instance, in a microservices architecture, each service can scale independently to handle increased load.</li></ul><p>Imagine a scenario where a user requests information about the product through the application. It’s crucial to deliver this information to avoid losing the customer.</p><p>In the code below, the ProductInfoPorvider interface has a single method that returns a product by its ID. The implementation of this interface first attempts to find the product in the database and then, if the product is not found, it calls an external API. The consumer of this contract only knows the interface and remains unaware of how ProductInfoProvider gets the information. On the contrary, the implementation in ProductDataAccessFacadeis Highly Cohesive, representing a single component of the system with the sole purpose of providing data to the consumer.</p><pre>// Interface for accessing product data<br>interface ProductInfoPorvider {<br>    Product findProductById(String productId);<br>}<br><br>// Implementation of product data access, first in the DB, then via API<br>class ProductDataAccessFacade implements ProductInfoPorvider {<br><br>    private ProductRepository productRepository;<br>    private ProductApiService productApi;<br><br>    @Override<br>    public Product findProductById(String productId) {<br>        Product product = productRepository.findById(productId);<br>        if (product == null) {<br>            product = productApi.getProductById(productId);<br>        }<br>        return product;<br>    }<br>}</pre><p>Low Coupling plays a major role in many software design concepts.</p><p>It is a foundation for <strong>Separation of Concerns</strong> design principle, the core idea of which is to break down a complex problem into manageable pieces.</p><p>In <strong>Domain-Driven Design</strong> Low Coupling is key to success in every aspect: building domain models, defining context boundaries, forming aggregates, use cases, and events for information exchange between domains.</p><ul><li><strong>Bounded Contexts</strong> are explicitly defined with boundaries of terms and models that are loosely coupled.</li><li><strong>Aggregates</strong> are organized in the way, that changes in one do not affect another.</li><li><strong>Domain Services</strong> provide common operations that are not naturally part of an aggregate. Weak dependencies between different services, ensure low coupling and improve system flexibility.</li><li>Using <strong>domain</strong> <strong>events</strong> for information exchange between system components promotes low coupling. Even the source of the events can be changed or replaced, and it will not affect the listeners.</li></ul><h4>Misuse of Low Coupling</h4><p>Like any principle, if misapplied, Low Coupling can lead to unintended consequences: fragmenting system into many tiny, isolated components, which can cause performance degradation and maintainability. This is often referred to as “over-engineering” or “design by committee”.</p><p>Let’s consider an example.</p><pre>// Single-method interfaces<br>interface Printable { void print(); }<br>interface Shareable { void share(); }<br>interface Editable { void edit(); }<br>interface Deletable { void delete(); }<br>interface Viewable { void view(); }<br>interface Downloadable { void download(); }<br><br>// Concrete classes implementing multiple interfaces<br>class Document implements Printable, Shareable, Editable, Deletable, Viewable {<br>    // Implementations...<br>}<br><br>class Image implements Shareable, Viewable, Deletable, Downloadable {<br>    // Implementations...<br>}<br><br>class Video implements Shareable, Viewable, Deletable, Downloadable {<br>    // Implementations...<br>}</pre><p>There are multiple problems with this approach:</p><ul><li><strong>Interface Explosion:</strong> We have a multitude of single-method interfaces, leading to an explosion of small classes that don’t provide much value.</li><li><strong>Configuration Hell:</strong> It becomes hard to maintain correct combination of dependencies for each use case. This can lead to extremely verbose and error-prone configuration.</li><li><strong>Reduced Cohesion:</strong> The logic of fetching and transforming data is scattered across multiple classes, making it harder to understand the overall process.</li></ul><h4>The Solution</h4><p>The problem isn’t inherently having many concrete implementations. It’s about finding the right balance between abstraction and concreteness. Over-abstraction can lead to complexity, while too little abstraction can make the system inflexible.</p><pre>// More cohesive interfaces<br>interface Media {<br>    void share();<br>    void view();<br>    void delete();<br>}<br><br>interface DocumentMedia extends Media {<br>    void print();<br>    void edit();<br>}<br><br>interface DownloadableMedia extends Media {<br>    void download();<br>}<br><br>// Concrete classes implementing more cohesive interfaces<br>class Document implements DocumentMedia {<br>    // Implementations...<br>}<br><br>class Image implements DownloadableMedia {<br>    // Implementations...<br>}<br><br>class Video implements DownloadableMedia {<br>    // Implementations...<br>}</pre><p>The key takeaway is that while Low Coupling is beneficial, it should be balanced with other design principles and the ability to maintain a reasonable level of complexity. Overemphasis on Low Coupling at the expense of these other principles can lead to a system that, although theoretically flexible, is practically difficult to work with.</p><p><em>Continue reading</em>: <a href="https://medium.com/@safonovb2c/high-cohesion-in-software-design-685784471c39">High Cohesion in Software Design</a></p><p>See a <a href="https://medium.com/@safonovb2c/understanding-grasp-16d4f01fb78c">full list of GRASP principles here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1818bb93e14f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>