<?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 Vishal Yadav on Medium]]></title>
        <description><![CDATA[Stories by Vishal Yadav on Medium]]></description>
        <link>https://medium.com/@vishal637yadav?source=rss-6e215e292544------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZPGLakDuVlApMDHwzm6Emg.jpeg</url>
            <title>Stories by Vishal Yadav on Medium</title>
            <link>https://medium.com/@vishal637yadav?source=rss-6e215e292544------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 06:48:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vishal637yadav/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[Least Recently Used (LRU) Cache Implementation in Java]]></title>
            <link>https://medium.com/@vishal637yadav/least-recently-used-lru-cache-implementation-in-java-7460346ffe73?source=rss-6e215e292544------2</link>
            <guid isPermaLink="false">https://medium.com/p/7460346ffe73</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[lru-cache]]></category>
            <category><![CDATA[uml-class-diagram]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Vishal Yadav]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 03:25:49 GMT</pubDate>
            <atom:updated>2025-11-25T03:25:49.662Z</atom:updated>
            <content:encoded><![CDATA[<h4>LRU- Cache Implementation</h4><h4>LLD - Low Level Design</h4><h3>🧠 What is LRU Cache ?</h3><p>An LRU (Least Recently Used) cache is a <strong><em>data structure</em></strong> or <strong><em>caching strategy</em></strong> that stores a fixed number of items and automatically evicts the item that has not been accessed for the longest period when the cache reaches its maximum capacity.</p><h3>Applications in Real-World Systems</h3><ol><li><strong>Web browsers:</strong> Cache web pages or images recently visited for quick reload</li><li><strong>Operating systems:</strong> Manage memory pages to keep recently accessed disk pages in RAM.</li><li><strong>Database systems: </strong>Keep recently queried results or data pages in cache to speed up subsequent queries.</li><li><strong>Distributed caches: </strong>Systems like <strong>Redis</strong> or <strong>Memcached</strong> use LRU for automatic cache eviction.</li></ol><h3>Understanding the Least Recently Used (LRU) Cache Eviction Policy</h3><p>The <strong>LRU</strong> policy is a strategy for <strong>managing a cache of a fixed size</strong>. When the cache becomes full and a new item needs to be added, the <strong>LRU algorithm</strong> decides which <strong>existing item to discard </strong>(or “evict”).</p><p><strong>LRU </strong>algorithm <strong>core principle </strong>is simple: The item that has not been used for the longest period of time is the first one to be evicted.</p><p>This policy operates on the assumption of “temporal locality,” which suggests that if you’ve used an item recently, you are likely to use it again soon. Conversely, an item that hasn’t been touched in a while is less likely to be needed.</p><h3>Core Functionality: How It Works</h3><p>Imagine you have a small bookshelf that can only hold 5 books (this is your cache).</p><ol><li><strong>Cache Hit </strong>(Item is found): You need a book that is already on your shelf. You take it out, use it, and when you’re done, you place it back on the most accessible end of the shelf (let’s say, the far right). This action marks it as the “most recently used” item.</li><li><strong>Cache Miss </strong>(Space is available): You need a new book that isn’t on the shelf, and there’s an empty spot. You get the book from the library (the main memory or database) and place it on the most accessible end (the far right), marking it as the most recently used.</li><li><strong>Cache Miss</strong> (Cache is full): This is where the eviction happens. You need a new book, but your 5-book shelf is full.</li></ol><ul><li>You look at the book on the least accessible end (the far left). This is the book you haven’t touched for the longest time — your “least recently used” item.</li><li>You remove that book from the shelf to make space.</li><li>You get your new book and place it on the most accessible end (the far right).</li></ul><p>This constant reordering ensures that the items at one end are the “hottest” (most recently used), and the items at the other end are the “coldest” (least recently used) and are candidates for eviction.</p><h3><strong>How to Implement an LRU cache</strong> :</h3><h4>It uses two data structures together:</h4><ul><li>A <strong>Hash Map</strong> for fast lookups (O(1)) to check if an item exists in the cache.</li><li>A <strong>Doubly Linked</strong> List to maintain the order of usage. The list’s head can be the most recently used item, and the tail can be the least recently used, allowing for O(1) additions and removals.</li></ul><h3>LRU Cache → UML Class Diagram</h3><figure><img alt="LRU-Cache → UML Class Diagram" src="https://cdn-images-1.medium.com/max/1024/1*hBXzbZFxJhdd_jh8SoYnog.png" /></figure><h3>LRU Implementation in Java</h3><ol><li>Create<strong> LRU </strong>Interface</li></ol><pre>public interface LRU&lt;K, V&gt; {<br><br>    void writeToCache(K key, V value);<br><br>    V readFromCache(K key);<br><br>}</pre><p>2. Create <strong>LRUCache </strong>class</p><pre>import lombok.Getter;<br>import lombok.Setter;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.stereotype.Component;<br><br>import java.util.Map;<br>import java.util.concurrent.ConcurrentHashMap;<br><br>@Slf4j<br>@Component<br>public class LRUCache&lt;K, V&gt; implements LRU&lt;K, V&gt; {<br>    private static final int DEFAULT_CACHE_SIZE = 4;<br><br>    //Inner Class --&gt; Node<br>    private static class Node&lt;K, V&gt; {<br>        K key;<br>        V value;<br>        Node&lt;K, V&gt; prev;<br>        Node&lt;K, V&gt; next;<br><br>        public Node(K key, V value) {<br>            this.key = key;<br>            this.value = value;<br>        }<br><br>        @Override<br>        public String toString() {<br>            return &quot;Node(&quot; + key + &quot;, &quot; + value + &quot;, Prev-&quot; + (prev != null ? prev.key : null) + &quot;, Next-&quot; + (next != null ? next.key : null) + &quot;)&quot;;<br>        }<br>    }<br><br>    private Node&lt;K, V&gt; head;<br>    private Node&lt;K, V&gt; tail;<br>    private final Map&lt;K, Node&lt;K, V&gt;&gt; nodeMap;<br>    @Getter<br>    @Setter<br>    private int cacheSize;<br><br>    public LRUCache() {<br>        cacheSize = DEFAULT_CACHE_SIZE;<br>        nodeMap = new ConcurrentHashMap&lt;&gt;();<br>    }<br><br>    private void addToFront(K key, V value) {<br>        Node&lt;K, V&gt; newNode = new Node&lt;&gt;(key, value);<br><br>        if (nodeMap.isEmpty()) {<br>            head = newNode;<br>            tail = newNode;<br>        } else {<br>            head.prev = newNode;<br>            newNode.next = head;<br>            head = newNode;<br>        }<br>        nodeMap.put(key, newNode);<br>    }<br><br>    private Node&lt;K, V&gt; removeFromTail() {<br>        Node&lt;K, V&gt; removedNode = tail;<br><br>        tail.prev.next = null;<br>        tail = tail.prev;<br><br>        return nodeMap.remove(removedNode.key);<br>    }<br><br>    //  |.|5|.| --&gt; |.|5|.| --&gt; |.|5|.| --&gt; |.|5|.|<br>    private Node&lt;K, V&gt; cacheLookUp(K key) {<br>        // return null, if below conditions meat<br>        if (nodeMap.isEmpty() || !nodeMap.containsKey(key)) {<br>            return null;<br>        }<br><br>        //Node already Exists<br>        Node&lt;K, V&gt; node = nodeMap.get(key);<br><br>        //If Reading Head<br>        if (head == node) {<br>            return head;<br>        }<br><br>        //If Reading Tail<br>        if (tail == node) {<br>            // Updating pointers<br>            tail.prev.next = null;<br>            tail = tail.prev;<br>        } else {<br>            // Updating pointers<br>            node.prev.next = node.next;<br>            node.next.prev = node.prev;<br>            node.prev = null;<br>        }<br><br>        // Add to Front<br>        head.prev = node;<br>        node.next = head;<br>        head = node;<br><br>        return head;<br>    }<br><br>    @Override<br>    public void writeToCache(K key, V value) {<br>        if (key == null) {<br>            throw new IllegalArgumentException(&quot;Cannot Write to Cache as key is Null&quot;);<br>        }<br><br>        log.info(&quot;!! Write To Cache !!&quot;);<br>        // add to cache<br>        this.addToFront(key, value);<br><br>        // evict cache<br>        if (nodeMap.size() &gt; cacheSize) {<br>            Node&lt;K, V&gt; removedNode = removeFromTail();<br>            log.info(&quot;Remove From Tail!!--------{}&quot;, removedNode.toString());<br>        }<br>    }<br><br>    @Override<br>    public V readFromCache(K key) {<br>        if (key == null) {<br>            throw new IllegalArgumentException(&quot;Cannot Read from Cache as key is Null&quot;);<br>        }<br>        Node&lt;K, V&gt; node = cacheLookUp(key);<br>        if (node != null) {<br>            log.info(&quot;Read From Cache !! =={}&quot;, node);<br>            return node.value;<br>        }<br>        return null;<br>    }<br>}</pre><p>3. Optional Just for Testing purpose. Create <strong>LRUCacheTest</strong> class.</p><pre>import org.junit.jupiter.api.*;<br>import org.junit.jupiter.params.ParameterizedTest;<br>import org.junit.jupiter.params.provider.ValueSource;<br>import org.junit.jupiter.params.provider.CsvSource;<br>import org.springframework.boot.test.context.SpringBootTest;<br>import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;<br><br>import static org.junit.jupiter.api.Assertions.*;<br><br>import ch.qos.logback.classic.Logger;<br>import ch.qos.logback.classic.spi.ILoggingEvent;<br>import ch.qos.logback.core.read.ListAppender;<br>import org.slf4j.LoggerFactory;<br><br>import java.lang.reflect.Field;<br>import java.util.Map;<br>import java.util.Objects;<br>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br>import java.util.concurrent.Future;<br>import java.util.concurrent.TimeUnit;<br><br>/**<br> * Comprehensive JUnit Test Cases for LRUCache<br> * Tests all functionality including edge cases, concurrency, and error handling<br> */<br>@SpringBootTest<br>@SpringJUnitConfig<br>class LRUCacheTest {<br><br>    private LRUCache&lt;String, String&gt; stringCache;<br>    private LRUCache&lt;Integer, Integer&gt; integerCache;<br><br>    private ListAppender&lt;ILoggingEvent&gt; listAppender;<br><br>    @BeforeEach<br>    void setUp() {<br>        stringCache = new LRUCache&lt;&gt;();<br>        integerCache = new LRUCache&lt;&gt;();<br><br>        // Set up logging capture<br>        // For logging verification<br>        Logger logger = (Logger) LoggerFactory.getLogger(LRUCache.class);<br>        listAppender = new ListAppender&lt;&gt;();<br>        listAppender.start();<br>        logger.addAppender(listAppender);<br>    }<br><br>    // ====================================================================<br>    // CONSTRUCTOR AND INITIALIZATION TESTS<br>    // ====================================================================<br><br>    @Test<br>    @DisplayName(&quot;Should initialize with default cache size&quot;)<br>    void testDefaultConstructorInitialization() {<br>        // Given &amp; When<br>        LRUCache&lt;String, String&gt; cache = new LRUCache&lt;&gt;();<br><br>        // Then<br>        assertEquals(4, cache.getCacheSize(), &quot;Default cache size should be 4&quot;);<br>        assertNotNull(getNodeMap(cache), &quot;Node map should be initialized&quot;);<br>        assertTrue(Objects.requireNonNull(getNodeMap(cache)).isEmpty(), &quot;Node map should be empty initially&quot;);<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Should be a Spring Component&quot;)<br>    void testSpringComponentAnnotation() {<br>        // Then<br>        assertTrue(LRUCache.class.isAnnotationPresent(org.springframework.stereotype.Component.class),<br>                &quot;LRUCache should be annotated with @Component&quot;);<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Should implement LRU interface&quot;)<br>    void testImplementsLRUInterface() {<br>        // Then<br>        assertTrue(true,<br>                &quot;LRUCache should implement LRU interface&quot;);<br>    }<br><br>    // ====================================================================<br>    // CACHE SIZE TESTS<br>    // ====================================================================<br><br>    @Test<br>    @DisplayName(&quot;Should allow setting and getting cache size&quot;)<br>    void testCacheSizeSetterAndGetter() {<br>        // Given<br>        int newSize = 10;<br><br>        // When<br>        stringCache.setCacheSize(newSize);<br><br>        // Then<br>        assertEquals(newSize, stringCache.getCacheSize(),<br>                &quot;Cache size should be updated to new value&quot;);<br>    }<br><br>    @ParameterizedTest<br>    @ValueSource(ints = {1, 2, 5, 10, 100})<br>    @DisplayName(&quot;Should work with different cache sizes&quot;)<br>    void testVariousCacheSizes(int cacheSize) {<br>        // Given<br>        stringCache.setCacheSize(cacheSize);<br><br>        // When &amp; Then<br>        assertEquals(cacheSize, stringCache.getCacheSize());<br>    }<br><br>    // ====================================================================<br>    // WRITE TO CACHE TESTS<br>    // ====================================================================<br><br>    @Test<br>    @DisplayName(&quot;Should write single item to empty cache&quot;)<br>    void testWriteSingleItemToEmptyCache() {<br>        // When<br>        stringCache.writeToCache(&quot;key1&quot;, &quot;value1&quot;);<br><br>        // Then<br>        assertEquals(1, getNodeMapSize(stringCache), &quot;Cache should contain 1 item&quot;);<br>        assertTrue(containsKey(stringCache, &quot;key1&quot;), &quot;Cache should contain the added key&quot;);<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Should write multiple items within cache limit&quot;)<br>    void testWriteMultipleItemsWithinLimit() {<br>        // Given<br>        stringCache.setCacheSize(5);<br><br>        // When<br>        stringCache.writeToCache(&quot;key1&quot;, &quot;value1&quot;);<br>        stringCache.writeToCache(&quot;key2&quot;, &quot;value2&quot;);<br>        stringCache.writeToCache(&quot;key3&quot;, &quot;value3&quot;);<br><br>        // Then<br>        assertEquals(3, getNodeMapSize(stringCache), &quot;Cache should contain 3 items&quot;);<br>        assertTrue(containsKey(stringCache, &quot;key1&quot;));<br>        assertTrue(containsKey(stringCache, &quot;key2&quot;));<br>        assertTrue(containsKey(stringCache, &quot;key3&quot;));<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Should evict least recently used item when cache exceeds limit&quot;)<br>    void testEvictionWhenCacheExceedsLimit() {<br>        // Given<br>        stringCache.setCacheSize(3);<br><br>        // When<br>        stringCache.writeToCache(&quot;key1&quot;, &quot;value1&quot;);  // Cache: [key1]<br>        stringCache.writeToCache(&quot;key2&quot;, &quot;value2&quot;);  // Cache: [key2, key1]<br>        stringCache.writeToCache(&quot;key3&quot;, &quot;value3&quot;);  // Cache: [key3, key2, key1]<br>        stringCache.writeToCache(&quot;key4&quot;, &quot;value4&quot;);  // Cache: [key4, key3, key2], evict key1<br><br>        // Then<br>        assertEquals(3, getNodeMapSize(stringCache), &quot;Cache should maintain size limit&quot;);<br>        assertFalse(containsKey(stringCache, &quot;key1&quot;), &quot;Oldest item should be evicted&quot;);<br>        assertTrue(containsKey(stringCache, &quot;key2&quot;));<br>        assertTrue(containsKey(stringCache, &quot;key3&quot;));<br>        assertTrue(containsKey(stringCache, &quot;key4&quot;));<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Should log write operations&quot;)<br>    void testWriteLogging() {<br>        // When<br>        stringCache.writeToCache(&quot;testKey&quot;, &quot;testValue&quot;);<br><br>        // Then<br>        assertTrue(listAppender.list.stream()<br>                        .anyMatch(event -&gt; event.getMessage().contains(&quot;Write To Cache&quot;)),<br>                &quot;Should log write operation&quot;);<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Should log eviction when cache is full&quot;)<br>    void testEvictionLogging() {<br>        // Given<br>        stringCache.setCacheSize(2);<br>        stringCache.writeToCache(&quot;key1&quot;, &quot;value1&quot;);<br>        stringCache.writeToCache(&quot;key2&quot;, &quot;value2&quot;);<br><br>        // When<br>        stringCache.writeToCache(&quot;key3&quot;, &quot;value3&quot;); // This should trigger eviction<br><br>        // Then<br>        assertTrue(listAppender.list.stream()<br>                        .anyMatch(event -&gt; event.getMessage().contains(&quot;Remove From Tail&quot;)),<br>                &quot;Should log eviction operation&quot;);<br>    }<br><br>    // ====================================================================<br>    // READ FROM CACHE TESTS<br>    // ====================================================================<br><br>    @Test<br>    @DisplayName(&quot;Should read existing item from cache&quot;)<br>    void testReadExistingItem() {<br>        // Given<br>        stringCache.writeToCache(&quot;key1&quot;, &quot;value1&quot;);<br><br>        // When<br>        String result = stringCache.readFromCache(&quot;key1&quot;);<br><br>        // Then<br>        assertEquals(&quot;value1&quot;, result, &quot;Should return correct value&quot;);<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Should move accessed item to front (most recently used)&quot;)<br>    void testReadMovesToFront() {<br>        // Given<br>        stringCache.setCacheSize(3);<br>        stringCache.writeToCache(&quot;key1&quot;, &quot;value1&quot;);  // Cache: [key1]<br>        stringCache.writeToCache(&quot;key2&quot;, &quot;value2&quot;);  // Cache: [key2, key1]<br>        stringCache.writeToCache(&quot;key3&quot;, &quot;value3&quot;);  // Cache: [key3, key2, key1]<br>        System.out.println(&quot;-1---------&quot; + stringCache);<br><br>        // When<br>        stringCache.readFromCache(&quot;key1&quot;);           // Cache: [key1, key3, key2]<br>        System.out.println(&quot;-2---------&quot; + stringCache);<br>        stringCache.writeToCache(&quot;key4&quot;, &quot;value4&quot;);  // Cache: [key4, key1, key3], evict key2<br>        System.out.println(&quot;-3---------&quot; + stringCache);<br><br>        // Then<br>        assertFalse(containsKey(stringCache, &quot;key2&quot;), &quot;key2 should be evicted&quot;);<br>        assertTrue(containsKey(stringCache, &quot;key1&quot;), &quot;key1 should still exist (was accessed)&quot;);<br>        assertTrue(containsKey(stringCache, &quot;key3&quot;));<br>        assertTrue(containsKey(stringCache, &quot;key4&quot;));<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Should log read operations&quot;)<br>    void testReadLogging() {<br>        // Given<br>        stringCache.writeToCache(&quot;testKey&quot;, &quot;testValue&quot;);<br><br>        // When<br>        stringCache.readFromCache(&quot;testKey&quot;);<br><br>        // Then<br>        assertTrue(listAppender.list.stream()<br>                        .anyMatch(event -&gt; event.getMessage().contains(&quot;Read From Cache&quot;)),<br>                &quot;Should log read operation&quot;);<br>    }<br><br>    // ====================================================================<br>    // LRU ALGORITHM TESTS<br>    // ====================================================================<br><br>    @Test<br>    @DisplayName(&quot;Should maintain LRU order correctly&quot;)<br>    void testLRUOrderMaintenance() {<br>        // Given<br>        stringCache.setCacheSize(3);<br><br>        // When<br>        stringCache.writeToCache(&quot;A&quot;, &quot;1&quot;);  // Cache: [A]<br>        stringCache.writeToCache(&quot;B&quot;, &quot;2&quot;);  // Cache: [B, A]<br>        stringCache.writeToCache(&quot;C&quot;, &quot;3&quot;);  // Cache: [C, B, A]<br><br>        // Access A to make it most recently used<br>        stringCache.readFromCache(&quot;A&quot;);      // Cache: [A, C, B]<br><br>        // Add new item - B should be evicted<br>        stringCache.writeToCache(&quot;D&quot;, &quot;4&quot;);  // Cache: [D, A, C]<br><br>        // Then<br>        assertFalse(containsKey(stringCache, &quot;B&quot;), &quot;B should be evicted (was LRU)&quot;);<br>        assertTrue(containsKey(stringCache, &quot;A&quot;), &quot;A should exist (was accessed)&quot;);<br>        assertTrue(containsKey(stringCache, &quot;C&quot;), &quot;C should exist&quot;);<br>        assertTrue(containsKey(stringCache, &quot;D&quot;), &quot;D should exist (just added)&quot;);<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Should handle complex access patterns correctly&quot;)<br>    void testComplexAccessPattern() {<br>        // Given<br>        stringCache.setCacheSize(4);<br><br>        // When<br>        stringCache.writeToCache(&quot;1&quot;, &quot;A&quot;);<br>        stringCache.writeToCache(&quot;2&quot;, &quot;B&quot;);<br>        stringCache.writeToCache(&quot;3&quot;, &quot;C&quot;);<br>        stringCache.writeToCache(&quot;4&quot;, &quot;D&quot;);  // Cache: [4, 3, 2, 1]<br><br>        stringCache.readFromCache(&quot;2&quot;);      // Cache: [2, 4, 3, 1]<br>        stringCache.readFromCache(&quot;1&quot;);      // Cache: [1, 2, 4, 3]<br>        stringCache.writeToCache(&quot;5&quot;, &quot;E&quot;);  // Cache: [5, 1, 2, 4], evict 3<br><br>        // Then<br>        assertFalse(containsKey(stringCache, &quot;3&quot;), &quot;3 should be evicted&quot;);<br>        assertTrue(containsKey(stringCache, &quot;1&quot;));<br>        assertTrue(containsKey(stringCache, &quot;2&quot;));<br>        assertTrue(containsKey(stringCache, &quot;4&quot;));<br>        assertTrue(containsKey(stringCache, &quot;5&quot;));<br>    }<br><br>    // ====================================================================<br>    // EDGE CASES AND ERROR HANDLING<br>    // ====================================================================<br><br>    @Test<br>    @DisplayName(&quot;Should handle null keys gracefully&quot;)<br>    void testNullKeys() {<br>        // When &amp; Then<br>        IllegalArgumentException exception1 = assertThrows(<br>                IllegalArgumentException.class,<br>                () -&gt; stringCache.writeToCache(null, &quot;value&quot;),<br>                &quot;Cannot Write to Cache as key is Null&quot;<br>        );<br><br>        // Verify exception message<br>        assertEquals(&quot;Cannot Write to Cache as key is Null&quot;, exception1.getMessage());<br><br>        // When &amp; Then<br>        IllegalArgumentException exception2 = assertThrows(<br>                IllegalArgumentException.class,<br>                () -&gt; stringCache.readFromCache(null),<br>                &quot;Cannot Read from Cache as key is Null&quot;<br>        );<br><br>        // Verify exception message<br>        assertEquals(&quot;Cannot Read from Cache as key is Null&quot;, exception2.getMessage());<br><br>    }<br><br>    @Test<br>    @DisplayName(&quot;Should handle cache size of 1&quot;)<br>    void testCacheSizeOne() {<br>        // Given<br>        stringCache.setCacheSize(1);<br><br>        // When<br>        stringCache.writeToCache(&quot;key1&quot;, &quot;value1&quot;);<br>        stringCache.writeToCache(&quot;key2&quot;, &quot;value2&quot;);  // Should evict key1<br><br>        // Then<br>        assertEquals(1, getNodeMapSize(stringCache), &quot;Cache should contain only 1 item&quot;);<br>        assertFalse(containsKey(stringCache, &quot;key1&quot;));<br>        assertTrue(containsKey(stringCache, &quot;key2&quot;));<br>    }<br><br>    @Disabled(&quot;Will Think this scenario later!&quot;)<br>    @Test<br>    @DisplayName(&quot;Should handle overwriting existing keys&quot;)<br>    void testOverwriteExistingKey() {<br>        // Given<br>        stringCache.writeToCache(&quot;key1&quot;, &quot;value1&quot;);<br><br>        // When<br>        stringCache.writeToCache(&quot;key1&quot;, &quot;newValue&quot;);<br><br>        // Then<br>        assertEquals(2, getNodeMapSize(stringCache), &quot;Should add new entry for same key&quot;);<br>        // Note: Current implementation doesn&#39;t check for existing keys, it adds new nodes<br>    }<br><br>    // ====================================================================<br>    // DIFFERENT DATA TYPES TESTS<br>    // ====================================================================<br><br>    @Test<br>    @DisplayName(&quot;Should work with Integer keys and values&quot;)<br>    void testIntegerKeysAndValues() {<br>        // When<br>        integerCache.writeToCache(1, 100);<br>        integerCache.writeToCache(2, 200);<br>        integerCache.writeToCache(3, 300);<br><br>        // Then<br>        assertEquals(Integer.valueOf(100), integerCache.readFromCache(1));<br>        assertEquals(Integer.valueOf(200), integerCache.readFromCache(2));<br>        assertEquals(Integer.valueOf(300), integerCache.readFromCache(3));<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Should work with mixed object types&quot;)<br>    void testMixedObjectTypes() {<br>        // Given<br>        LRUCache&lt;String, Object&gt; objectCache = new LRUCache&lt;&gt;();<br><br>        // When<br>        objectCache.writeToCache(&quot;string&quot;, &quot;stringValue&quot;);<br>        objectCache.writeToCache(&quot;integer&quot;, 42);<br>        objectCache.writeToCache(&quot;double&quot;, 3.14);<br>        objectCache.writeToCache(&quot;boolean&quot;, true);<br><br>        // Then<br>        assertEquals(&quot;stringValue&quot;, objectCache.readFromCache(&quot;string&quot;));<br>        assertEquals(42, objectCache.readFromCache(&quot;integer&quot;));<br>        assertEquals(3.14, objectCache.readFromCache(&quot;double&quot;));<br>        assertEquals(true, objectCache.readFromCache(&quot;boolean&quot;));<br>    }<br><br>    // ====================================================================<br>    // PERFORMANCE TESTS<br>    // ====================================================================<br><br>    @Test<br>    @DisplayName(&quot;Should perform well with large number of operations&quot;)<br>    void testPerformanceWithManyOperations() {<br>        // Given<br>        stringCache.setCacheSize(100);<br>        long startTime = System.currentTimeMillis();<br><br>        // When<br>        for (int i = 0; i &lt; 1000; i++) {<br>            stringCache.writeToCache(&quot;key&quot; + i, &quot;value&quot; + i);<br>        }<br><br>        for (int i = 0; i &lt; 500; i++) {<br>            try {<br>                stringCache.readFromCache(&quot;key&quot; + (i + 500)); // Read from cache<br>            } catch (AssertionError ignored) {<br>                // Some keys might be evicted<br>            }<br>        }<br><br>        // Then<br>        long duration = System.currentTimeMillis() - startTime;<br>        assertTrue(duration &lt; 1000, &quot;Operations should complete within 1 second&quot;);<br>        assertEquals(100, getNodeMapSize(stringCache), &quot;Cache should maintain size limit&quot;);<br>    }<br><br>    @RepeatedTest(5)<br>    @DisplayName(&quot;Should maintain consistency across multiple test runs&quot;)<br>    void testConsistencyAcrossRuns() {<br>        // Given<br>        stringCache.setCacheSize(3);<br><br>        // When<br>        stringCache.writeToCache(&quot;A&quot;, &quot;1&quot;);<br>        stringCache.writeToCache(&quot;B&quot;, &quot;2&quot;);<br>        stringCache.writeToCache(&quot;C&quot;, &quot;3&quot;);<br>        stringCache.writeToCache(&quot;D&quot;, &quot;4&quot;); // Should evict A<br><br>        // Then<br>        assertEquals(3, getNodeMapSize(stringCache));<br>        assertFalse(containsKey(stringCache, &quot;A&quot;));<br>        assertTrue(containsKey(stringCache, &quot;D&quot;));<br>    }<br><br>    // ====================================================================<br>    // CONCURRENCY TESTS<br>    // ====================================================================<br><br>    @Test<br>    @DisplayName(&quot;Should handle concurrent write operations&quot;)<br>    void testConcurrentWrites() throws Exception {<br>        // Given<br>        stringCache.setCacheSize(50);<br>        ExecutorService executor = Executors.newFixedThreadPool(10);<br><br>        // When<br>        Future&lt;?&gt;[] futures = new Future[100];<br>        for (int i = 0; i &lt; 100; i++) {<br>            final int index = i;<br>            futures[i] = executor.submit(() -&gt; stringCache.writeToCache(&quot;key&quot; + index, &quot;value&quot; + index));<br>        }<br><br>        // Wait for all operations to complete<br>        for (Future&lt;?&gt; future : futures) {<br>            future.get(1, TimeUnit.SECONDS);<br>        }<br><br>        // Then<br>        assertEquals(50, getNodeMapSize(stringCache), &quot;Cache should maintain size limit&quot;);<br>        executor.shutdown();<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Should handle concurrent read and write operations&quot;)<br>    void testConcurrentReadsAndWrites() throws Exception {<br>        // Given<br>        stringCache.setCacheSize(10);<br>        // Pre-populate cache<br>        for (int i = 0; i &lt; 5; i++) {<br>            stringCache.writeToCache(&quot;key&quot; + i, &quot;value&quot; + i);<br>        }<br><br>        ExecutorService executor = Executors.newFixedThreadPool(5);<br><br>        // When<br>        Future&lt;?&gt;[] futures = new Future[20];<br>        for (int i = 0; i &lt; 20; i++) {<br>            final int index = i;<br>            futures[i] = executor.submit(() -&gt; {<br>                if (index % 2 == 0) {<br>                    stringCache.writeToCache(&quot;newKey&quot; + index, &quot;newValue&quot; + index);<br>                } else {<br>                    try {<br>                        stringCache.readFromCache(&quot;key&quot; + (index % 5));<br>                    } catch (AssertionError ignored) {<br>                        // Key might have been evicted<br>                    }<br>                }<br>            });<br>        }<br><br>        // Wait for completion<br>        for (Future&lt;?&gt; future : futures) {<br>            future.get(2, TimeUnit.SECONDS);<br>        }<br><br>        // Then<br>        assertTrue(getNodeMapSize(stringCache) &lt;= 10, &quot;Cache should not exceed size limit&quot;);<br>        executor.shutdown();<br>    }<br><br>    // ====================================================================<br>    // PARAMETERIZED TESTS<br>    // ====================================================================<br><br>    @ParameterizedTest<br>    @CsvSource({<br>            &quot;1, key1, value1&quot;,<br>            &quot;5, testKey, testValue&quot;,<br>            &quot;10, anotherKey, anotherValue&quot;<br>    })<br>    @DisplayName(&quot;Should work with various cache sizes and key-value pairs&quot;)<br>    void testVariousConfigurations(int cacheSize, String key, String value) {<br>        // Given<br>        stringCache.setCacheSize(cacheSize);<br><br>        // When<br>        stringCache.writeToCache(key, value);<br><br>        // Then<br>        assertEquals(value, stringCache.readFromCache(key));<br>        assertEquals(1, getNodeMapSize(stringCache));<br>    }<br><br>    // ====================================================================<br>    // NESTED TEST CLASSES<br>    // ====================================================================<br><br>    @Nested<br>    @DisplayName(&quot;Cache Eviction Tests&quot;)<br>    class CacheEvictionTests {<br><br>        @Test<br>        @DisplayName(&quot;Should evict in correct LRU order&quot;)<br>        void testCorrectEvictionOrder() {<br>            // Given<br>            stringCache.setCacheSize(2);<br><br>            // When<br>            stringCache.writeToCache(&quot;first&quot;, &quot;1&quot;);   // [first]<br>            stringCache.writeToCache(&quot;second&quot;, &quot;2&quot;);  // [second, first]<br>            stringCache.writeToCache(&quot;third&quot;, &quot;3&quot;);   // [third, second] - evict first<br><br>            // Then<br>            assertFalse(containsKey(stringCache, &quot;first&quot;));<br>            assertTrue(containsKey(stringCache, &quot;second&quot;));<br>            assertTrue(containsKey(stringCache, &quot;third&quot;));<br>        }<br><br>        @Test<br>        @DisplayName(&quot;Should not evict when cache is not full&quot;)<br>        void testNoEvictionWhenNotFull() {<br>            // Given<br>            stringCache.setCacheSize(5);<br><br>            // When<br>            stringCache.writeToCache(&quot;key1&quot;, &quot;value1&quot;);<br>            stringCache.writeToCache(&quot;key2&quot;, &quot;value2&quot;);<br>            stringCache.writeToCache(&quot;key3&quot;, &quot;value3&quot;);<br><br>            // Then<br>            assertEquals(3, getNodeMapSize(stringCache));<br>            assertTrue(containsKey(stringCache, &quot;key1&quot;));<br>            assertTrue(containsKey(stringCache, &quot;key2&quot;));<br>            assertTrue(containsKey(stringCache, &quot;key3&quot;));<br>        }<br>    }<br><br>    @Nested<br>    @DisplayName(&quot;Node Operations Tests&quot;)<br>    class NodeOperationsTests {<br><br>        @Test<br>        @DisplayName(&quot;Should maintain proper node linking&quot;)<br>        void testNodeLinking() {<br>            // Given<br>            stringCache.setCacheSize(3);<br><br>            // When<br>            stringCache.writeToCache(&quot;A&quot;, &quot;1&quot;);<br>            stringCache.writeToCache(&quot;B&quot;, &quot;2&quot;);<br>            stringCache.writeToCache(&quot;C&quot;, &quot;3&quot;);<br><br>            // Access middle node<br>            stringCache.readFromCache(&quot;B&quot;);<br><br>            // Then<br>            // Verify that the cache still functions correctly<br>            assertEquals(&quot;1&quot;, stringCache.readFromCache(&quot;A&quot;));<br>            assertEquals(&quot;2&quot;, stringCache.readFromCache(&quot;B&quot;));<br>            assertEquals(&quot;3&quot;, stringCache.readFromCache(&quot;C&quot;));<br>        }<br>    }<br><br>    // ====================================================================<br>    // HELPER METHODS FOR REFLECTION-BASED TESTING<br>    // ====================================================================<br><br>    @SuppressWarnings(&quot;unchecked&quot;)<br>    private Map&lt;Object, Object&gt; getNodeMap(LRUCache&lt;?, ?&gt; cache) {<br>        try {<br>            Field nodeMapField = LRUCache.class.getDeclaredField(&quot;nodeMap&quot;);<br>            nodeMapField.setAccessible(true);<br>            return (Map&lt;Object, Object&gt;) nodeMapField.get(cache);<br>        } catch (Exception e) {<br>            fail(&quot;Failed to access nodeMap field: &quot; + e.getMessage());<br>            return null;<br>        }<br>    }<br><br>    private int getNodeMapSize(LRUCache&lt;?, ?&gt; cache) {<br>        return Objects.requireNonNull(getNodeMap(cache)).size();<br>    }<br><br>    private boolean containsKey(LRUCache&lt;?, ?&gt; cache, Object key) {<br>        return Objects.requireNonNull(getNodeMap(cache)).containsKey(key);<br>    }<br><br>    // ====================================================================<br>    // INTEGRATION TESTS<br>    // ====================================================================<br><br>    @Test<br>    @DisplayName(&quot;Should integrate properly with Spring context&quot;)<br>    void testSpringIntegration() {<br>        // This test verifies that the cache can be used as a Spring bean<br>        // The @SpringBootTest annotation ensures Spring context is loaded<br><br>        assertNotNull(stringCache, &quot;Cache should be instantiated&quot;);<br>        assertInstanceOf(LRU.class, stringCache, &quot;Should implement LRU interface&quot;);<br>    }<br><br>    @Test<br>    @DisplayName(&quot;Should work as expected in real-world scenario&quot;)<br>    void testRealWorldScenario() {<br>        // Given - Simulate a web application cache scenario<br>        LRUCache&lt;String, String&gt; webCache = new LRUCache&lt;&gt;();<br>        webCache.setCacheSize(3);<br><br>        // When - Simulate user session data caching<br>        webCache.writeToCache(&quot;user:123&quot;, &quot;John Doe&quot;);      // Cache: [user:123]<br>        webCache.writeToCache(&quot;user:456&quot;, &quot;Jane Smith&quot;);    // Cache: [user:456, user:123]<br>        webCache.writeToCache(&quot;user:789&quot;, &quot;Bob Johnson&quot;);   // Cache: [user:789, user:456, user:123]<br><br>        // Access user 123 (making it most recently used)<br>        assertEquals(&quot;John Doe&quot;, webCache.readFromCache(&quot;user:123&quot;));  // Cache: [user:123, user:789, user:456]<br><br>        // Add new user (should evict user:456 - least recently used)<br>        webCache.writeToCache(&quot;user:999&quot;, &quot;Alice Brown&quot;);   // Cache: [user:999, user:123, user:789]<br><br>        // Then<br>        assertEquals(3, getNodeMapSize(webCache), &quot;Cache should maintain size limit&quot;);<br>        assertTrue(containsKey(webCache, &quot;user:123&quot;), &quot;Recently accessed user should remain&quot;);<br>        assertFalse(containsKey(webCache, &quot;user:456&quot;), &quot;Least recently used should be evicted&quot;);<br>        assertTrue(containsKey(webCache, &quot;user:789&quot;), &quot;Should contain user:789&quot;);<br>        assertTrue(containsKey(webCache, &quot;user:999&quot;), &quot;Should contain newly added user&quot;);<br><br>        // Verify values are correct<br>        assertEquals(&quot;John Doe&quot;, webCache.readFromCache(&quot;user:123&quot;));<br>        assertEquals(&quot;Bob Johnson&quot;, webCache.readFromCache(&quot;user:789&quot;));<br>        assertEquals(&quot;Alice Brown&quot;, webCache.readFromCache(&quot;user:999&quot;));<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7460346ffe73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging State Design Patterns for Implementing Media Player]]></title>
            <link>https://medium.com/@vishal637yadav/leveraging-state-design-patterns-for-implementing-media-player-186e8dbebd3c?source=rss-6e215e292544------2</link>
            <guid isPermaLink="false">https://medium.com/p/186e8dbebd3c</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[state-design-pattern]]></category>
            <dc:creator><![CDATA[Vishal Yadav]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 06:47:53 GMT</pubDate>
            <atom:updated>2025-11-09T06:47:53.885Z</atom:updated>
            <content:encoded><![CDATA[<h4>Design Patterns in Action : LOW LEVEL DESIGN</h4><h4>Menu-Driven Media Player Implementation in Java</h4><h3>1. What is State Desing Pattern ?</h3><p>The State Design Pattern is a <strong>behavioral pattern</strong> that <strong><em>allows an object to alter its behavior when its internal state changes.</em></strong> The object appears to change its class.</p><ul><li><strong>What it does :</strong> It encapsulates state-specific behavior into separate classes and delegates behavior to the current state object.</li><li><strong>What is avoids : </strong>This avoids large conditional statements and makes state transitions explicit and maintainable.</li></ul><h3>2. Real-World Application ( State Design Pattern )</h3><ol><li>Media Player (Play → Pause → Stop)</li><li>Traffic Light Management (Red → Yellow → Green → Yellow)</li><li>Order Lifecycle (New → Paid → Shipped → Delivered → Cancelled)</li><li>Vending Machine (Idle → HasCredit → Dispensing → OutOfStock)</li><li>Document Workflow (Draft → Review → Published → Archived)</li><li>Elevator Management System (Idle → MovingUp → MovingDown → DoorOpening → DoorOpen →DoorClosing → OutOfService).</li></ol><p>7. Complex ATM State Management.</p><h3>3. Core Components ( State Design Pattern )</h3><ol><li><strong>Context: </strong>This is the primary class that has a <strong><em>State</em></strong>. It maintains an instance of a <strong><em>ConcreteStateA</em></strong> subclass that <strong>defines the current state</strong>. The <strong><em>Context</em></strong> delegates <strong>state-specific requests</strong> to this <strong>current state object</strong>.</li><li><strong>State (Interface or Abstract Class): </strong>This defines a <strong>common interface</strong> for <strong>all classes</strong> that represent a specific state. This interface <strong>declares</strong> the <strong>methods that the </strong><strong><em>Context</em> will call</strong>.</li><li><strong>ConcreteState (Classes):</strong> These classes implement the <strong><em>State</em></strong> interface. Each class is <strong>responsible for implementing the behavior associated with a particular state of the </strong><strong><em>Context</em></strong>. A <strong><em>ConcreteState</em></strong> object may also be <strong>responsible for transitioning </strong>the <strong><em>Context</em></strong> to a <strong>new state</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dr2AiXL260uB7_y_6IUAWQ.png" /><figcaption>Core Components of State Design Pattern</figcaption></figure><h3>4. Problem Solved ( State Design Pattern )</h3><ul><li><strong>Removes Complex Conditionals:</strong> No need for long chains of if/else or switch statements making code readable and maintainable.</li><li>✅ <strong>OCP ( Open Close Principle ) : </strong>Adding a new state <strong><em>ConcreteStateX</em></strong> only requires implementing a new class, no need to interfere with the main context logic.</li><li>✅ <strong>SRP ( Single Responsibility Principle ) : </strong>Each state handles only the behavior related to that state.</li><li>✅ <strong>Encapsulates : </strong>Each state has its own class with distinct behavior.</li><li>✅ <strong>Polymorphism ( dynamic binding) :</strong> The <strong><em>Context</em></strong> can <strong>change its behavior</strong> on-the-fly by changing its concrete state <strong><em>State</em></strong>.</li></ul><h3>5. High-Level Approach ( Media Player )</h3><ol><li>Create <strong><em>PlayerState</em></strong> interface.</li><li>Create <strong><em>PlayerState</em></strong> concrete classes like<strong><em>StoppedState </em></strong>,<strong><em>PlayingState </em></strong>and <strong><em>PausedState </em></strong>which <strong><em>implements </em></strong><strong><em>PlayerState </em></strong>Interface<strong><em>.</em></strong></li><li>Create <strong><em>PlayerContext that composes </em></strong><strong><em>PlayerState.</em></strong></li><li>Create <strong><em>MainDrivingPlayerDemo </em></strong>which contains the<strong><em> Menu-Driven Logic </em></strong>to<strong><em> Run </em></strong>and<strong><em> Test the Media Player.</em></strong></li></ol><h3>6. UML — Class Diagram for Media Player</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iSyYljxnkapxyyAjnETczA.png" /><figcaption>UML:Class Diagram of Media Player(State Design Pattern)</figcaption></figure><h3>7. Code Implementation Media Player</h3><h4>1. Creating <strong><em>PlayerState</em></strong> interface.</h4><pre>public interface PlayerState {<br>    // State-specific behavior methods<br>    void switchToPlayingState(PlayerContext ctx);<br>    void switchToPausedState(PlayerContext ctx);<br>    void switchToStoppedState(PlayerContext ctx);<br>    // Get the Current State<br>    String getCurrentState();<br>}</pre><h4>2. Creating <strong><em>PlayerState</em></strong> Concrete classes</h4><p><strong><em>1. StoppedState</em></strong></p><pre>public class StoppedState implements PlayerState {<br><br>    @Override<br>    public void switchToPlayingState(PlayerContext ctx) {<br>        System.out.println(&quot;Starting playback...&quot;);<br>        ctx.setState(new PlayingState());<br>    }<br><br>    @Override<br>    public void switchToPausedState(PlayerContext ctx) {<br>        System.out.println(&quot;Cannot pause. Media is stopped.&quot;);<br>        throw new IllegalStateException(&quot;Cannot pause media as it is Stopped!!&quot;);<br>    }<br><br>    @Override<br>    public void switchToStoppedState(PlayerContext ctx) {<br>        System.out.println(&quot;Media is already stopped.&quot;);<br>        throw new IllegalStateException(&quot;Cannot stop media as it is already Stopped!!&quot;);<br>    }<br><br>    @Override<br>    public String getCurrentState() {<br>        return &quot;Stopped&quot;;<br>    }<br><br>}</pre><p><strong><em>2. PlayingState</em></strong></p><pre>public class PlayingState implements PlayerState {<br><br>    @Override<br>    public void switchToPlayingState(PlayerContext ctx) {<br>        System.out.println(&quot;Already in playing state.&quot;);<br>        throw new IllegalStateException(&quot;Already in playing state.&quot;);<br>    }<br><br>    @Override<br>    public void switchToPausedState(PlayerContext ctx) {<br>        System.out.println(&quot;Pausing playback...&quot;);<br>        ctx.setState(new PausedState());<br>    }<br><br>    @Override<br>    public void switchToStoppedState(PlayerContext ctx) {<br>        System.out.println(&quot;Stopping playback...&quot;);<br>        ctx.setState(new StoppedState());<br>    }<br><br>    @Override<br>    public String getCurrentState() {<br>        return &quot;Playing&quot;;<br>    }<br><br>}</pre><p><strong><em>3. PausedState</em></strong></p><pre>public class PausedState implements PlayerState {<br><br>    @Override<br>    public void switchToPlayingState(PlayerContext ctx) {<br>        System.out.println(&quot;Resuming playback...&quot;);<br>        ctx.setState(new PlayingState());<br>    }<br><br>    @Override<br>    public void switchToPausedState(PlayerContext ctx) {<br>        System.out.println(&quot;Already in paused state.&quot;);<br>        throw new IllegalStateException(&quot;Cannot pause media as it is Already in PausedState!!&quot;);<br>    }<br><br>    @Override<br>    public void switchToStoppedState(PlayerContext ctx) {<br>        System.out.println(&quot;Stopping from paused...&quot;);<br>        ctx.setState(new StoppedState());<br>    }<br><br>    @Override<br>    public String getCurrentState() {<br>        return &quot;Paused&quot;;<br>    }<br><br>}</pre><h4>3. Creating <strong><em>PlayerContext — composes → </em></strong><strong><em>PlayerState</em></strong></h4><p>Create <strong><em>PlayerContext that composes </em></strong><strong><em>PlayerState</em></strong></p><pre>public class PlayerContext {<br>    private PlayerState state;<br><br>    public PlayerContext() {<br>        this.state = new StoppedState();<br>    }<br><br>    public void setState(PlayerState newState) {<br>        System.out.println(&quot;Transition: &quot; + this.state.getCurrentState() + &quot; -&gt; &quot; + newState.getCurrentState());<br>        this.state = newState;<br>    }<br><br>    public void play() {<br>        state.switchToPlayingState(this);<br>    }<br><br>    public void pause() {<br>        state.switchToPausedState(this);<br>    }<br><br>    public void stop() {<br>        state.switchToStoppedState(this);<br>    }<br><br>    public String getStateName() {<br>        return state.getCurrentState();<br>    }<br>}</pre><h4>4. Creating <strong><em>MainDrivingPlayerDemo </em></strong>to<strong><em> Run </em></strong>and<strong><em> Test Media Player</em></strong></h4><pre>import java.io.BufferedReader;<br>import java.io.IOException;<br>import java.io.InputStreamReader;<br><br>public class MainDrivingPlayerDemo {<br><br>    public static void main(String[] args) throws IOException {<br>        PlayerContext player = new PlayerContext();<br>        System.out.println(&quot;Initial: &quot; + player.getStateName());<br><br>        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));<br>        String choice;<br>        String doYouWantToContinue;<br>        do {<br>            System.out.println(&quot;=====================================================&quot;);<br>            System.out.println(&quot;Current State: &quot; + player.getStateName());<br>            System.out.println(&quot;Choose action: 1-Play, 2-Pause, 3-Stop, 4-Exit&quot;);<br>            System.out.print(&quot;You have Chosen: &quot;);<br>            choice = br.readLine();<br>            System.out.println(&quot;-----------------------------------------------------&quot;);<br><br>            switch (choice) {<br>                case &quot;1&quot;:<br>                    try {<br>                        player.play();<br>                    } catch (IllegalStateException e) {<br>                        System.out.println(e.getMessage());<br>                    }<br>                    break;<br>                case &quot;2&quot;:<br>                    try {<br>                        player.pause();<br>                    } catch (IllegalStateException e) {<br>                        System.out.println(e.getMessage());<br>                    }<br>                    break;<br>                case &quot;3&quot;:<br>                    try {<br>                        player.stop();<br>                    } catch (IllegalStateException e) {<br>                        System.out.println(e.getMessage());<br>                    }<br>                    break;<br>                case &quot;4&quot;:<br>                    System.out.println(&quot;Exiting...&quot;);<br>                    return;<br>                default:<br>                    System.out.println(&quot;Invalid choice. Please try again.&quot;);<br>            }<br>            System.out.print(&quot;Do you want to continue? (Yes - Y or y ) :&quot;);<br>            doYouWantToContinue = br.readLine();<br>        } while (doYouWantToContinue.equalsIgnoreCase(&quot;Y&quot;));<br><br>    }<br>}</pre><h3><strong>8. Advantages</strong> of Using <strong>State Design Pattern:</strong></h3><h4>1. Single Responsibility Principle</h4><blockquote>1. Each state handles its own behavior</blockquote><blockquote>2. State-specific logic is encapsulated</blockquote><blockquote>3. Easy to understand and maintain</blockquote><h4>2. Open/Closed Principle</h4><blockquote>1. New states can be added without modifying existing code</blockquote><blockquote>2. Existing states can be modified independently</blockquote><blockquote>3. Supports extension without modification</blockquote><h4>3. Eliminates Complex Conditionals</h4><blockquote>1. No need for large if-else or switch statements</blockquote><blockquote>2. Behavior is distributed across state classes</blockquote><blockquote>3. More readable and maintainable code</blockquote><h4>4. Runtime State Changes</h4><blockquote>1. Objects can change behavior dynamically</blockquote><blockquote>2. State transitions are explicit and controlled</blockquote><blockquote>3. Easy to track state changes</blockquote><h3>9. Disadvantages of Using State Design Pattern</h3><h4>1. Increased Complexity</h4><blockquote>1. More classes to manage</blockquote><blockquote>2. Additional indirection in method calls</blockquote><blockquote>3. Can be overkill for simple state machines</blockquote><h4>2. Memory Overhead</h4><blockquote>1. Multiple state objects may be created</blockquote><blockquote>2. Context needs to maintain state reference</blockquote><blockquote>3. Potential for memory leaks if not managed properly</blockquote><h4>3. State Explosion</h4><blockquote>1. Complex systems may have many states</blockquote><blockquote>2. Managing numerous state classes becomes difficult</blockquote><blockquote>3. State transitions can become complex</blockquote><h4>4. Performance Impact</h4><blockquote>1. Additional method calls through delegation</blockquote><blockquote>2. Object creation overhead</blockquote><blockquote>3. May not be suitable for high-performance scenarios</blockquote><h3>10. ✅ Use When ( State Design Pattern)</h3><h4>1. Complex State-Dependent Behavior</h4><ul><li>Object behavior varies significantly based on state</li><li>Many conditional statements based on state</li><li>State transitions are well-defined</li></ul><h4>2. State Machines</h4><ul><li>Implementing finite state machines</li><li>Game character states (idle, running, jumping)</li><li>UI component states (enabled, disabled, focused)</li></ul><h4>3. Business Process Workflows</h4><ul><li>Order processing states</li><li>Document approval workflows</li><li>Payment processing states</li></ul><h4>4. Protocol Implementation</h4><ul><li>Network protocol states</li><li>Connection states (connected, disconnected, connecting)</li></ul><h3>11. ❌ Avoid When( State Design Pattern )</h3><h4>1. Simple State Logic</h4><ul><li>Few states with simple behavior</li><li>State changes are infrequent</li><li>Boolean flags are sufficient</li></ul><h4>2. Performance-Critical Code</h4><ul><li>Real-time systems with strict performance requirements</li><li>High-frequency state changes</li><li>Memory-constrained environments</li></ul><h4>3. Static State Behavior</h4><ul><li>States don’t change during object lifetime</li><li>Behavior is determined at creation time</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=186e8dbebd3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Framework’s JdbcTemplate]]></title>
            <link>https://medium.com/@vishal637yadav/spring-frameworks-jdbctemplate-fe8bb036f254?source=rss-6e215e292544------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe8bb036f254</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[template-method-pattern]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Vishal Yadav]]></dc:creator>
            <pubDate>Tue, 04 Nov 2025 02:50:23 GMT</pubDate>
            <atom:updated>2025-11-05T17:07:34.604Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stop writing endless JDBC boilerplate — Spring’s JdbcTemplate does it better</h4><h4>A canonical example of the Template Design Pattern in action</h4><h3>The Problem : Before JdbcTemplate</h3><p>Developers writing database access code using plain <strong>JDBC</strong> had to write a lot of repetitive <strong><em>&quot;boilerplate&quot;</em></strong> code for <strong><em>every single query</em></strong>:</p><h4>Steps to Fetch Data Using JDBC :</h4><ol><li><strong>Load</strong> &amp; <strong>Register</strong> <strong>Drivers</strong>.</li><li><strong>Open a connection</strong> to the database.</li><li><strong>Create a </strong><strong>Statement </strong>or <strong>PreparedStatement</strong>object.</li><li><strong>Execute the query</strong>.</li><li><strong>Process the </strong><strong>ResultSet</strong>.</li><li><strong>Exception Handling potential </strong><strong>SQLException</strong>.</li><li><strong>Closing</strong> <strong><em>Connection</em></strong>, <strong><em>S</em>tatement</strong> &amp; <strong><em>ResultSet</em></strong> in finally block.</li></ol><blockquote><strong>Ensure</strong> the <strong>connection</strong>, <strong>statement</strong>, and <strong>result</strong> set <strong>are closed in a </strong><strong>finally block is crucial to prevent resource leaks, regardless of whether an error occurred.</strong></blockquote><p><strong>Identical Steps</strong> : 1, 2, 5 &amp; 6 (almost same for every query run using JDBC).</p><p><strong>Unique Steps :</strong> 3, 4 (only <strong>unique</strong> as per the requirement/functionality).</p><p>SAMPLE CODE :<strong> </strong>JdbcDemo.java</p><pre>import java.sql .*;<br><br>class JdbcDemo {<br>    public static void main(String[] args) throws Exception {<br>        //Database credentials<br>        String url = &quot;jdbc:mysql://localhost:3306/database_name&quot;;<br>        String username = &quot;scott&quot;;<br>        String password = &quot;tiger&quot;;<br>        //Query to be executed<br>        String query = &quot;select * from students&quot;;<br><br>        try {<br>            //Step 1 -&gt; Load and Register the driver<br>            Class.forName(&quot;com.mysql.cj.jdbc.Driver&quot;);<br><br>            //Step 2 -&gt; Establish connection<br>            Connection con = DriverManager.getConnection(url, username, password);<br>            System.out.println(&quot;Connection Established successfully&quot;);<br><br>            //Step 3 -&gt; Create a statement<br>            Statement st = con.createStatement();<br><br>            //Step 4 -&gt; Execute the query<br>            ResultSet rs = st.executeQuery(query);<br><br>            //Step 5 -&gt; Process the results<br>            while (rs.next()) {<br>                String name = rs.getString(&quot;name&quot;); // Retrieve name from db<br>                System.out.println(name); // Print result on console<br>            }<br>        }<br>        catch (SQLException e) {<br>            //Step 6 -&gt; Exception Handeling<br>            con.rollback();<br>            System.err.println(&quot;Insert error, rolled back: &quot; + e.getMessage());<br>            e.printStackTrace();<br>        }finally {<br>            //Step 7 -&gt; Closing Connection,Statement,ResultSet<br>            rs.close();<br>            st.close();<br>            con.close();<br>            System.out.println(&quot;Connection Closed....&quot;);<br>        }<br>    }<br>}</pre><h3>How Problem Solved : Template Pattern is Applied</h3><p>Spring’s <strong>JdbcTemplate</strong> provides the <strong>template</strong> for this entire process.</p><ol><li>The Algorithm Skeleton (Template Method): The JdbcTemplate.query() method defines the fixed workflow:</li></ol><ul><li>Acquire a <strong>database</strong> connection.</li><li>Create a PreparedStatement.</li><li>Execute the query.</li><li>Iterate through the ResultSet.</li><li>For each row, call a user-provided callback method to map the row to an object.</li><li>Perform exception handling (SQLException translation).</li><li>Clean up and close all resources (connection, statement, etc.).</li></ul><p>2. Abstract Steps (Provided by the Developer): The developer only needs to provide the variable parts of the algorithm by implementing interfaces like:</p><ul><li>RowMapper: Its mapRow() method contains the logic for how to convert one row of the ResultSet into a Java object.</li><li>PreparedStatementCreator: Provides the specific SQL query to be executed.</li></ul><h4>Simple Code Example</h4><pre>// The developer&#39;s focus is only on the business logic.<br>String sql = &quot;SELECT id, name, email FROM users WHERE id = ?&quot;;<br><br>// 1. The template method is &#39;jdbcTemplate.queryForObject()&#39;<br>User user = jdbcTemplate.queryForObject(<br>        sql,<br>        new Object[]{1L}, // 2. The variable part: query arguments<br>        // 3. The variable part: logic to map a DB row to a User object<br>        (resultSet, rowNum) -&gt; new User(<br>                resultSet.getLong(&quot;id&quot;),<br>                resultSet.getString(&quot;name&quot;),<br>                resultSet.getString(&quot;email&quot;)<br>        )<br>);</pre><h3>Benefits of JdbcTemplate</h3><ol><li>The JdbcTemplate handles all the boilerplate resource management and error handling.</li><li>Reduces code duplication and</li><li>Reduces the risk of resource leaks.</li><li>Allow developers to focus solely on writing the Correct SQL and mapping logic and business logic implementation.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe8bb036f254" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying Template Design Pattern in Spring Boot Application]]></title>
            <link>https://medium.com/@vishal637yadav/applying-template-design-pattern-in-spring-boot-application-20202356f4db?source=rss-6e215e292544------2</link>
            <guid isPermaLink="false">https://medium.com/p/20202356f4db</guid>
            <category><![CDATA[template-design-pattern]]></category>
            <category><![CDATA[uml-class-diagram]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Vishal Yadav]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 16:40:32 GMT</pubDate>
            <atom:updated>2025-11-05T03:19:28.635Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What is Template Design Pattern</h3><p><strong>Template Design Pattern</strong> is a <strong>behavioral</strong> design pattern that <strong>defines</strong> the <strong>skeleton of an algorithm</strong> in a <strong>base class</strong> but <strong>lets subclasses override </strong>specific steps of the algorithm <strong>without changing </strong>its structure<strong>.</strong></p><h3>2. Problem : Design Data Processing Pipeline</h3><ul><li>Design a system that processes data from different <strong>sources/format</strong>.</li><li>Data Processing Pipeline will have same<strong> Core-Logic </strong>as below :</li><li><strong>R</strong>ead() → <strong>V</strong>alidate() → <strong>T</strong>ransform() → <strong>S</strong>ave()</li><li><strong>Varying Step </strong>: <strong>R</strong>ead() &amp; <strong>T</strong>ransform() steps vary depending upon the on the source/format.</li></ul><h3>3. High-Level Approach</h3><ol><li>Define a <strong>Abstract</strong> class <strong><em>AbstractFileProcessor</em> </strong>and defines the T<strong>emplate method</strong> <strong><em>process()</em></strong>:</li></ol><ul><li><strong>Skeleton </strong>of the<strong> algorithm </strong>is present in the<strong> process() Template method:</strong></li></ul><p><strong><em>readData() ---&gt; validateDate() ---&gt; transformData() ---&gt; saveData()</em></strong></p><ul><li>Some steps are hooks or abstract methods</li></ul><p><strong><em>readData() &amp; transformData()</em></strong></p><p>2. Concrete implementations override variable steps:</p><p><strong><em>CsvFileProcessor --(overrides)--&gt; readData() &amp; transformData()</em></strong></p><p><strong><em>JsonFileProcessor--(overrides)--&gt; readData() &amp; transformData()</em></strong></p><p><strong><em>XmlFileProcessor --(overrides)--&gt; readData() &amp; transformData()</em></strong></p><p>3. <strong>Spring Boot</strong> wires FileProcessors and exposes REST endpoints to trigger processing.</p><h3>4. UML - Class Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vDhk6VyT3nGn-bCTklMww.png" /></figure><h3>4. Code Implementation</h3><p><strong>4.1. </strong>Create <strong>FileFormat</strong> enum.</p><pre>public enum FileFormat {<br>    JSON,<br>    XML,<br>    CSV<br>}</pre><p><strong>4.2. </strong>Create <strong><em>Abstract Class</em></strong> AbstractFileProcessor containing <strong><em>Template Method </em></strong>process().</p><blockquote><strong>Note</strong> : Template Method is <strong>final,</strong> so it <strong>cannot</strong> be <strong>overridden</strong> by child-classes.</blockquote><pre>import lombok.extern.slf4j.Slf4j;<br><br>@Slf4j<br>public abstract class AbstractFileProcessor {<br><br>    // The template method remains unchanged<br>    public final void process() {<br>        readData();<br>        if (validateData()) {<br>            transformData();<br>            saveData();<br>        } else {<br>            log.warn(&quot;Validation failed for {}. Aborting process.&quot;, getFileFormat());<br>        }<br>    }<br><br>    // NEW: Each subclass must declare its type<br>    public abstract FileFormat getFileFormat();<br><br>    protected abstract void readData();<br><br>    protected abstract void transformData();<br><br>    protected void saveData() {<br>        log.info(&quot;[{}] Saving transformed data to the database...&quot;, getFileFormat());<br>    }<br><br>    protected boolean validateData() {<br>        log.info(&quot;[{}] Performing common data validation...&quot;, getFileFormat());<br>        return true;<br>    }<br>}</pre><p><strong>4.3. </strong>Create <strong><em>Concrete Classes </em>overriding</strong> <strong><em>abstract methods</em></strong> of <strong>AbstractFileProcessor </strong>class</p><ul><li><strong>CsvFileProcessor</strong></li></ul><pre>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.stereotype.Component;<br><br>@Slf4j<br>@Component<br>public class CsvFileProcessor extends AbstractFileProcessor {<br><br>    @Override<br>    public FileFormat getFileFormat() {<br>        return FileFormat.CSV;<br>    }<br><br>    @Override<br>    protected void readData() {<br>        log.info(&quot;Reading data from a CSV file.&quot;);<br>    }<br><br>    @Override<br>    protected void transformData() {<br>        log.info(&quot;Transforming CSV data to a domain object.&quot;);<br>    }<br><br>}</pre><ul><li><strong>JsonFileProcessor</strong></li></ul><pre>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.stereotype.Component;<br><br>@Slf4j<br>@Component<br>public class JsonFileProcessor extends AbstractFileProcessor {<br><br>    @Override<br>    public FileFormat getFileFormat() {<br>        return FileFormat.JSON;<br>    }<br><br>    @Override<br>    protected void readData() {<br>        log.info(&quot;Reading data from a JSON file.&quot;);<br>    }<br><br>    @Override<br>    protected void transformData() {<br>        log.info(&quot;Transforming JSON data to a domain object.&quot;);<br>    }<br><br>}</pre><ul><li><strong>XmlFileProcessor</strong></li></ul><pre>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.stereotype.Component;<br><br>@Slf4j<br>@Component<br>public class XmlFileProcessor extends AbstractFileProcessor {<br><br>    @Override<br>    public FileFormat getFileFormat() {<br>        return FileFormat.XML;<br>    }<br><br>    @Override<br>    protected void readData() {<br>        log.info(&quot;Reading data from a XML file.&quot;);<br>    }<br><br>    @Override<br>    protected void transformData() {<br>        log.info(&quot;Transforming data from a XML file.&quot;);<br>    }<br><br>}</pre><p><strong>4.4. </strong>Create <strong><em>Service Classes.</em></strong></p><blockquote>Service class contains <strong>Map&lt;FileFormat, AbstractFileProcessor&gt; </strong>processMap</blockquote><blockquote>In <strong>FileProcessingService</strong> constructor we are <strong>injecting</strong> all bean of type <strong>AbstractDataProcessor</strong> into the <strong>processMap</strong>.</blockquote><blockquote>Now <strong>processMap</strong> contains the Reference of the Beans of Type <strong>AbstractFileProcessor </strong>Created by Spring Application Context at boot time.</blockquote><pre>import com.sourcecode.spring.dp.template.file.processor.AbstractFileProcessor;<br>import com.sourcecode.spring.dp.template.file.processor.FileFormat;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br><br>import java.util.EnumMap;<br>import java.util.List;<br>import java.util.Map;<br>import java.util.Optional;<br><br>@Slf4j<br>@Service<br>public class FileProcessingService {<br><br>    private final Map&lt;FileFormat, AbstractFileProcessor&gt; processorMap;<br><br>    // Spring injects all beans of type AbstractDataProcessor into the list<br>    public FileProcessingService(List&lt;AbstractFileProcessor&gt; processors) {<br>        processorMap = new EnumMap&lt;&gt;(FileFormat.class);<br>        for (AbstractFileProcessor processor : processors) {<br>            processorMap.put(processor.getFileFormat(), processor);<br>        }<br>    }<br><br>    public void processData(FileFormat type) {<br>        // Find the correct processor from the map<br>        AbstractFileProcessor processor = Optional.ofNullable(processorMap.get(type))<br>                .orElseThrow(() -&gt; new IllegalArgumentException(&quot;Unsupported data processor type: &quot; + type));<br><br>        processor.process(); // Execute the template method<br>    }<br>}</pre><p><strong>4.5. </strong>Create <strong><em>Controller Classes</em></strong></p><pre>package com.sourcecode.spring.dp.template.file;<br><br>import com.sourcecode.spring.dp.template.file.processor.FileFormat;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.PathVariable;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@Slf4j<br>@RequiredArgsConstructor<br>@RestController<br>public class FileProcessorController {<br><br>    private final FileProcessingService fileProcessingService;<br><br>    // Spring automatically converts the string path variable to an Enum<br>    @GetMapping(&quot;/{type}&quot;)<br>    public ResponseEntity&lt;String&gt; processData(@PathVariable FileFormat type) {<br>        try {<br>            fileProcessingService.processData(type);<br>            return ResponseEntity.ok(&quot;Successfully processed &quot; + type.name() + &quot; data. Check console logs.&quot;);<br>        } catch (IllegalArgumentException e) {<br>            return ResponseEntity.badRequest().body(e.getMessage());<br>        }<br>    }<br><br>}</pre><p><strong>4.6. Gradle/Maven Dependency</strong></p><ol><li>Spring Boot Starter Web: web endpoints.</li><li>Spring Boot Starter: core DI.</li></ol><p><strong>Gradle :</strong></p><pre>dependencies {<br> implementation &#39;org.springframework.boot:spring-boot-starter-validation&#39;<br> implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br> compileOnly &#39;org.projectlombok:lombok&#39;<br> annotationProcessor &#39;org.projectlombok:lombok&#39;<br> testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br> }</pre><p><strong>Maven :</strong></p><pre>&lt;dependencies&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>      &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>      &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>      &lt;optional&gt;true&lt;/optional&gt;<br>    &lt;/dependency&gt;  <br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><h3>5. When to Use Template Method</h3><ol><li>You have a <strong>fixed algorithm</strong> workflow with <strong>steps that are common</strong>, but <strong>some steps vary</strong>.</li><li>You want to <strong>enforce the order of execution</strong> while <strong>allowing subclasses to override specific steps</strong>.</li><li>You prefer <strong>inheritance-based variation over composition</strong> (Strategy) for <strong>controlled extension</strong>.</li></ol><h3>6. When Not To Use</h3><ol><li>Many <strong>steps vary </strong>or <strong>need runtime swapping</strong> → Strategy/Chain of Responsibility.</li><li>You need to combine <strong>multiple interchangeable</strong> behaviors → composition over inheritance.</li><li>Risk of subclass explosion → consider Policy objects or pipelines.</li></ol><h3>7. Real-World Application: Template Method Pattern</h3><ol><li><a href="https://medium.com/@vishal637yadav/spring-frameworks-jdbctemplate-fe8bb036f254">Spring Framework’s <strong><em>JdbcTemplate</em></strong></a>.</li><li>Report Generation Systems.</li><li>Notification Sending.</li><li>DevOps Deployment Pipelines.</li><li>Payment Processing Pipelines.</li><li>ETL/Data Import Pipelines.</li><li>Authentication Flows.</li><li>Order Fulfilment in E-Commerce.</li><li>Machine Learning Training Jobs</li><li>Financial Reconciliation</li></ol><h3>8. Benefits of Template Design:</h3><ol><li><strong>Code Reusability/DRY Principle : </strong>Promotes to reuse the <strong><em>BoilerPlate Code</em></strong>/<strong><em>Algorithm Skeleton</em></strong>.</li><li><strong>Eliminates Code Duplication : </strong>Low <strong><em>Maintenance</em></strong> and <strong><em>Testing Efforts</em></strong>.</li><li><strong>Open/Close Principle : </strong>Open for Extensions &amp; Close for Modifications.</li><li><strong>Uniform Workflow :</strong> Consistency &amp; Standard</li><li><strong>Low Maintenance :</strong> Centralised algorithm Changes</li><li><strong>Design Benefits :</strong></li></ol><ul><li><strong>Inversion of Control :</strong> A high-level framework class calls the low-level implementation details, simplifying the work for the subclass developer.</li><li><strong>Separation of concerns (SoC)</strong> : A software design principle that divides a complex system into distinct, manageable sections, with each section handling a specific responsibility or “concern”.</li></ul><p>7. <strong>Performance Benefits</strong> and and Resource Benefits:</p><ol><li>Less object churn than heavy composition when variations are minimal.</li><li>Shared setup/teardown in the template avoids repeated work in subclasses.</li><li>EnumMap/registry routing plus a fixed flow can be highly efficient.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNo78KcETrTlG2o1cXaztg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20202356f4db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy Design Pattern in Spring Boot]]></title>
            <link>https://medium.com/@vishal637yadav/strategy-design-pattern-in-spring-boot-5e52dacb69ee?source=rss-6e215e292544------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e52dacb69ee</guid>
            <category><![CDATA[spring-b]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[strategy-design-pattern]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[enum]]></category>
            <dc:creator><![CDATA[Vishal Yadav]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 20:57:41 GMT</pubDate>
            <atom:updated>2025-10-26T20:57:41.056Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Is the Strategy Pattern?</h3><p>The <strong>Strategy pattern</strong> lets you define a <strong>family of algorithms</strong>, <strong>encapsulate each one</strong>, and <strong>make them interchangeable at runtime</strong>. In Spring Boot, you typically wire strategies as Spring beans and select the right one dynamically based on some input.</p><h3>High-Level Approach</h3><ol><li>Define a enum listing all available strategies.</li><li>Define a Strategy interface.</li><li>Implement concrete strategies as @Component beans.</li><li>Use a selector (factory/registry) that maps a key to a strategy bean.</li><li>Inject the selector into services/controllers and delegate calls.</li></ol><h3>UML-Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kpp_vnYHXdEZ6OGTElRbnA.jpeg" /></figure><h3>1. Create SortAlgo enum</h3><pre>public enum SortAlgo {<br>    BUBBLE_SORT,<br>    QUICK_SORT,<br>    MERGE_SORT<br>}</pre><h3>Why EnumMap:</h3><ol><li>Fast, memory-efficient map keyed by enum.</li><li>Prevents typo-prone string keys.</li></ol><h3>2. Create <strong>SortStrategy</strong> interface</h3><pre>import java.util.List;<br><br>public interface SortStrategy {<br>    SortAlgo getSortAlgorithm();<br>    List&lt;Integer&gt; getSortedList(int[] array);<br>}</pre><h3>3.1 Create <strong>BubbleSort</strong> Class implementing SortStrategy Interface</h3><pre>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.stereotype.Component;<br><br>import java.util.Arrays;<br>import java.util.List;<br><br>@Slf4j<br>@Component<br>public class BubbleSort implements SortStrategy {<br><br>    @Override<br>    public SortAlgo getSortAlgorithm() {<br>        return SortAlgo.BUBBLE_SORT;<br>    }<br><br>    @Override<br>    public List&lt;Integer&gt; getSortedList(int[] array) {<br>        log.info(&quot;Sorting using Bubble Sort&quot;);<br>        // Bubble Sort algorithm<br>        for (int i = 0; i &lt; array.length - 1; i++) {<br>            for (int j = 0; j &lt; array.length - 1 - i; j++) {<br>                if (array[j] &gt; array[j + 1]) {<br>                    // swap array[j] and array[j + 1]<br>                    int temp = array[j];<br>                    array[j] = array[j + 1];<br>                    array[j + 1] = temp;<br>                }<br>            }<br>        }<br>        return Arrays.stream(array).boxed().toList();<br>    }<br>}</pre><h3>3.2 Create <strong>MergeSort</strong> Class implementing SortStrategy Interface</h3><pre>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.stereotype.Component;<br><br>import java.util.Arrays;<br>import java.util.List;<br><br>@Slf4j<br>@Component<br>public class MergeSort implements SortStrategy{<br>    @Override<br>    public SortAlgo getSortAlgorithm() {<br>        return SortAlgo.MERGE_SORT;<br>    }<br><br>    @Override<br>    public List&lt;Integer&gt; getSortedList(int[] array) {<br>        log.info(&quot;Sorting using Merge Sort&quot;);<br>        // Actual Merge Sort algorithm should be implemented here<br>        Arrays.sort(array);<br>        return Arrays.stream(array).boxed().toList();<br>    }<br><br>}</pre><h3>3.3 Create <strong>QuickSort</strong> Class implementing SortStrategy Interface</h3><pre>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.stereotype.Component;<br><br>import java.util.Arrays;<br>import java.util.List;<br><br>@Slf4j<br>@Component<br>public class QuickSort implements SortStrategy {<br>    @Override<br>    public SortAlgo getSortAlgorithm() {<br>        return SortAlgo.QUICK_SORT;<br>    }<br><br>    @Override<br>    public List&lt;Integer&gt; getSortedList(int[] array) {<br>        log.info(&quot;Sorting using Quick Sort&quot;);<br>        // Actual Quick Sort algorithm should be implemented here<br>        return Arrays.stream(array).sorted().boxed().toList();<br>    }<br><br>}</pre><h3>4. Create <strong>SortAlgoResolver</strong> : Factory Method</h3><pre>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.stereotype.Component;<br><br>import java.util.EnumMap;<br>import java.util.Map;<br><br>@Slf4j<br>@Component<br>public class SortAlgoResolver {<br><br>    private final Map&lt;SortAlgo, SortStrategy&gt; sortStrategies = new EnumMap&lt;&gt;(SortAlgo.class);<br><br>    public SortAlgoResolver(ApplicationContext ctx) {<br>        // Collect all strategies and index by enum key<br>        ctx.getBeansOfType(SortStrategy.class).values()<br>                .forEach(s -&gt; sortStrategies.put(s.getSortAlgorithm(), s));<br>        log.info(&quot;Available Sort Strategies: {}&quot;, sortStrategies.keySet());<br>    }<br><br>    public SortStrategy resolveSortStrategy(SortAlgo sortAlgo) {<br>        SortStrategy s = sortStrategies.get(sortAlgo);<br>        if (s == null) throw new IllegalArgumentException(&quot;Unsupported Sort Algo :-:=&gt;&gt; &quot; + sortAlgo);<br>        return s;<br>    }<br><br>}</pre><h3>5. Create <strong>SortService : </strong>Service Class</h3><pre>import lombok.RequiredArgsConstructor;<br>import org.springframework.stereotype.Service;<br><br>import java.util.List;<br><br>@Service<br>@RequiredArgsConstructor<br>public class SortService {<br>    private final SortAlgoResolver sortAlgoResolver;<br><br>    public List&lt;Integer&gt; performSorting(SortAlgo sortAlgo, int[] array) {<br>        SortStrategy strategy = sortAlgoResolver.resolveSortStrategy(sortAlgo);<br>        return strategy.getSortedList(array);<br>    }<br><br>    public List&lt;SortAlgo&gt; getSupportedSortAlgorithms() {<br>        return List.of(SortAlgo.values());<br>    }<br>}</pre><h3>6. Create SortController : Controller Class</h3><pre>import lombok.RequiredArgsConstructor;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.*;<br><br>import java.util.Arrays;<br>import java.util.List;<br><br>@Slf4j<br>@RequiredArgsConstructor<br>@RestController<br>public class SortController {<br><br>    private final SortService sortService;<br><br>    @PostMapping(&quot;/sort/{sortAlgo}&quot;)<br>    public ResponseEntity&lt;List&lt;Integer&gt;&gt; performSorting(<br>            @PathVariable SortAlgo sortAlgo,<br>            @RequestBody int[] numbers) {<br>        try {<br>            log.info(&quot;Received: {}&quot;, Arrays.toString(numbers));<br>            List&lt;Integer&gt; sortedList = sortService.performSorting(sortAlgo, numbers);<br>            log.info(&quot;performSorting -- Sorted:----&gt;&gt;&gt; {}&quot;, sortedList);<br>            return ResponseEntity.ok(sortedList);<br>        } catch (IllegalArgumentException e) {<br>            return ResponseEntity.badRequest().build();<br>        }<br>    }<br><br>    @GetMapping(&quot;/allSortAlgo&quot;)<br>    public ResponseEntity&lt;List&lt;SortAlgo&gt;&gt; getSupportedSortAlgo() {<br>        return ResponseEntity.ok(sortService.getSupportedSortAlgorithms());<br>    }<br>}</pre><h3>7. Gradle Dependency Notes</h3><ol><li>Spring Boot Starter Web: web endpoints.</li><li>Spring Boot Starter: core DI.</li><li>Optionally validation for request DTOs.</li></ol><p><strong>Maven:</strong></p><pre>&lt;dependencies&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>      &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>      &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>      &lt;optional&gt;true&lt;/optional&gt;<br>    &lt;/dependency&gt;  <br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p><strong>Gradle:</strong></p><pre>dependencies {<br> implementation &#39;org.springframework.boot:spring-boot-starter-validation&#39;<br> implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br> compileOnly &#39;org.projectlombok:lombok&#39;<br> annotationProcessor &#39;org.projectlombok:lombok&#39;<br> testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br> }</pre><h3>8. When to Use/Not Use</h3><p><strong>Use when</strong>:</p><ol><li>You have multiple interchangeable behaviors selected at runtime.</li><li>You want open-closed principle: add new algorithms without touching clients.</li></ol><p><strong>Avoid when:</strong></p><ol><li>Only one behavior exists or selection is compile-time.</li><li>Strategies share too much state or require heavy orchestration — consider template method or policy objects instead.</li></ol><h3>9. Benefits of This Approach</h3><ol><li><strong>Open/Closed Principle:</strong> You can add new sorting strategies (e.g., InsertionSortStrategy) by simply creating a new class that implements the interface and annotating it with @Component. No changes are needed in the SortService or SortAlgoResolver.</li><li><strong>Decoupling:</strong> The SortService is not tightly coupled to any specific implementation. It only knows about the SortAlgoResolver class which only deals with SortStrategy interface.</li><li><strong>No </strong><strong>if-else/</strong><strong>switch:</strong> The logic for selecting a strategy is handled cleanly by the Spring container and the Map lookup, eliminating messy conditional blocks.</li><li><strong>Testability: </strong>Each strategy can be unit-tested in isolation. The SortService can also be tested easily by mocking the SortAlgoResolver.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e52dacb69ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lombok Annotation : @Data and @ToString]]></title>
            <link>https://medium.com/@vishal637yadav/lombok-annotation-data-and-tostring-adf4cf49244f?source=rss-6e215e292544------2</link>
            <guid isPermaLink="false">https://medium.com/p/adf4cf49244f</guid>
            <category><![CDATA[lombok]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[tostring]]></category>
            <dc:creator><![CDATA[Vishal Yadav]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 19:00:28 GMT</pubDate>
            <atom:updated>2025-10-24T01:57:52.445Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lombok Annotation : @Data and @ToString</h3><h3>Together vs Separately</h3><h3>1. Understanding @Data and @ToString</h3><blockquote>What <strong>@Data</strong> Includes</blockquote><pre>// @Data is equivalent to combining these annotations:<br>@Getter<br>@Setter  <br>@ToString<br>@EqualsAndHashCode<br>@RequiredArgsConstructor<br><br>// So this:<br>@Data<br>public class User {<br>    private String name;<br>    private int age;<br>}<br><br>// Is equivalent to this:<br>@Getter<br>@Setter<br>@ToString<br>@EqualsAndHashCode<br>@RequiredArgsConstructor<br>public class User {<br>    private String name;<br>    private int age;<br>}</pre><blockquote>What <strong>@ToString</strong> Provides</blockquote><pre>@ToString<br>public class User {<br>    private String name;<br>    private int age;<br>    private String password;<br>}<br><br>// Generates:<br>public String toString() {<br>    return &quot;User(name=&quot; + this.name + &quot;, age=&quot; + this.age + &quot;, password=&quot; + this.password + &quot;)&quot;;<br>}</pre><h3>2. When to Use @Data and @ToString Together</h3><blockquote><strong>Scenario 1</strong>: Overriding @Data’s Default @ToString Behavior</blockquote><pre>// ✅ CUSTOMIZING @ToString WHILE KEEPING @Data BENEFITS<br>@Data<br>@ToString(exclude = {&quot;password&quot;, &quot;secretKey&quot;}) // Override @Data&#39;s @ToString<br>public class User {<br>    private String username;<br>    private String email;<br>    private int age;<br>    private String password;      // Excluded from toString<br>    private String secretKey;     // Excluded from toString<br>    private LocalDateTime lastLogin;<br>}<br><br>// Generated toString (customized):<br>// User(username=john, email=john@example.com, age=30, lastLogin=2024-01-15T10:30:00)</pre><blockquote><strong>Scenario 2:</strong> Including Only Specific Fields</blockquote><pre>// ✅ SELECTIVE FIELD INCLUSION<br>@Data<br>@ToString(onlyExplicitlyIncluded = true) // Override @Data&#39;s @ToString<br>public class BankAccount {<br>    @ToString.Include<br>    private String accountNumber;<br>    <br>    @ToString.Include  <br>    private String accountType;<br>    <br>    private BigDecimal balance;        // Not included in toString<br>    private String routingNumber;      // Not included in toString<br>    private String pin;                // Not included in toString<br>}<br><br>// Generated toString (selective):<br>// BankAccount(accountNumber=ACC-123, accountType=SAVINGS)</pre><blockquote><strong>Scenario 3: </strong>Custom toString Format</blockquote><pre>// ✅ CUSTOM FORMATTING WITH @Data<br>@Data<br>@ToString(includeFieldNames = false) // Override @Data&#39;s @ToString<br>public class Coordinate {<br>    private double latitude;<br>    private double longitude;<br>    private String description;<br>}<br><br>// Generated toString (without field names):<br>// Coordinate(40.7128, -74.0060, New York City)<br><br>// vs Default @Data toString would be:<br>// Coordinate(latitude=40.7128, longitude=-74.0060, description=New York City)</pre><blockquote><strong>Scenario 4: </strong>Method Call Integration</blockquote><pre>// ✅ INCLUDING METHOD RESULTS IN toString<br>@Data  <br>@ToString(includeFieldNames = true, callSuper = false)<br>public class Product {<br>    private String productId;<br>    private String name;<br>    private BigDecimal price;<br>    private int stockQuantity;<br>    <br>    @ToString.Include(name = &quot;totalValue&quot;)<br>    public BigDecimal calculateTotalValue() {<br>        return price.multiply(BigDecimal.valueOf(stockQuantity));<br>    }<br>    <br>    @ToString.Include(name = &quot;inStock&quot;)  <br>    public boolean isInStock() {<br>        return stockQuantity &gt; 0;<br>    }<br>}<br><br>// Generated toString:<br>// Product(productId=PROD-001, name=Laptop, price=999.99, stockQuantity=10, totalValue=9999.90, inStock=true)</pre><h3>3. When to Use @Data WITHOUT Additional @ToString</h3><blockquote><strong>Scenario 1: </strong>Default Behaviour is Sufficient</blockquote><pre>// ✅ SIMPLE DATA CLASSES - @Data ALONE IS PERFECT<br>@Data<br>public class Address {<br>    private String street;<br>    private String city; <br>    private String state;<br>    private String zipCode;<br>    private String country;<br>}<br><br>// Default @Data toString is fine:<br>// Address(street=123 Main St, city=New York, state=NY, zipCode=10001, country=USA)</pre><blockquote><strong>Scenario 2: </strong>All Fields are Safe to Display</blockquote><pre>// ✅ PUBLIC/SAFE DATA - NO CUSTOMIZATION NEEDED<br>@Data<br>public class ProductCategory {<br>    private String categoryId;<br>    private String categoryName;<br>    private String description;<br>    private boolean active;<br>    private LocalDateTime createdDate;<br>}<br><br>// Default toString is appropriate for all fields</pre><blockquote><strong>Scenario 3:</strong> Internal/Private Classes</blockquote><pre>// ✅ INTERNAL CLASSES WHERE ALL FIELDS CAN BE LOGGED<br>@Data<br>class DatabaseConnectionConfig { // Package-private internal class<br>    private String host;<br>    private int port;<br>    private String database;<br>    private int connectionTimeout;<br>    private int maxConnections;<br>}</pre><h3>4. When to Use @ToString WITHOUT @Data</h3><blockquote><strong>Scenario 1:</strong> Immutable Classes with Custom Constructor</blockquote><pre>// ✅ IMMUTABLE CLASSES - ONLY @ToString NEEDED<br>@ToString<br>public class ImmutableUser {<br>    private final String username;<br>    private final String email;<br>    private final LocalDateTime createdAt;<br>    <br>    public ImmutableUser(String username, String email) {<br>        this.username = username;<br>        this.email = email;<br>        this.createdAt = LocalDateTime.now();<br>    }<br>    <br>    // Custom getters only<br>    public String getUsername() { return username; }<br>    public String getEmail() { return email; }<br>    public LocalDateTime getCreatedAt() { return createdAt; }<br>    <br>    // No setters needed - @Data would add unwanted setters<br>}</pre><blockquote><strong>Scenario 2:</strong> Classes with Custom Business Logic</blockquote><pre>// ✅ BUSINESS LOGIC CLASSES - AVOID @Data&#39;s GENERIC APPROACH<br>@ToString(exclude = &quot;auditLog&quot;)<br>public class Order {<br>    private String orderId;<br>    private String customerId;<br>    private List&lt;OrderItem&gt; items;<br>    private OrderStatus status;<br>    private BigDecimal totalAmount;<br>    private List&lt;AuditEntry&gt; auditLog; // Excluded from toString<br>    <br>    // Custom constructor with validation<br>    public Order(String customerId, List&lt;OrderItem&gt; items) {<br>        this.orderId = generateOrderId();<br>        this.customerId = validateCustomerId(customerId);<br>        this.items = new ArrayList&lt;&gt;(items);<br>        this.status = OrderStatus.PENDING;<br>        this.totalAmount = calculateTotal(items);<br>        this.auditLog = new ArrayList&lt;&gt;();<br>        <br>        auditLog.add(new AuditEntry(&quot;ORDER_CREATED&quot;, LocalDateTime.now()));<br>    }<br>    <br>    // Business methods with side effects<br>    public void addItem(OrderItem item) {<br>        items.add(item);<br>        totalAmount = calculateTotal(items);<br>        auditLog.add(new AuditEntry(&quot;ITEM_ADDED&quot;, LocalDateTime.now()));<br>    }<br>    <br>    public void updateStatus(OrderStatus newStatus) {<br>        OrderStatus oldStatus = this.status;<br>        this.status = newStatus;<br>        auditLog.add(new AuditEntry(&quot;STATUS_CHANGED&quot;, oldStatus, newStatus, LocalDateTime.now()));<br>    }<br>    <br>    // Custom getters with business logic<br>    public BigDecimal getTotalAmount() {<br>        return totalAmount; // Always recalculated<br>    }<br>    <br>    // No generic setters - @Data would break encapsulation<br>}</pre><blockquote><strong>Scenario 3:</strong> Performance-Critical Classes</blockquote><pre>// ✅ PERFORMANCE-SENSITIVE - AVOID @Data OVERHEAD<br>@ToString(onlyExplicitlyIncluded = true)<br>public class HighFrequencyTradingData {<br>    @ToString.Include<br>    private final String symbol;<br>    <br>    @ToString.Include<br>    private final long timestamp;<br>    <br>    @ToString.Include<br>    private final double price;<br>    <br>    private final double volume;<br>    private final byte[] rawData; // Large field excluded<br>    <br>    // Minimal constructor<br>    public HighFrequencyTradingData(String symbol, long timestamp, double price, double volume, byte[] rawData) {<br>        this.symbol = symbol;<br>        this.timestamp = timestamp;<br>        this.price = price;<br>        this.volume = volume;<br>        this.rawData = rawData;<br>    }<br>    <br>    // Only essential getters - no setters to prevent mutations<br>    public String getSymbol() { return symbol; }<br>    public long getTimestamp() { return timestamp; }<br>    public double getPrice() { return price; }<br>    public double getVolume() { return volume; }<br>    <br>    // No @Data - avoid unwanted equals/hashCode computation overhead<br>}</pre><h3>5. Common Problems and Solutions</h3><blockquote><strong>Problem 1:</strong> Sensitive Data in Logs</blockquote><pre>// ❌ DANGEROUS - SENSITIVE DATA EXPOSED<br>@Data<br>public class User {<br>    private String username;<br>    private String email;<br>    private String password;        // Will appear in toString!<br>    private String socialSecurityNumber; // Will appear in toString!<br>}<br><br>// Logs will show:<br>// User(username=john, email=john@example.com, password=secret123, socialSecurityNumber=123-45-6789)<br><br>// ✅ SOLUTION - OVERRIDE @ToString<br>@Data<br>@ToString(exclude = {&quot;password&quot;, &quot;socialSecurityNumber&quot;})<br>public class User {<br>    private String username;<br>    private String email; <br>    private String password;<br>    private String socialSecurityNumber;<br>}</pre><blockquote><strong>Problem 2:</strong> Circular References</blockquote><pre>// ❌ PROBLEMATIC - CIRCULAR REFERENCES<br>@Data<br>public class Department {<br>    private String name;<br>    private List&lt;Employee&gt; employees;<br>}<br><br>@Data<br>public class Employee {<br>    private String name;<br>    private Department department; // Circular reference!<br>}<br><br>// toString() calls will cause StackOverflowError!<br><br>// ✅ SOLUTION - EXCLUDE CIRCULAR FIELDS<br>@Data<br>@ToString(exclude = &quot;employees&quot;) // Break the cycle<br>public class Department {<br>    private String name;<br>    private List&lt;Employee&gt; employees;<br>}<br><br>@Data  <br>@ToString(exclude = &quot;department&quot;) // Break the cycle<br>public class Employee {<br>    private String name;<br>    private Department department;<br>}</pre><blockquote><strong>Problem 3:</strong> Performance with Large Collections</blockquote><pre>// ❌ PERFORMANCE ISSUE - LARGE COLLECTIONS<br>@Data<br>public class DataProcessor {<br>    private String processorId;<br>    private List&lt;String&gt; processedItems; // Could be millions of items!<br>    private Map&lt;String, Object&gt; cache;   // Could be huge!<br>}<br><br>// toString() will iterate through all items - very slow!<br><br>// ✅ SOLUTION - EXCLUDE LARGE COLLECTIONS  <br>@Data<br>@ToString(exclude = {&quot;processedItems&quot;, &quot;cache&quot;})<br>public class DataProcessor {<br>    private String processorId;<br>    private List&lt;String&gt; processedItems;<br>    private Map&lt;String, Object&gt; cache;<br>    <br>    @ToString.Include(name = &quot;itemCount&quot;)<br>    public int getProcessedItemCount() {<br>        return processedItems != null ? processedItems.size() : 0;<br>    }<br>    <br>    @ToString.Include(name = &quot;cacheSize&quot;)<br>    public int getCacheSize() {<br>        return cache != null ? cache.size() : 0;<br>    }<br>}</pre><h3>6. Best Practices Decision Matrix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AruDtt6uItUG3RDYSnmfQ.png" /></figure><h3>7. Real-World Examples</h3><h3>Example 1: E-commerce Order System</h3><pre>// ✅ CUSTOMER - @Data ALONE (SAFE DATA)<br>@Data<br>public class Customer {<br>    private String customerId;<br>    private String firstName;<br>    private String lastName;<br>    private String email;<br>    private CustomerTier tier;<br>    private LocalDateTime createdDate;<br>}<br><br>// ✅ ORDER - @Data + @ToString (EXCLUDE SENSITIVE/LARGE DATA)<br>@Data<br>@ToString(exclude = {&quot;paymentDetails&quot;, &quot;auditTrail&quot;})<br>public class Order {<br>    private String orderId;<br>    private String customerId;<br>    private List&lt;OrderItem&gt; items;<br>    private OrderStatus status;<br>    private BigDecimal totalAmount;<br>    private PaymentDetails paymentDetails; // Sensitive - excluded<br>    private List&lt;AuditEntry&gt; auditTrail;   // Large - excluded<br>    <br>    @ToString.Include(name = &quot;itemCount&quot;)<br>    public int getItemCount() {<br>        return items != null ? items.size() : 0;<br>    }<br>}<br><br>// ✅ PAYMENT DETAILS - @ToString ONLY (IMMUTABLE + SENSITIVE)<br>@ToString(onlyExplicitlyIncluded = true)<br>public class PaymentDetails {<br>    @ToString.Include<br>    private final PaymentMethod method;<br>    <br>    @ToString.Include  <br>    private final String last4Digits;<br>    <br>    private final String fullCardNumber; // Never in toString<br>    private final String cvv;            // Never in toString<br>    private final LocalDateTime expiryDate;<br>    <br>    public PaymentDetails(PaymentMethod method, String cardNumber, String cvv, LocalDateTime expiryDate) {<br>        this.method = method;<br>        this.fullCardNumber = cardNumber;<br>        this.cvv = cvv;<br>        this.expiryDate = expiryDate;<br>        this.last4Digits = cardNumber.substring(cardNumber.length() - 4);<br>    }<br>    <br>    // Only safe getters<br>    public PaymentMethod getMethod() { return method; }<br>    public String getLast4Digits() { return last4Digits; }<br>    public LocalDateTime getExpiryDate() { return expiryDate; }<br>    <br>    // No setters - immutable<br>    // No getter for sensitive fields<br>}</pre><h3>Example 2: User Management System</h3><pre>// ✅ USER PROFILE - @Data + @ToString (MIXED SENSITIVITY)<br>@Data<br>@ToString(exclude = {&quot;password&quot;, &quot;securityQuestions&quot;, &quot;loginHistory&quot;})<br>public class UserProfile {<br>    private String userId;<br>    private String username;<br>    private String email;<br>    private String firstName;<br>    private String lastName;<br>    private boolean emailVerified;<br>    private LocalDateTime lastLoginDate;<br>    <br>    // Sensitive fields excluded from toString<br>    private String password;<br>    private List&lt;SecurityQuestion&gt; securityQuestions;<br>    private List&lt;LoginHistory&gt; loginHistory;<br>    <br>    @ToString.Include(name = &quot;loginCount&quot;)<br>    public int getLoginCount() {<br>        return loginHistory != null ? loginHistory.size() : 0;<br>    }<br>}<br><br>// ✅ SECURITY QUESTION - @ToString ONLY (PARTIAL SENSITIVITY)<br>@ToString(exclude = &quot;answer&quot;)<br>public class SecurityQuestion {<br>    private final String questionId;<br>    private final String question;<br>    private final String answer; // Sensitive - excluded<br>    <br>    public SecurityQuestion(String questionId, String question, String answer) {<br>        this.questionId = questionId;<br>        this.question = question;<br>        this.answer = answer;<br>    }<br>    <br>    // Getters but no setters (immutable)<br>    public String getQuestionId() { return questionId; }<br>    public String getQuestion() { return question; }<br>    <br>    // Verify answer without exposing it<br>    public boolean verifyAnswer(String providedAnswer) {<br>        return this.answer != null &amp;&amp; this.answer.equals(providedAnswer);<br>    }<br>}<br><br>// ✅ PUBLIC SETTINGS - @Data ALONE (ALL SAFE)<br>@Data<br>public class UserSettings {<br>    private String userId;<br>    private String theme;<br>    private String language;<br>    private boolean emailNotifications;<br>    private boolean smsNotifications;<br>    private TimeZone timeZone;<br>    private DateFormat dateFormat;<br>}</pre><h3>8. Testing Implications</h3><h4>Testing @Data Classes</h4><pre>@Test<br>public void testDataClassEquality() {<br>    // @Data generates equals() and hashCode()<br>    Customer customer1 = new Customer();<br>    customer1.setCustomerId(&quot;CUST-001&quot;);<br>    customer1.setFirstName(&quot;John&quot;);<br>    <br>    Customer customer2 = new Customer();<br>    customer2.setCustomerId(&quot;CUST-001&quot;);  <br>    customer2.setFirstName(&quot;John&quot;);<br>    <br>    // equals() works automatically<br>    assertThat(customer1).isEqualTo(customer2);<br>    <br>    // toString() available for debugging<br>    System.out.println(&quot;Customer: &quot; + customer1); // Full details<br>}</pre><h3>Testing @ToString Only Classes</h3><pre>@Test<br>public void testToStringOnlyClass() {<br>    PaymentDetails payment = new PaymentDetails(<br>        PaymentMethod.CREDIT_CARD,<br>        &quot;4111111111111234&quot;, <br>        &quot;123&quot;,<br>        LocalDateTime.of(2025, 12, 31, 0, 0)<br>    );<br>    <br>    String toString = payment.toString();<br>    <br>    // Verify sensitive data is NOT in toString<br>    assertThat(toString).doesNotContain(&quot;4111111111111234&quot;); // Full card number<br>    assertThat(toString).doesNotContain(&quot;123&quot;);              // CVV<br>    <br>    // Verify safe data IS in toString<br>    assertThat(toString).contains(&quot;CREDIT_CARD&quot;);<br>    assertThat(toString).contains(&quot;1234&quot;); // Last 4 digits only<br>}</pre><h3>9. Performance Considerations</h3><h4>@Data Performance Impact</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4rgraXjPd0Lg-4_pQooAw.png" /></figure><h3>Optimization Strategies</h3><pre>// ✅ OPTIMIZED FOR PERFORMANCE<br>@Data<br>@ToString(exclude = {&quot;largeDataSet&quot;, &quot;heavyObject&quot;}) // Exclude expensive fields<br>@EqualsAndHashCode(exclude = {&quot;lastModified&quot;, &quot;auditTrail&quot;}) // Exclude from equality<br>public class OptimizedEntity {<br>    private String id;           // Included in equals/hashCode<br>    private String name;         // Included in equals/hashCode<br>    private String description;  // Included in equals/hashCode<br>    <br>    private LocalDateTime lastModified;    // Excluded from equals/hashCode<br>    private List&lt;AuditEntry&gt; auditTrail;  // Excluded from equals/hashCode<br>    private byte[] largeDataSet;           // Excluded from toString<br>    private ExpensiveObject heavyObject;   // Excluded from toString<br>}</pre><h3>10. Migration Strategies</h3><blockquote>From @Data to @Data + @ToString</blockquote><pre>// BEFORE: Exposing sensitive data<br>@Data<br>public class User {<br>    private String username;<br>    private String password;<br>}<br><br>// AFTER: Protected sensitive data  <br>@Data<br>@ToString(exclude = &quot;password&quot;)<br>public class User {<br>    private String username;<br>    private String password;<br>}</pre><blockquote>From @Data to @ToString Only</blockquote><pre>// BEFORE: Unwanted setters<br>@Data<br>public class ImmutableConfig {<br>    private final String apiKey;<br>    private final String endpoint;<br>}<br><br>// AFTER: True immutability<br>@ToString<br>@AllArgsConstructor<br>@Getter<br>public class ImmutableConfig {<br>    private final String apiKey;<br>    private final String endpoint;<br>}</pre><h3>11. Summary and Recommendations</h3><blockquote>Quick Decision Guide</blockquote><pre>// ✅ USE @Data ALONE WHEN:<br>// - Simple data transfer objects<br>// - All fields are safe to display<br>// - No complex business logic<br>// - Standard getters/setters needed<br><br>@Data<br>public class SimpleDTO {<br>    private String field1;<br>    private String field2;<br>}<br><br>// ✅ USE @Data + @ToString WHEN:<br>// - Need @Data benefits but want to customize toString<br>// - Have sensitive fields to exclude<br>// - Have performance-heavy fields to exclude  <br>// - Need to include method results in toString<br><br>@Data<br>@ToString(exclude = {&quot;sensitiveField&quot;, &quot;largeCollection&quot;})<br>public class CustomizedData {<br>    private String publicField;<br>    private String sensitiveField;<br>    private List&lt;String&gt; largeCollection;<br>}<br><br>// ✅ USE @ToString ONLY WHEN:<br>// - Immutable classes<br>// - Classes with complex business logic<br>// - Performance-critical code<br>// - Custom encapsulation requirements<br><br>@ToString(exclude = &quot;internalState&quot;)<br>public class BusinessLogicClass {<br>    private String publicData;<br>    private ComplexState internalState;<br>    <br>    // Custom methods and encapsulation<br>}</pre><h3>Key Takeaways</h3><ol><li>@Data is powerful but not always appropriate — Consider the implications</li><li>Sensitive data requires @ToString customization — Never expose passwords, keys, etc.</li><li>Performance matters — Exclude large collections and expensive objects</li><li>Immutability often needs @ToString only — Avoid unwanted setters</li><li>Business logic classes rarely need @Data — Custom encapsulation is better</li><li>Testing becomes easier — But be aware of what’s being compared/displayed</li></ol><blockquote>Remember: The choice between these annotations depends on your specific use case, security requirements, and performance needs. Always consider what data should be exposed in toString() and whether you need the full @Data functionality.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adf4cf49244f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lombok @Builder annotation Use-Cases]]></title>
            <link>https://medium.com/@vishal637yadav/lombok-builder-annotation-use-cases-5cb88c13b903?source=rss-6e215e292544------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cb88c13b903</guid>
            <dc:creator><![CDATA[Vishal Yadav]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 02:40:23 GMT</pubDate>
            <atom:updated>2025-10-23T02:40:23.220Z</atom:updated>
            <content:encoded><![CDATA[<h3>When to Use @Builder</h3><p>✅ <strong>Use @Builder</strong> when:</p><ul><li>Creating complex objects with many optional parameters</li><li>You want fluent, readable object construction</li><li>Building immutable objects</li><li>Working with collections that need incremental building</li><li>API responses or DTOs with many fields</li></ul><p>✅ <strong>Don’t Use @Builder</strong> when:</p><ul><li>Simple objects with few fields (2–3 fields)</li><li>Performance is critical (tiny overhead)</li><li>You need complex validation logic</li><li>Working with frameworks that require specific constructors</li></ul><h3>Key Benefits</h3><ol><li>Readability — Code reads like natural language</li><li>Flexibility — Optional parameters handled elegantly</li><li>Immutability — Promotes immutable object design</li><li>Maintainability — Easy to add/remove fields</li><li>Reduced Boilerplate — 90%+ code reduction</li></ol><p>The @Builder annotation is one of Lombok&#39;s most powerful features, transforming complex object creation into clean, maintainable code while preserving all the benefits of the Builder pattern.</p><h3>At Compile-Time Generated Code by Lombok</h3><pre>public class YourClass {<br>    private final String field1;<br>    private final int field2;<br>    // ... other fields<br><br>    // Private constructor used by builder<br>    private YourClass(String field1, int field2) {<br>        this.field1 = field1;<br>        this.field2 = field2;<br>    }<br><br>    // Static builder() method to get builder instance<br>    public static YourClassBuilder builder() {<br>        return new YourClassBuilder();<br>    }<br><br>    // Static inner builder class<br>    public static class YourClassBuilder {<br>        private String field1;<br>        private int field2;<br><br>        // Private constructor<br>        private YourClassBuilder() {<br>        }<br><br>        // Fluent setter methods that return the builder<br>        public YourClassBuilder field1(String field1) {<br>            this.field1 = field1;<br>            return this;<br>        }<br><br>        public YourClassBuilder field2(int field2) {<br>            this.field2 = field2;<br>            return this;<br>        }<br><br>        // build() method that creates the final object<br>        public YourClass build() {<br>            return new YourClass(field1, field2);<br>        }<br><br>        // toString() implementation<br>        public String toString() {<br>            return &quot;YourClass.YourClassBuilder(field1=&quot; + field1 <br>                   + &quot;, field2=&quot; + field2 + &quot;)&quot;;<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cb88c13b903" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should I implement the Singleton design pattern when using the Spring Framework ?]]></title>
            <link>https://medium.com/@vishal637yadav/should-i-implement-the-singleton-design-pattern-when-using-the-spring-framework-2de160eba5f2?source=rss-6e215e292544------2</link>
            <guid isPermaLink="false">https://medium.com/p/2de160eba5f2</guid>
            <dc:creator><![CDATA[Vishal Yadav]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 18:04:32 GMT</pubDate>
            <atom:updated>2025-10-22T18:04:32.021Z</atom:updated>
            <content:encoded><![CDATA[<h3>Should I implement the Singleton design pattern when using the Spring Framework ?</h3><p>This is an excellent and fundamental question for any developer using the Spring Framework.</p><p>The short and direct answer is: No, you should almost never implement the Singleton design pattern yourself when using the Spring Framework.</p><p>Relying on Spring’s built-in mechanism is the correct, idiomatic, and more powerful approach. Spring’s core feature, the Inversion of Control (IoC) container, manages this for you in a superior way.</p><h3>The Core Concept: Spring’s Singleton Scope</h3><p>By default, every bean you define in the Spring container is a singleton. This means the Spring container creates exactly one instance of that bean and caches it. Every time another bean requests that type, the container injects a reference to that same, single instance.</p><p>However, a “Spring Singleton” is not the same as the classic “Gang of Four (GoF) Singleton Pattern.” The differences are significant and highlight why the Spring approach is better.</p><h3>Comparison: Classic Singleton vs. Spring Singleton Bean</h3><p>This table clearly illustrates the advantages of letting Spring manage the lifecycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35pyDrnpqYgk3wGxTSqLqw.png" /></figure><h3>Code Example: The Difference in Practice</h3><p>Let’s see how much cleaner and more testable the Spring approach is.</p><h4>1. The Wrong Way: The Classic Singleton Pattern</h4><p>This pattern mixes business logic with lifecycle management and is hard to test.</p><p>java</p><p>Problem: How do you test OrderService without connecting to a real database? It&#39;s very difficult because you can&#39;t easily replace DatabaseConnection.getInstance() with a mock.</p><h4>2. The Right Way: The Spring Singleton Bean</h4><p>This is clean, decoupled, and easy to test.</p><p>java</p><p>Benefit: To test OrderService, you can simply pass a mock DatabaseConnection object to its constructor. The class is completely decoupled from how its dependencies are created.</p><h3>Conclusion and Recommendation</h3><p>Embrace the Spring IoC container.</p><p>Letting Spring manage your singletons is the core philosophy of the framework. You gain:</p><ol><li>Decoupling: Your components don’t know or care if they are talking to a singleton, a prototype, or a mock.</li><li>Testability: Your code becomes trivial to unit test by injecting mocks.</li><li>Flexibility: Your application’s architecture is not rigidly locked in.</li><li>Clarity: Your classes are simple POJOs focused purely on business logic, not on managing their own lifecycle.</li></ol><p>Implementing a classic singleton in Spring is considered an anti-pattern because it fights against the framework’s fundamental principles and negates many of its most powerful benefits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2de160eba5f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Composite Design Pattern]]></title>
            <link>https://medium.com/@vishal637yadav/composite-design-pattern-ff45376b13b1?source=rss-6e215e292544------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff45376b13b1</guid>
            <category><![CDATA[composite-design-pattern]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <dc:creator><![CDATA[Vishal Yadav]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 04:10:24 GMT</pubDate>
            <atom:updated>2024-12-03T04:10:24.972Z</atom:updated>
            <content:encoded><![CDATA[<h3>Composite Method | Structural Design Pattern</h3><p>Composite Pattern is a structural design pattern that allows you to <em>compose objects into tree structures</em> to represent <em>part-whole hierarchies</em>. The main idea behind the Composite Pattern is to build a tree structure of objects, where individual objects and composite objects <em>share a common interface</em>. This common interface allows clients to interact with both types of objects without needing to distinguish between them.</p><h3>Important Topics for the Composite Method Design Patterns</h3><ul><li>What are Part-Whole or Whole-Part Object hierarchies?</li><li>Use Cases of Composite Pattern</li><li>Example for Composite Design Pattern</li><li>Advantages of the Composite Design Patterns</li><li>Disadvantages of Composite Design Patterns</li><li>Potential Pitfalls</li><li>Conclusion</li></ul><h3>What are Part-Whole or Whole-Part Object hierarchies?</h3><p>Example:</p><p>In a graphic design application, you might have shapes as individual elements (like circles and rectangles), and you can combine these shapes to create more complex shapes (like a smiley face with eyes and a mouth). The Composite Pattern lets you work with both simple shapes and complex shapes using the same set of operations, making it easier to manage and manipulate them.</p><p>In this context:</p><ul><li>The parts are individual shapes (like circles, rectangles).</li><li>The wholes are the complex shapes (like a smiley face composed of circles and rectangles).</li></ul><h3>Use Cases of Composite Pattern :</h3><p>The Composite Pattern is useful in various scenarios, such as:</p><ol><li>Graphics and GUI Libraries: Building complex graphical structures like shapes and groups.</li><li>File Systems: Representing files, directories, and their hierarchical relationships.</li><li>Organization Structures: Modeling hierarchical organizational structures like departments, teams and employees.</li></ol><h3>Example for Composite Design Pattern :</h3><p><em>You are tasked with developing a software component to manage a hierarchical file system structure. The goal is to implement the Composite Pattern to seamlessly work with individual files and directories as part of a unified hierarchy.</em></p><h3>Implementing the Composite Pattern for File System Hierarchy :</h3><p>Let’s understand the components of the Composite Pattern using file system hierarchy example:</p><h3>Key Component in the Composite Pattern</h3><ol><li>Component: The Component is the common interface for all objects in the composition. It defines the methods that are common to both leaf and composite objects.</li><li>Leaf: The Leaf is the individual object that does not have any children. It implements the component interface and provides the specific functionality for individual objects.</li><li>Composite: The Composite is the container object that can hold Leaf objects as well as the other Composite objects. It implements the Component interface and provides methods for adding, removing and accessing children.</li><li>Client: The Client is responsible for using the Component interface to work with objects in the composition. It treats both Leaf and Composite objects uniformly.</li></ol><h3>Step Wise Implementation of Composite Design Pattern</h3><ol><li>Component In the file system hierarchy example, the Component is represented by the FileSystemComponenet interface. This interface defines the common interface for both leaf and composite objects. It declares a method, display(), which all classes in the hierarchy must implement.</li><li>class FileSystemComponent { public: virtual void display() const = 0; };</li></ol><p>The Component serves as the foundation for all objects within the hierarchy. Whether it’s file or a directory, they all must adhere to this common interface.</p><ol><li>Leaf In the context of our file system hierarchy example, Leaf objects are the individual files. These are the objects that do not have any children. Here is an implementation of a leaf object, a file:</li><li>class File : public FileSystemComponent { public: File(const std::string&amp; name, int size) : name(name), size(size) {}</li></ol><ul><li>void display() const override { std::cout &lt;&lt; &quot;File: &quot; &lt;&lt; name &lt;&lt; &quot; (&quot; &lt;&lt; size &lt;&lt; &quot; bytes)&quot; &lt;&lt; std::endl; }</li></ul><ol><li>private: std::string name; int size; }; Here, File is a leaf object. It implements the FileSystemComponent interface by providing a display method. It contains data specific to files, such as their name and size.</li><li>Composite In the file system hierarchy example, Composite objects are directories. These are objects that contain other components, including both leaf objects (files) and other composite objects (subdirectories). Here’s an implementation of a composite object, a directory:</li><li>class Directory : public FileSystemComponent { public: Directory(const std::string&amp; name) : name(name) {}</li></ol><ul><li>void display() const override { std::cout &lt;&lt; &quot;Directory: &quot; &lt;&lt; name &lt;&lt; std::endl; for (const auto&amp; component : components) { component-&gt;display(); } } void addComponent(FileSystemComponent* component) { components.push_back(component); }</li></ul><ol><li>display(); } } void addComponent(FileSystemComponent* component) { components.push_back(component); } “ tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1), background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</li><li>private: std::string name; std::vector&lt;FileSystemComponent*&gt; components; }; In this example, Directory is a composite object. Like the File class, it also implements the FileSystemComponent interface by providing a display method. Additionally it, contains a vector of FileSystemComponent to store child components (files or subdirectories). The addComponent method allows adding components to the directory.</li><li>Client The Client code interacts with the components through the Component interface, and it doesn’t need to be aware of whether it’s working with a leaf or a composite object.</li><li>int main() { // Create leaf objects (files) FileSystemComponent* file1 = new File(“document.txt”, 1024); FileSystemComponent* file2 = new File(“image.jpg”, 2048);</li></ol><ul><li>// Create a composite object (directory) Directory* directory = new Directory(&quot;My Documents&quot;); // Add leaf objects to the directory directory-&gt;addComponent(file1); directory-&gt;addComponent(file2); // Display the directory (including its contents) directory-&gt;display(); return 0;</li></ul><ol><li>addComponent(file1); directory-&gt;addComponent(file2); // Display the directory (including its contents) directory-&gt;display(); return 0; “ tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1), background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</li><li>} In this client code, you can see how the client interacts with both leaf (file) and composite (directory) objects uniformly, without needing to know the specific type of each object. The display method of the FileSystemComponent interface is used to display the entire hierarchy.</li></ol><h3>Diagrammatic representation of the Composite Design Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X91f6Kt0S_sgDksn.JPG" /></figure><h3>Composite-Design-Pattern</h3><p>UML Diagram: Composite Design Pattern</p><p>Code Implementation of the above Problem:</p><pre>#include &lt;bits/stdc++.h&gt;<br>class FileSystemComponent {<br>public:<br>virtual void display() const = 0;<br>};<br>class File : public FileSystemComponent {<br>public:<br>File(const std::string&amp; name, int size)<br>: name(name)<br>, size(size)<br>{<br>}</pre><pre>void display() const override <br>{ <br>    std::cout &lt;&lt; &quot;File: &quot; &lt;&lt; name &lt;&lt; &quot; (&quot; &lt;&lt; size <br>              &lt;&lt; &quot; bytes)&quot; &lt;&lt; std::endl; <br>} </pre><pre>private:<br>std::string name;<br>int size;<br>};<br>class Directory : public FileSystemComponent {<br>public:<br>Directory(const std::string&amp; name)<br>: name(name)<br>{<br>}</pre><pre>void display() const override <br>{ <br>    std::cout &lt;&lt; &quot;Directory: &quot; &lt;&lt; name &lt;&lt; std::endl; <br>    for (const auto&amp; component : components) { <br>        component-&gt;display(); <br>    } <br>} </pre><pre>void addComponent(FileSystemComponent* component) <br>{ <br>    components.push_back(component); <br>} </pre><pre>private:<br>std::string name;<br>std::vector&lt;FileSystemComponent*&gt; components;<br>};<br>int main()<br>{<br>// Create leaf objects (files)<br>FileSystemComponent* file1<br>= new File(&quot;document.txt&quot;, 1024);<br>FileSystemComponent* file2<br>= new File(&quot;image.jpg&quot;, 2048);</pre><pre>// Create a composite object (directory) <br>Directory* directory = new Directory(&quot;My Documents&quot;); </pre><pre>// Add leaf objects to the directory <br>directory-&gt;addComponent(file1); <br>directory-&gt;addComponent(file2); </pre><pre>// Display the directory (including its contents) <br>directory-&gt;display(); </pre><pre>return 0; <br>}</pre><p>class FileSystemComponent { public: virtual void display() const = 0; }; class File : public FileSystemComponent { public: File(const std::string&amp; name, int size) : name(name) , size(size) { } void display() const override { std::cout display(); } } void addComponent(FileSystemComponent* component) { components.push_back(component); } private: std::string name; std::vector components; }; int main() { // Create leaf objects (files) FileSystemComponent* file1 = new File(“document.txt”, 1024); FileSystemComponent* file2 = new File(“image.jpg”, 2048); // Create a composite object (directory) Directory* directory = new Directory(“My Documents”); // Add leaf objects to the directory directory-&gt;addComponent(file1); directory-&gt;addComponent(file2); // Display the directory (including its contents) directory-&gt;display(); return 0; }” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1), background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><h3>Output</h3><p>Directory: My Documents File: document.txt (1024 bytes) File: image.jpg (2048 bytes)</p><h3>Advantages of the Composite Design Pattern</h3><ol><li>Hierarchical Structure: The Composite Pattern provides a way to represent complex hierarchical structures of objects. You can create tree-like structures where both individual objects and composite objects (objects that contain other objects) can be treated uniformly.</li><li>Simplified Client Code: Clients (code that uses the composite structure) can work both with individual objects and composites without needing to know the difference. This simplifies client code, making it more intuitive and easier to maintain.</li><li>Flexibility: The pattern allows you to add and remove objects in the hierarchy without affecting the client code. This flexibility makes it easy to modify the structure of the tree.</li><li>Scalability: You can easily create more complex structures by nesting composites within composites, making it a scalable solution for modeling part-whole hierarchies.</li><li>Code Reusability: The pattern encourages the reuse of code. You can apply the same operations to both individual objects and composites, reducing duplication of code.</li></ol><h3>Disadvantages of Composite Design Pattern</h3><ol><li>Complex Implementation: Implementing the Composite Pattern can be more complex compared to a non-composite approach. It involves creating a common interface for both individual objects and compositions, which can make the code more intricate.</li><li>Performance Overhead: In some cases, traversing and performing operations on a composite structure can result in performance overhead, especially when dealing with deep and complex hierarchies. This is because you may need to navigate through multiple layers of objects.</li><li>Limited Type Safety: Since the Composite Pattern involves a common interface for both leaf and composite objects, it can lead to a lack of type safety. It’s possible to call methods on composite objects that are not applicable, leading to runtime errors. This requires careful handling to ensure that only relevant operations are performed on objects.</li><li>Reduced Clarity: While the pattern provides flexibility for building complex structures, it can also reduce the clarity of the code. It might be less obvious when you’re working with a composite structure, and this can make the code harder to understand, especially for developers who are not familiar with the pattern.</li><li>Extra Memory Usage: Composite structures can consume additional memory due to the need to store references to child objects within composite objects. This can be a concern when dealing with large hierarchies.</li></ol><h3>Potential Pitfalls</h3><p>While the Composite Pattern is a powerful tool, it’s important to be aware of some potential pitfalls:</p><ol><li>Complexity: While the Composite Pattern simplifies client code, it can make the implementation of the composite structure more complex. Managing the hierarchy and dealing with different types of objects within the hierarchy can be challenging.</li><li>Performance Overhead: The pattern can introduce performance overhead, especially when dealing with deep or large hierarchies. Traversing and performing operations on composite structures may be slower than working with individual objects directly.</li><li>Type Safety: In languages that do not provide strong type checking, it can be challenging to ensure type safety, as the client code may inadvertently attempt operations on incompatible objects within the hierarchy.</li><li>Design Complexity: The Composite Pattern is not suitable for all scenarios. In some cases, it may be an overkill and make the design overly complex. It’s essential to carefully consider whether the pattern is appropriate for the specific problem at hand.</li><li>Limited Use Cases: The Composite Pattern is primarily used for part-whole hierarchies. It may not be the best choice for situations where you need more specialized behavior or interactions between objects that do not fit this structure.</li></ol><h3>Conclusion</h3><p>The Composite Pattern is a fundamental design pattern for building complex hierarchical structures. It provides a uniform interface for both individual and composite objects, enabling flexible and dynamic hierarchies. By understanding its structure, advantages, use cases and potential pitfalls, you can effectively apply the Composite Pattern in your projects to create maintainable and extensible code.</p><p>Design-Patterns/src/document/md/Composite-Design-Pattern.md at master</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff45376b13b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Composite Design Pattern]]></title>
            <link>https://medium.com/@vishal637yadav/composite-design-pattern-69ed7111f537?source=rss-6e215e292544------2</link>
            <guid isPermaLink="false">https://medium.com/p/69ed7111f537</guid>
            <dc:creator><![CDATA[Vishal Yadav]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 03:42:25 GMT</pubDate>
            <atom:updated>2024-12-03T03:42:25.338Z</atom:updated>
            <content:encoded><![CDATA[<p>Design Pattern : Composite</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69ed7111f537" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>