<?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 Elie Khoury on Medium]]></title>
        <description><![CDATA[Stories by Elie Khoury on Medium]]></description>
        <link>https://medium.com/@elie.khoury.progmod?source=rss-b82702ccc04d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E8enbxv97St0XODuP1l64w.jpeg</url>
            <title>Stories by Elie Khoury on Medium</title>
            <link>https://medium.com/@elie.khoury.progmod?source=rss-b82702ccc04d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:00:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elie.khoury.progmod/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[Flow Driven Domain (FDD) - enhance your domain with flow capabilities]]></title>
            <link>https://medium.com/@elie.khoury.progmod/flow-driven-domain-fdd-enhance-your-domain-with-flow-capabilities-5687d04ad379?source=rss-b82702ccc04d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5687d04ad379</guid>
            <category><![CDATA[aggregates]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[saga]]></category>
            <category><![CDATA[bpmn]]></category>
            <category><![CDATA[ddd]]></category>
            <dc:creator><![CDATA[Elie Khoury]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 19:03:42 GMT</pubDate>
            <atom:updated>2024-01-27T09:25:50.363Z</atom:updated>
            <content:encoded><![CDATA[<p>What is this <strong>FDD</strong> everybody is talking about? 🌍 haven’t you heard about FDD yet? 🤔 are you serious ??</p><blockquote>wait dont panic, it is a brand new concept 🙂</blockquote><p>Welcome to a deep dive into<strong> Flow Driven Domain (FDD)</strong>, an innovative approach that enhances domain models in <strong>DDD</strong> by introducing a <strong>process-centric perspective </strong>into account.</p><p>FDD effectively bridges the gap between <strong>the static nature of domain models </strong>and the <strong>dynamic nature of business processes.</strong></p><p>FDD is a practical approach to bringing your domain aggregates to life, ensuring they’re not only reflective of your business entities and relationships but also dynamically aligned with your ever-evolving business processes.</p><blockquote>In simple terms, FDD bring bpm/flow capabilities at your Aggregate Level</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQHo1F3_BQ6ozcAMBKuWZw.png" /></figure><h3>❓What is Flow Driven Domain?</h3><p><strong>FDD</strong> is a methodology that integrates DDD principles with a <strong>process-centric</strong> point of vue.<br>This integration allows for a more natural and fluid management of business processes within the domain model itself.<br><strong><br></strong>This approach proposes an integration of process management directly into the domain model, tackling the complexities of evolving domain processes and leading to more scalable and cohesive models.</p><blockquote>The result? More flexible, scalable, and cohesive models.</blockquote><h3>🌱The Genesis of FDD</h3><p>Traditionally, DDD focuses on creating a model based on the <strong>domain’s entities, their relationship </strong>and<strong> their behaviour.</strong></p><p>However, FDD emerges from the necessity to seamlessly integrate these elements with <strong>process flows</strong>, thereby creating a <strong>more dynamic and responsive model</strong>.</p><blockquote>For more insights, you can read the first <a href="https://medium.com/@elie.khoury.partner/intertwine-ddd-and-bpm-make-your-domain-process-centric-894c460df509">article</a> of this series</blockquote><h3>📚FDD Library</h3><blockquote>The goal of this article is only to present the FDD library with a practical guide.<br>🔍 For a complete documentation check the <a href="https://github.com/progmodEK/flow-driven-domain">git repository</a></blockquote><h4>🛠️ Library Core principals:</h4><p>The library was designed with these concepts and needs in mind:</p><ul><li><strong>Simplicity and Coverage<br> → </strong>Aiming to fulfil over 95% of use cases needs with essential functionalities.</li><li><strong>Flexibility in Flow Definitions<br> → </strong>Supporting multiple flow definitions across various JSON files.</li><li><strong>Agile Aggregate Flow</strong><br> → Aggregates can transition smoothly through defined flows</li><li><strong>Interactive Domain Actions</strong><br> → facilitates synchronous responses and checks action eligibility based on flow definitions.</li><li><strong>System-Initiated Actions<br> →</strong> ability to automatically launch actions by the system after reaching a certain state.</li><li><strong>Eligibles Actions<br> → </strong>computed and exposed to users on every state of the process.</li><li><strong>Expiration Management<br> → </strong>incorporates an <strong>ExpiresAt</strong> property computed at each state.</li><li><strong>External Interaction<br> → i</strong>nteract with the other systems through <strong>actionDelegates</strong> (ex call external Apis)</li><li><strong>Return predefined objects:<br> → </strong>the response after invoking an action is very flexible (ex we can return the response from an external API directly to the client)</li><li><strong>Performance Efficiency<br> → </strong>Eliminates the need for separate state machines or BPM tools.<br> → load the aggregate, perform process related functionalities (through actionDelegates), call the aggregate methods and finally save the aggregate in one unified transaction.</li><li><strong>Scalability and adaptability</strong>: <br> → Seamlessly accommodates changing business processes.</li><li><strong>Consistent State Management<br> → </strong>Ensures aggregate and process states are always synchronized.</li></ul><h3>📖 Case Study: Order Preparation</h3><p>Let’s illustrate FDD with an example — the Order Preparation process. This case study takes you through the journey of an order preparation moving through various states like TO_PREPARE, IN_PREPARATION, PENDING_PICKUP, DELIVERED, guided by a sequential flow of actions. like START_PREPARATION, PICK_ITEMS, PICKUP.<br>At at the final step (DELIVERED) a system action is automatically triggered to notify the Order Manager.</p><blockquote>For a complete description of this case study, refer to the first <a href="https://medium.com/@elie.khoury.partner/intertwine-ddd-and-bpm-make-your-domain-process-centric-894c460df509">article</a> of this series.</blockquote><h3>💻 Implementation FDD : A pratical guide</h3><p>First lets check our aggregate, it has a list of items to prepare and an orderRef referencing the Order inside the Order Manager system.</p><pre>public class OrderPreparation {<br>  @Builder.Default<br>  private UUID id = UUID.randomUUID();<br>  private String orderRef;<br>  private List&lt;Item&gt; items;<br><br>  /**<br>   * Update Preparation while maintaining Aggregate invariants.<br>   */<br>  public void updatePreparation(final PickItemsRequest pickItemsRequest) {<br>    // check picked items exist<br>    final List&lt;String&gt; pickedSkus = pickItemsRequest.pickItems().stream()<br>        .map(PickItemRequest::skuId)<br>        .toList();<br>    final List&lt;String&gt; existingSkus = items.stream()<br>        .map(Item::getSkuId)<br>        .toList();<br>    final boolean allExists = pickedSkus.stream().allMatch(s -&gt; existingSkus.contains(s));<br>    if (!allExists) {<br>      throw new IllegalArgumentException(&quot;prepared items does not exists&quot;);<br>    }<br><br>    // update Items preparation while maintaining Aggregate invariants.<br>    pickItemsRequest.pickItems().stream()<br>        .forEach(<br>            pickItemRequest -&gt; items.stream().filter(item -&gt; item.skuId.equals(pickItemRequest.skuId())).findFirst()<br>                .map(item -&gt; item.updatePreparedQty(pickItemRequest.qty()))<br>        );<br>  }<br><br>  @Transient<br>  public boolean isFullyPrepared() {<br>    return items.stream()<br>        .filter(item -&gt; item.qty == item.qtyPrepared)<br>        .toList().size() == items.size();<br><br>  }<br>}</pre><p>and each item look like:</p><pre>public class Item {<br>  String skuId;<br>  String name;<br>  int qty;<br>  int qtyPrepared;<br>  boolean pickedUp;<br><br><br>  /**<br>   * Update Prepared Qty and maintain item invariants.<br>   */<br>  public Item updatePreparedQty(final int qtyPrepared) {<br>    if (qtyPrepared &gt; this.qty) {<br>      throw new IllegalArgumentException(&quot;prepared qty is greater than order qty&quot;);<br>    }<br>    this.qtyPrepared = qtyPrepared;<br>    if (qty == qtyPrepared) {<br>      pickedUp = true;<br>    }<br>    return this;<br>  }<br>}</pre><p>Next we will make this Aggregate <strong>flowable, </strong>means<strong> </strong>the Aggregate lifecycle will be handled by the defined business flows.<br>Each business flow is represented by a Json file and can act as a complete business process.</p><h4>📦 Step1 — library dependency</h4><pre>dependencies {<br> implementation &quot;io.github.progmodek:flow-reactive:1.0.1&quot; // &quot;io.github.progmodek:flow:1.0.1&quot; for non-reactive<br>}</pre><h4>🎛️ Step2 — Action, States and flow.json</h4><p>Define Actions, States and a (or multiple) process/flow presented by JSON files.</p><ul><li><strong>ACTION enum</strong></li></ul><pre>public enum OrderPreparationAction implements FlowAction {<br>  START_PREPARATION(USER),<br>  PICK_ITEMS(USER),<br>  PICKUP(USER),<br>  NOTIFY_OM(SYSTEM); // Notify the Order Manager than the preparation is completed<br><br>  private final ActionType type;<br>}</pre><blockquote>USER vs SYSTEM indicates if its a user action or system action (NOTIFY_OM is a system action invoked automatically by the system).</blockquote><ul><li><strong>STATE enum</strong></li></ul><pre>public enum OrderPreparationState implements FlowState {<br>  TO_PREPARE,<br>  IN_PREPARATION,<br>  PENDING_PICKUP,<br>  DELIVERED,<br>  RETRY_NOTIFICATION,<br>  COMPLETED,<br>  ERROR<br>}</pre><ul><li><strong>FlowType enum</strong></li></ul><pre>public enum OrderPreparationFlowType implements FlowType {<br>  DEFAULT(&quot;flow/in-store-workflow.json&quot;, OrderPreparationAction.class, OrderPreparationState.class);<br><br>  @Getter<br>  private final String template;<br>  @Getter<br>  private final Class&lt;? extends FlowAction&gt; flowActionType;<br>  @Getter<br>  private final Class&lt;? extends FlowState&gt; flowStateType;<br><br>}</pre><blockquote>This means that <strong>DEFAULT</strong> flowType is based on <strong>OrderPreparationAction</strong> and <strong>OrderPreparationState</strong> enums, and presented by <strong>in-store-workflow.json</strong> file.<br>you can have for ex another type EXPRESS with another Json file defining another flow.</blockquote><ul><li><strong>Json file</strong></li></ul><pre>{<br>  &quot;actions&quot;: [<br>    {<br>      &quot;name&quot;: &quot;START_PREPARATION&quot;,<br>      &quot;delegate&quot;: &quot;startPreparationDelegate&quot;<br>    },<br>    {<br>      &quot;name&quot;: &quot;PICK_ITEMS&quot;,<br>      &quot;delegate&quot;: &quot;pickItemsDelegate&quot;<br>    },<br>    {<br>      &quot;name&quot;: &quot;PICKUP&quot;,<br>      &quot;delegate&quot;: &quot;pickupDelegate&quot;<br>    },<br>    {<br>      &quot;name&quot;: &quot;NOTIFY_OM&quot;,<br>      &quot;delegate&quot;: &quot;notifyDelegate&quot;<br>    }<br>  ],<br>  &quot;states&quot;: [<br>    {<br>      &quot;name&quot;: &quot;TO_PREPARE&quot;,<br>      &quot;initial&quot;: true,<br>      &quot;transitions&quot;: [<br>        {<br>          &quot;action&quot;: &quot;START_PREPARATION&quot;,<br>          &quot;result&quot;: {<br>            &quot;success&quot;: &quot;IN_PREPARATION&quot;<br>          }<br>        }<br>      ]<br>    },<br>    {<br>      &quot;name&quot;: &quot;IN_PREPARATION&quot;,<br>      &quot;transitions&quot;: [<br>        {<br>          &quot;action&quot;: &quot;PICK_ITEMS&quot;,<br>          &quot;result&quot;: {<br>            &quot;partial&quot;: &quot;IN_PREPARATION&quot;,<br>            &quot;full&quot;: &quot;PENDING_PICKUP&quot;<br>          }<br>        }<br>      ]<br>    },<br>    {<br>      &quot;name&quot;: &quot;PENDING_PICKUP&quot;,<br>      &quot;transitions&quot;: [<br>        {<br>          &quot;action&quot;: &quot;PICKUP&quot;,<br>          &quot;result&quot;: {<br>            &quot;success&quot;: &quot;DELIVERED&quot;<br>          }<br>        }<br>      ]<br>    },<br>    {<br>      &quot;name&quot;: &quot;DELIVERED&quot;,<br>      &quot;transitions&quot;: [<br>        {<br>          &quot;action&quot;: &quot;NOTIFY_OM&quot;,<br>          &quot;result&quot;: {<br>            &quot;success&quot;: &quot;COMPLETED&quot;<br>          },<br>          &quot;exceptions&quot;: {<br>            &quot;001&quot;: &quot;RETRY_NOTIFICATION&quot;<br>          },<br>          &quot;timer&quot;: {<br>            &quot;sec&quot;: 0<br>          }<br>        }<br>      ]<br>    },<br>    {<br>      &quot;name&quot;: &quot;RETRY_NOTIFICATION&quot;,<br>      &quot;transitions&quot;: [<br>        {<br>          &quot;action&quot;: &quot;NOTIFY_OM&quot;,<br>          &quot;result&quot;: {<br>            &quot;success&quot;: &quot;COMPLETED&quot;<br>          },<br>          &quot;exceptions&quot;: {<br>            &quot;001&quot;: &quot;RETRY_NOTIFICATION&quot;<br>          },<br>          &quot;retry&quot;: {<br>            &quot;number&quot;: 3,<br>            &quot;exceeded&quot;: &quot;ERROR&quot;<br>          },<br>          &quot;timer&quot;: {<br>            &quot;sec&quot;: 10<br>          }<br>        }<br>      ]<br>    },<br>    {<br>      &quot;name&quot;: &quot;ERROR&quot;,<br>      &quot;transitions&quot;: []<br>    },<br>    {<br>      &quot;name&quot;: &quot;COMPLETED&quot;,<br>      &quot;transitions&quot;: []<br>    }<br>  ]<br>}</pre><blockquote>→ define <strong>Actions</strong> with their associated <strong>delegates</strong> (these delegates will be invoked when the action is invoked)<br> → define <strong>States</strong> and <strong>Transitions</strong> using the defined <strong>Actions,</strong> each transition can lead to a different state based on a <strong>functional result</strong> (like “full” or “partial” preparation)<br> → define <strong>Timers </strong>if you want the Transition to be invoked automatically by the system (timer of zero, means invoked immediately — as soon as possible),<br>ex: when arriving to DELIVERED state, the NOTIFY_OM action will be called in an async way directly by the system</blockquote><h4>⚙️ Step3 — Implement Flowable interface</h4><p>The Aggregate must implement the Flowable interface, which means nothing more than adding Id, State and Flow properties to the Aggregate</p><pre>public class OrderPreparation implements Flowable&lt;UUID&gt; {<br>  @Builder.Default<br>  private UUID id = UUID.randomUUID();<br>  private String orderRef;<br>  private List&lt;Item&gt; items;<br><br>  ////////////////////////////<br>  // These are the properties related to the process<br>  private String state;<br>  private Flow flow;<br>  //////////////////////////<br><br><br>// the rest is the same as initila code<br>}</pre><h4>✍️ Step4 — Implement delegates defined in flow.json</h4><p>Define an ActionDelegate for each Action.<br>these delegate encapsulate the necessary business logic for the corresponding action.</p><p>Ex:</p><pre>public class startPreparationDelegate<br>    implements ActionDelegate&lt;OrderPreparation, Map&lt;String, String&gt;, OrderPreparation&gt; {<br><br>  @Override<br>  public Mono&lt;OrderPreparation&gt; execute(final OrderPreparation orderPreparation,<br>                                        final Map&lt;String, Object&gt; actionContext,<br>                                        final Map&lt;String, String&gt; inputParams) {<br>    log.info(&quot;startPreparation invoked&quot;);<br>    return Mono.just(orderPreparation);<br>  }<br>}</pre><blockquote>Each delegate must implement the generic <strong>ActionDelegate&lt;T extends Flowable, I, R&gt;</strong><br> -<strong>T</strong> type is your aggregate<br> -<strong>I</strong> type is the input that you can pass to the delegate (a request object containing params)<br> -<strong>R</strong> type is the return type (in our ex its the aggregate itself, but you can return a response from calling an external api for ex)</blockquote><blockquote><strong>Note</strong>: for the system action **TIMEOUT” we extends <strong>SystemActionDelegate</strong> which is a special implementation of ActionDelegate without input params and the aggregate as return value</blockquote><h4>🗄️ Step5 —Define Your domain Repository and your DataBase</h4><p>your DomainRepository must extends the <strong>FlowRepository</strong> interface, <br>ex:</p><pre>public interface OrderPreparationRepository extends ReactiveCrudRepository&lt;OrderPreparation, UUID&gt;, FlowRepository&lt;OrderPreparation, UUID&gt; {<br>}</pre><h4>🚀 Step6 — Create the FlowEngine</h4><p>The FlowEngine is pivotal in managing the lifecycle of flowable domain objects, interfacing with the repository to maintain state consistency and handle transitions.</p><pre>@Bean<br>FlowEngine&lt;OrderPreparation, UUID&gt; flowEngine(OrderPreparationRepository repo) {<br>    return new FlowEngine&lt;&gt;(UUID.class, OrderPreparation.class, repo);<br>}</pre><blockquote>-ID class type of your Aggregate<br>-Aggregate class type<br>-Repository of your domain</blockquote><h4>🔄 Step7 — Make your domain flowable and invoke actions</h4><h4>1- Make your domain flowable:</h4><pre>// create your aggregate<br>OrderPreparation orderPreparation = OrderPreparation.builder().build();<br>// make your domain flowable<br>flowEngine.makeFlowable(orderPreparation, OrderPreparationFlowType.DEFAULT, Map.of());</pre><h4>2- Invoke Actions:</h4><pre>// invoke START_PREPARATION action<br>flowEngine.applyAction(id, START_PREPARATION, inputParams) </pre><p>And here you are, now your aggregate look likes:</p><pre>{<br>    &quot;id&quot;: &quot;fac59542-f5cb-4024-8dee-df584bfb8b4d&quot;,<br>    &quot;orderRef&quot;: &quot;orderXYZ&quot;,<br>    &quot;items&quot;: [<br>        {<br>            &quot;skuId&quot;: &quot;123&quot;,<br>            &quot;name&quot;: &quot;sku123&quot;,<br>            &quot;qty&quot;: 2,<br>            &quot;qtyPrepared&quot;: 0,<br>            &quot;pickedUp&quot;: false<br>        },<br>        {<br>            &quot;skuId&quot;: &quot;456&quot;,<br>            &quot;name&quot;: &quot;sku456&quot;,<br>            &quot;qty&quot;: 3,<br>            &quot;qtyPrepared&quot;: 0,<br>            &quot;pickedUp&quot;: false<br>        }<br>    ],<br>    &quot;state&quot;: &quot;IN_PREPARATION&quot;,<br>    &quot;flow&quot;: {<br>        &quot;expiresAt&quot;: null,<br>        &quot;actions&quot;: [<br>            {<br>                &quot;name&quot;: &quot;START_PREPARATION&quot;,<br>                &quot;type&quot;: &quot;USER&quot;,<br>                &quot;count&quot;: 1,<br>                &quot;variables&quot;: {<br>                    &quot;transition&quot;: &quot;success&quot;<br>                },<br>                &quot;executions&quot;: [<br>                    {<br>                        &quot;executedAt&quot;: &quot;2024-01-21T19:48:27.575419Z&quot;,<br>                        &quot;result&quot;: &quot;success&quot;,<br>                        &quot;error&quot;: null,<br>                        &quot;fromState&quot;: &quot;TO_PREPARE&quot;,<br>                        &quot;toState&quot;: &quot;IN_PREPARATION&quot;<br>                    }<br>                ]<br>            }<br>        ],<br>        &quot;flowType&quot;: &quot;DEFAULT&quot;,<br>        &quot;eligibleActions&quot;: [<br>            &quot;PICK_ITEMS&quot;<br>        ],<br>        &quot;variables&quot;: {}<br>    }<br>}</pre><blockquote>we can see when the <strong>START_PREPARATION</strong> action was executed, and the current state is <strong>IN_PREPARATION</strong> and we see that the next eligible action <strong>PICK_ITEMS</strong></blockquote><h4>📣 Step8 — Listen and publish flow events</h4><p>Each executed Action is considered as a flow Event.<br>All flow events are pushed to EventsPublishers, implementing custom event publishers allows you to have an event-driven architecture.<br>You can define your own Event Publisher:</p><pre>@Component<br>@Slf4j<br>public class KafkaEventPublisher implements EventsPublisher {<br>  @Override<br>  public void publishEvents(final Flowable aggregate) {<br>    log.info(&quot;PUBLISH EVENTS TO KAFKA IF YOU WANT&quot;);<br>  }<br>}</pre><h3>🏗️ Library DDD Design</h3><p>The framework design follows DDD principles.</p><ul><li>Your Aggregate (your principal entity), is at the heart of the domain</li><li>The Framework flowEngine acts as the Application layer of your domain</li><li>The flow related mechanism (actions eligibility, transitions, etc..) is coded as a Domain Service</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4Lmzjskrw_FTcPrKTbqLA.png" /><figcaption>Sequence Diagram</figcaption></figure><blockquote>BLUE : Framework Components<br>GREEN : Your components</blockquote><h3>✅ Advantages : Why FDD?</h3><p>FDD is not just a technical framework, it’s a <strong>mindset shift</strong>.<br>here is some of the benefits it brings:</p><h4>Consistency and auditability</h4><p>→ Enables easy tracking and auditing of all state changes<br> → With state and transition history within the domain, there’s no loss of data or inconsistencies</p><h4>Unit Testing</h4><p>→ Facilitates independent testing of aggregate and process behaviours.</p><h4>Synchronous user request-response capabilities:</h4><p>→ Improve system-user interactions and provides UX flexibility</p><h4><strong>Asynchronous system actions:</strong></h4><p>→ Define system-triggered Actions, like timeouts, to automate specific flow transitions<br>→ Non blocking operations: by handling actions asynchronously, the system can continue performing other actions, improving overall efficiency</p><h4>Facilitate the UX of your domain with process-centric features:</h4><p>→ expiresAt: let users know when and if the process will expire<br> → eligibleActions: gives the user the possible allowed actions (depending on the state)</p><h4>Enhanced Maintainability:</h4><p>→ Say goodbye to scattered business logic. Everything resides cohesively within your domain<br> → Simplifies future evolutions with dynamic workflows</p><h4>Easy to use and fun to integrate:</h4><p>→ Intuitive design with simple configuration steps.<br> → Seamless integration with only some few components to configure</p><h4>Cost &amp; time effective:</h4><p>→ Reduces the overhead of managing separate BPM tools<br> → Quick learning curve, very simple to understand</p><h3>💼 Other Use Cases</h3><p>FDD isn’t confined to a single use case. Whether it’s managing c<strong>heckout processes</strong>, <strong>product lifecycles</strong>, or <strong>job applications</strong>, FDD can be adapted to a myriad of scenarios, making every domain inherently process-centric.</p><blockquote>🌟 In reality even static domain can have their own process-centric view with a single unchanged state, dont you think ?</blockquote><h3>🤝 Get in Touch for Support and Collaboration</h3><p>If you’re intrigued by FDD and its potential, reach out for support, collaboration, or just to share your thoughts. <br>Im eager for your feedbacks and to support your projects using this framework.<br>Let’s innovate and create together!</p><p><strong>Explore the documentation</strong>: <a href="https://github.com/progmodEK/flow-driven-domain">GitHub Repository</a> <br><strong>Contact Me: </strong><a href="/service/mailto:elie.khoury.progmod@gmail.com">email</a></p><p>Cheers,</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5687d04ad379" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intertwine DDD and BPM — make your domain process centric]]></title>
            <link>https://medium.com/@elie.khoury.progmod/intertwine-ddd-and-bpm-make-your-domain-process-centric-894c460df509?source=rss-b82702ccc04d------2</link>
            <guid isPermaLink="false">https://medium.com/p/894c460df509</guid>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[bpmn]]></category>
            <category><![CDATA[saga]]></category>
            <category><![CDATA[orchestration]]></category>
            <dc:creator><![CDATA[Elie Khoury]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 10:42:43 GMT</pubDate>
            <atom:updated>2024-01-24T11:41:32.828Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Crafting Process-Centric Domain Models in DDD</strong></h3><p>This article addresses the complexities arising when domain models in Domain-Driven Design (DDD) encompass both state-based and process-based rules.</p><p>It explores the concept of a <strong>process-centric domain</strong> as a means to effectively manage this complexity.</p><h3>📜 <strong>Background</strong></h3><p>In <strong>Domain-Driven Design</strong> (DDD) complex application are decomposed into smaller contexts or <strong>bounded contexts</strong> each driven by its unique domain to achieve a more flexible and scalable solution.<br> Each context maintains its own <strong>ubiquitous language </strong>ensuring clarity and consistency in communication.<br> Central to these contexts are domain models composed of aggregates — key elements that enforce the integrity and consistency of business rules and logic, known as business invariants.</p><h3>🌀<strong>The Complexity of Integrating State and Process in Domain Models</strong></h3><p>Domains often incorporate <strong>state-based </strong>and<strong> process-based rules.<br> </strong>When these state-dependent rules come into the picture, the domain’s overall structure becomes more complex over time, making both evolutionary changes and maintenance more difficult.</p><p>Managing the state complexity often leads us to use state machines or business process management (BPM) tools.<br> While valuable, <strong>these tools operates as distinct units</strong> from the aggregate, leading to</p><ul><li><strong>potential inconsistencies </strong>when comparing BPM state versus Aggregate state</li><li><strong>integration challenges </strong>that emerge from trying to synchronize separate systems.</li><li><strong>scattered business logic </strong>where responsibilities are divided between BPM tools and aggregate invariants, leading to a fragmented domain model.</li></ul><p>Here is the corresponding design</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hqFyDtJ8HiCyKFbwxLraeg.png" /><figcaption>fig1 → 2 separate states</figcaption></figure><blockquote>the same problem applies when using a StateMachine (like Spring state Machine)</blockquote><p>The next section is about how we can tackle this complexity by crafting a process-centric domain.</p><h3>📈 <strong>Embracing a Process-Centric Approach in Domain Models</strong></h3><p>Addressing the complexities identified earlier, we shift our focus to a process-centric approach in Domain-Driven Design (DDD). This paradigm views the domain itself as an <strong>evolving process</strong>, inherently incorporating elements like <strong>actions</strong>, <strong>transitions</strong>, and <strong>states</strong> into the <strong>ubiquitous language.</strong></p><p>The <strong>domain model</strong> becomes not just a static representation of data and rules, but a dynamic reflection of the process in its current state.<br> This integration is crucial for maintaining a clear and consistent view of the process within the domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVN7bHdRyJGFUGxakBTExw.png" /><figcaption>fig2 → the aggregate holds the process state</figcaption></figure><p>Let’s explore this concept further with a practical use case, applying DDD principles to achieve our goal of a truly integrated process-centric domain model.</p><h3>💼 <strong>Illustrating Process-Centric Domain : The Order Preparation Case Study</strong></h3><p>When a customer places an order online with the click-and-collect option, our system initiates an orderPreparation in a TO_PREPARE state. The objective is to navigate the order through various steps until it’s ready for customer pickup.</p><p><strong>From a process point-of-vue</strong>, the journey of the order preparation can be defined by the following states, actions, and rules (integral to the ubiquitous language):</p><p><strong>States:</strong></p><p>→ TO_PREPARE: <em>initial state<br> → IN_PREPARATION: The order is actively being prepared, items are being picked<br> → PENDING_PICKUP: Preparation is complete, and the order is waiting for the customer to collect it<br> → DELIVERED: The customer has picked up the order, completing the process</em></p><p><strong>Actions<em>:</em></strong></p><p>→ START_PREPARATION: <em>start the preparation, transitioning to IN_PREPARATION state<br> → PICK_ITEMS: Select items for the order. This can occur multiple times. Once all items are picked, the order moves to PENDING_PICKUP<br> → PICKUP: The customer collects their order, transitioning it to the DELIVERED state.<br> → NOTIFY_OM: notify Order Manager, automatically triggered when the order reaches the DELIVERED state, informing the Order Manager that the order has been picked up.</em></p><p><strong>Process rules:</strong></p><ul><li><strong>Sequential Flow</strong>: The order must follow the sequence of steps</li><li><strong>Multiple Item Picking</strong>: <em>PICK_ITEMS can </em>be repeated several times as needed. Only when all items are ready then it transit to <em>PENDING_PICKUP</em></li><li><strong>Automatic Notification</strong>: Upon reaching <em>DELIVERED </em>state, the system must automatically notifies the Order Manager.</li><li><strong>Error Handling</strong>: In case of notification failure, the order enters RETRY_NOTIFICATION , where it attempts re-notification every 10 seconds, up to 3 retries, then moves to a COMPLETED state in case of success, or ERROR state in case of failure.</li></ul><p><strong>From an aggregate point-of-vue </strong>we have these invariants:</p><ul><li><strong>Item Existence Check</strong>: The system checks that the items being picked are part of the original order.</li><li><strong>Quantity Verification</strong>: The quantity of each item picked cannot exceed the quantity specified in the order.</li></ul><h3>🛠️ <strong>Implementing the Process-Centric Model</strong></h3><p>To effectively implement a process-centric domain model, we need to address two main aspects:</p><p><strong>1) Implement process rules</strong></p><p>Adhering to DDD principles, it’s clear that process rules cannot be wholly contained within the aggregate itself. A more pragmatic solution is to employ a <strong>Stateless Domain Service</strong>. This service is responsible for several key functions:</p><ul><li>check the eligibility of an action</li><li>Performing necessary operations related to the process, which may include calling external APIs.</li><li>invoke relevant methods on the aggregate</li></ul><p>Of course this approach presents challenges, and the goal is not to develop a complete BPM product</p><p><strong>2) Maintaining Process State within the Aggregate</strong></p><p>This is achieved by adding to the aggregate these 2 properties:</p><ul><li>a <strong>State</strong> String to capture the current state of the aggregate</li><li>a <strong>Flow</strong> to hold a view of the process, such as executed actions, results of transitions, process variables, and so on.</li></ul><p>This integration approach effectively resolves the issue of dual states as depicted in fig1, leading to a more unified and coherent domain model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B51GXN6ixpqD112mCqbMcQ.png" /><figcaption>fig3 → DDD design of a process-centric domain</figcaption></figure><h3>💡<strong>Advantages of the process-centric model</strong></h3><ul><li><strong>Consistency</strong>: By maintaining both state and transition history within the domain, we ensure data integrity and resolve potential inconsistencies.</li><li><strong>Auditability</strong>: Facilitating tracking and auditing of state changes.</li><li><strong>Business Insight</strong>: The integration enables the generation of new KPIs, like tracking conversion rates from one process step to another.</li><li><strong>Performance</strong>: The entire process — from loading the aggregate, executing domain service rules, to saving the updated aggregate — becomes more efficient, eliminating the need to query separate units for process states.</li></ul><p>In the following section, we will explore the technical requirements needed to realize this model</p><h3>🧩 <strong>Technical Requirements</strong></h3><p>To fully realise the process-centric domain model in practice, specific technical components are necessary:</p><ol><li><strong>Workflow Engine</strong> : The ideal solution is a workflow engine that aligns with the DDD design outlined in fig3. This engine should act as the <strong>application layer of our domain</strong>, receiving and processing actions.</li><li><strong>FlowService — Stateless Domain Service</strong>: As previously mentioned, this service is crucial for handling process rules. It should be capable of invoking aggregate methods and updating the State and Flow value objects within the aggregate, thus ensuring a seamless integration of process logic with domain data.</li></ol><h3>🚀 <strong>The implementation: Flow Driven Domain Library</strong></h3><p>Well let me tell you that this engine we talked about was developed to implement a <strong>complete checkout process</strong> for one of the <strong>biggest retail company</strong>.</p><p>We developed our own workflow engine crafted to our specific business needs such as:</p><ul><li>A significant portion of the flow being synchronous, exposed via APIs.</li><li>Process timeouts after a period of inactivity.</li><li>High performance in processing actions, including process creation, as we operate in a synchronous communication environment.</li><li>Robust error handling and retry mechanisms.</li><li>The capability to complete asynchronous tasks (like sending notifications to an Order Manager).</li><li>Flexibility to accommodate different types of processes (e.g., standard checkout vs. express checkout).</li></ul><p>The project was a <strong>big success</strong> specially due to the DDD design we talked about and the advantages that comes with such as:</p><ul><li><strong>Consistency</strong>: The aggregate itself maintains its state and executed steps, ensuring a coherent and reliable process flow.</li><li><strong>Monitoring</strong>: The model facilitates the creation of dashboards and monitoring tools by logging the aggregate state, including both domain invariants (like item quantities) and process-related data (like executed steps and expiration times).</li><li><strong>Debugging and Auditing</strong>: The centralized nature of the model simplifies troubleshooting and auditing processes.</li><li><strong>Adaptability</strong>: The framework easily adapts to new business flows and requirements.</li><li><strong>Accessible KPIs</strong>: Process-related KPIs, such as conversion rates, are readily available and easy to interpret.</li><li><strong>Performance</strong>: The streamlined process of reading, processing, and saving the aggregate ensures high performance, with no need for querying separate units for process-related state.</li><li><strong>Synchronous API Communication</strong>: The library supports efficient synchronous communication via APIs.</li></ul><p>The success of this project led us to the decision of developing the <strong>FDD (Flow driven domain) </strong>making it available as a Spring library for broader use, enabling every domain to become <strong>process-centric </strong>and<strong> flowable.</strong></p><p>A very short descriptif of how it function is:</p><ul><li>Define <strong>ACTIONS</strong> and <strong>STATES</strong> as Java enums and describe the process in a <strong>flow.json </strong>file.</li><li>Implement a <strong>Flowable</strong> interface in your domain aggregate, which involves adding state and flow properties.</li><li>Create an <strong>ActionDelegate</strong> Java class for each action, separating process-related tasks from aggregate behaviour.</li></ul><p>The framework then takes charge of parsing the JSON file, validating defined actions and states, and acting as the application layer of your domain by orchestrating necessary actions.</p><h4>🏗️ Framework DDD Design</h4><p>The global design follows the <strong>DDD principles</strong> we talked about earlier, here is a sequence diagram to understand how it works</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMPKFCe2OB4NQJs_rOv_XA.png" /></figure><p><strong><em>blue</em></strong><em> : Framework Components<br></em><strong><em>green</em></strong><em> : Your components<br>NB: The Port/Interface part that links the domain to the infra layer is not shown to simplify the diagram</em></p><blockquote>🔍 For those interested in exploring this innovative approach, please find the full documentation of the FDD library <a href="https://github.com/progmodEK/flow-driven-domain">here</a>.<br>And a complete implementation example of the Order Preparation process <a href="https://github.com/progmodEK/flow-driven-domain/tree/main/order-preparation-poc">here</a>.</blockquote><p><strong><em>I would love to have your feedbacks, please feel feee to review, test, ask as many questions as you want :)</em></strong></p><p>→ please read the second part about “Flow Driven Domain”</p><p><a href="https://medium.com/@elie.khoury.progmod/flow-driven-domain-fdd-enhance-your-domain-with-flow-capabilities-5687d04ad379">Flow Driven Domain (FDD) - enhance your domain with flow capabilities</a></p><p>Cheers,</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=894c460df509" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>