<?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 Mohammed Atif on Medium]]></title>
        <description><![CDATA[Stories by Mohammed Atif on Medium]]></description>
        <link>https://medium.com/@mohammed-atif?source=rss-b74f8fa7395a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5l5GcjtXnD4bfwTpvSGC0g.jpeg</url>
            <title>Stories by Mohammed Atif on Medium</title>
            <link>https://medium.com/@mohammed-atif?source=rss-b74f8fa7395a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:30:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohammed-atif/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[Building a Catalog — Part 1: The Core Object Model]]></title>
            <link>https://tech.licious.com/building-a-catalog-core-object-model-85ef37f91e47?source=rss-b74f8fa7395a------2</link>
            <guid isPermaLink="false">https://medium.com/p/85ef37f91e47</guid>
            <category><![CDATA[object-model]]></category>
            <category><![CDATA[catalog]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[e-commerce-solution]]></category>
            <category><![CDATA[high-level-design]]></category>
            <dc:creator><![CDATA[Mohammed Atif]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 04:53:52 GMT</pubDate>
            <atom:updated>2023-09-18T05:05:58.704Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Catalog — Part 1: The Core Object Model</h3><h4>Conceptualise and Design a Robust Catalog</h4><figure><img alt="Cover Image of restaurant menu" src="https://cdn-images-1.medium.com/max/1024/1*BKynsQm9ZgNZtBg_fTd-8A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@foovisuals?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Foo Visuals</a> on <a href="https://unsplash.com/photos/5AMSZcgN_cM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>To sell a Product or Service to a Consumer, or to manage raw materials for production in assembly line, or to manage the distribution of products from warehouse to hubs a central repository to store the product details is often required. This kind of central repository is generally termed as a Catalog.</p><p>In this article, I will walk you through the process of visualising how a Catalog might look and what are the steps and preparation required to build a fully functional and extensible Catalog.</p><h3>What is a Catalog?</h3><p>In general, a Catalog is a representation of a company’s product or service offerings. It includes detailed information about each item, such as product descriptions, images, prices, availability, and any other relevant specifications or attributes.</p><p>While most of the Catalogs are limited to store the basic product details, a few require a lot more than that. Along with the product details for the Consumer, a Company might also need information like where the product comes from, what is the raw material required for a product, how a product is built/manufactured/prepared, how the product is stored, how each product is categorised internally for Business and externally for End Users, details about its availability, tax slabs, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWQWns9slCfAAG7Zp66WNQ.png" /></figure><h3>Visualising the Catalog</h3><h4>Understanding the Big Picture</h4><p>With the definition of Catalog, it feels like a straightforward requirement and something which is not too complicated to build. But let us dive a little deeper into what are the bare-minimum features that an average Catalog is supposed to serve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x1f-U5qvDjgr-QqZOEfReg.png" /></figure><ol><li><strong><em>Different types of Product: </em></strong>Different products might have their own unique set of attributes or details. <br> — A Mobile phone needs to have information like display size, screen resolution, battery life, carrier information, etc.<br> — A Shirt needs to have information like colour, size, fabric, washing instructions, etc.<br> — A Table/Chair needs to have information like material, height, etc.<br> → Hence different schema for different type of Products.</li><li><strong><em>Access to different Products:</em></strong> Different users might have access to different products within the Catalog. <br> — A buyer might see Shirts in the listing and nothing else.<br> — A manufacturer see other products too like Buttons, Threads, etc., which are not visible to a regular buyer.<br> → Hence Role Based Access to different products.</li><li><strong><em>Access to different information about a Product:</em></strong> Different users might have access to different information about the same product. <br> — A buyer sees basic information of the product like Name, Description, Images, or any other details as mentioned in above point.<br> — A distributor needs to know information like storage temperature in warehouse, preferred mode of transit, etc.<br> — A manufacturer need to know what are the different raw materials or products required to build the mentioned product.<br> → Hence Role Based Access for different information about a Product.</li><li><strong><em>Different Category Tree:</em></strong> <br> — A Consumer uses the Product Categories to easily navigate to the desired Product. For example, a Consumer who needs a mobile charger can navigate like Electronics → Mobiles → Accessories.<br> — A warehouse just needs very simple classification to maintain efficient storage. For example, simple categories like Electronics, Electrical, Apparels, etc are enough to store all the respective Products without further classification.<br> → Hence different Category Tree for different users.</li></ol><h4>What kind of Information does a Catalog represent?</h4><p>In general, a Catalog stores the following information about a Product or a Service.</p><ol><li><strong><em>Product Information:</em></strong><br> — <strong><em>Product Name/Title:</em></strong> The name or title of the product.<br><strong><em> — Description:</em></strong> A detailed written explanation of the product, including its features, benefits, and specifications.<br> <strong><em>— Price: </em></strong>The cost of the product, often listed in the local currency.<br> <strong><em>— SKU (Stock Keeping Unit):</em></strong> A unique identifier or code assigned to each product to track inventory.<br><strong><em> — Status:</em></strong> Indicates whether the product is Actively sold or not.</li><li><strong><em>Product Attributes:</em></strong><br><strong><em> — Size:</em></strong> Dimensions or measurements of the product, such as height, width, and depth.<br> <strong><em>— Colour:</em></strong> Available colour options for the product.<br> <strong><em>— Weight:</em></strong> The weight of the product in relevant units.<br> <strong><em>— Material:</em></strong> The materials used in the product’s construction.<br> <strong><em>— Brand: </em></strong>The manufacturer or brand name of the product.<br><strong><em> — Model: </em></strong>For products with different versions or models, the specific model being offered.</li><li><strong><em>Images and Media:</em></strong> High-quality images or photographs of the product from various angles to visually represent it.</li><li><strong><em>Product Variations:</em></strong><br> — Options related to the product that customers can choose from, such as size, colour, or capacity.<br> — Different variants may have their own set of attributes and prices.</li><li><strong><em>Category and Subcategory: </em></strong>The product’s category or classification within the Catalog to help customers navigate to relevant sections.</li><li><strong><em>Pricing and Discounts:</em></strong><br> — Original product price and any discount or promotional pricing.<br> — Information about sales, discounts, and special offers.</li><li><strong><em>Shipping and Production: </em></strong>Details about production time of the product and shipping options.</li><li><strong><em>Warranty and Returns: </em></strong>Information about product warranties, return policies, and procedures.</li><li><strong><em>Keywords and Tags:</em></strong> Words or phrases associated with the product to improve search-ability within the Catalog.</li></ol><h4>How do these values get populated?</h4><p>So far we have seen the dynamic nature of the Catalog. But before talking about how these values get populated let us look at the example below.</p><p><strong>Example 1 — Shirts:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wM604_Wd6TnDjrFGwrw6Qg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Q4xjgqC55mduNFJ6zBFzg.png" /></figure><p>In above example, same shirt is available in different colours and different sizes. But each variant is not just changing by its colour and size but also the title, image and description is also changing for every variant.</p><p><strong>Example 2 — Mobile Phones:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4LlkplwaF5LukYHGKo3pQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FjagpcE8hhn_H7Jo6jnDZg.png" /></figure><p>In above example, same mobile phone is available with different RAM and colour. And just like shirts, each variant has additional information that changes like images and details.</p><p>That means not the just the attributes are different for different products, but also which attributes can change and which attributes cannot change for a variant within a product can also be different.</p><p>Confusing enough? If just reading this requirement is so confusing then imagine the kind of error we can get while filling these details if they are not controlled and validated.</p><p>To enable safe and fast onboarding of the product, we use templates to define the blue-print of the Product. Template is nothing but a collection of attributes for a given type of product. It also specifies which attribute are global (non changing), which attributes belong to a variant (changing) and which attributes act as an anchor point (for example, a user can choose different phones based on a colour and then the description changes accordingly, but generally s/he cannot see different colours by selecting a description).</p><p>Using a template, attributes get clearly defined and avoids the unnecessary overlap of information. Which means using a template we can ensure that attribute like battery life never gets added to a product like Regular T shirt Small BLue. These templates are generally tied to the onboarding console and ensures that the input form only shows the relevant fields based on that template.</p><h3>Designing the Catalog</h3><h4>Some commonly used resources in a Catalog</h4><p>Just like any other application, Catalog also needs some building blocks or resources. While on a very high level we have discussed that the <strong>Product</strong>, <strong>Variant</strong> and their respective <strong>Categories</strong> are the key building blocks of the Catalog, here are few of the most commonly used resources that are used to store and represent these information respectively.</p><figure><img alt="High Level ER Diagram" src="https://cdn-images-1.medium.com/max/1024/1*WxdVcZmOtnskf7vqkt8QmQ.png" /></figure><ol><li><strong><em>Attribute and Attribute Value:<br> — </em></strong>An attribute in a Catalog is a distinctive quality or property associated with a product or service that goes beyond its basic description. <br> — These attributes provide detailed information and may vary from one product to another.<br> — Attribute Value holds the value corresponding to the attribute.<br> — <em>Example:</em> size, colour, weight, etc.</li><li><strong><em>Template: <br> — </em></strong>A template is a collection of attributes that form the blueprint for specific products.<br> — Templates are used to define the schema for different type of products and they provide us a safe solution to handle varying nature of the products in Catalog.<br> — Product and Template may have their own template. This gives more flexibility in defining variations for a product.<br> — <em>For example,</em> all the mobile phones will have one template with attributes like screen size and washing machines will have another template with attributes like rotation speed.</li><li><strong><em>Product: <br> — </em></strong>A product in a Catalog represents a specific item or offering that a business sells. <br> — It is the core entity around which information is organised. <br> — <em>Example:</em> Men’s Leather Jacket</li><li><strong><em>Variant: <br> — </em></strong>Variants, also known as product variations, are different versions or options of a particular product. <br> — They are linked to the main product but have distinct attributes that differentiate them from each other. <br> — <em>Example:</em> Men’s leather jacket brown small, Men’s leather jacket black large.</li><li><strong><em>Bundle: <br> — </em></strong>In simple words, Bundles are combination of 2 or more Variants of similar or different Products. <br> — Bundles are designed to provide customers with added value, convenience, and potentially cost savings compared to purchasing each item individually.<br> — <em>Example:</em> Burger Meals Combo (Burger + Soft Drink + Fries).</li><li><strong><em>Category and Category Tree: <br> — </em></strong>A<strong><em> </em></strong>category is a systematic way of organising and grouping similar products or items together based on common characteristics, features, or functions.<br> — A category tree can be used to organise products into various product categories and subcategories, making it easier for customers to find and browse products.</li><li><strong><em>Association: <br> — </em></strong>Association typically refers to the practice of linking or connecting related products or items in a way that encourages customers to explore additional options or make complementary purchases. <br> — Associations are established to enhance the shopping experience, promote cross-selling and upselling, and increase overall sales.<br> — <em>Example:</em> A user might be prompted to buy a <em>Popular Game</em> on purchase of a <em>Gaming Console.</em></li></ol><h4>Standardisation and Definitions</h4><p>As one of the critical steps of designing a Catalog, it is very important that the use case for each organisation is clearly defined and the whole data setup is done in accordance with the defined requirement. Even though this Catalog design supports ample flexibility and extensibility, not having a clear understanding on different types of information that will be stored can lead to hacky and breaking solutions in the long run.</p><p>Few examples of standardisation could be,</p><ol><li>Fixed pool of attributes to pick from while designing the template. For example, always use the thumbnail attribute to store the thumbnail or image of the product. This will ensure that front end or social media will not have to search through different attributes to find the right image.</li><li>Define the type of data that can be stored as part of the Catalog. For example, the thumbnail attribute can store only media information similarly product weight attribute can store only the weight of the product along with its unit of measurement and so on. This will prevent the misuse of the Attributes.</li></ol><h3>Security and RBAC</h3><p>As we have observed that certain parts of the Catalog require data protection, control and audit it is a good choice to secure the APIs that require data manipulation or send sensitive data.</p><figure><img alt="Role Based Access Control Representation" src="https://cdn-images-1.medium.com/max/1024/1*4w-kJlLQqGhz-TX4RbduGw.png" /></figure><p>Here we have four different user interacting with different attributes of the same product.</p><ol><li><strong><em>Cataloger:</em></strong> They adds and updates the details of all the attributes for a Product and its Variants.</li><li><strong><em>Consumer:</em></strong> A consumer can only see the primary details of a Product like Name, Description and Image.</li><li><strong><em>Analyst: </em></strong>An analyst is interested only in the product name and which raw material is required to manufacture that product.</li><li><strong><em>Marketing: </em></strong>Marketing team can create promotions for the products and update the respective deep-links for those products.</li></ol><p>In real world scenario, different types of users interacting with the Catalog system can increase or decrease which may affect the final complexity of the role based access to the Catalog.</p><h4>Summary</h4><p>In this article, we have visualised how a Catalog can look like and how it can be used to serve different departments of an Organisation. Based on this information we have come up with a High Level Representation of Catalog Design.</p><p>In the next part of this article, I will dive deeper into building a detailed Database Model to store various information of the Catalog and explain how it can be leveraged to apply RBAC and other security features.</p><p>Feel free to share your thoughts, feedbacks or questions in the comment section below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85ef37f91e47" width="1" height="1" alt=""><hr><p><a href="https://tech.licious.com/building-a-catalog-core-object-model-85ef37f91e47">Building a Catalog — Part 1: The Core Object Model</a> was originally published in <a href="https://tech.licious.com/">Licious Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an Event Driven Spring Boot Application without Message Queue]]></title>
            <link>https://levelup.gitconnected.com/event-driven-spring-boot-application-without-mq-e781110275ee?source=rss-b74f8fa7395a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e781110275ee</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[event-driven-programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Mohammed Atif]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 14:01:40 GMT</pubDate>
            <atom:updated>2023-09-18T13:31:40.512Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let us hop into a journey of understanding the implementation and advantages of Low Cost Event Driven Application without using Message Queue</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*jzeao0ESjQFJ5tpi" /><figcaption>img src: <a href="https://unsplash.com/photos/wc3jFFQxo8k">https://unsplash.com/photos/wc3jFFQxo8k</a></figcaption></figure><h3>Recap : Understanding Event Driven Design</h3><p>Event-driven design is a software design paradigm that focuses on building systems or applications that respond to events or changes in the system’s state. In an event-driven architecture, the flow of the program is determined by events, which can be user interactions, messages from other parts of the system, hardware signals, or any other kind of input that triggers a response</p><p>There are excellent articles available that talk about Event Driven Design in detail. So in this article I will keep the focus limited to how to implement one using Spring Events.</p><h3>Spring Events and Event Driven Design</h3><h4>What are Spring Events?</h4><p>The Spring Events library is a part of the Spring Framework that provides a mechanism for implementing event-driven programming within Spring-based applications. It allows different parts of an application to communicate and respond to events or changes that occur during the application’s runtime. This enables a decoupled and modular design, where components can interact without tight dependencies.</p><p>It is one of the most underrated Spring feature with great potential of making a code loosely coupled and easy to maintain. And it works equally great with small as well as large projects</p><h4>Working of Spring Events</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XobUF-4hXco0gqJl5FwgPQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3r_VVqa4O5UbKvRTeL6LXg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dTaLV3BwE9Em12f2zaEoA.jpeg" /></figure><ol><li>First we register the Listeners to Spring Context using @EventListener</li><li>Next we publish the Events to the Spring Context using ApplicationEventPublisher</li><li>Then Spring Context calls the respective listeners based on the class of the Event and the Listener registered</li></ol><h4>Components of Spring Events</h4><ol><li><strong><em>ApplicationEvent:</em></strong> An ApplicationEvent is a base class for events in Spring. It represents an event that can occur within the application. You can create custom event classes by extending ApplicationEvent to represent specific events that you want to handle.</li><li><strong><em>ApplicationEventPublisher:</em></strong> The ApplicationEventPublisher interface is used to publish events within a Spring application. Beans that implement this interface can publish events, which will be delivered to registered listeners.</li><li><strong><em>ApplicationListener:</em></strong> The ApplicationListener interface is implemented by beans that want to listen for specific types of events. When an event is published, all registered listeners of that event type will be notified and can respond accordingly.</li><li><strong><em>@EventListener Annotation:</em></strong> Spring provides the @EventListener annotation that can be used on methods within a bean to mark them as event listeners. The methods annotated with @EventListener will be automatically invoked when a matching event is published.</li><li><strong><em>Event Propagation:</em></strong> Spring supports different levels of event propagation, such as synchronous and asynchronous. You can configure whether an event listener should be invoked synchronously or asynchronously when an event is published</li></ol><h3>Getting it done in the code — The offline bookstore</h3><blockquote><strong>Github link:</strong> <a href="https://github.com/mohammed-atif/spring-resource-management">https://github.com/mohammed-atif/spring-resource-management</a></blockquote><p>To demonstrate the working of Spring Events, let us build a <a href="https://github.com/mohammed-atif/spring-resource-management">Spring Boot Application</a> that will serve the purpose of offline bookstore. Using this application we will be able to see which author has written which books and which book store in the city is selling which books.</p><h4>Decoupling the Publisher</h4><p>As I explained in one of my earlier <a href="https://medium.com/gitconnected/are-you-correctly-using-static-classes-in-java-51b1f8dff40f">articles on why to decouple certain implementations</a>, we will be decoupling the publisher in this project too. This will ensure that whenever we want to migrate to Message Queue we can do it easily without any major code changes or compromises on the features implemented.</p><p><strong>LocalEventPublisher.java</strong></p><pre>import org.springframework.lang.NonNull;<br><br>public interface EventPublisher&lt;T&gt; {<br>    void publishEvent(@NonNull T applicationEvent);<br>}</pre><p><strong>SpringEventPublisherImpl.java</strong></p><pre>import org.springframework.context.ApplicationEvent;<br>import org.springframework.context.ApplicationEventPublisher;<br>import org.springframework.lang.NonNull;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class SpringEventPublisherImpl implements EventPublisher&lt;ApplicationEvent&gt; {<br><br>    private final ApplicationEventPublisher applicationEventPublisher;<br><br>    public SpringEventPublisherImpl(final ApplicationEventPublisher applicationEventPublisher) {<br>        this.applicationEventPublisher = applicationEventPublisher;<br>    }<br><br>    @Override<br>    public void publishEvent(@NonNull final ApplicationEvent applicationEvent) {<br>        applicationEventPublisher.publishEvent(applicationEvent);<br>    }<br>}</pre><p>We have further decoupled the code by allowing generics in the interface. We can make it more strongly typed by defining a BasePayload too.</p><h4>Creating the Event POJOs</h4><p>As we have established above, ApplicationEventPublisher needs POJOs that extend ApplicationEvent . For this application we will need 3 Events to represent changes in Books, Authors and BookStores. We will discuss more about these resources during the course of implementation.</p><p><strong>ResourceLifecycleEvent.java</strong></p><pre>import lombok.EqualsAndHashCode;<br>import lombok.Getter;<br>import lombok.Setter;<br>import org.springframework.context.ApplicationEvent;<br><br>@Setter<br>@Getter<br>@EqualsAndHashCode(callSuper = true)<br>public abstract class ResourceLifecycleEvent extends ApplicationEvent {<br><br>    private final int resourceId;<br>    private final OperationType operationType;<br><br>    protected ResourceLifecycleEvent(<br>            final Object source,<br>            final int resourceId,<br>            final OperationType operationType<br>    ) {<br>        super(source);<br>        this.resourceId = resourceId;<br>        this.operationType = operationType;<br>    }<br><br>    public enum OperationType {<br>        CREATED,<br>        UPDATED,<br>        DELETED<br>    }<br>}</pre><p>This class acts like a base class for all the events encapsulating all the common attributes making it easier to use across the Application. But since Spring Events works on class type, we can either filter the listener by adding resource type attribute to the class or creating the dedicated classes itself.</p><p>For this article to demonstrate both class level and field level filtering I will create different classes for each resource but filter the listener based on operationType .</p><p><strong>AuthorResourceEvent.java</strong></p><pre>import com.mohammedatif.rm.springevents.configs.ResourceLifecycleEvent;<br><br>public class AuthorResourceEvent extends ResourceLifecycleEvent {<br>    public AuthorResourceEvent(final Object source, final int resourceId, final OperationType operationType) {<br>        super(source, resourceId, operationType);<br>    }<br>}</pre><ol><li><strong><em>source:</em></strong> Source is required by ApplicationEventPublisher to keep track of which class triggered the event.</li><li><strong><em>resourceId: </em></strong>Id of the resource affected (In this case Author Id).</li><li><strong><em>operationType:</em></strong> Defines whether the resource was created, updated or deleted.</li></ol><p>While source is a mandatory field, other fields can be added or removed as per the project requirement.</p><h4>Publishing the Events</h4><p>Once the above setup is done, publishing an event is as simple as making a method call.</p><p><strong>AuthorServiceImpl.java</strong></p><pre>@Service<br>public class AuthorServiceImpl implements AuthorService {<br>    private static final AuthorMapper authorMapper = Mappers.getMapper(AuthorMapper.class);<br><br>    private final AuthorRepository authorRepository;<br>    private final AddressRepository addressRepository;<br><br>    private final EventPublisher&lt;ApplicationEvent&gt; localEventPublisher;<br><br>    // Other code and methods<br><br>    @Override<br>    @Transactional<br>    public AuthorDto createAuthor(@NonNull final AuthorDto request) {<br>        final var requestModel = authorMapper.mapToModel(request);<br>        final var updatedAddress = addressRepository.save(requestModel.getOfficeAddress());<br>        requestModel.setOfficeAddress(updatedAddress);<br><br>        final var updatedModel = authorRepository.save(requestModel);<br><br>        // Publish the event that an author is created<br>        localEventPublisher.publishEvent(new AuthorResourceEvent(<br>                this,<br>                updatedModel.getId(),<br>                ResourceLifecycleEvent.OperationType.CREATED<br>        ));<br>        return authorMapper.mapToDto(updatedModel);<br>    }<br>}</pre><p>In above code, we first inject the publisher to the class and then we simply call the localEventPublisher.publishEvent() with AuthorResourceEvent . That’s it, any other tasks that are supposed to be done after the creation of Author will be handled in their respective codes which we will see in the next section.</p><h4>Listening the Events</h4><p><strong>BookStoreServiceImpl.java</strong></p><pre>@Slf4j<br>@Service<br>public class BookStoreServiceImpl implements BookStoreService {<br>    <br>    // Rest of the code and implementation<br><br>    @EventListener(condition = &quot;#event.operationType.name() == &#39;CREATED&#39;&quot;)<br>    public void onAuthorAdded(final AuthorResourceEvent event) {<br>        log.info(&quot;Author Added {}&quot;, event.getResourceId());<br>        // Perform other actions<br>    }<br><br>    @EventListener(condition = &quot;#event.operationType.name() == &#39;UPDATED&#39;&quot;)<br>    public void onAuthorUpdated(final AuthorResourceEvent event) {<br>        log.info(&quot;Author Updated {}&quot;, event.getResourceId());<br>        // Perform other actions<br>    }<br><br>    @EventListener(condition = &quot;#event.operationType.name() == &#39;REMOVED&#39;&quot;)<br>    public void onAuthorRemoved(final AuthorResourceEvent event) {<br>        log.info(&quot;Author Deleted {}&quot;, event.getResourceId());<br>        // Perform other actions<br>    }<br>}</pre><p>Adding listeners is as easy as above code. Let us understand in detail of what is happening above.</p><ol><li><strong><em>Class Level Filtering:</em></strong> First all the events of class AuthorResourceEvent are sent to these 3 listeners.</li><li><strong><em>Field Level Filtering:</em></strong> Then each listener further filters out the events based on the condition provided.</li><li>This type of filtering ensures error free loose coupling and minimal overlap of code. i.e. We can independently decide how our code behaves for different type of operations performed on different resources.</li></ol><p>One key point to note is that <strong><em>all the listeners are synchronous by default</em></strong>. That means if any of the listener throws an exception then it will be propogated back to the method where the event was originally published.</p><h4>Asynchronous Listeners</h4><p>Asynchronous listeners might be needed in a project for reasons like</p><ol><li>Independent processing of related tasks. i.e. Main task terminates and free up the resources while the related tasks continue independently.</li><li>Exceptions are not propagated with asynchronous listeners. Which means the original task is not affected by the state of the listeners.</li></ol><p>We can make the above listener asynchronous by adding the below configuration</p><p><strong>application.yaml</strong></p><pre>rm:<br>  spring-events:<br>    async: false</pre><p>Here rm is custom key for our project Resource Management.</p><p><strong>SpringEventConfig.java</strong></p><pre>import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.context.event.ApplicationEventMulticaster;<br>import org.springframework.context.event.SimpleApplicationEventMulticaster;<br>import org.springframework.core.task.SimpleAsyncTaskExecutor;<br><br>@Configuration<br>@ConditionalOnExpression(&quot;${rm.spring-events.async:true}&quot;)<br>public class SpringEventConfig {<br><br>    private static final String APPLICATION_EVENT_BEAN = &quot;applicationEventMulticaster&quot;;<br><br>    @Bean(name = APPLICATION_EVENT_BEAN)<br>    public ApplicationEventMulticaster simpleApplicationEventMulticaster() {<br>        final var eventMulticaster = new SimpleApplicationEventMulticaster();<br>        eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());<br>        return eventMulticaster;<br>    }<br>}</pre><ol><li>@ConditionalOnExpression : This annotation allows us to enable or disable asynchronous listeners directly from application.properties or application.yaml without having to rewrite the code for every change.</li><li>ApplicationEventMulticaster : It is a central component in the Spring Framework responsible for managing the distribution of events to registered event listeners. It facilitates the publish-subscribe mechanism, where components (event publishers) publish events and other components (event listeners) subscribe to and handle those events.</li><li>SimpleAsyncTaskExecutor : It is a basic implementation of the Spring TaskExecutor interface that provides a simple way to execute tasks asynchronously in separate threads. It&#39;s commonly used for achieving asynchronous behaviour within Spring applications, including asynchronous event handling, asynchronous method execution, and more.</li></ol><h3>Advantages of using Spring Events</h3><ol><li>Low cost out of the box solution for Event Driven Design provided by Spring Boot.</li><li>Easy to use as we don’t have to perform additional setup that is required for Kafka or any other Message Queue.</li><li>Any kind of Message Queue is not required either in memory or externally deployed which reduces the overall cost drastically.</li><li>Code is loosely coupled, which means making changes or adding new features is relatively easier.</li><li>Debugging and testing is also easier as each section of the code is independently available to debug and test.</li></ol><h3>With great feature comes some side effects 😕</h3><ol><li>Unlike Message Queue (MQ), Spring Events does not provide data consistency i.e. in case of server crash, all the in-progress tasks and events are lost.</li><li>While using asynchronous listeners, if a server crashes, there are chances that few listeners are successfully executed while few fail that may cause inconsistent system state. So it becomes critical to handle these edge cases while working with asynchronous listeners.</li><li>In case of multi tenant deployment, MQ based solution routes the events across different listeners on different nodes thereby balancing the load but in case of Spring Events both publisher and listener are in same machine. So if some heavy weight tasks are to be performed across multiple listeners then Spring Events must be avoided.</li></ol><h3>Debate: Spring Events vs Message Queue</h3><p>A common debate that arises when talking about Spring Events is why not use Message Queue directly instead of using Spring Events? Here are few points to note while considering Spring Events vs Message Queue</p><ol><li>For most of the projects, Message Queue is not required on day 1. But feature still needs to be built correctly to enhance the code later. In such scenarios Spring Events come vey handy.</li><li>While building a prototype or small scale application, idea is faster GTM (Go To Market) with minimal technical and financial overhead. In this case Spring Events enable both faster development as well as drastically reduce the environment and setup cost.</li><li>While Asynchronous Spring Events are not fault tolerant, they can still be leveraged to write decoupled synchronous code. That means instead of manually calling 5 different methods after performing a task, those 5 different methods can synchronously listen to the event and perform post processing by still keeping the system in consistent state.</li><li>It is critical to remember that Spring Events are not complete replacement of Message Queue. While they tremendously help to decouple light to medium weight synchronous code, Message Queue must still be used for heavy weight tasks after rolling out the Application Completely.</li><li>Spring Events Listeners work within instance, which means during a multi tenant deployed, each node will have its own publisher and listener that is both beneficial and problematic. And hence if any listener can hog the resource, then its better to use the Message Queue directly instead of Spring Events for such scenarios.</li><li>While this section is about Spring Events vs Message Queue, we must not forget that we can use combination of both to perform different types of tasks. Remember that Spring Events are nothing but Spring Context making the calls to listeners on your behalf, hence there will be negligible impact on the performance but huge impact on the code cleanliness even when Message Queue and Spring Event are used together.</li></ol><h3>Conclusion</h3><p>The usage of Spring Events offers a powerful and flexible mechanism for implementing event-driven programming within Spring applications. By allowing different components to communicate through events, Spring Events promote loose coupling, modular design, and better separation of concerns. This approach enhances the maintainability, scalability, and responsiveness of applications.</p><p>While it has some limited downsides, it offers some great features out of the box and helps accelerate the development process along with having clean and highly maintainable code.</p><h3>Further Reads</h3><ol><li>Sample Project: <a href="https://github.com/mohammed-atif/spring-resource-management">https://github.com/mohammed-atif/spring-resource-management</a></li><li>Introduction to Message Kafka: <a href="https://medium.com/@mohammed-atif/understanding-kafka-in-simple-english-e46b4ed7b621">https://medium.com/@mohammed-atif/understanding-kafka-in-simple-english-e46b4ed7b621</a></li></ol><p>Share your thoughts and feedback below in the comments for further discussion on this topic. Don’t forget to clap and follow if you found this article insightful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e781110275ee" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/event-driven-spring-boot-application-without-mq-e781110275ee">Build an Event Driven Spring Boot Application without Message Queue</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot : Does every dependency need to be injected?]]></title>
            <link>https://mohammed-atif.medium.com/spring-boot-does-every-dependency-need-to-be-injected-757fa2cc69d8?source=rss-b74f8fa7395a------2</link>
            <guid isPermaLink="false">https://medium.com/p/757fa2cc69d8</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mohammed Atif]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 15:27:44 GMT</pubDate>
            <atom:updated>2023-04-06T06:33:19.874Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot : Does every dependency need to be injected?</h3><p>In my <a href="https://medium.com/engineering-zemoso/when-not-to-autowire-in-spring-spring-boot-93e6a01cb793">older article</a> I have mentioned about some better practices around Dependency Injection that can make your coding life easy. In this article I will make it more easy by talking about whether Dependency Injection is required at all or not?</p><figure><img alt="Cover Image" src="https://cdn-images-1.medium.com/max/1000/0*VT1jHalHII780bHv" /><figcaption>img src: <a href="https://unsplash.com/photos/LJ9KY8pIH3E">unsplash</a></figcaption></figure><h3>What is Dependency Injection?</h3><p>Dependency injection is a design pattern in software engineering that involves injecting dependencies, or required objects or services, into a component or class rather than having the component or class create those dependencies itself. In other words, instead of a component creating its own dependencies, the dependencies are provided to the component from outside, usually by a framework or container.</p><p>This approach decouples the components from their dependencies, making them more modular and easier to test and maintain. It also allows for more flexibility in the configuration of the system, as different implementations of the same dependency can be easily swapped in and out without changing the component’s code.</p><h3>OK! But what are Dependencies to start with?</h3><p>In programming languages, dependencies refer to internal or external modules, libraries, or packages that a program or project requires to function correctly. These dependencies may include code, data, or other resources that the program needs to access or utilise in order to run as intended.</p><p>In simpler terms, everything required to make sure your business logic runs smoothly without hectic boilerplate or overhead is called dependency.</p><p>Generally on high level in a layered architecture, dependencies can be classified into following</p><ol><li>Business Logic</li><li>Data Access Layer</li><li>Supporting Components like AWS wrapper</li><li>Reusable components like Date or Currency Formatter</li><li>Utility components like POJO to Model mapper, Input validator, etc</li></ol><p>Let us break down and group these dependencies quickly,</p><ol><li>Business logic might change depending on the implementation</li><li>Data Access Layer might change its underlying implementation while moving to another DB</li><li>Supporting components like AWS might change its implementation if you decide to move to some other cloud provider</li><li>Date Formatter, Currency Formatter, Object Mappers, etc never change based on business logic. (Exceptions always exists)</li></ol><h3>When not to Inject the dependencies</h3><p>Based on above example we have established that dependencies are of two types</p><ol><li>One whose implementation changes based on external factor</li><li>One which remains constant throughout the project</li></ol><p>Now going back to the definition of Dependency Injection, we are hardly getting any advantage either from framework or code when injecting static or non changing dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8d82d8b97e8be2a17a2126470b22704/href">https://medium.com/media/a8d82d8b97e8be2a17a2126470b22704/href</a></iframe><p>Above code is pretty straightforward and easy to implement and does not deviate from any good design principles.</p><ol><li>ObjectMapper hardly changes across the project and can be directly initialised. As long as your project does not have any need to override the behaviour of the GSON or Jackson Object Mapper then direct initialising causes no harm because for any given json String it will always map it the same way to a POJO and vice versa.</li><li>Mapstruct Mapper used Factory pattern to initialise the correct implementation. So even here we have achieve a totally decoupled code inspite of having a static dependency.</li></ol><p>Similarly almost all the static code can be used directly without dependency injection</p><h3>Few points to consider</h3><ol><li>Not all static dependencies can be initialised directly. There are few heavy weight classes that might take up memory or other resources. Even though they might feel static they can cause a heavy toll to the application. Hence Dependency Injection.</li><li>Like I mentioned above, Mapstruct uses Factory Pattern so it is easier to override the behaviour without making changes anywhere else. But to override the behaviour of ObjectMapper globally, a bean with required changes like Global date time format, etc needs to be created and injected. So make sure to analyse the project requirements and ability of dependencies before making the call. In case of confusion, benefit of doubt always goes to Dependency Injection</li><li>Another point that you can debate on is why can’t we create a Singleton for static but changeable scenarios like ObjectMapper mentioned above? Answer is you can. But unlike Mapstruct’s Factory which is controlled by Mapstruct itself you will have to create a singleton for ObjectMapper yourself. So whether to create a Bean or Create a singleton or initialise it directly becomes the decision of the developer. And if in doubt, always go ahead with Dependency Injection.</li></ol><h3>Related Articles</h3><ol><li><a href="https://medium.com/engineering-zemoso/when-not-to-autowire-in-spring-spring-boot-93e6a01cb793">https://medium.com/engineering-zemoso/when-not-to-autowire-in-spring-spring-boot-93e6a01cb793</a></li><li><a href="https://medium.com/gitconnected/are-you-correctly-using-static-classes-in-java-51b1f8dff40f">https://medium.com/gitconnected/are-you-correctly-using-static-classes-in-java-51b1f8dff40f</a></li><li><a href="https://medium.com/engineering-zemoso/testable-spring-boot-application-right-from-day-1-7d3b11bd7660">https://medium.com/engineering-zemoso/testable-spring-boot-application-right-from-day-1-7d3b11bd7660</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=757fa2cc69d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The beginner’s guide to Kafka — Introduction]]></title>
            <link>https://mohammed-atif.medium.com/the-beginners-guide-to-kafka-introduction-518ce9588489?source=rss-b74f8fa7395a------2</link>
            <guid isPermaLink="false">https://medium.com/p/518ce9588489</guid>
            <category><![CDATA[kafka-producer]]></category>
            <category><![CDATA[kafka-consumer]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Mohammed Atif]]></dc:creator>
            <pubDate>Mon, 31 Oct 2022 10:57:59 GMT</pubDate>
            <atom:updated>2022-10-31T11:20:10.783Z</atom:updated>
            <content:encoded><![CDATA[<h3>The beginner’s guide to Kafka — Introduction</h3><p>In this article we will try to understand the working of Kafka with simple English and relatable examples</p><p>In my previous article <a href="https://mohammed-atif.medium.com/understanding-kafka-in-simple-english-e46b4ed7b621">Understanding Kafka in simple English</a> I have explained what Kafka is and how it helps in the development. In this article I will dive deeper into the technical details and working of Kafka Queue in simple and easy to understand way.</p><p>Please note that I will try to avoid detailed technical explanation as much as possible in this article and dive deeper into technical implementation in my upcoming article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*gaH7PSjvehOUvbSy" /><figcaption>img src: <a href="https://unsplash.com/photos/CrHG_ZYn1Dw">unsplash</a></figcaption></figure><h3>Terminologies</h3><p>To understand the emotions of any story, it is very important to know the backstory of the characters. So let us try to understand the key characters that are responsible for Kafka being a worldwide super hit release.</p><ol><li>Event</li><li>Payload</li><li>Topic</li><li>Producer</li><li>Consumer</li><li>Kafka Brokers</li><li>Replication</li><li>Partition</li><li>Zookeeper</li></ol><h4>Event</h4><p>An event, as the name indicates, is a trigger or information that has been added to the queue. Events are added by Producers to the Queue which are then later processed by the Consumers or may be simply ignored.</p><h4>Payload</h4><p>Payload is the data that is passed as part of the event that is used to identify the purpose of the event. Payload must contain sufficient information to identify, debug and audit the event but at the same time small enough to not to overload the queue. Payload is generally in the form of String and can be furthermore formatted as JSON String to transmit structured data.</p><h4>Topic</h4><p>Assume your queue to be a Highway where vehicles and pedestrians move from one point to the other. Cops name each entity as Pedestrians, bikes, cars, trucks, etc to act on them differently. For example there can be different lanes dedicated for different entity or different speed limits or drive through restaurants where trucks are not allowed or may be different rules for jaywalkers. To implement all the rules efficiently it is critical to identify them correctly right from the point they enter the Highway i.e. you know who is a pedestrian and what is a truck just by looking at it, we don’t stop a person and ask them “are you a truck?”.</p><p>Same is the concept for the Kafka Queues, to identify the purpose of each event they are categorised into topics. Even though each topic uses the same queue, they can be configured differently depending on their use cases. For example we might have topics called “pedestrian”, “bike”, “truck” to identify the events associated with these entities respectively.</p><h4>Producer</h4><p>A Producer can be a CLI or a backend server or any entity that can generate an event.</p><p>There can be a producer that publishes messages for notification which are later consumed by real time push notification services or there can be a producer that takes in preliminary data from the front end and pushes information to the queue so that the heavy calculations can be done later without blocking the front end.</p><h4>Consumer</h4><p>Consumers listen on the events by subscribing to one or more topics and take actions based on the payload.</p><p>A topic may or may not have a consumer but each consumer must have at least one topic subscribed.</p><h4><strong>Kafka Brokers</strong></h4><p>These are the servers or nodes where Kafka runs. Your local machine, EC2, or any remote host can work as a broker. In general practise, to achieve reliability there should be more than one broker.</p><h4>Replication</h4><p>As explained in my previous article, replication is duplicating the data across multiple nodes or brokers. This ensures that in case one node decides to go on a vacation or breakdown then other node can still continue carrying the information without losing any information. We can have any number of replication as long as Replication ≤ Brokers .</p><h4>Partition</h4><p>Partition is a way to share the message across multiple nodes.</p><h4>Zookeeper</h4><p>Zookeeper in simple terms is a manager that takes of managing Primary and Supporting Brokers and sharing the messages across them.</p><h3>Putting them all together</h3><p>Now since we have roughly gone through all the major terminologies, let us quickly piece them together in a simple non technical example</p><h4>The Shopping Center</h4><p>This is the closest example I could think of that should be valid in most of the countries.</p><p>Imagine you are shopping in a mall and now you want to go for billing, what happens now?</p><ol><li>There will be some billing counters — <strong>Nodes or Brokers</strong></li><li>There will be queues of people waiting to get the billing done — <strong>Messages</strong></li><li>Each person will have some items in their cart —<strong> Payload</strong></li><li>You were probably out of milk and hence you came to shop at first place — This is the <strong>Event</strong> or trigger that made you stand in the queue</li><li>The person who asked you to get the items is the <strong>Producer</strong> of this event</li><li>Cashier at the billing counter is the <strong>consumer</strong>, note that sometimes you might end up fighting with the cashier and the Manager also gets involved, yes Manager is also the <strong>consumer</strong> for same event in this case</li><li>There might be different queues for Food Items, Apparels, Hardware, etc — These are the <strong>topics</strong></li><li>There might be different queues for Cash and Card payments too or different queues for Male and Female — These are also the <strong>topics</strong></li><li>One billing counter might be handling multiple items like Apparels and Hardware at one counter — This represents that same node or broker can process multiple topics</li><li>There can be more than one queue for taking care of Food Items because of high demand — This is <strong>partitioning</strong> of the messages</li><li>You might make someone stand in another line just in case your line slows down as the cashier might decide to go for a break. In this case other person still continues to move forward in the line get your billing done without any issues — This is similar to <strong>replication</strong></li><li>Now imagine a staff standing near the billing counters who is managing all the people. Helping them to stand in correct line depending on the items they are purchasing. Coordinating the rearrangement of queues when the billing counter is closed for any reason and taking care of calling the manager when you fight with the cashier. This staff member is <strong>Zookeeper</strong> which coordinates the brokers and messages.</li></ol><h3>Consumer Groups</h3><p>We pretty much covered everything to understand the different terminologies in Kafka.</p><p>One thing without which most of the Production Level Applications don’t deploy is consumer groups.</p><p>To understand the consumer group let us take the shopping example again but this time let us consider online shopping.</p><p>Suppose you purchase something from a store online and choose self pickup option. You go the store and pick up the item and your shopping is complete.</p><p>But now imagine that store has multiple branches, how will the store ensure that you are not visiting all their branches and collecting the same order again and again? They will mark the order as complete and will not allow you to pick up the same item again.</p><p>Same concept is used in Consumer Groups, in a real world scenario more than one instance of the server is deployed and all of them are listening to the same topics. So to avoid duplicate processing of the information only one member of the consumer group processes the data.</p><p>Note that we can still have more than one consumer from different groups listening to the same topic and perform their process independently but two consumers from same group will never respond to the same message from same topic.</p><p>In my next article I will dive a bit more deeper into the implementation level of Kafka and talk about how to run and debug the Kafka Applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=518ce9588489" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Kafka in simple English]]></title>
            <link>https://mohammed-atif.medium.com/understanding-kafka-in-simple-english-e46b4ed7b621?source=rss-b74f8fa7395a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e46b4ed7b621</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mohammed Atif]]></dc:creator>
            <pubDate>Wed, 27 Apr 2022 11:23:25 GMT</pubDate>
            <atom:updated>2022-04-28T06:49:45.980Z</atom:updated>
            <content:encoded><![CDATA[<h4>Kafka (or Message Queues) is simple yet difficult to understand topic. Let us try to understand it in simple English.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*g75e-eoAuhFEaXE9" /><figcaption>img src: <a href="https://unsplash.com/photos/CrHG_ZYn1Dw">unsplash</a></figcaption></figure><h3>Different ways of data transfer / processing</h3><p>Even before we understand what Kafka is, we need to understand the different ways to transfer the data in a Software Application</p><p>Majorly it can be classified as</p><ol><li>Synchronous</li><li>Asynchronous</li></ol><p>In synchronous form of communication, response or data is returned soon after making the request</p><p>In asynchronous form of communication, response may or may not be received. And if received it is received once the request processing is done and the caller need not wait for it</p><p>Kafka deals with the latter i.e. Asynchronous Communication</p><h4>Short examples (non technical) of each of the process</h4><ol><li><strong>Synchronous<br></strong>a. You give money to the shopkeeper and he gives you the product — REST API or Function Call<br>b. You wait patiently in the Salon to get the hair cut done — Long running synchronous calls</li><li><strong>Asynchronous<br></strong>a. Luggage conveyor belt in Airports where Airport staffs drops the luggage on the belt without bothering about who will pick it and when they will pick it<br>b. Making an order on an e-commerce website. You continue doing your regular while the order is being processed and shipped independently<br>c. Making an announcement in a gathering. Only the interested ones respond while the others ignore</li></ol><p>As you might have noticed I related the synchronous ones to their respective coding analogy but not the asynchronous ones because we are going to find out in detail about them</p><h3>Technical yet simple understanding of Kafka</h3><p>Let us start understanding Kafka now,</p><p>Kafka is a Messaging Queue — That means it is a <strong>Queue</strong> (FIFO) that stores <strong>Messages</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F51Ww5M9tIBzLbdfUlU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F51Ww5M9tIBzLbdfUlU%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F51Ww5M9tIBzLbdfUlU%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/98913901a6924fb630090c62b8044a5b/href">https://medium.com/media/98913901a6924fb630090c62b8044a5b/href</a></iframe><p>Think of it like a conveyor belt in a Sushi restaurant, a queue full of sushis (messages) and the person eats the one they like and ignores the rest. Same is the case with Kafka</p><p>But before diving deeper into how it happens let us understand some terminology</p><h3><strong>Kafka Terminologies</strong></h3><ol><li><strong>Topic </strong>— It specifies the category of the of the message or the classification of the message. Listeners can then just respond to the messages that belong to the topics they are listening on.</li><li><strong>Partitions</strong> —Number of nodes or servers serving the queue. Think of it like number of conveyor belts in the restaurant. Suppose a restaurant has 3 belts and 2 of them are damaged, restaurant can still continue to run on single belt. Similarly with more number of partitions Kafka gets better reliability and lower downtime.</li><li><strong>Replicas </strong>— Number of copies of each message. Single partition can have only one copy of the message. That means replica&lt;=partitions. Replicas are important to have data consistency, suppose a node crashes completely along with the messages in it, then there will always be a copy of that message in some other node which will be used for communication</li><li><strong>Group </strong>— In micro service world, it is very common to have more than one deployment of the server and if all of them starts to respond to the incoming messages then there will be duplication in processing. To avoid this duplicate processing only one listener (consumer) in the group responds to the message.</li></ol><h3>When to use Kafka then? And when not to…</h3><p>As we understand now, Kafka can deliver the message or events asynchronously with reliability and consistency without the loss of information hence it can be used for all the asynchronous tasks that require the data consistency. Few of such examples can be</p><ol><li>Sending an email to consumer — Emails might contain important information which might get lost if email servers are not responding correctly, using Kafka can make sure that messages are adequately retried before actually failing</li><li>Processing a user information — Sometimes user information or requests take time to process and you don’t want to keep the user waiting during this time</li><li>Publishing an event — Your server might have updated some data or performed some task and now you want to notify all the other servers that are dependant on this task. Calling them individually can be troublesome instead a Kafka event can be produced and all the other dependant servers can listen to it and respond accordingly</li></ol><p>Few of the other simple asynchronous can still be performed using multithreading and may not require Kafka</p><ol><li>Performing a large calculation</li><li>Inserting some non critical records to DB</li><li>Performing some cleanup operations</li></ol><p>I will wrap up the Introduction here, in my next article I will walk through the technical details and integration with Spring Boot</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e46b4ed7b621" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using static classes correctly in Java]]></title>
            <link>https://levelup.gitconnected.com/are-you-correctly-using-static-classes-in-java-51b1f8dff40f?source=rss-b74f8fa7395a------2</link>
            <guid isPermaLink="false">https://medium.com/p/51b1f8dff40f</guid>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[decoupling]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Mohammed Atif]]></dc:creator>
            <pubDate>Tue, 08 Mar 2022 13:59:02 GMT</pubDate>
            <atom:updated>2022-11-09T08:44:45.912Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using a library that has static Java classes for its functionality seems straightforward and easy unless…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*yx3kCOvTxJXTuR6L.jpg" /></figure><p>Let me begin with an incident</p><p>We were working on payment integration in our Spring Boot Application and here is one sample code our of it</p><pre>Stripe.apiKey = &quot;sk_test_4eC39HqLyjWDarjtT1zdp7dc&quot;;<br><br>Map&lt;String, Object&gt; params = new HashMap&lt;&gt;();<br>params.put(<br>  &quot;description&quot;,<br>  &quot;My First Test Customer (created for API docs)&quot;<br>);<br><br>Customer customer = Customer.create(params);</pre><p>Looks like a simple code block unless you notice the create that is happening on a static method Customer.create(params)</p><p>You might ask, what’s wrong in this?</p><p>Firstly, unit testing static classes becomes difficult. Yes you can use PowerMock kind of tools, but it is not recommended. I will elaborate on this further in one of my other articles</p><p>Secondly, the update disaster. One fine day Stripe team decided to provide a mandatory update due to a security fix and all the payments that were made using prior versions were failing.</p><p>So we started updating the Library and faced these issues</p><ol><li>New library was not backward compatible, so we had to rewrite the code</li><li>Rewriting the code was another pain as all the static calls were lying all across the application</li><li>Not just the inputs, but the way data was handled, returned and processed also changed. That means we had to rework on the business logic and data handling logic at multiple places</li><li>Whole process took about 1 dedicated sprint with 3 developers working on the migration and regression testing. (P.S. Since everything changed, Power Mock also failed)</li></ol><h4>What did we learn?</h4><ol><li>As the statement in <a href="https://williamdurand.fr/2013/07/30/from-stupid-to-solid-code/">STUPID vs SOLID</a> says, Singleton is a big trouble</li><li>It creates tight coupling on the code and making any changes to the code becomes really difficult</li><li>In case of library updates, regression tests fail as the method signature itself changes</li><li>Many teams or projects hesitate to perform the upgrades due to the time consuming nature of the migration of static referenced code</li><li>If we wanted to change our Service Provider from Stripe to something else, then we would have been in a bigger trouble as our whole code was tightly couple to Stripe by using the static classes, Exceptions and the model classes provided by them</li></ol><h4>What is the solution?</h4><p>Solution is simple and straightforward,</p><ol><li>Write a wrapper around the static classes of third party libraries</li><li>Never use the classes provided by the library directly in the Application</li><li>Never propagate the Exceptions that are provided by the library</li><li>Write test cases around your wrapper classes or interfaces instead of library. i.e. Instead of Mocking a response from Stripe (static class), mock the interface or class you defined as wrapper. This way even if you change your underlying library, your dependant code will not change as you will just re write the implementation with other library.</li></ol><h4>Let us look into a sample code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82c530fc0c789d56a359d7a6c0c0c41b/href">https://medium.com/media/82c530fc0c789d56a359d7a6c0c0c41b/href</a></iframe><p>Then in your actual code, you use the PaymentRepository instead of using StripePaymentRepositoryImpl and all your code changes are then confined to a single class</p><p>It also simplifies the test cases because now you will just have to verify or mock the results of your interface which will not change when you. change the library</p><p>Also by decoupling the Exception and DTO (or Model) classes, you totally get rid of any dependency on the library in rest of your code and making any migrations or changes becomes much more easier</p><p>In my upcoming articles I will talk in detail about how knowledge of design patterns can simplify our day to day coding without causing any major overheads in the development process</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51b1f8dff40f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/are-you-correctly-using-static-classes-in-java-51b1f8dff40f">Using static classes correctly in Java</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Work From Home : RAC Model of Communication for Software Developers]]></title>
            <link>https://mohammed-atif.medium.com/work-from-home-rac-model-of-communication-for-software-developers-530648fd43e2?source=rss-b74f8fa7395a------2</link>
            <guid isPermaLink="false">https://medium.com/p/530648fd43e2</guid>
            <category><![CDATA[meetings]]></category>
            <category><![CDATA[communication]]></category>
            <category><![CDATA[software-developer]]></category>
            <category><![CDATA[work-from-home]]></category>
            <dc:creator><![CDATA[Mohammed Atif]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 13:57:46 GMT</pubDate>
            <atom:updated>2022-02-02T13:57:46.386Z</atom:updated>
            <content:encoded><![CDATA[<h3>Work From Home : RAC Model of Communication for Software Developers</h3><p>One major problem that we all face during work from home is Communication. Let us try to simplify it as much as possible.</p><h3>The Problem</h3><p>This problem is so relatable that it can be explained using memes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*O_TDw5Z-Wd1oRDyE" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*qgbxVsJWue3pXZe4.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*jTfN1um0PugrFPdM.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*GGsK2f7gzg2dsNc3.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LDaYQcqhIPTmhMnz.jpg" /></figure><h3>The Solution</h3><p>Enough laughing at the memes, let us talk business here…</p><p>While it is not easy to solve the communication problem as a whole, let us at least try to make our daily communication problem as simple as possible by using RAC model of communication</p><h4>What is RAC model?</h4><p>RAC model stands for</p><ul><li>Refer</li><li>Ask</li><li>Connect</li></ul><p>As we all know, it is impossible to be present for a meeting during work from home because of various reasons like being stuck in other work, meeting or occupied in some household work. So using RAC model we can improve our overall productivity and efficiently utilise our time.</p><h4>Refer</h4><p>Before we ask someone to get on a meeting, it is our duty to wait and think if this meeting is actually required? But how can we judge that?</p><ul><li>Break down the problem into technical, functional and progress based problem</li><li>If it is a technical problem then <strong>Refer</strong> the code you are currently working on, if that doesn’t help then <strong>Refer </strong>some online resources</li><li>If it is functional problem then try to find the details in Jira or the right documentation provided by the team</li><li>If it is regarding asking the progress of work, then it can either be a simple message or meeting depending on how much details is expected as part of the status update. Is it just the status or even a small demo.</li></ul><h4>Ask</h4><p>Sometimes it is not possible to solve the problem even after referring multiple resources. In that can <strong>ask</strong> your team to guide you to the right resources.</p><p>Resource can either be Technical Documentation or Project Documentation</p><h4>Connect</h4><p>Even after asking, if the shared resources does not help only then ask for the meeting.</p><p>When requesting someone for a meeting, make sure to explain them the context and details so that the other person can plan accordingly.</p><h4>But when to move from one step to another?</h4><p>Depending the complexity of the work, add a threshold. Ideally 2 hours.</p><p>That means, if you are not able to make any progress for 2 hours then move from one step to other. This time can also be 1 hour or 3 hours depending on the complexity of the work as not all resources take same time to understand</p><h3>Other Considerations</h3><p>While RAC model drastically improves the efficiency and productivity, it may not always fit in, few of the scenarios are as mentioned below</p><ul><li>If team always needs guidance or discussions on technical implementation on daily basis then schedule a recurring meeting so that everyone is prepared for it before hand</li><li>Sometimes few meetings are unavoidable because of the impact that it might cause. In that case it is always better to schedule a meeting after 10–15 minutes to give sufficient time to all the stake holders to be prepared and present. Also provide the detailed context in the invite to keep everyone on the same page</li><li>Inform the team or necessary participants before hand if their requirement is anticipated during the course of the work. These situations can be like Deployments, Peak Hours, Project Setup or Onboarding, etc.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=530648fd43e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Primitive Type vs Wrapper Class : Which one to use in Java?]]></title>
            <link>https://levelup.gitconnected.com/primitive-type-vs-wrapper-class-which-one-to-use-in-java-e0742144f768?source=rss-b74f8fa7395a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0742144f768</guid>
            <category><![CDATA[oops-in-java]]></category>
            <category><![CDATA[wrapper-class]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[datatypes-in-java]]></category>
            <category><![CDATA[primitive-data-types]]></category>
            <dc:creator><![CDATA[Mohammed Atif]]></dc:creator>
            <pubDate>Tue, 05 Oct 2021 14:41:51 GMT</pubDate>
            <atom:updated>2021-10-08T07:24:13.121Z</atom:updated>
            <content:encoded><![CDATA[<h3>Primitive Type vs Wrapper Class : Which one to use in Java?</h3><h4>Though looks like a small thing, it makes a huge difference to your code</h4><p>In this short article, I will walk you through the differences and implementations of Primitive Type and Wrapper Classes and the related consequences when used incorrectly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*rfT51txl1Iup4Mju.png" /></figure><h3>What are Primitive Types and Wrapper Classes?</h3><p>While many of us know what they mean, let me still give a quick overview</p><h4>Primitive Types</h4><p>A primitive data type specifies the size and type of variable values, and it has no additional methods.</p><h4>Wrapper Classes</h4><p>Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.</p><p>One major difference from the explanation above is, default values of the primitive types depend on type like int is 0, char is \u0000, boolean is false etc but default value for wrapper classes of all types is null since they are objects.</p><h3>Which one to use?</h3><p>Both primitive types and wrapper classes need to be used in a code depending on how you want your code to behave. Though it sounds like a difficult thing, I will cover up most of the use cases with examples to help you get a better understanding of it.</p><blockquote>When not sure what to use, always use the primitive type</blockquote><p>When writing a code, drive yourself with questions instead of solutions. What does that mean?</p><ul><li>What happens if I use int instead of Integer?</li><li>What happens if I use Stringconstant instead of enum</li><li>What happens if I use Boolean instead of boolean</li><li>And so on…</li></ul><p>That being said, lets see how these questions can help us in using the right datatype</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8bf600afeb418b92b252a4062252e0f/href">https://medium.com/media/b8bf600afeb418b92b252a4062252e0f/href</a></iframe><p>Let us analyse above codes</p><ul><li>What is the default value of latitude and longitude until the consignment is assigned? 0.0, 0.0 ? No, as it is a proper location, so it must be null until it is assigned, hence we used Float instead of float</li><li>Can isActive be null? What will that mean? Something is either active or inactive, there is not third state for being active and hence boolean</li><li>Can weight of a product be 0? highly unlikely. So the float that we have used in above code is incorrect as it can give incorrect result when used in the code</li><li>In OrderManagementService.java interface I have used the same concept, for example userId needs to be a valid value and cannot be null</li></ul><h3>Other scenarios where we can drive the correct datatype from the Application itself</h3><h4>Database Models</h4><ul><li>Databases can have all kind of values including null, so Model Objects or Entities must always have Wrapper Classes</li></ul><h4><strong>DTOs (Request and Response)</strong></h4><ul><li>DTOs used for Request and Response <strong><em>may</em></strong> have Wrapper Classes if your API design includes nullable values</li></ul><h4>Implementations and Solutions</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/947ec02dddef6e511379ec934e384a91/href">https://medium.com/media/947ec02dddef6e511379ec934e384a91/href</a></iframe><ul><li>Variables with local scope are always primitive type</li><li>Field variables should be primitive, until and unless it does not satisfy the questions we ask regarding its usage</li></ul><h3>Consequences</h3><ul><li>NullPointerExceptionwhile incorrectly using Wrapper Classes</li><li>Unexpected defaults while incorrectly using primitive types</li><li>Days of debugging (if you don’t know how to use debugger in IDE)</li><li>Additional memory usage while incorrectly using Wrapper Classes</li></ul><h3>Epilogue</h3><p>These concepts are good to know and easy to implement once you understand the concept behind them. Do share your views in the comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0742144f768" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/primitive-type-vs-wrapper-class-which-one-to-use-in-java-e0742144f768">Primitive Type vs Wrapper Class : Which one to use in Java?</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lombok: To use or not to use, that is the blog]]></title>
            <link>https://levelup.gitconnected.com/lombok-to-use-or-not-to-use-that-is-the-blog-e7a3a8f97e8f?source=rss-b74f8fa7395a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7a3a8f97e8f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[lombok]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Mohammed Atif]]></dc:creator>
            <pubDate>Wed, 29 Sep 2021 13:59:29 GMT</pubDate>
            <atom:updated>2021-10-08T07:21:30.385Z</atom:updated>
            <content:encoded><![CDATA[<h4>If you use then how to use, that is also the blog</h4><figure><img alt="project lombok" src="https://cdn-images-1.medium.com/max/1024/1*Jt34KK87zw10NOLYqU-CNQ.jpeg" /></figure><p>Project Lombok is a Java library that automatically plugs into your editor and build tools, spicing up your java. Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.<br> <a href="https://projectlombok.org/">— Team Lombok</a></p><p>Project Lombok is an excellent tool to make coding in Java easy. And it is a good answer to devs who say that Java codes are extremely large when compared to Python. Lombok helps the developers to focus on the implementation by not worrying about writing the boiler plate codes and keeping the final code shorter (relatively 😅).</p><p>But… Most of the IDEs these days come with a support of generating the boiler plate codes then why do we need Lombok again?<br>Yes, while we can still generate the code in IDE, it still is a boilerplate code adding up to the total LOC and thereby reducing the readability and maintainability of the code.</p><p>In this article I will discuss some myths, key features and implementation details of Lombok.</p><h3>Demystifying the myths</h3><p>There are some common assumptions and theories when teams discuss about using Lombok in their Application. So it becomes important to discuss about them first in this article too before we even talk about the implementation.</p><ol><li>It adds tight coupling to the code</li><li>It reduces the ability to foresee the code smells</li><li>It hinders with the good design practices</li></ol><p>Yes, most of them are valid points when we talk about adding Project Lombok to our Application but the question is what is the impact? Let us see.</p><h4>Tight Coupling</h4><p>All the classes and codes depend on Lombok hence making them dependant on each other resulting in tight coupling. And if it happens that Lombok is to shut down then whole project will be in trouble.</p><ol><li>But that’s not the case, since Lombok comes with DeLombok tool, even if you have to remove Lombok from your application you can easily DeLombok it and remove the dependency from Application.</li><li>Since all the dependency to Lombok is unidirectional i.e. classes depends on Lombok but Lombok doesn’t directly depend on the classes, it doesn’t create the real tight coupling. Also the compiled code is finally Lombok free hence making it safe to use.</li></ol><h4>Code smells and impact on clean code</h4><p>This is tricky, many senior developers face the issue of their juniors incorrectly using the Lombok making it more troublesome than advantageous. But there are some tips and tricks that can help to correctly use Lombok. One of those tricks is to make your juniors read this Article 😂</p><p>There are three possible scenarios,</p><ol><li>Project is for a well established organisation where code quality is of utmost importance</li><li>Project is a fast faced Application where completion is important and code quality is of medium importance</li><li>Project is a medium scale Application where both time and quality is crucial</li></ol><p>For case 1, a team will have enough qualified members to review the code thereby reducing the overall risk of bad code after integrating Lombok and rest of the team members eventually pick up the good practices.</p><p>For case 2, little bit of bad code is anyways acceptable. Team will eventually learn going forward and improve the overall quality gradually.</p><p>For case 3, it becomes a call for team, depending on previous experience of team members on Lombok and scale of the Application, you can choose to either pick it or drop it.</p><h3>Setting up Lombok</h3><p>I will try to keep this blog short and interesting to read. You can find detailed <a href="https://github.com/mohammed-atif/medium-project-lombok">implemented project on Github</a> for reference.</p><h4>Adding Lombok to project</h4><ol><li><a href="https://projectlombok.org/setup/maven">Adding Lombok to Maven project</a></li><li><a href="https://projectlombok.org/setup/gradle">Adding Lombok to Gradle project</a></li></ol><h4>Setting up the IDE</h4><ol><li><a href="https://projectlombok.org/setup/eclipse">Eclipse</a></li><li><a href="https://projectlombok.org/setup/intellij">IntelliJ</a></li><li><a href="https://projectlombok.org/setup/vscode">VS Code</a></li></ol><h3>Implementing Lombok</h3><p>There are some really good articles out there that explain in detail on how to use Lombok, so I will focus on how to use them correctly.</p><p>These are few official documents to begin with</p><ul><li><a href="https://projectlombok.org/">https://projectlombok.org/</a></li><li><a href="https://objectcomputing.com/resources/publications/sett/january-2010-reducing-boilerplate-code-with-project-lombok">https://objectcomputing.com/resources/publications/sett/january-2010-reducing-boilerplate-code-with-project-lombok</a></li></ul><p>If you need this article to cover the detailed implementation too, then let me know in the comments.</p><h3>Common mistakes while using Lombok</h3><h4>Incorrectly using @Data</h4><p>@Data is most commonly used Annotation, but it is equally risky annotation. Since it adds @Tostring and @EqualsAndHashCode too it makes your code dangerous when using it with Collections or other similar items</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0788e410b33cda02cf2ba49f571b3192/href">https://medium.com/media/0788e410b33cda02cf2ba49f571b3192/href</a></iframe><p>Expectation will be that both the assertions will pass because we are creating two different objects and adding it to a set but since @Data adds EqualsAndHashCode too, set inserts only one value because the contents of the objects are same and hence second test case will fail.</p><p>Many developers are not familiar with this feature and end up spending several days in debugging what is wrong.</p><h4>Incorrectly using Constructor annotations</h4><ul><li>In same example above, you can notice that I have added AllArgsConstructor but have not marked the fields final. This process has two flaws, anyone else cannot access default constructor and fields can be modified using setters which is a bad design combination.</li><li>Similarly if there are more than 5 parameters in a constructor then it is assumed to be a bad class as it is most probably deviating from Single Responsibility Principle. When using AllArgsConstructor or RequiredArgsConstructor a developer can easily oversight this and code can easily become unmanageable going forward</li></ul><h3>Some Good Practices</h3><p>Few things to remember,</p><ul><li>Lombok is just a tool to make your life easy. It does not provide any assistance or support for clean code.</li><li>If clean code and design principles are not of importance (trust me it’s not that bad as it sounds in most of the cases), then using Lombok to simplify development process is the best option.</li></ul><p>having said that, let us look into some good coding practices using Lombok</p><ul><li>Use only the features that are absolutely required</li><li>If in doubt, always refer the documentation. It takes less than 5 minutes to read the documentation but 5 days to identify and fix a silly bug</li></ul><p>Find detailed implementation here : <a href="https://github.com/mohammed-atif/medium-project-lombok">https://github.com/mohammed-atif/medium-project-lombok</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7a3a8f97e8f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/lombok-to-use-or-not-to-use-that-is-the-blog-e7a3a8f97e8f">Lombok: To use or not to use, that is the blog</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 mistakes of my coding: Spring Boot]]></title>
            <link>https://mohammed-atif.medium.com/3-mistakes-of-my-coding-spring-boot-223ff5cb1c5a?source=rss-b74f8fa7395a------2</link>
            <guid isPermaLink="false">https://medium.com/p/223ff5cb1c5a</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[sonarlint]]></category>
            <dc:creator><![CDATA[Mohammed Atif]]></dc:creator>
            <pubDate>Sun, 12 Sep 2021 13:20:14 GMT</pubDate>
            <atom:updated>2021-09-12T13:20:14.842Z</atom:updated>
            <content:encoded><![CDATA[<h4>Inspired by Marvel Studios new series “<strong><em>What If” it occurred to me What If</em></strong> I knew better coding concepts early in my career, would it have helped me to improve the overall quality of the application?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*jtuww7jVPBI-tqta.jpg" /><figcaption>src: <a href="https://depositphotos.com/">DepositPhotos</a></figcaption></figure><p>While working on projects, big or small, it is very difficult to get everything good right from the start. Not only because we did not know about better process or concept but also because the good process we already know might have been outdated or even obsolete by the time we implement it. In this series I will share some of my experiences of how various factors and concepts could have helped me improve the overall application I have worked on.</p><blockquote>This is not a Spring Boot tutorial. Just some parody based on my experience which apparently were faced by others too.</blockquote><h3>1. SonarLint</h3><p>Sonar lint is boon for Java developers, be it experienced or fresher. It helps to reduce the code smells drastically during development process itself. During early days of my career I used to blindly copy paste the code, fight people on StackOverflow but even after all that code smells used to be pretty high. Then using SonarLint helped to improve my Java code during development itself.</p><p>Let’s see few examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYV6OlVaJNxOZ2I52HSdmg.png" /><figcaption>Yes, I am not at all smart 😂</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ny2G-VUR_soIfpAtjWjd2w.png" /><figcaption>Why declare when you can return immediately?</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*f2otfM6o4nF_umX6mrpgJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MliT4sCd94Eee2iDnkLpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*s0RY4sYaHCrrGaOScQsthg.png" /><figcaption>if true return true? 😭</figcaption></figure><p>These are few of the many warnings that are provided by sonar lint and can be really helpful for the developers to reduce the obvious code smells.</p><h3>2. Spring Security</h3><p>Often unknown or underrated by freshers (At least 60% of the developers I have interviewed in past 3 years did not know about Spring Security, so did I when I started 😔) Spring Security helps a lot to start a Spring / Spring Boot Application.</p><p>I still remember writing my own authentication logic.</p><ul><li>First in each controller</li><li>Then externalising it to a different class</li><li>Then got to know about interceptors</li><li>Finally using Spring Security and the results were amazing</li></ul><h4>Few uses of Spring Security:</h4><ol><li>Comprehensive and extensible support for both Authentication and Authorization</li><li>Protection against attacks like session fixation, clickjacking, cross site request forgery, etc</li></ol><h4>Why are they relevant for newbies or small projects?</h4><ul><li>Adding third party integrations like Firebase, Okta, Auth0, etc is straight forward</li><li>Separation of concerns, application security is totally isolated from the rest of the application.</li><li>You may remove, disable or mock any blocking feature for testing purposes without affecting the critical business logic</li><li>And many more</li></ul><p><strong><em>Reminder: This is not a tutorial, so no sample codes. Add in a comment if you want a dedicated article on Application Security.</em></strong></p><h3>Integration Tests</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FSACoDGYTvVNhZYNb5a%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Famine-mind-blown-mindblown-blowing-SACoDGYTvVNhZYNb5a&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZjg3MHhqNXdua3c2ZHQ3YTN6eTJzZTI1YTUzNjJnbmdtYjZpemZxaSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FSACoDGYTvVNhZYNb5a%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/7440e091fdc97736518da128baa291e8/href">https://medium.com/media/7440e091fdc97736518da128baa291e8/href</a></iframe><p>Tests, tests, tests…. they are irritating, and so it the trouble to restart the Spring Boot Application every time and performing the tests manually.</p><h4>Before:</h4><ol><li>Make code changes</li><li>Start the application</li><li>Login to system to get the Auth Token (or configure Postman to auto fetch)</li><li>Make an api call to get the list of processed records</li><li>Using this list, get the first item and make another api call to get the list of sub result</li><li>Final result is incorrect, something went wrong, lets debug and retry</li></ol><h4>After:</h4><ol><li>Write integration test of the service that was supposed to process the final result</li><li>Mock the inputs</li><li>Inject the DB and other service dependencies</li><li>Run the test with a button click even 100 times with ease</li></ol><p>As you can see, building a complex application with multiple moving parts is not easy and manually testing them step by step multiple times is pain in the Postman. But running the sequence of steps in the form of tests are much easier and faster and helps increase the overall productivity.</p><h3>Bonus: H2 Database</h3><p>Ideally it is part of Integration testing, but writing it separately for better attention. Yes this is an in memory mention for the H2 database (Pun Intended)</p><p>For those who don’t know about H2 or in memory databases, they are databases which store the information in Memory</p><p>Confused? It simply means that the data is volatile and will disappear every time you restart your Application.</p><p>Since data is never saved, it becomes really helpful to perform integration testing of your DB calls. While doing so directly on MySql, Postgres, Mongo, etc can affect the running servers or even slow down your machine when running locally, using H2 helps to replicate the same without actually having an overhead of running an actual DB separately.</p><p>Share your coding experiences in the comment section and help me expand the overall base of common mistakes that most of us did in nearly stages of our career to help others from not repeating them</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=223ff5cb1c5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>