<?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 Ahmet Uygun on Medium]]></title>
        <description><![CDATA[Stories by Ahmet Uygun on Medium]]></description>
        <link>https://medium.com/@ygnhmt?source=rss-97432bd3696f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c03VCgEvGtjmSEPuRGAXNQ.jpeg</url>
            <title>Stories by Ahmet Uygun on Medium</title>
            <link>https://medium.com/@ygnhmt?source=rss-97432bd3696f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:00:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ygnhmt/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[Distrubuted transactions (SpringBoot 3 + Atomikos)]]></title>
            <link>https://medium.com/@ygnhmt/distrubuted-transactions-springboot-3-atomikos-a5adfcba2c41?source=rss-97432bd3696f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5adfcba2c41</guid>
            <category><![CDATA[distributed-transaction]]></category>
            <category><![CDATA[global-transaction]]></category>
            <category><![CDATA[spring-boot-3]]></category>
            <dc:creator><![CDATA[Ahmet Uygun]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 10:42:51 GMT</pubDate>
            <atom:updated>2023-09-15T10:43:30.021Z</atom:updated>
            <content:encoded><![CDATA[<p>Local transactions are effective at managing database operations within a single database or system, ensuring data consistency within a code block. However, their limitations become apparent when confronted with the complexities of coordinating and upholding data integrity across multiple databases or services.</p><p>For instance, consider a basic REST API POST operation that requires interactions with multiple databases and JMS sources. In such scenarios, relying solely on Spring’s local transactions (annotated with @Transactional) may lead to significant issues. If any part of the transaction encounters a failure, there is no straightforward way to roll back the changes made or prevent the dispatch of JMS messages.</p><p>Imagine a more practical use case: when a specific API call triggers a couple of actions.</p><ul><li>Firstly, data is inserted into the Account database,</li><li>Then an update in the Customer database,</li><li>Finally, three different messages are sent to a consumer via Kafka or JMS.</li></ul><p>Success in all these steps signifies a successful operation. However, real-world situations are rarely so straightforward.</p><p>Following issues might happen;</p><ul><li>A constraint violation or network problem while saving data in the Customer or Account database.</li><li>Problems might happed during message delivery due to a malfunctioning JMS or Kafka server.</li><li>Perhaps only the third message(first 2 messages was sent successfully) fails to send.</li></ul><p>In any of these scenarios, data consistency and reliability are compromised.</p><p>This is where distributed transactions step in as a vital solution. They offer robust mechanisms for achieving atomicity, isolation, durability, and coordination across various systems. Distributed transactions ensure that operations either fully succeed or have no lasting impact, effectively preventing data inconsistencies in complex distributed environments.</p><p>Spring had direct support for distributed transaction tools like Atomikos in the past. However, starting from Spring 3, this support has been discontinued, as indicated in the Spring Boot 3.0 Migration Guide <a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide">link</a>. I encountered a similar data consistency issue a few weeks ago, prompting me to seek assistance on Stack Overflow <a href="https://stackoverflow.com/questions/76837954/spring-boot-3-with-atomikos">link</a>. Today, I’m pleased to share that I’ve made significant progress in resolving this issue within my company, and I’m eager to document the solution in this article.</p><p>To illustrate the solution, I’ll be using a Java project derived from my previous article on Domain-Driven Design, and you can access the full code on <a href="https://github.com/ahmetuygun/xa-demo">GitHub</a>.</p><p>In this scenario, I’ve envisioned a visa application system for the fictional country of Krakozhia, which involves three key steps:</p><ol><li>Saving VisaApplication entities in a MySQL Visa database.</li><li>Saving SecurityCheck entities in another MySQL Security database.</li><li>Sending three distinct messages to three separate JMS consumers.</li></ol><p>To achieve this, we’ll need specific dependencies to integrate Atomikos into our project.</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;com.atomikos&lt;/groupId&gt;<br>   &lt;artifactId&gt;transactions-spring-boot3-starter&lt;/artifactId&gt;<br>   &lt;version&gt;6.0.0&lt;/version&gt;<br>&lt;/dependency&gt;<br><br>&lt;dependency&gt;<br>   &lt;groupId&gt;javax.transaction&lt;/groupId&gt;<br>   &lt;artifactId&gt;jta&lt;/artifactId&gt;<br>   &lt;version&gt;1.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>As I mentioned earlier, prior to Spring 3, we had the capability to utilize the following dependency. However, it’s worth noting that this support is no longer available.</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-jta-atomikos&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>For Mysql;</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;mysql&lt;/groupId&gt;<br>   &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;<br>   &lt;version&gt;8.0.33&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p><strong>For Jms</strong>;</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-artemis&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p><strong>UserTransaction defination;</strong></p><p>We’ll use JTA UserTransaction for defining transaction boundaries, while all additional transaction service tasks, such as resource enlistment and delisting, will be handled automatically.</p><pre>@Bean(name = &quot;userTransaction&quot;)<br>public UserTransaction userTransaction() throws Throwable {<br>    UserTransactionImp userTransactionImp = new UserTransactionImp();<br>    userTransactionImp.setTransactionTimeout(10000);<br>    return userTransactionImp;<br>}</pre><p><strong>Configuring Jms adapter;</strong></p><pre>@Bean<br>public JmsTemplate jmsTemplate() throws Throwable {<br>    return new JmsTemplate(connectionFactory());<br>}<br><br>@Bean(initMethod = &quot;init&quot;, destroyMethod = &quot;close&quot;)<br>public ConnectionFactory connectionFactory() throws JMSException {<br>    ActiveMQXAConnectionFactory activeMQXAConnectionFactory = new<br>            ActiveMQXAConnectionFactory();<br>    activeMQXAConnectionFactory.setBrokerURL(jmsUrl);<br>    activeMQXAConnectionFactory.setUser(jmsUserName);<br>    activeMQXAConnectionFactory.setPassword(jmsPassport);<br>    AtomikosConnectionFactoryBean atomikosConnectionFactoryBean = new AtomikosConnectionFactoryBean();<br>    atomikosConnectionFactoryBean.setUniqueResourceName(&quot;xamq&quot;);<br>    atomikosConnectionFactoryBean.setLocalTransactionMode(false);<br>    atomikosConnectionFactoryBean.setXaConnectionFactory(activeMQXAConnectionFactory);<br>    return atomikosConnectionFactoryBean;<br>}</pre><p><strong>Configuring Datasource ;</strong></p><pre>    @Bean(&quot;securityCheckDataSource&quot;)<br>    public DataSource securityCheckDataSource(@Qualifier(&quot;securityCheckDataSourceProperties&quot;) DataSourceProperties dataSourceProperties) {<br>        MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();<br>        mysqlXaDataSource.setUrl(dbUrl);<br>        mysqlXaDataSource.setUser(username);<br>        mysqlXaDataSource.setPassword(passport);<br><br>        AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();<br>        xaDataSource.setXaDataSource(mysqlXaDataSource);<br>        xaDataSource.setUniqueResourceName(&quot;xa_securityCheck&quot;);<br>        xaDataSource.setMaxPoolSize(30);<br>        return xaDataSource;<br>    }</pre><p>In conclusion, in the realm of modern application development, distributed transactions have emerged as a critical solution for ensuring data consistency and reliability across multiple systems and resources. The example code provided showcases the integration of Atomikos for managing distributed transactions within a Spring-based application. It addresses the complexities of coordinating database operations, JMS messaging, and more, offering a practical glimpse into how to maintain data integrity in distributed environments.</p><p>**Full code is <a href="https://github.com/ahmetuygun/xa-demo">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5adfcba2c41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Soft Introduction to Domain-Driven Design: From Theory to Java Code Implementation — Part 2]]></title>
            <link>https://medium.com/@ygnhmt/a-soft-introduction-to-domain-driven-design-from-theory-to-java-code-implementation-part-2-5aa7e1cfef65?source=rss-97432bd3696f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aa7e1cfef65</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[distributed-transaction]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Ahmet Uygun]]></dc:creator>
            <pubDate>Sat, 02 Sep 2023 12:09:48 GMT</pubDate>
            <atom:updated>2024-10-04T09:57:48.927Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Soft Introduction to Domain-Driven Design: From Theory to Java Code Implementation — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KN9afzPpCIQr0T_HGDVrQg.png" /></figure><p>Welcome back to the second part of our series on implementing Domain-Driven Design (DDD) in the real world using Java. In the previous article, we laid the groundwork by exploring the theoretical aspects of DDD. Now, we’re ready to bridge theory and practice by turning our knowledge into functional code.</p><p>I&#39;m planning to utilize the following technologies for our project: <strong>Java 17, Spring Boot 3, JMS , Spring Events, Atomikos, and MySQL.</strong></p><p><a href="https://github.com/ahmetuygun/VisaApplication">https://github.com/ahmetuygun/VisaApplication</a></p><blockquote>**It’s important to note that DDD doesn’t prescribe a specific architecture or technology stack. How you implement the communication between microservices, manage data persistence, and choose technologies is up to you and should be based on your team’s expertise and the specific requirements of your application.</blockquote><blockquote>**We will use Event-Driven Architecture with Spring events and JMS messages to communicate between domains demonstrates an event-driven architecture. DDD encourages asynchronous communication through events, enabling loose coupling and better scalability.</blockquote><blockquote>I am using <strong>Atomikos </strong>to implement distributed transactions, ensuring that processes like saving data and sending JMS messages are handled within a transactional framework.</blockquote><h3>Real-world Implementation in Java</h3><p>This article takes the DDD concepts we discussed earlier and applies them to Java programming. Java’s versatility and object-oriented nature make it an ideal candidate for translating DDD principles into tangible software solutions.</p><p>We’ll guide you through the practical steps of implementing DDD in a real-world scenario. From defining bounded contexts and aggregates to understanding entities and value objects, we’ll illustrate how repositories and services play a pivotal role in facilitating domain communication. Furthermore, we’ll emphasize key design concepts like ubiquitous language, context mapping, and maintaining a clear separation between domain logic and infrastructure.</p><h3>A Brief Recap of DDD</h3><p>Domain-Driven Design is more than a methodology — it’s a philosophy that aligns software development with the complexities of the real-world domain it serves. By collaborating with domain experts and stakeholders, DDD creates applications that not only work but also reflect the true nature of the problem domain.</p><p>Through concepts like aggregates, entities, value objects, and bounded contexts, DDD equips developers with tools to build maintainable, scalable applications. This shared understanding between technical and non-technical parties bridges the gap between software development and business needs.</p><p>As we proceed, we’ll witness DDD principles come alive in our Java project, showcasing the real-world impact of Domain-Driven Design. Let’s dive into the heart of our DDD implementation, where theory becomes practice.</p><p>Scenario: <strong>Visa Application and Security System</strong></p><p>Fictional country, Krakozhia, a picturesque land known for its rich culture and breath-taking landscapes. To ensure security and manage its borders, Krakozhia requires visitors from certain countries to apply for E-Visa before entering. In this scenario, we’ll create a Visa Application System that handles the visa application process while maintaining security and efficiency.</p><blockquote>Visa application flow: First, the visa officer collects important information such as personal details, passport information, the applicant’s country of origin, the purpose of the visit, intended travel period, and their current address. Then, a security check is conducted using three key security resources: Source1, Source2, and Source3. If the check yields positive results, the visa is issued.</blockquote><p>Visa Application Microservice(visa-application)</p><p>Domains:</p><p>1.VisaApplication Domain:</p><ul><li>Responsible for handling visa applications.</li><li>Entities: VisaApplication</li><li>Actions: Receive and validate visa applications, save application to database, send events to Security domain.</li></ul><p>2. Security Domain:</p><ul><li>Handles security checks for visa applications.</li><li>Entities: SecurityCheck</li><li>Actions: Validate application data, save security check result to database, send messages to Security Microservice.</li></ul><p>3. VisaIssue Domain:</p><ul><li>Deals with visa issuance after successful security checks.</li><li>Entities: VisaIssue</li><li>Actions: Receive security check results, issue visas, update database, send events to notify successful visa issuance.</li></ul><p>Security Microservice:</p><ul><li>Handles security checks and interacts with Security Domain.</li><li>Focus is on security checks and <strong>not covered</strong> in detail in this scenario.</li></ul><p>Flow of Actions:</p><ol><li>An Applicant submits a visa application through the Visa Application System.</li><li>The VisaApplication Domain validates the application data, creates a VisaApplication object, and saves it to the database.</li><li>Upon successful application storage, a SecurityCheckRequiredEvent is sent to the Security Domain using Spring events.</li><li>The SecurityCheck Domain receives the event, performs security checks, and creates a SecurityCheck object based on the validation outcome. It saves the result in the database.</li><li>The Security Domain publishes a SecurityCheckMessageEntity to Source1, Source2, and Source3 JMS queues for further processing.</li><li>The Security Microservice listens to the JMS queue and receives the SecurityCheckResultMessage. It performs additional security checks (not detailed in this scenario).</li><li>Once security checks are completed by the Security Microservice, it sends a SecurityCheckResult back for each source to the Security Domain via JMS.</li><li>The Security Domain receives the SecurityCheckResult for each source and updates the security check status in the database, and sends a SecurityCheckCompletedEvent to the VisaApplication Domain.</li><li>The VisaApplication Domain applies security check and sends VisaApprovedEvent or VisaRejectedEvent to VisaIssue domain.</li></ol><p>In this scenario, we’ve established a multi-domain interaction for visa application and security checks. Each domain has its own responsibilities and interactions, communicating via Spring events and JMS messages. This design ensures a clear separation of concerns and allows for the individual scalability of each domain while maintaining effective communication throughout the visa application and security process.</p><p><strong>Recommended Practice: Application, Domain, Infrastructure Layers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*Wnp4sr4x62I5wM-de5zRnw.png" /></figure><p>The division of modules into “Application,” “Domain,” and “Infrastructure” is a common and recommended practice in DDD to organize your codebase and maintain a clear separation of concerns. Let’s delve into each module’s role:</p><ol><li><strong>Domain Module:</strong></li></ol><ul><li>This module holds the core business logic and domain model of your application. It encapsulates entities, aggregates, value objects, domain services, and business rules. The domain module focuses on representing and solving the business problems.</li><li>Here, we define the essential building blocks that capture the concepts and behavior of our domain. This is where you model the unique aspects of our business and ensure the integrity and consistency of our data.</li><li>The domain module <strong>should be independent </strong>of frameworks, libraries, and external dependencies.</li></ul><p><strong>2. Application Module:</strong></p><ul><li>The application module is responsible for coordinating the interaction between different parts of your system. It contains use cases, application services, and orchestration logic.</li><li>This module utilizes the domain model from the domain module to implement specific user actions and use cases. It acts as the entry point for external interactions and triggers domain behaviour.</li><li>The application module might also handle things like authorization, validation, and user input processing.</li><li>It’s important to keep this module thin and focused on coordinating actions rather than implementing business logic.</li></ul><p><strong>3. Infrastructure Module:</strong></p><ul><li>The infrastructure module deals with technical concerns such as data storage, external communication, and framework integrations.</li><li>This module includes components for database access, messaging (like JMS in our scenario), APIs, external services, and any other infrastructure-related code.</li><li>The infrastructure module often adapts the domain to external technologies and provides implementations for repository interfaces, event publishing, etc.</li><li>By isolating infrastructure code, you keep the core domain code clean and maintainable.</li></ul><p>Dividing your codebase into these three modules helps you achieve the following benefits:</p><ul><li><strong>Separation of Concerns</strong>: Each module has a specific role, making it easier to understand, modify, and maintain different aspects of your application.</li><li><strong>Flexibility and Replaceability</strong>: Because the modules are separated, you can change or replace one module without affecting others. For example, you can swap out the data storage mechanism without altering the core business logic.</li><li><strong>Testability</strong>: The modular structure enhances testability. The domain logic can be tested in isolation without involving external dependencies.</li><li><strong>Collaboration</strong>: Different teams or developers can work on different modules concurrently, as long as they adhere to the defined interfaces and boundaries.</li></ul><p>Lets start coding;</p><p>1-Writing VisaApplicationDomain.</p><pre>public class VisaApplication extends AggregateRoot&lt;VisaApplicationId&gt; {<br>    private Applicant applicantPersonalInfo;<br>    private PassportInformation applicantPassportInfo;<br>    private LocalDate applicationDate;<br>    private VisaType purposeOfVisit;<br>    private LocalDate intendedArriveDate;<br>    private Address applicantAddress;<br>    private VisaApplicationStatus status;<br>    private VisaFeeReceipt visaFeeReceipt;<br><br>//constractor<br><br>public void validateForSubmission() {<br>        // Perform validation checks here<br>        if (applicantPersonalInfo == null) {<br>            throw new DomainException(&quot;Applicant personal information is required.&quot;);<br>        }<br>     <br>        // Perform additional validation checks as needed<br><br>        // If any validation fails, throw appropriate exceptions<br>    }<br>    public void applySecurityCheck() {<br>        // Implement security check logic here<br>        // This method can involve coordinating with the Security domain<br>        // and updating the status of the visa application accordingly<br>    }<br>}</pre><p><strong>Why </strong>VisaApplicationId<strong>is a value object rather than Long?</strong></p><p>Using VisaApplicationId as a value object rather than a simple Long identifier enhances your code&#39;s clarity and adherence to Domain-Driven Design principles. This approach adds a layer of semantic meaning, encapsulates validation rules, and promotes type safety. By containing logic within the value object, you ensure the identifier&#39;s validity and maintain domain integrity. This design choice also allows for future flexibility and easier separation of concerns within your domain model.</p><p><strong>What does it mean to have an </strong><strong>AggregateRoot&lt;VisaApplicationId&gt; in Domain-Driven Design, and why would an entity class extend from it?</strong></p><pre>public abstract class AggregateRoot&lt;T&gt; {<br>    private T id;<br>    private List&lt;ApplicationEvent&gt; domainEvents = new ArrayList&lt;&gt;();<br>    // Constructor<br>    protected AggregateRoot(T id) {<br>        this.id = id;<br>    }<br>    // Getter for the aggregate&#39;s domain events<br>    public List&lt;ApplicationEvent&gt; getDomainEvents() {<br>        return domainEvents;<br>    }<br>    // Apply a domain event to the aggregate<br>    protected void registerEvent(ApplicationEvent event) {<br>        domainEvents.add(event);<br>    }<br>    // Clear domain events after they have been handled<br>    public void clearDomainEvents() {<br>        domainEvents.clear();<br>    }<br>    // Getter for the aggregate root&#39;s identifier<br>    public T getId() {<br>        return id;<br>    }<br>}</pre><p>Creating aggregate roots is a key practice in Domain-Driven Design (DDD) that brings substantial benefits to complex domain modeling.</p><ol><li><strong>Transaction Management</strong>: Aggregate roots define transactional boundaries. Changes made within an aggregate are usually persisted together, ensuring that the data remains consistent and valid.</li><li><strong>Concurrency Control</strong>: Aggregates provide a natural boundary for managing concurrent access and updates. By controlling access through the aggregate root, you can implement optimistic or pessimistic concurrency control strategies.</li><li><strong>Domain Events</strong>: Aggregate roots are often responsible for generating and handling domain events that capture significant state changes. These events enable different parts of the system to react to changes in the domain.</li><li><strong>Enforce Business Rules</strong>: Aggregates encapsulate business rules and invariants, ensuring that the objects within an aggregate adhere to valid and consistent states. The aggregate root acts as a gatekeeper, enforcing these rules and maintaining data integrity.</li></ol><p><strong>Why is </strong><strong>VisaApplication considered an aggregate in the context of this application, and what characteristics define it as such?</strong></p><p>VisaApplication is considered an aggregate in the context of this application because it represents a cohesive group of domain objects that are treated as a single unit for maintaining data consistency. Within the aggregate, VisaApplication acts as the aggregate root, responsible for enforcing business rules, managing the state of related objects, and ensuring data integrity. By encapsulating related entities like PersonalInformation and value objects like PassportInformation and Address, the VisaApplication aggregate ensures that changes to its internal objects are controlled and coordinated through its root. This approach simplifies interactions, transaction management, and business logic enforcement, aligning with the principles of Domain-Driven Design.</p><p><strong>Writing VisaApplicationRepository interface.</strong></p><p>As mentioned earlier, repositories serve as abstractions that provide access methods to interact with the domain objects. These repository interfaces should reside within the Domain layer, defining the contract for data access operations. The concrete implementations of these repository interfaces belong in the Infrastructure layer, where the actual data access and storage mechanisms are implemented.</p><pre>public interface VisaApplicationRepository {<br>    Long generateId();<br><br>    VisaApplication retrieveVisaApplicationById(VisaApplicationId visaApplicationId) throws DomainException;<br>    <br>    void save(VisaApplication visaApplication);<br>  *<br>  *<br>  *<br>}</pre><p><strong>Writing </strong>VisaApplicationService.</p><p>A Service is a conceptual entity employed to encapsulate operations or behaviors that do not naturally align with the boundaries of a single entity or aggregate. In this example, we populate necessary objects such as Applicant details, address, and fee receipt. It’s important to note that all objects utilized here are located within the Domain layer, and database entities are not carried within this context. Additionally, any exceptions thrown within the service should be limited to Domain Exceptions.</p><p>Since domains operate within a single unit of work, they typically require transactional support. In our case, due to the utilization of distinct sources like JPA and JMS, distributed transactions become a necessity in this project to ensure data consistency and reliability.</p><pre>@Transactional(transactionManager = &quot;transactionManager&quot;)<br>public void processVisaApplication(VisaApplicationRequest request) throws DomainException {<br><br><br>    PassportInformation passportInformation = new PassportInformation(request.getPassportNumber(), request.getPassportExpirationDate(), request.getPassportIssuingCountryCode());<br>    VisaFeeReceipt visaPayment = repository.getVisaFeeReceipt(request.getPaymentId())<br>            .orElseThrow(() -&gt; new DomainException(&quot;Visa Fee Receipt couldn&#39;t found. &quot;));<br>    Applicant applicant = repository.getApplicant(request.getApplicantId())<br>            .orElseThrow(() -&gt; new DomainException(&quot;Applicant couldn&#39;t found. &quot;));<br>    Address address = repository.getAddress(request.getApplicantId())<br>            .orElseThrow(() -&gt; new DomainException(&quot;Address couldn&#39;t found. &quot;));<br><br>    if (!repository.isCountryEligibleForVisa(passportInformation.country().getCountryCode())) {<br>        throw new DomainException(&quot;Applicant&#39;s country is not eligible for the selected purpose of visit.&quot;);<br>    }<br><br>   /*<br>    some other checks<br>   * */<br><br>    VisaApplication visaApplication = new VisaApplication(new VisaApplicationId(repository.generateId()),<br>            applicant, passportInformation, LocalDate.now(), request.getVisaType(), request.getIntendedArriveDate(), address, visaPayment);<br><br>    visaApplication.validateForSubmission();<br>    repository.save(visaApplication);<br><br>    visaApplication.getDomainEvents().stream().forEach(applicationEventPublisher::publishEvent);<br>    visaApplication.clearDomainEvents();<br><br><br>}</pre><p>After initializing and performing external validations, we proceed to construct a Domain Entity, which in this example is also an aggregate. Subsequently, we invoke the necessary business method, validateForSubmission(). This method is responsible for ensuring the readiness of the entity for submission while enforcing domain-specific validation rules</p><pre>public void validateForSubmission() throws DomainException {<br><br><br>    if (intendedArriveDate != null &amp;&amp; intendedArriveDate.isAfter(maxIntendedArriveDate)) {<br>        throw new DomainException(&quot;Intended arrival date should be within a reasonable range from the application date.&quot;);<br>    }<br>    if (visaFeeReceipt == null || !visaFeeReceipt.valid()) {<br>        throw new DomainException(&quot;A valid visa fee receipt is required.&quot;);<br>    }<br><br>   *<br>   some other business validation<br>   *<br><br>    this.registerEvent(new SecurityCheckRequiredEvent(this,this));<br><br>}</pre><p>Once the values have been validated, we proceed to create an Event, which is then registered using the registerEvent method provided by the Aggregate.</p><p>After the successful execution of the validation method, we persist the entity by saving it. Subsequently, we publish all the events that have been registered</p><pre>visaApplication.getDomainEvents().stream().forEach(applicationEventPublisher::publishEvent);<br>visaApplication.clearDomainEvents();</pre><p>Writing <strong>VisaApplicationRepositoryImpl;</strong></p><p>We’ve previously defined the VisaApplicationRepository as an interface. Now, it’s time to provide the concrete implementation of this repository, and we do so within the Infrastructure layer. It’s crucial to emphasize that this layer is distinct from both the Domain and Application layers. In the Infrastructure layer, we address technical considerations like data storage, external communication, and framework integrations.</p><pre>@Service<br>public class VisaApplicationRepositoryImpl implements VisaApplicationRepository {<br>    private final JpaAddressEntityRepository addressEntityRepository;<br>    private final JpaApplicantEntityRepository applicantEntityRepository;<br>    private final JpaPassportEntityRepository passportEntityRepository;<br>    private final JpaPaymentEntityRepository paymentEntityRepository;<br>    private final JpaVisaApplicationEntityRepository visaApplicationEntityRepository;<br>    private final JmsTemplate jmsTemplate;<br>    <br>    public VisaApplicationRepositoryImpl(JpaAddressEntityRepository addressEntityRepository, JpaApplicantEntityRepository applicantEntityRepository, JpaPassportEntityRepository passportEntityRepository, JpaPaymentEntityRepository paymentEntityRepository, JpaVisaApplicationEntityRepository visaApplicationEntityRepository, JmsTemplate jmsTemplate) {<br>        this.addressEntityRepository = addressEntityRepository;<br>        this.applicantEntityRepository = applicantEntityRepository;<br>        this.passportEntityRepository = passportEntityRepository;<br>        this.paymentEntityRepository = paymentEntityRepository;<br>        this.visaApplicationEntityRepository = visaApplicationEntityRepository;<br>        this.jmsTemplate = jmsTemplate;<br>    }<br>*<br>*<br>*<br>    @Override<br>    public Long generateId() {<br>        return UniqueIdGenerator.generateUniqueId();<br>    }<br><br>    @Override<br>    public Optional&lt;VisaFeeReceipt&gt; getVisaFeeReceipt(Long paymentId) {<br><br>        return paymentEntityRepository.findById(paymentId)<br>                .map(entity -&gt; new VisaFeeReceipt(new VisaFeeReceiptId(entity.getId()), entity.getChargedAmount(), entity.getValid()));<br><br>    }</pre><p>It’s essential to keep in mind that within the Infrastructure layer, we should avoid throwing Domain Exceptions.</p><p><strong>Writing </strong>VisaApplicationEventListener.</p><p>After successful validation and data persistence, we triggered the ‘SecurityCheckRequiredEvent.’ As previously discussed, Domain-Driven Design advocates for Event-Driven Architecture to facilitate communication between different Domains. Now, our next step is to implement an event handler for this particular event.</p><pre>@Component<br>public class SecurityCheckEventListener {<br>    private final SecurityCheckService securityCheckService;<br><br>    public SecurityCheckEventListener(SecurityCheckService securityCheckService) {<br>        this.securityCheckService = securityCheckService;<br>    }<br><br>    @EventListener<br>    public void handle(SecurityCheckRequiredEvent securityCheckRequiredEvent) {<br><br>        securityCheckService.processSecurityCheckRequest(securityCheckRequiredEvent);<br><br>    }<br><br>}</pre><p>At this point, we’ve successfully completed the Visa Application acceptance process. Our next step is to perform security compliance checks. As previously detailed in the flow, the SecurityCheck Domain assumes the role of dispatching the necessary JMS messages to the queues of three security sources: Source1, Source2, and Source3.</p><p>SecuriyCheck has similar structure with in terms of layers, and behaviours. No need to elaborate them again and I&#39;m a bit tired to write:)</p><p>You can review all code from Github.</p><p>This article aimed to provide an accessible introduction to the concept of Domain-Driven Design (DDD) and demonstrates its practical implementation in Java. It begins by offering a brief overview of the previous article, establishing a real-world context for the Java code implementation that follows.</p><p>DDD, as explained, is a design approach that focuses on aligning software systems with the underlying domain or business it serves. It emphasizes the creation of well-defined domain models, clear boundaries between domains, and the use of events for effective domain communication.</p><p>The article then introduces a fictional visa application system set in the fictional country of Krakozhia. Three main domains — VisaApplication, Security, and VisaIssue — are defined, each responsible for specific aspects of the visa application process. Interactions between these domains are orchestrated using Spring events and JMS messaging.</p><p>VisaApplication serves as the central domain, encompassing entities like Applicant and PassportInformation. Validation and event publication are key components of this domain. SecurityCheck, the second domain, handles security compliance checks by sending JMS messages to Source1, Source2, and Source3. It maintains similar structural and behavioral patterns to the VisaApplication domain. VisaIssue, the third domain, comes into play after successful security checks, updating the visa issuance status.</p><p>Throughout the implementation, the article emphasizes the importance of adhering to DDD principles, including using domain events for communication and placing repository interfaces in the Domain layer while their implementations reside in the Infrastructure layer.</p><p>The article underscores the significance of maintaining clear boundaries between layers — Domain, Application, and Infrastructure — and the need for distributed transactions due to multi-source data interactions (JPA and JMS).</p><p>In conclusion, this article provides a practical, hands-on demonstration of how DDD principles can be applied in Java to solve complex real-world problems. It showcases the power of DDD in aligning software systems with business domains, ultimately leading to more robust and maintainable applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aa7e1cfef65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Soft Introduction to Domain-Driven Design: From Theory to Java Code Implementation]]></title>
            <link>https://medium.com/@ygnhmt/before-joining-my-current-company-domain-driven-design-ddd-used-to-be-a-subject-that-required-1a6af0c4535d?source=rss-97432bd3696f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a6af0c4535d</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ahmet Uygun]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 20:30:31 GMT</pubDate>
            <atom:updated>2024-10-04T09:56:04.422Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Soft Introduction to Domain-Driven Design: From Theory to Java Code Implementation - Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lGIZ0bTleSD05RAv3puRw.png" /></figure><p>Before joining my current company, Domain-Driven Design (DDD) used to be a subject that required preparation before interviews, just in case the interviewer decided to ask me about DDD. Fast forward to today, it’s an active part of my daily work. With every task, I find myself uncovering new insights thanks to DDD’s principles.</p><p>Initially, DDD seemed complex and challenging to grasp. Terms like ‘Aggregates,’ ‘Entities,’ and the fancy ‘Ubiquitous Language’ felt like barriers. But now, these terms are bridges that help us understand one another clearly. Ubiquitous Language? It’s just a way to say, ‘ we all understand each other.’</p><p>Domain-Driven Design (DDD) is like a solution for project chaos. It’s a toolkit that brings order to development. Instead of things being messy, DDD helps organise everything. It’s like a tool that makes business goals, technical work, and user needs fit together nicely. With DDD, things become more organised and structured, creating software that works well, even in complex situations.</p><p>This article is divided into two parts. The first part might not be the most exciting for everyone as it covers theory and DDD terminology.I will keep this part short as much as possible. The second part, on the other hand, gets hands-on with a real-world Java coding example. Let’s roll.</p><p><strong>Part 1. Theory and Terminology</strong></p><p>Domain-Driven Design (DDD) is an approach to software development that emphasises understanding and modelling the real-world problem domain within the software design process. It’s a methodology that aims to align the software closely with the complexities and intricacies of the business domain it serves.</p><p>At its core, DDD focuses on effective communication and collaboration between technical teams and domain experts. It provides a set of principles, patterns, and guidelines to structure and organise software projects, making them more maintainable, adaptable, and reflective of the underlying business requirements.</p><p>I will concentrate on explaining seven key terms that play a crucial role in understanding Domain-Driven Design (DDD): <strong>Ubiquitous Language, Bounded Contexts, Entities, Value Objects, Aggregates, Services, and Repositories.</strong> Before diving into the details of each concept, let’s take a brief overview of what they essentially are and the basic advice they provide</p><ol><li><strong>Ubiquitous Language</strong>: DDD advises to use the same words for things in your program that you use when talking about them with others. When you’re talking about code or having a tea/coffee chat, you’re speaking the same language. This helps everyone understand and work together.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUmopY7Hamwmx0m-jZgYcw.jpeg" /></figure><ol><li><strong>Bounded Contexts</strong>: Think of Bounded Contexts as different parts of a big library. Each section has its own type of books and special words to describe them, so people can find what they want easily. Use Bounded Contexts to keep things clear and separate. Make sure each area has its own way of talking about things, so everyone knows what’s going on.</li><li><strong>Entities</strong>: Think of entities as the main characters in a story. They’re like special characters with their own names, personalities, behaviours, and they can change over time. Each one has its own identity and can do different things as the story goes on.</li><li><strong>Value Objects</strong>: Value objects are special details that describe important things, like colors or prices. One important thing to remember is that value objects are usually immutable, which means once you create them, they don’t change. They stay the same, like a snapshot, to make sure everything is clear and reliable.</li><li><strong>Aggregates</strong>: Imagine putting things together in a group that make sense. This group is like a team and helps us understand things better.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*xMgd6fxWI8jnJxrfghurZw.jpeg" /></figure><ol><li><strong>Services</strong>: Think of helpers that can do special jobs for you. They don’t have their own lives, but they can help you get things done.</li><li><strong>Repositories: </strong>They are bridges between your application’s code and the data storage layer, like a JPA and JMS. They are facilitators data abstraction and management. (Generally Interfaces).</li></ol><p><strong>Ubiquitous Language</strong> is like a secret code in Domain-Driven Design (DDD) that makes communication super clear between techies and experts in a field. It’s about using the same words for stuff in the software as experts use in real life. So, when you’re talking about code or having a tea/coffee chat, you’re speaking the same language. This makes it way easier to understand each other, avoids confusion, and helps teams work together smoothly. It’s like having a translator that makes sure everyone is on the same page.</p><p>For example, think of making a fancy banking app. With Ubiquitous Language, the names you give to classes, methods, and things like account balances match the real banking terms like “Account,” “Transaction,” and “Balance.” This way, when developers and banking experts chat, they’re speaking the same lingo. A class named “Account” really is about bank accounts, and methods like “processTransaction” and variables like “accountBalance” make sense to everyone. It’s like turning a foreign language into something everyone understands, which helps the tech folks and the financial folks work together like a well-oiled machine.</p><p><strong>Bounded Contexts:</strong> Explicitly defined contexts that encapsulate specific parts of the domain and provide clear boundaries for concepts and terms. Basically, DDD advise to define clear boundaries between different bounded contexts. This separation prevents confusion and ensures that each context can evolve independently.</p><p>Let’s say, we’re developing an e-commerce platform with two bounded contexts: “Product Catalog” and “Order Management.”</p><p>In the “Product Catalog” context:</p><ul><li>Focus on managing product information like names, descriptions, and prices.</li><li>Define classes and methods specifically tailored to product-related operations.</li><li>Use terminology like “Product,” “Catalog,” and “Price” to reflect the context’s domain.</li></ul><p>In the “Order Management” context:</p><ul><li>Concentrate on handling customer orders, payments, and fulfillment.</li><li>Define classes and methods that deal with order processing and tracking.</li><li>Use terms like “Order,” “Payment,” and “Fulfillment” to match the context’s language.</li></ul><p>By maintaining these clear boundaries, the “Product Catalog” context remains separate from the “Order Management” context. Each context can evolve independently, and the codebase remains organized and focused on its specific domain concerns.</p><p><strong>Entities</strong> are the most important concept in Domain-Driven Design (DDD). They represent distinct and identifiable objects with a unique identity that runs through time and various states. Unlike simple data objects, entities have a lifecycle, and changes to their attributes are tracked over time. An entity’s identity remains constant even if its attributes change.</p><p>Entities are like real-world things that are special and have their own life stories. Think of them as important items in a game or a story. For example, in a banking app, you could have things like “Accounts,” “Transactions,” and “Customers” as entities. Account has an identity, state and life cycle. it’s not just any account, it’s one with its own identity, it has some important details (like how much money it has), and it goes through different phases (like when it’s opened, used, or closed). These entities help us keep track of special things and understand how they change over time.</p><p><strong>Value Objects</strong> are an essential building block in DDD. They represent objects that are immutable, meaning their state cannot be changed once they’re created. Unlike entities, value objects don’t have a distinct identity; they are defined solely by their attributes. They are used to encapsulate concepts in your domain that don’t change their meaning based on identity, and they help in modelling the behaviours and characteristics of those concepts.</p><p>Value objects don’t have their own lifecycle, state or identity; instead, they are characterised solely by their attributes and properties.</p><p>For instance, consider the “Address” of an Account holder. This “Address” doesn’t have a unique identity by itself, but it contributes to defining the Account holder’s information. Since it’s solely based on its attributes (like street, city, and postal code), it’s a prime candidate for being a value object.</p><p>Another example could be the “Amount” in a transaction. Each amount doesn’t need its own identity; rather, it’s just a number associated with the transaction. Therefore, “Amount” could be modelled as a value object.</p><p><strong>Choosing Between Entity and Value Object for an Objective</strong></p><p>Distinguishing between Entities and Value Objects in Domain-Driven Design (DDD) is important because they serve different roles and have different characteristics in your domain model. Here are some guidelines to help you differentiate between them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*r0qfbTJzOmtNxAPYacUBVw.png" /></figure><p>**BTW these are guidelines, and the final decision should be based on the unique requirements of your domain.</p><p><strong>Aggregates</strong>:</p><p>An aggregate is a fundamental concept in Domain-Driven Design (DDD) that groups together related entities and value objects into a single unit, forming a boundary for transactional consistency and enforcing business rules. Aggregates are a way to manage complexity and ensure that changes to the data maintain the integrity of the domain.</p><p><strong>Key Characteristics of Aggregates; Boundary and Transactional Consistency</strong></p><p><strong>Boundary</strong>: Aggregates define a boundary within which business rules and invariants are enforced. The internal components (entities and value objects) should be consistent and valid when viewed from outside the aggregate.</p><p><strong>Transactional Consistency:</strong> All changes to the data within an aggregate are treated as a single unit of work. Transactions are atomic, and changes within the aggregate are persisted or rolled back together to ensure consistency. In other words, all changes to the data within an aggregate either succeed together or fail together. This guarantees that the data remains in a valid and consistent state, even in the face of failures or interruptions.</p><p><strong>Repositories</strong> are abstractions that provide methods to access and store aggregates, isolating the domain from the data storage details. They play a significant role in managing the storage and retrieval of aggregates from the underlying data storage, such as a JPA, JMS. Repositories act as a bridge between the domain model and the data access layer, providing a way to store and retrieve aggregates while encapsulating the underlying storage details.</p><p>Repositories abstract the data access and storage details from the domain model. They provide a higher-level interface for working with aggregates without exposing the specifics of how data is persisted. They are mostly defined as Interface. Implementation of this interface will be somewhere else (I will explain in Structures section) In other words, aggregates or entities or any domain member will be unaware about how repositories will be implemented.</p><p><strong>Services</strong>: Operations or behaviors that do not naturally fit within the scope of an entity or value object and are used to perform specific actions. It is a concept used to represent operations or behaviors that don’t naturally fit within the boundaries of a single entity or aggregate. Services are a way to encapsulate domain logic that involves multiple entities or aggregates, or logic that doesn’t belong to a specific entity at all. Services are often used to model operations, calculations, validations, and other behaviors that span multiple parts of the domain.</p><p>In conclusion, understanding these foundational concepts of Domain-Driven Design (DDD) empowers us to create more effective and maintainable software solutions. By embracing the Ubiquitous Language, defining clear Bounded Contexts, identifying Entities and Value Objects, forming well-structured Aggregates, utilizing Services, and mastering Repositories, we pave the way for building robust and domain-centric applications.</p><p>To bring these concepts to life, let’s delve into a real-life example in the world of Java programming. We’ll explore how these principles are applied to a practical scenario, demonstrating how DDD can lead to elegant and efficient solutions in software development. So, stay tuned as we dive into the exciting world of DDD in action through Java.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a6af0c4535d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>