<?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 Agam Kakkar on Medium]]></title>
        <description><![CDATA[Stories by Agam Kakkar on Medium]]></description>
        <link>https://medium.com/@agamkakkar?source=rss-c352c15536c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QugNPmBcPNChuLIsh9YqCQ.png</url>
            <title>Stories by Agam Kakkar on Medium</title>
            <link>https://medium.com/@agamkakkar?source=rss-c352c15536c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:14:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@agamkakkar/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[Interview Lessons I’ve Learned: It’s Not Always About the Right Answer]]></title>
            <link>https://medium.com/@agamkakkar/interview-lessons-ive-learned-it-s-not-always-about-the-right-answer-77c834caa382?source=rss-c352c15536c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/77c834caa382</guid>
            <category><![CDATA[job-interview]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[interview-tips]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Agam Kakkar]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 17:53:04 GMT</pubDate>
            <atom:updated>2025-09-16T17:53:04.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*YTgXEsiwiKq3eFFYLeGxxw@2x.jpeg" /></figure><p>Over the years, I’ve been through several interviews – some that boosted my confidence, and others that left me replaying every answer in my head. But one consistent lesson stands out: interviewers are not always looking for the perfect answer.</p><p>We often prepare for interviews like exams – revising concepts, practicing coding questions, and memorizing frameworks. But the reality is, interviews are less about reciting correct answers and more about how you react, reason, and navigate uncertainty.</p><p><strong>Why Correct Answers Aren’t Everything</strong></p><p>No one can know it all. Technology evolves so fast that even the most experienced engineers get stumped at times. Interviewers know this. Instead of checking if you know everything, they often evaluate:</p><p>•	How you approach problems you don’t fully know</p><p>•	How you reason through trade-offs and constraints</p><p>•	How you communicate your thought process</p><p>•	How you handle pressure and uncertainty</p><p>In short, they want to see your problem-solving strategy and mindset, not just your ability to recall information.</p><p><strong>Real Examples From My Interviews</strong></p><p>Here are a few moments where this became crystal clear to me:</p><ol><li>When I didn’t know a system design concept</li></ol><p>In one interview, I was asked:</p><p>“How would you design a rate limiter for an API?”</p><p>I hadn’t worked on rate limiting before, so I admitted that upfront. But instead of freezing, I reasoned it out:</p><p>•	First, I clarified the problem – “Do we want to limit requests per user, per IP, or globally?”</p><p>•	Then I brainstormed options I did know – like using counters with timestamps, or caching solutions like Redis.</p><p>•	Finally, I discussed trade-offs – memory vs. accuracy, sliding window vs. fixed window.</p><p>Even though I didn’t know the “perfect” answer, the interviewer appreciated my approach and guided me toward the industry-standard solution.</p><p>⸻</p><p>2. When my code wasn’t compiling</p><p>During a coding round, I was asked to implement an algorithm to detect cycles in a linked list. I quickly explained the Floyd’s Tortoise and Hare algorithm, but when writing code, I got stuck on some minor syntax errors.</p><p>Instead of panicking, I kept explaining:</p><p>•	Why two pointers moving at different speeds would eventually meet in a cycle</p><p>•	How the space complexity would be O(1) compared to using a hash set</p><p>The interviewer saw that I understood the underlying concept, and syntax was just a small hiccup.</p><p>⸻</p><p>3. When I faced a behavioral curveball</p><p>Once, I was asked:</p><p>“Tell me about a time you strongly disagreed with your team’s approach.”</p><p>I didn’t have a rehearsed answer. I took a moment, thought back, and shared a story where I disagreed with using a third-party library because of long-term maintenance concerns. I walked them through:</p><p>•	Why I disagreed</p><p>•	How I presented my reasoning to the team</p><p>•	And how I eventually compromised by documenting pros/cons and leaving a fallback plan</p><p>The interviewer wasn’t testing my memory – they wanted to see how I handle conflict constructively.</p><p>⸻</p><p>What Interviewers Really Want to See</p><p>From my experiences, these are the traits interviewers are testing for:</p><p>1.	Reasoning ability – Can you break down problems logically?</p><p>2.	Adaptability – Do you stay calm when you don’t know the answer?</p><p>3.	Communication – Can you explain ideas clearly?</p><p>4.	Collaboration – Do you treat the interviewer like a teammate, not a judge?</p><p>5.	Mindset – Do you show curiosity and openness, rather than panic or overconfidence?</p><p>⸻</p><p>How I Changed My Preparation</p><p>Once I realized this, my prep shifted completely:</p><p>•	I still revise core concepts, but I don’t chase “knowing everything.”</p><p>•	I practice thinking aloud, even when I’m unsure.</p><p>•	I treat interviews as discussions, not exams.</p><p>⸻</p><p>Final Thoughts</p><p>Technical interviews are not just about testing your knowledge – they’re about testing your approach, reasoning, and behavior under uncertainty.</p><p>So, the next time you face a question you don’t know, don’t panic. Take a breath, reason it out, ask clarifying questions, and treat it as a collaborative discussion.</p><p>Because in the real world too, we rarely have all the answers upfront. What matters most is how we find them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77c834caa382" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Garbage Collection in Java: Types, Evolutions & Reference Handling]]></title>
            <link>https://medium.com/@agamkakkar/demystifying-garbage-collection-in-java-types-evolutions-reference-handling-4227014cf2d3?source=rss-c352c15536c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4227014cf2d3</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[java-garbage-collection]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Agam Kakkar]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 06:14:35 GMT</pubDate>
            <atom:updated>2025-08-29T06:20:15.772Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CAHRpx2B5W6GCJMp_sBhbg.png" /><figcaption>Created By: ChatGPT</figcaption></figure><p>Garbage Collection (GC) is one of Java’s superpowers — it automatically manages memory, freeing developers from manual allocation and deallocation headaches. But to truly master Java performance tuning, you must understand how GC works, its <strong>types</strong>, <strong>activities</strong>, <strong>evolution across versions</strong>, and <strong>object reference types</strong>.</p><h3>⚙️ How Garbage Collection Works in Java</h3><p>The JVM automatically manages memory in a process called <strong>Garbage Collection</strong>.<br> Any object that is no longer reachable through any chain of references from active threads or static fields becomes <em>eligible for collection</em>.</p><p>Java uses a <strong>Generational Heap Model</strong>:</p><pre>+---------------------------------------------+<br>|                  Heap                       |<br>|                                             |<br>|  Young Generation       Old Generation      |<br>|  (Eden + Survivor)      (Tenured Objects)   |<br>|                                             |<br>+---------------------------------------------+</pre><h3>Young Generation</h3><ul><li><strong>Eden Space</strong>: Where all new objects are allocated.</li><li><strong>Survivor Spaces (S0, S1)</strong>: Surviving objects from GC in Eden are copied here.</li><li>Objects that “survive” multiple Minor GCs are promoted to the <strong>Old Generation</strong>.</li></ul><h3>Old Generation</h3><ul><li>Holds long-lived objects.</li><li>Collected less frequently but with more expensive operations (Major GC / Full GC).</li></ul><h3>Two Types of Garbage Collection Activities</h3><h3>1️. Minor GC</h3><ul><li>Cleans up the <strong>Young Generation</strong> (Eden + Survivor).</li><li>Usually <strong>fast</strong> because most objects die young.</li></ul><p><strong>Steps in Minor GC</strong>:</p><ol><li>Stop-the-world pause occurs.</li><li>Mark objects in Eden that are alive.</li><li>Copy surviving objects into Survivor space.</li><li>If an object survives multiple Minor GCs, it’s promoted to Old Gen.</li><li>Eden is cleared.</li></ol><p><strong>ASCII Flow</strong>:</p><pre>Before Minor GC:<br>Eden: [objA, objB(dead), objC]  S0: []  S1: []<br>After Minor GC:<br>Eden: []  <br>S0: [objA, objC]  <br>Old Gen: []</pre><h3>2️. Major / Full GC</h3><ul><li>Cleans up the <strong>Old Generation</strong> (and sometimes the entire heap).</li><li>Much more <strong>expensive</strong> than Minor GC.</li></ul><p><strong>Steps in Major GC</strong>:</p><ol><li>Stop-the-world pause.</li><li>Mark phase: Identify all reachable objects.</li><li>Sweep phase: Reclaim memory from unreachable objects.</li><li>Compact phase (depending on GC type): Rearrange objects to avoid fragmentation.</li></ol><p><strong>ASCII Flow</strong>:</p><pre>Old Gen before Full GC:<br>[obj1, obj2(dead), obj3, obj4(dead)]<br>After Full GC (with compaction):<br>[obj1, obj3]</pre><h3>Types of Garbage Collectors in Java</h3><h3>1. Serial GC (Best for small apps)</h3><ul><li>Single-threaded, simple.</li><li>Suitable for <strong>client machines</strong> with small heaps.</li></ul><p>Steps:</p><ol><li>Minor GC: Copy objects from Eden → Survivor.</li><li>Major GC: Compact Old Gen.</li></ol><h3>2. Parallel GC (Throughput Collector)</h3><ul><li>Multi-threaded Minor &amp; Major GC.</li><li>Focuses on <strong>maximizing throughput</strong>, not latency.</li></ul><p>Steps:</p><ol><li>Multiple threads scan Eden.</li><li>Copy surviving objects in parallel.</li><li>Compact Old Gen using multiple threads.</li></ol><h3>3. CMS (Concurrent Mark Sweep) (Deprecated after JDK 14)</h3><ul><li>Low-latency collector.</li><li>Runs <strong>concurrently</strong> with application threads.</li></ul><p>Steps:</p><ol><li>Initial mark (stop-the-world).</li><li>Concurrent mark (tracing reachable objects).</li><li>Remark (short pause).</li><li>Concurrent sweep (reclaim memory).</li></ol><h3>4. G1 GC (Garbage-First) (Default since JDK 9)</h3><ul><li>Divides heap into <strong>regions</strong> instead of just Young/Old.</li><li>Collects regions with <strong>most garbage first</strong>.</li><li>Balances throughput &amp; latency.</li></ul><p>Steps:</p><ol><li>Identify regions with most garbage.</li><li>Evacuate live objects.</li><li>Compact regions incrementally.</li></ol><p>ASCII View:</p><pre>Heap divided into regions:<br>[Reg1: live][Reg2: garbage][Reg3: mix][Reg4: garbage]<br>GC cleans Reg2 &amp; Reg4 first.</pre><h3>5. ZGC (JDK 11+)</h3><ul><li>Ultra-low latency (&lt;10ms pauses).</li><li>Can handle heaps up to <strong>16 TB</strong>.</li><li>Mostly concurrent.</li></ul><p>Steps:</p><ol><li>Load barriers mark references concurrently.</li><li>Compact objects while app threads run.</li><li>Only very short pauses.</li></ol><h3>6. Shenandoah (JDK 12+)</h3><ul><li>Also ultra-low pause collector.</li><li>Region-based like G1 but focuses on <strong>concurrent compaction</strong>.</li></ul><p>Steps:</p><ol><li>Concurrent marking.</li><li>Concurrent evacuation.</li><li>Minimal pause times.</li></ol><h3>Four Types of Object References in Java</h3><p>Java defines reference types in java.lang.ref to control GC behavior:</p><h3>1. Strong Reference (default)</h3><ul><li><strong>Definition</strong>: This is the “normal” reference we use in everyday Java.</li><li><strong>Behavior</strong>: If an object has a strong reference, <strong>GC will never collect it</strong> until the reference is removed (set to null) or goes out of scope.</li><li><strong>Example</strong>:</li></ul><pre>String strongRef = new String(&quot;Hello Strong Reference&quot;);</pre><ul><li><strong>Use case</strong>: Regular programming — default behavior.</li></ul><h3>🔹 2. Soft Reference</h3><ul><li><strong>Definition</strong>: A reference that allows an object to be collected <strong>only when the JVM absolutely needs memory</strong>.</li><li><strong>Behavior</strong>: GC prefers to keep these objects around as long as possible. They are cleared <strong>before JVM throws OutOfMemoryError</strong>.</li><li><strong>Example</strong>:</li></ul><pre>import java.lang.ref.SoftReference;<br><br>String data = new String(&quot;Hello Soft Reference&quot;);<br>SoftReference&lt;String&gt; softRef = new SoftReference&lt;&gt;(data);<br>data = null; // now only softRef refers to object</pre><ul><li>Access: softRef.get()</li><li><strong>Use case</strong>: <strong>Caching</strong> (like image caches, file caches in memory).</li></ul><h3>🔹 3. Weak Reference</h3><ul><li><strong>Definition</strong>: A reference that does not prevent GC at all.</li><li><strong>Behavior</strong>: If no strong or soft references exist, the object will be collected <strong>at the next GC cycle</strong>.</li><li><strong>Example</strong>:</li></ul><pre>import java.lang.ref.WeakReference;<br><br>String data = new String(&quot;Hello Weak Reference&quot;);<br>WeakReference&lt;String&gt; weakRef = new WeakReference&lt;&gt;(data);<br>data = null;</pre><ul><li>After GC → weakRef.get() returns null.</li><li><strong>Use case</strong>: <strong>WeakHashMap</strong> (keys are weak references → entries are auto-removed when key is no longer referenced). Useful for metadata, listeners, or mappings that should not prevent object reclamation.</li></ul><h3>🔹 4. Phantom Reference</h3><ul><li><strong>Definition</strong>: A reference that does not even let you access the object.</li><li><strong>Behavior</strong>: Its get() always returns null. It’s only useful with a <strong>ReferenceQueue</strong>, letting you know exactly when the object was <strong>finalized and is about to be reclaimed</strong>.</li><li><strong>Example</strong>:</li></ul><pre>import java.lang.ref.PhantomReference;<br>import java.lang.ref.ReferenceQueue;<br><br>String data = new String(&quot;Hello Phantom Reference&quot;);<br>ReferenceQueue&lt;String&gt; refQueue = new ReferenceQueue&lt;&gt;();<br>PhantomReference&lt;String&gt; phantomRef = new PhantomReference&lt;&gt;(data, refQueue);<br>data = null;</pre><ul><li>When GC runs → the reference gets enqueued in refQueue.</li><li><strong>Use case</strong>: <strong>Post-mortem cleanup</strong> (like closing native resources). Replacing finalize() safely.</li></ul><h3>Evolution of Garbage Collectors in Java Versions</h3><ul><li><strong>Java 8</strong> → Default GC: Parallel. G1 available.</li><li><strong>Java 9</strong> → G1 becomes default.</li><li><strong>Java 11</strong> → ZGC introduced.</li><li><strong>Java 12</strong> → Shenandoah introduced.</li><li><strong>Java 14</strong> → CMS removed.</li><li><strong>Java 15+</strong> → Continued improvements to G1, ZGC, and Shenandoah.</li></ul><h3>🎯 Key Takeaways</h3><ul><li>Minor GC cleans Young Gen, Major GC cleans Old Gen.</li><li>GC has evolved from <strong>Serial → Parallel → CMS → G1 → ZGC/Shenandoah</strong>.</li><li>Java offers <strong>reference types</strong> to fine-tune memory behavior.</li><li>Modern collectors (ZGC, Shenandoah) are built for <strong>low-latency apps</strong> like finance &amp; real-time systems.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4227014cf2d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Achieving Data Consistency in Microservices: A Practical Guide]]></title>
            <link>https://medium.com/@agamkakkar/achieving-data-consistency-in-microservices-a-practical-guide-da9704b822bb?source=rss-c352c15536c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/da9704b822bb</guid>
            <category><![CDATA[strong-consistency]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[data-consistency]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[eventual-consistency]]></category>
            <dc:creator><![CDATA[Agam Kakkar]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 07:05:26 GMT</pubDate>
            <atom:updated>2025-08-25T07:05:26.377Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the biggest challenges when designing <strong>microservices</strong> is ensuring <strong>data consistency</strong> across multiple independent services. Unlike monolithic applications where everything resides in a single database and ACID transactions are straightforward, microservices often span <strong>distributed databases</strong>, <strong>different domains</strong>, and <strong>asynchronous communication patterns</strong>. This makes achieving consistency far more complex — especially in domains like <strong>banking, healthcare, and e-commerce</strong>, where data correctness is non-negotiable.</p><p>In this article, let’s break down the key approaches to <strong>achieving consistency in microservices</strong> with practical, real-world perspectives.</p><h3>1. The Consistency Problem in Microservices</h3><p>Imagine you are building an <strong>e-commerce platform</strong> with three microservices:</p><ul><li><strong>Order Service</strong> — places orders</li><li><strong>Payment Service</strong> — processes payments</li><li><strong>Inventory Service</strong> — manages stock</li></ul><p>If a customer buys a laptop, you must:</p><ol><li>Deduct stock from inventory</li><li>Process the payment</li><li>Confirm the order</li></ol><p>What happens if the payment fails after the inventory is already deducted? Or if the inventory update succeeds but the order confirmation fails?</p><p>This is the <strong>consistency problem</strong>: ensuring all services either reflect the same <strong>final state</strong> or roll back gracefully without leaving the system in a broken state.</p><h3>2. Types of Consistency</h3><h3>🔹 Strong Consistency</h3><p>All services reflect the same data immediately after a transaction. Common in monoliths with relational databases but hard to achieve in distributed systems due to network latency and partitions.</p><h3>🔹 Eventual Consistency</h3><p>Services may temporarily have different states, but they will converge to a consistent state <strong>eventually</strong>. This is acceptable for most real-world microservices, except for highly sensitive domains (e.g., banking transactions).</p><h3>3. Approaches to Achieve Consistency</h3><h3>a. Distributed Transactions (2PC)</h3><ul><li><strong>How it works</strong>: Uses a <strong>two-phase commit protocol</strong> to ensure either all services commit or all rollback.</li><li><strong>Pros</strong>: Strong consistency</li><li><strong>Cons</strong>: Slow, complex, not scalable for large distributed systems</li><li><strong>Use Case</strong>: Rarely used in microservices, but may be necessary in <strong>financial applications</strong> where absolute correctness is required</li></ul><h3>b. Saga Pattern</h3><ul><li><strong>How it works</strong>: Breaks a transaction into smaller steps. Each service performs its action and publishes an event. If one step fails, compensating actions are triggered to undo previous steps.</li><li><strong>Example</strong>:</li></ul><ol><li>Order Service creates an order → event published</li><li>Payment Service charges the user → success event</li><li>Inventory Service reduces stock → success event</li><li>If <strong>payment fails</strong>, a compensating event is triggered → Order Service cancels the order, Inventory restores stock</li></ol><ul><li><strong>Pros</strong>: Scalable, asynchronous, works well in microservices</li><li><strong>Cons</strong>: Complex error handling, eventual consistency (not immediate)</li><li><strong>Use Case</strong>: E-commerce, travel bookings, logistics</li></ul><h3>c. Event-Driven Consistency</h3><ul><li><strong>How it works</strong>: Services publish domain events (e.g., “OrderPlaced”, “PaymentConfirmed”). Other services subscribe and update their state accordingly.</li><li><strong>Pros</strong>: Decoupled, scalable, natural for microservices</li><li><strong>Cons</strong>: Eventual consistency, requires idempotency and retry mechanisms</li><li><strong>Use Case</strong>: Social media feeds, notification systems, customer onboarding</li></ul><h3>d. CQRS (Command Query Responsibility Segregation)</h3><ul><li><strong>How it works</strong>: Separate write and read models. Commands change state, and queries read from a different store. Sync is achieved via events.</li><li><strong>Pros</strong>: Scales well, improves read performance</li><li><strong>Cons</strong>: Eventual consistency between write and read models</li><li><strong>Use Case</strong>: Systems with high read demand (e.g., dashboards, reporting, CRM)</li></ul><h3>e. Idempotency &amp; Retry Mechanisms</h3><ul><li><strong>How it works</strong>: Ensure that repeated operations produce the same result (e.g., charging a credit card twice should not duplicate payment).</li><li><strong>Use Case</strong>: Payment gateways, order processing</li></ul><h3>4. Real-World Examples</h3><ul><li><strong>Banking (Strong Consistency Needed)</strong>: When transferring money, both debit and credit must either succeed together or fail together. Distributed transactions or carefully designed sagas are critical.</li><li><strong>E-Commerce (Eventual Consistency Works)</strong>: Inventory may take a few seconds to update across warehouses. As long as reconciliation happens eventually, the system works fine.</li><li><strong>Ride-Sharing Apps</strong>: Payment capture, driver allocation, and trip status updates often rely on event-driven consistency with compensating actions.</li></ul><h3>5. Key Best Practices</h3><ol><li><strong>Design for failure</strong> — Assume any service can fail at any time.</li><li><strong>Use idempotent operations</strong> — Reprocessing events should not cause duplicate effects.</li><li><strong>Apply compensating transactions</strong> — Rollback logic is as important as forward logic.</li><li><strong>Monitor and audit</strong> — Log every state transition for traceability.</li><li><strong>Choose the right consistency model</strong> — Strong consistency for financials, eventual consistency for less critical flows.</li></ol><h3>6. Conclusion</h3><p>Data consistency in microservices is not about making everything strongly consistent — that would break scalability and resilience. Instead, it’s about choosing the <strong>right strategy for the right domain</strong>.</p><ul><li>For <strong>financial systems</strong>, strong consistency (2PC or carefully designed Sagas) is a must.</li><li>For <strong>most business domains</strong>, eventual consistency with Saga and event-driven designs provides the right balance of <strong>scalability, performance, and reliability</strong>.</li></ul><p>In the world of distributed systems, <strong>consistency is a spectrum, not a binary choice</strong>. The key is making <strong>informed trade-offs</strong> while always keeping the <strong>business requirements</strong> in focus.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da9704b822bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Internal Working of HTTPS: How the Web Stays Secure]]></title>
            <link>https://medium.com/@agamkakkar/the-internal-working-of-https-how-the-web-stays-secure-769a11663a8f?source=rss-c352c15536c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/769a11663a8f</guid>
            <category><![CDATA[asymmetric-encryption]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[symmetric-encryption]]></category>
            <category><![CDATA[tls]]></category>
            <category><![CDATA[http-vs-https]]></category>
            <dc:creator><![CDATA[Agam Kakkar]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 11:31:47 GMT</pubDate>
            <atom:updated>2025-08-20T11:31:47.420Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s digital world, security on the internet is non-negotiable. When you visit a website that starts with https://, you’re seeing HTTPS in action—an encrypted, secure version of HTTP. At the heart of HTTPS lies TLS (Transport Layer Security), the protocol that ensures your data is transmitted securely. In this article, we’ll break down the internal working of HTTPS with TLS, step by step.</p><h3>What is HTTPS?</h3><p>HTTP (HyperText Transfer Protocol) is the protocol used for transferring data between your browser (client) and a web server.</p><p>HTTPS is simply HTTP + TLS/SSL encryption. It ensures:</p><ul><li>Confidentiality → Data is encrypted.</li><li>Integrity → Data is not modified in transit.</li><li>Authentication → You’re communicating with the right server.</li></ul><h3>What is TLS?</h3><p>TLS (Transport Layer Security) is a cryptographic protocol that:</p><ul><li>Encrypts communication between client and server.</li><li>Prevents eavesdropping and tampering.</li><li>Replaced SSL (Secure Sockets Layer), which is now outdated.</li></ul><p>TLS is what makes the lock icon appear in your browser.</p><h3>Internal Working of HTTPS with TLS</h3><p>Let’s walk through what happens when you type https://example.com in your browser.</p><p><strong>Step 1: Client Hello</strong><br> The browser (client) sends a ClientHello message to the server. It includes supported TLS versions, supported encryption algorithms (cipher suites), and a random number (used for key generation).</p><p><strong>Step 2: Server Hello</strong><br> The server responds with a ServerHello message. It includes the chosen TLS version, chosen cipher suite, and another random number.</p><p><strong>Step 3: Server Certificate</strong><br> The server sends its digital certificate (issued by a Certificate Authority — CA). The certificate proves the server’s identity and contains its public key.</p><p><strong>Step 4: Certificate Verification</strong><br> The client verifies the certificate: Is it signed by a trusted CA? Is it valid (not expired/revoked)? Does the domain name match? If verification fails, the connection is blocked (browser shows “Not Secure”).</p><p><strong>Step 5: Key Exchange</strong><br> Using asymmetric encryption (public/private key pairs), the client and server securely agree on a shared session key. The session key will be used for symmetric encryption (faster than asymmetric).</p><p><strong>Step 6: Session Key Established</strong><br> Both client and server now have the same session key. From this point, communication is encrypted using symmetric encryption (AES, ChaCha20, etc.).</p><p><strong>Step 7: Secure Communication</strong><br> All HTTP requests and responses (GET, POST, etc.) are now encrypted. Even if an attacker intercepts the data, it’s unreadable without the session key.</p><h3>Encryption in Action</h3><ul><li>Asymmetric Encryption: Used only in the handshake phase (RSA, ECDHE). Slower but secure.</li><li>Symmetric Encryption: Used after handshake for data transfer (AES, ChaCha20). Fast and efficient.</li><li>Message Authentication Codes (MACs): Ensure integrity of data.</li></ul><h3>Why HTTPS with TLS Matters</h3><ul><li>Protects sensitive data (passwords, credit cards, personal info).</li><li>Prevents man-in-the-middle (MITM) attacks.</li><li>Builds user trust (the lock icon).</li><li>Required for modern web features (HTTP/2, service workers, PWAs).</li></ul><h3>Final Thoughts</h3><p>HTTPS powered by TLS is the backbone of secure communication on the web. Behind that little padlock icon, a sophisticated dance of cryptography takes place — ensuring that your data remains private, authentic, and secure.</p><p>So, the next time you load a website with HTTPS, you’ll know exactly what’s happening under the hood. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=769a11663a8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PECS in Java Generics — Mastering Upper Bounds, Lower Bounds, Wildcards, and Type Erasure]]></title>
            <link>https://medium.com/@agamkakkar/pecs-in-java-generics-mastering-upper-bounds-lower-bounds-wildcards-and-type-erasure-bf32c49f169a?source=rss-c352c15536c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf32c49f169a</guid>
            <category><![CDATA[pecsrule]]></category>
            <category><![CDATA[upper-bound]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[typeeraser]]></category>
            <dc:creator><![CDATA[Agam Kakkar]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 05:13:23 GMT</pubDate>
            <atom:updated>2025-08-14T05:13:23.651Z</atom:updated>
            <content:encoded><![CDATA[<h3>PECS in Java Generics — Mastering Upper Bounds, Lower Bounds, Wildcards, and Type Erasure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfT5g4ODPxCcTE6akkGtNw.png" /></figure><p>Java Generics are one of those concepts that <em>look</em> easy in the “Hello World” examples but suddenly become a brain teaser when you’re faced with real-world code involving ? extends, ? super, and something called <strong>PECS</strong>.</p><p>If you’ve ever stared at a method signature like:</p><pre>public &lt;T&gt; void copy(List&lt;? extends T&gt; src, List&lt;? super T&gt; dest) { ... }</pre><p>…and thought <em>“What sorcery is this?”</em>, you’re in the right place.</p><p>In this article, we’ll break down:</p><ul><li><strong>Why bounds exist in generics</strong></li><li>The difference between <strong>upper bound</strong> and <strong>lower bound</strong></li><li>The <strong>wildcard (</strong><strong>?)</strong></li><li>The mysterious <strong>type erasure</strong></li><li>And most importantly, the <strong>PECS</strong> rule that will make everything click</li></ul><h3>1. Why Generics Even Exist</h3><p>Before Java 5, collections were a free-for-all. You could store anything in a List, but you had to manually cast it back:</p><pre>List list = new ArrayList();<br>list.add(&quot;Hello&quot;);<br>String s = (String) list.get(0); // Risky cast!</pre><p>The compiler couldn’t protect you from mistakes like:</p><pre>list.add(42); // Added an Integer by mistake</pre><p>You’d only find out <strong>at runtime</strong> when you got a ClassCastException.</p><p>Generics fixed this by adding <strong>compile-time type safety</strong>:</p><pre>List&lt;String&gt; list = new ArrayList&lt;&gt;();<br>list.add(&quot;Hello&quot;);<br>String s = list.get(0); // No cast, and type-safe</pre><p>But generics didn’t just give us type safety — they also gave us <strong>bounds</strong> to make our APIs more flexible without sacrificing safety.</p><h3>2. Upper Bound — extends</h3><p><strong>Definition:</strong><br> An <strong>upper bound</strong> restricts a type parameter to a class <strong>or any of its subclasses</strong>.</p><p><strong>Syntax:</strong></p><pre>List&lt;? extends Number&gt; numbers;</pre><p>This says: “numbers can be a list of Number or any subclass of Number (Integer, Double, Float, etc.).&quot;</p><h3>What you can do:</h3><ul><li>✅ <strong>Read</strong> elements from the list (as Number)</li><li>❌ <strong>Add</strong> elements to the list (except null)</li></ul><p>Example:</p><pre>public static double sum(List&lt;? extends Number&gt; list) {<br>    double total = 0;<br>    for (Number n : list) {<br>        total += n.doubleValue();<br>    }<br>    return total;<br>}</pre><h3>Why no adding?</h3><p>If you have:</p><pre>List&lt;? extends Number&gt; nums = new ArrayList&lt;Integer&gt;();<br>nums.add(3.14); // ❌ Compiler error</pre><p>The compiler says: <em>“I know it’s a subtype of Number, but I don’t know which one — it could be Integer, and adding a Double would break it.”</em></p><p>So, upper bound = <strong>safe to read, unsafe to write</strong>.</p><h3>3. Lower Bound — super</h3><p><strong>Definition:</strong><br> A <strong>lower bound</strong> restricts a type parameter to a class <strong>or any of its superclasses</strong>.</p><p><strong>Syntax:</strong></p><pre>List&lt;? super Integer&gt; integers;</pre><p>This says: “integers can be a list of Integer, Number, or Object.&quot;</p><h3>What you can do:</h3><ul><li>✅ <strong>Add</strong> Integer or its subclasses</li><li>❌ Safely <strong>read</strong> as more than Object</li></ul><p>Example:</p><pre>public static void addNumbers(List&lt;? super Integer&gt; list) {<br>    list.add(1);<br>    list.add(2);<br>}</pre><p>If you read from it:</p><pre>Object obj = list.get(0); // Only safe type is Object</pre><p>So, lower bound = <strong>safe to write, limited to read</strong>.</p><h3>4. PECS Rule</h3><p>Joshua Bloch (author of <em>Effective Java</em>) gave us this brilliant mnemonic:</p><blockquote><strong><em>PECS</em></strong><em> = </em><strong><em>Producer Extends, Consumer Super</em></strong></blockquote><ul><li><strong>Producer (</strong><strong>extends)</strong>: If the collection is producing data for you to read, use ? extends.</li><li><strong>Consumer (</strong><strong>super)</strong>: If the collection is consuming data you give it, use ? super.</li></ul><p>Example: A copy method</p><pre>public static &lt;T&gt; void copy(List&lt;? extends T&gt; src,<br>                            List&lt;? super T&gt; dest) {<br>    for (T item : src) {<br>        dest.add(item);<br>    }<br>}</pre><p>Here:</p><ul><li>src <strong>produces</strong> items → extends</li><li>dest <strong>consumes</strong> items → super</li></ul><h3>5. Wildcards (?)</h3><p>? is an <strong>unknown type</strong> — a placeholder for “some type, but I don’t know which”.</p><p><strong>Use cases:</strong></p><ul><li>When you want flexibility but don’t care about the exact type</li><li>When the method should work with multiple generic types</li></ul><p>Example:</p><pre>public static void printList(List&lt;?&gt; list) {<br>    for (Object obj : list) {<br>        System.out.println(obj);<br>    }<br>}</pre><p>Here, List&lt;?&gt; can be List&lt;String&gt;, List&lt;Integer&gt;, etc., but you can’t add anything (except null).</p><h3>6. Type Erasure</h3><p>Here’s a twist: generics don’t exist at runtime.</p><p><strong>Type Erasure</strong> means:</p><ul><li>The compiler enforces type rules and removes type information after compilation.</li><li>At runtime, List&lt;Integer&gt; and List&lt;String&gt; are just List.</li></ul><p>Example:</p><pre>public void print(List&lt;String&gt; list) {}<br>public void print(List&lt;Integer&gt; list) {} // ❌ Compile error</pre><p>Both become:</p><pre>public void print(List list) {}</pre><p><strong>Why Java does this:</strong></p><ul><li>Backwards compatibility with pre-Java 5 code</li><li>Avoids runtime performance overhead</li></ul><p><strong>Implications:</strong></p><ul><li>Can’t use instanceof with generics:</li></ul><pre>if (list instanceof List&lt;String&gt;) { } // ❌ Not allowed. </pre><ul><li>Can’t create arrays of parameterized types:</li></ul><pre>List&lt;String&gt;[] array = new List&lt;String&gt;[10]; // ❌</pre><h3>7. Common Gotchas</h3><p><strong>Generics are invariant</strong></p><pre>List&lt;Number&gt; nums = new ArrayList&lt;Integer&gt;(); // ❌</pre><p>You need wildcards to make it work:</p><pre>List&lt;? extends Number&gt; nums = new ArrayList&lt;Integer&gt;(); // ✅</pre><p><strong>Extends doesn’t mean you can add</strong><br> Many beginners think ? extends Number lets them add all Numbers — it doesn’t.</p><p><strong>Super restricts what you read</strong><br> From a List&lt;? super Integer&gt;, you can’t get Integer directly — only Object.</p><h3>8. Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NIiJiu8YEJBnjjLypcDZLg.png" /></figure><h3>9. Final Words</h3><p>Once you understand <strong>PECS</strong>, generics stop feeling like magic and start feeling like a tool.</p><p>The key mental model:</p><ul><li><strong>extends → I trust this source to give me things, but I can’t change it.</strong></li><li><strong>super → I can give things to this collection, but I don’t know exactly what’s inside.</strong></li></ul><p>And remember — no matter how fancy your generics look, the JVM only sees raw types at runtime thanks to <strong>type erasure</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf32c49f169a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Batch Loading vs Infinite Scrolling in React: How to Efficiently Render Hundreds of Cards]]></title>
            <link>https://medium.com/@agamkakkar/batch-loading-vs-infinite-scrolling-in-react-how-to-efficiently-render-hundreds-of-cards-8c4b88c3e3f6?source=rss-c352c15536c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c4b88c3e3f6</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[infinite-scroll-in-react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[batch-loading]]></category>
            <dc:creator><![CDATA[Agam Kakkar]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 08:16:50 GMT</pubDate>
            <atom:updated>2025-08-11T08:25:21.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9Qd6oOwuahcJLdmyRqDOQ.png" /></figure><p>If you’re building a React application that displays hundreds or even thousands of cards — say products in an e-commerce app, posts in a social feed, or any large dataset — rendering them all at once can kill your app’s performance and frustrate your users. So how do you load and display tons of data without crashing the browser or causing laggy scrolling?</p><p>Two popular techniques come into play here: <strong>Batch Loading</strong> and <strong>Infinite Scrolling</strong>. Both aim to <strong>load data in chunks</strong>, but they differ in user experience, control, and implementation.</p><p>In this article, I’ll break down both concepts, explain when to use which, and provide practical React examples to get you started.</p><h3>Why Not Load Everything At Once?</h3><p>Rendering hundreds or thousands of DOM nodes at once:</p><ul><li>Slows down initial page load.</li><li>Increases memory consumption.</li><li>Causes janky scrolling and unresponsive UI.</li><li>Overloads the browser’s rendering engine.</li></ul><p>Instead, the trick is to <strong>fetch and render data incrementally</strong>, so users get fast initial loads and smooth interaction.</p><h3>1. Batch Loading: Loading Data in Manageable Chunks</h3><h3>What Is Batch Loading?</h3><p>Batch loading means fetching and rendering your data in <em>fixed-size chunks</em> (batches), typically triggered by user action — usually a “Load More” button.</p><h3>Why Use Batch Loading?</h3><ul><li>Gives users control over how much content they want to load.</li><li>Improves initial page load time.</li><li>Easy to implement and understand.</li></ul><h3>React Example: Batch Loading with a “Load More” Button</h3><pre>import React, { useState, useEffect } from &quot;react&quot;;<br><br>const BATCH_SIZE = 20;<br><br>function BatchLoadingList() {<br>  const [items, setItems] = useState([]);<br>  const [page, setPage] = useState(0);<br><br>  useEffect(() =&gt; {<br>    fetch(`/api/items?offset=${page * BATCH_SIZE}&amp;limit=${BATCH_SIZE}`)<br>      .then(res =&gt; res.json())<br>      .then(newItems =&gt; setItems(prev =&gt; [...prev, ...newItems]));<br>  }, [page]);<br><br>  return (<br>    &lt;div&gt;<br>      {items.map(item =&gt; (<br>        &lt;div key={item.id}&gt;{item.name}&lt;/div&gt;<br>      ))}<br>      &lt;button onClick={() =&gt; setPage(prev =&gt; prev + 1)}&gt;Load More&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default BatchLoadingList;</pre><h3>2. Infinite Scrolling: Automatically Load More When You Scroll</h3><h3>What Is Infinite Scrolling?</h3><p>Infinite scrolling is like batch loading, but instead of clicking a button, the app automatically fetches the next batch of data when the user scrolls near the bottom of the page.</p><p>This technique is used by social media feeds, news sites, and image galleries to keep users engaged.</p><h3>Why Use Infinite Scrolling?</h3><ul><li>Creates a smooth, seamless browsing experience.</li><li>Reduces clicks — content just keeps coming.</li><li>Great for mobile devices where tapping small buttons is less ideal.</li></ul><h3>React Example: Infinite Scroll with Scroll Listener</h3><pre>import React, { useState, useEffect } from &quot;react&quot;;<br><br>const LIMIT = 20;<br><br>function InfiniteScrollList() {<br>  const [items, setItems] = useState([]);<br>  const [page, setPage] = useState(0);<br><br>  useEffect(() =&gt; {<br>    fetch(`/api/items?offset=${page * LIMIT}&amp;limit=${LIMIT}`)<br>      .then(res =&gt; res.json())<br>      .then(newItems =&gt; setItems(prev =&gt; [...prev, ...newItems]));<br>  }, [page]);<br><br>  useEffect(() =&gt; {<br>    const handleScroll = () =&gt; {<br>      if (window.innerHeight + window.scrollY &gt;= document.body.offsetHeight - 200) {<br>        setPage(prev =&gt; prev + 1);<br>      }<br>    };<br><br>    window.addEventListener(&quot;scroll&quot;, handleScroll);<br>    return () =&gt; window.removeEventListener(&quot;scroll&quot;, handleScroll);<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      {items.map(item =&gt; (<br>        &lt;div key={item.id}&gt;{item.name}&lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default InfiniteScrollList;</pre><h3>Batch Loading vs Infinite Scrolling: Which One to Use?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*Xo0KbOP8rSTJ7Uxjt4y13w.png" /></figure><h3>Performance Tips: Making It Even Better</h3><ul><li><strong>Combine with Virtualization:</strong> Use libraries like <a href="https://github.com/bvaughn/react-window">react-window</a> or <a href="https://github.com/bvaughn/react-virtualized">react-virtualized</a> to only render visible cards. This keeps the DOM light and scrolling smooth.</li><li><strong>Lazy-load Images:</strong> Use loading=&quot;lazy&quot; or specialized libraries to defer offscreen images loading.</li><li><strong>Memoize Components:</strong> Use React.memo and hooks like useCallback and useMemo to avoid unnecessary re-renders.</li></ul><h3>Final Thoughts</h3><p>Batch loading and infinite scrolling are powerful techniques that balance performance with user experience when dealing with large datasets in React apps. Choosing between them depends on your app’s context and users’ expectations.</p><p>And the real magic happens when you combine these with <strong>virtualization</strong> — enabling your app to render tens of thousands of cards effortlessly!</p><p>Want a working demo that combines infinite scrolling with virtualization? Let me know, and I’ll hook you up with one!</p><p>If you found this helpful, feel free to share it with your developer friends and colleagues. And don’t hesitate to ask me for more React performance tips anytime!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c4b88c3e3f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CAP Theorem in Microservices: Striking the Balance in a Distributed World]]></title>
            <link>https://medium.com/@agamkakkar/cap-theorem-in-microservices-striking-the-balance-in-a-distributed-world-378d2ffa2e5a?source=rss-c352c15536c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/378d2ffa2e5a</guid>
            <category><![CDATA[cap-theorem]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[fullstack-development]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <dc:creator><![CDATA[Agam Kakkar]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 06:41:11 GMT</pubDate>
            <atom:updated>2025-08-05T06:41:11.467Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rdt4lsY8U8QLz55nQ8xdjg.png" /></figure><h3>Introduction</h3><p>In the world of microservices and distributed systems, you’re bound to run into the <strong>CAP Theorem</strong> sooner or later. It’s one of those core concepts that helps you make architectural decisions — especially when things go sideways.</p><p>But what does CAP really mean when you have dozens of microservices talking to each other, databases split across the globe, and users demanding lightning-fast response times?</p><p>Let’s break it down, real-world style.</p><h3>🧩 What is CAP Theorem?</h3><p>Coined by Eric Brewer and formally proven later, the <strong>CAP Theorem</strong> states that in a distributed system, you can <strong>only guarantee two out of these three properties</strong> at any given time:</p><ul><li><strong>C — Consistency:</strong> Every read gets the latest write (like reading from a single up-to-date source).</li><li><strong>A — Availability:</strong> Every request gets a (non-error) response — even if it’s not the latest.</li><li><strong>P — Partition Tolerance:</strong> The system continues to function even when messages are lost or nodes can’t communicate due to network issues.</li></ul><blockquote><em>In a network-partitioned world (which is the real world), you can only choose between </em><strong><em>Consistency</em></strong><em> and </em><strong><em>Availability</em></strong><em>.</em></blockquote><h3>🎯 CAP Theorem in the Context of Microservices</h3><p>Let’s apply this to a <strong>microservices architecture</strong>. Imagine an <strong>e-commerce platform</strong> broken into services like:</p><ul><li><strong>Order Service</strong></li><li><strong>Inventory Service</strong></li><li><strong>Payment Service</strong></li><li><strong>Shipping Service</strong></li></ul><p>Each has its own database and communicates asynchronously via Kafka or synchronously via REST/gRPC.</p><h3>Now imagine:</h3><p>Suddenly, your <strong>Inventory Service</strong> becomes unreachable due to a network partition. What do you do?</p><h3>1. 🎯 Consistency over Availability (CP)</h3><p>In this case, <strong>you reject the request</strong> if Inventory can’t be checked. This guarantees <strong>data consistency</strong>, even if that means the user gets an error or waits longer.</p><h3>Example:</h3><blockquote><strong><em>Order Service waits for Inventory Service.</em></strong><em> If Inventory is down, it won’t place the order.</em></blockquote><p><strong>Pros:</strong></p><ul><li>Strong data integrity</li><li>No phantom orders</li></ul><p><strong>Cons:</strong></p><ul><li>Poor user experience during outages</li><li>Higher latency</li></ul><p>Use when: You’re dealing with <strong>financial systems</strong>, <strong>payments</strong>, or <strong>compliance-heavy domains</strong> where <strong>accuracy &gt; availability</strong>.</p><h3>2. ⚡ Availability over Consistency (AP)</h3><p>Here, your system continues operating <strong>even if Inventory is down</strong>, maybe by assuming stock is available or processing asynchronously.</p><h3>Example:</h3><blockquote><strong><em>Order Service queues the request</em></strong><em> and Inventory is updated eventually.</em></blockquote><p><strong>Pros:</strong></p><ul><li>Always responsive</li><li>Better UX during partial outages</li></ul><p><strong>Cons:</strong></p><ul><li>Risk of overselling</li><li>Requires reconciliation mechanisms</li></ul><p>Use when: You value <strong>user experience</strong>, and <strong>eventual consistency</strong> is acceptable (e.g., social media likes, e-commerce carts).</p><h3>3. 🛡️ Partition Tolerance (Always a Must)</h3><p>In the cloud and microservices world, <strong>partition tolerance is not optional</strong>.</p><p>Networks fail. Services go down. Data centers go offline.</p><p>So the real choice you’re always making is:</p><blockquote><strong><em>C vs. A</em></strong><em>, because </em><strong><em>P is assumed</em></strong><em>.</em></blockquote><h3>🔁 Real-world Example: Order Processing</h3><p>Let’s say an order needs to:</p><ol><li>Deduct inventory</li><li>Charge payment</li><li>Confirm order</li></ol><h3>Option 1: CP → Consistent but Not Always Available</h3><p>You check everything before confirming. If Payment or Inventory is down, the order fails.</p><h3>Option 2: AP → Always Available, Eventually Consistent</h3><p>You accept the order and <strong>use an event-driven saga</strong> to confirm inventory and payment asynchronously.</p><pre>Order Placed → [Event Bus]<br>  ↳ Payment Service<br>  ↳ Inventory Service<br>  ↳ Order Confirmation</pre><p>You might later:</p><ul><li>Cancel the order if payment fails</li><li>Notify the user if item is out of stock</li></ul><h3>💡 Design Patterns that Help Navigate CAP</h3><ul><li><strong>Event Sourcing</strong>: Capture every change as an event.</li><li><strong>CQRS</strong>: Separate reads and writes to balance consistency and performance.</li><li><strong>Saga Pattern</strong>: Handle distributed transactions with compensating actions.</li><li><strong>Idempotent APIs</strong>: Ensure retries don’t break consistency.</li><li><strong>Circuit Breakers</strong>: Improve availability during downstream failures.</li></ul><h3>🧠 Final Thoughts</h3><p>CAP isn’t just theory — it’s the <strong>reality</strong> behind every network call in your microservice architecture.</p><p>The trick isn’t to “solve” CAP — it’s to <strong>understand your business priorities</strong> and make <strong>conscious trade-offs</strong>.</p><ul><li>Do you care more about accuracy or responsiveness?</li><li>What happens if a service goes down — do you fail fast or wait it out?</li><li>Can your business tolerate eventual consistency?</li></ul><p>The next time you’re designing a service boundary or choosing between retry logic and a hard failure, <strong>remember CAP</strong> — and choose wisely.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=378d2ffa2e5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structural Design Patterns in Java (with Real-life and Sample code)]]></title>
            <link>https://medium.com/@agamkakkar/structural-design-patterns-in-java-with-real-life-and-sample-code-6c6df727a402?source=rss-c352c15536c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c6df727a402</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[designpatternsjava]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[maintainability]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Agam Kakkar]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 08:10:33 GMT</pubDate>
            <atom:updated>2025-07-28T08:10:33.762Z</atom:updated>
            <content:encoded><![CDATA[<p>Structural design patterns are all about <strong>composing classes and objects</strong> to form larger structures while keeping these structures <strong>flexible and efficient</strong>. These patterns help ensure that if one part of a system changes, the entire system doesn’t need to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vOnDbtGcvbd3VDl4eOc0Q.png" /></figure><h3>1. Adapter Pattern</h3><h4>Definition:</h4><p>The Adapter pattern allows objects with <strong>incompatible interfaces</strong> to work together by providing a <strong>wrapper</strong> (an adapter) that translates one interface into another.</p><h4>Real-Life Analogy:</h4><p>A <strong>mobile charger</strong> is an adapter. Your wall socket provides AC power, but your phone needs DC. The charger adapts the power format.</p><h4>Project Example:</h4><p>You have a legacy payment system with method makeLegacyPayment() and a new API expecting processNewPayment().</p><pre>// Old system<br>class LegacyPayment {<br>    void makeLegacyPayment() {<br>        System.out.println(&quot;Processing payment using Legacy system.&quot;);<br>    }<br>}<br><br>// New interface<br>interface Payment {<br>    void processNewPayment();<br>}<br><br>// Adapter<br>class PaymentAdapter implements Payment {<br>    private LegacyPayment legacyPayment;<br><br>    public PaymentAdapter(LegacyPayment legacyPayment) {<br>        this.legacyPayment = legacyPayment;<br>    }<br><br>    public void processNewPayment() {<br>        legacyPayment.makeLegacyPayment();<br>    }<br>}</pre><p>Usage:</p><pre>Payment payment = new PaymentAdapter(new LegacyPayment());<br>payment.processNewPayment();</pre><h3>2. Bridge Pattern</h3><h4>Definition:</h4><p>Separates abstraction from implementation so they can evolve independently. Useful when there are <strong>multiple dimensions</strong> of change.</p><h4>Real-Life Analogy:</h4><p>A <strong>remote control</strong> (abstraction) that can control different <strong>TVs</strong> (implementation).</p><h4>Project Example:</h4><p>You want to support different notification types (SMS, Email) across different priorities (High, Low).</p><h4>Code:</h4><pre>interface MessageSender {<br>    void sendMessage(String message);<br>}<br><br>class EmailSender implements MessageSender {<br>    public void sendMessage(String message) {<br>        System.out.println(&quot;Sending EMAIL: &quot; + message);<br>    }<br>}<br><br>class SMSSender implements MessageSender {<br>    public void sendMessage(String message) {<br>        System.out.println(&quot;Sending SMS: &quot; + message);<br>    }<br>}<br><br>abstract class Notification {<br>    protected MessageSender sender;<br><br>    Notification(MessageSender sender) {<br>        this.sender = sender;<br>    }<br><br>    abstract void notifyUser(String message);<br>}<br><br>class UrgentNotification extends Notification {<br>    UrgentNotification(MessageSender sender) {<br>        super(sender);<br>    }<br><br>    void notifyUser(String message) {<br>        sender.sendMessage(&quot;URGENT: &quot; + message);<br>    }<br>}</pre><p>Usage:</p><pre>Notification notification = new UrgentNotification(new SMSSender());<br>notification.notifyUser(&quot;System down!&quot;);</pre><h3>3. Composite Pattern</h3><h4>Definition:</h4><p>Used when dealing with <strong>tree structures</strong>. Treats individual objects and compositions of objects uniformly.</p><h4>Real-Life Analogy:</h4><p>A <strong>folder</strong> in your computer contains files and subfolders. Operations like “delete” work the same for both.</p><h4>Project Example:</h4><p>In a role-based access control system, a PermissionGroup can have nested Permissions or other groups.</p><h4>Code:</h4><pre>interface Component {<br>    void showDetails();<br>}<br><br>class FileLeaf implements Component {<br>    String name;<br>    FileLeaf(String name) { this.name = name; }<br><br>    public void showDetails() {<br>        System.out.println(&quot;File: &quot; + name);<br>    }<br>}<br><br>class FolderComposite implements Component {<br>    String name;<br>    List&lt;Component&gt; children = new ArrayList&lt;&gt;();<br><br>    FolderComposite(String name) { this.name = name; }<br><br>    void add(Component comp) { children.add(comp); }<br><br>    public void showDetails() {<br>        System.out.println(&quot;Folder: &quot; + name);<br>        for (Component c : children) {<br>            c.showDetails();<br>        }<br>    }<br>}</pre><p>Usage:</p><pre>FolderComposite root = new FolderComposite(&quot;Root&quot;);<br>root.add(new FileLeaf(&quot;README.md&quot;));<br>FolderComposite src = new FolderComposite(&quot;src&quot;);<br>src.add(new FileLeaf(&quot;App.java&quot;));<br>root.add(src);<br><br>root.showDetails();</pre><h3>4. Decorator Pattern</h3><h4>Definition:</h4><p>Adds behavior to objects dynamically without altering their structure.</p><h4>Real-Life Analogy:</h4><p>Putting on <strong>clothes</strong> like jackets or hats without changing your body.</p><h4>Project Example:</h4><p>A notification system where you can add SMS, Slack, and Email notifications dynamically.</p><h4>Code:</h4><pre>interface Notifier {<br>    void send(String message);<br>}<br><br>class BasicNotifier implements Notifier {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending basic notification: &quot; + message);<br>    }<br>}<br><br>class EmailDecorator implements Notifier {<br>    Notifier notifier;<br><br>    EmailDecorator(Notifier notifier) {<br>        this.notifier = notifier;<br>    }<br><br>    public void send(String message) {<br>        notifier.send(message);<br>        System.out.println(&quot;Also sending EMAIL: &quot; + message);<br>    }<br>}</pre><p>Usage:</p><pre>Notifier notifier = new EmailDecorator(new BasicNotifier());<br>notifier.send(&quot;New login detected&quot;);</pre><h3>5. Facade Pattern</h3><h4>Definition:</h4><p>Provides a simplified interface to a complex system of classes, libraries, or frameworks.</p><h4>Real-Life Analogy:</h4><p>A <strong>restaurant waiter</strong> provides a simple menu for the complex kitchen operations.</p><h4>Project Example:</h4><p>A complex video conversion system with codecs, buffers, encoders, etc.</p><h4>Code:</h4><pre>class CodecFactory {<br>    public String extract(String filename) {<br>        return &quot;Extracting codec for &quot; + filename;<br>    }<br>}<br><br>class BitrateReader {<br>    public String read(String file, String codec) {<br>        return &quot;Reading file &quot; + file + &quot; with codec &quot; + codec;<br>    }<br>}<br><br>class VideoConverterFacade {<br>    public void convert(String filename) {<br>        CodecFactory codecFactory = new CodecFactory();<br>        String codec = codecFactory.extract(filename);<br>        BitrateReader reader = new BitrateReader();<br>        String result = reader.read(filename, codec);<br>        System.out.println(result);<br>    }<br>}</pre><p>Usage:</p><pre>new VideoConverterFacade().convert(&quot;movie.mp4&quot;);</pre><h3>6. Flyweight Pattern</h3><h4>Definition:</h4><p>Reduces memory usage by sharing common object state.</p><h4>Real-Life Analogy:</h4><p>A <strong>character in a document editor</strong> — we reuse font styles instead of storing them per letter.</p><h4>Project Example:</h4><p>Rendering thousands of map markers with same icons or styles.</p><h4>Code:</h4><pre>class TreeType {<br>    String name, color;<br><br>    TreeType(String name, String color) {<br>        this.name = name;<br>        this.color = color;<br>    }<br><br>    void draw(int x, int y) {<br>        System.out.println(&quot;Drawing &quot; + name + &quot; tree at &quot; + x + &quot;, &quot; + y);<br>    }<br>}<br><br>class TreeFactory {<br>    private static Map&lt;String, TreeType&gt; types = new HashMap&lt;&gt;();<br><br>    public static TreeType getTreeType(String name, String color) {<br>        String key = name + color;<br>        if (!types.containsKey(key)) {<br>            types.put(key, new TreeType(name, color));<br>        }<br>        return types.get(key);<br>    }<br>}</pre><p>Usage:</p><pre>TreeType oak = TreeFactory.getTreeType(&quot;Oak&quot;, &quot;Green&quot;);<br>oak.draw(10, 20);</pre><h3>7. Proxy Pattern</h3><h4>Definition:</h4><p>Provides a <strong>placeholder</strong> or surrogate to control access to another object.</p><h4>Real-Life Analogy:</h4><p>Your <strong>bank ATM card</strong> is a proxy for the actual bank account.</p><h4>Project Example:</h4><p>A virtual proxy to load images lazily in a web app.</p><h4>Code:</h4><pre>interface Image {<br>    void display();<br>}<br><br>class RealImage implements Image {<br>    String filename;<br><br>    RealImage(String filename) {<br>        this.filename = filename;<br>        load();<br>    }<br><br>    void load() {<br>        System.out.println(&quot;Loading &quot; + filename);<br>    }<br><br>    public void display() {<br>        System.out.println(&quot;Displaying &quot; + filename);<br>    }<br>}<br><br>class ProxyImage implements Image {<br>    String filename;<br>    RealImage realImage;<br><br>    ProxyImage(String filename) {<br>        this.filename = filename;<br>    }<br><br>    public void display() {<br>        if (realImage == null) {<br>            realImage = new RealImage(filename);<br>        }<br>        realImage.display();<br>    }<br>}</pre><p>Usage:</p><pre>Image img = new ProxyImage(&quot;wallpaper.jpg&quot;);<br>img.display(); // loads &amp; displays<br>img.display(); // just displays</pre><h3>Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*PmFpQdL_73fBEeCSbm3IiA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c6df727a402" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices Design Patterns — With Real World Examples & Project Code]]></title>
            <link>https://medium.com/@agamkakkar/microservices-design-patterns-with-real-world-examples-project-code-aa816b0d04a8?source=rss-c352c15536c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa816b0d04a8</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[designpatternsjava]]></category>
            <dc:creator><![CDATA[Agam Kakkar]]></dc:creator>
            <pubDate>Tue, 22 Jul 2025 10:50:38 GMT</pubDate>
            <atom:updated>2025-07-25T08:02:12.935Z</atom:updated>
            <content:encoded><![CDATA[<h3>Microservices Design Patterns — With Real World Examples &amp; Sample Code</h3><p>Microservices architecture empowers organizations to build robust, scalable, and independent services. To keep such distributed systems manageable and reliable, <strong>design patterns</strong> are widely adopted.</p><p>Below, we’ll explore key microservices design patterns with real-world project insights and code examples using <strong>Spring Boot</strong>, <strong>Eureka</strong>, <strong>API Gateway</strong>, <strong>Kafka</strong>, <strong>Resilience4j</strong>, and <strong>MongoDB</strong>.</p><h3>1. API Gateway Pattern</h3><h4>Problem</h4><p>Clients shouldn’t talk directly to every microservice. Authentication, routing, rate-limiting, and CORS handling shouldn’t be repeated in each service.</p><h4>Solution</h4><p>Introduce an API Gateway that acts as a single entry point. It routes requests to the appropriate services and applies cross-cutting concerns.</p><h4>Tech Used</h4><ul><li><strong>Spring Cloud Gateway</strong></li><li><strong>Eureka for discovery</strong></li></ul><h4>Code Snippet</h4><pre># application.yml of API Gateway<br>spring:<br>  application:<br>    name: api-gateway<br>  cloud:<br>    gateway:<br>      discovery:<br>        locator:<br>          enabled: true<br>          lower-case-service-id: true<br>      routes:<br>        - id: order-service<br>          uri: lb://ORDER-SERVICE<br>          predicates:<br>            - Path=/orders/**<br>        - id: payment-service<br>          uri: lb://PAYMENT-SERVICE<br>          predicates:<br>            - Path=/payments/**</pre><h3>2. Database per Service Pattern</h3><h4>Problem</h4><p>Tightly coupled databases prevent service independence.</p><h4>Solution</h4><p>Each microservice should have its own database schema. Services interact via APIs, not shared DBs.</p><h4>Code Example</h4><ul><li>Order service → orders_db</li><li>Payment service → payments_db</li></ul><p>Each service connects to its own database:</p><pre>spring:<br>  datasource:<br>    url: jdbc:mysql://localhost:3306/orders_db<br>    username: root<br>    password: root</pre><h3>3. Circuit Breaker Pattern</h3><h4>Problem</h4><p>If a downstream service fails or is slow, it can degrade the whole system.</p><h4>Solution</h4><p>Use circuit breakers to detect failure and prevent cascading effects.</p><h4>Tech Used</h4><ul><li><strong>Resilience4j</strong> with Spring Boot</li></ul><h4>Code Example</h4><pre>@CircuitBreaker(name = &quot;paymentService&quot;, fallbackMethod = &quot;fallbackMethod&quot;)<br>public String callPaymentService() {<br>    return restTemplate.getForObject(&quot;http://PAYMENT-SERVICE/pay&quot;, String.class);<br>}<br><br>public String fallbackMethod(Exception e) {<br>    return &quot;Payment service is currently unavailable. Please try later.&quot;;<br>}</pre><h3>4. Service Discovery Pattern</h3><h4>Problem</h4><p>Services running on dynamic IPs and ports can’t be hardcoded.</p><h4>Solution</h4><p>Use a service registry like <strong>Eureka</strong>. Services register themselves and discover others.</p><h4>Code Snippets</h4><pre>@EnableEurekaServer<br>@SpringBootApplication<br>public class EurekaServerApp {}</pre><p>In services:</p><pre># application.yml<br>spring:<br>  application:<br>    name: order-service<br>  eureka:<br>    client:<br>      register-with-eureka: true<br>      fetch-registry: true<br>      service-url:<br>        defaultZone: http://localhost:8761/eureka</pre><h3>5. Event Sourcing Pattern</h3><h4>Problem</h4><p>Storing only the latest state loses valuable historical data.</p><h4>Solution</h4><p>Store each change as an event and derive current state by replaying events.</p><h4>Example</h4><ul><li>Kafka topic stores events: order-created, order-paid, order-shipped</li><li>A service rebuilds the order status from event history.</li></ul><h4>Code</h4><pre>public class OrderEvent {<br>    private String eventId;<br>    private String orderId;<br>    private String eventType; // CREATED, SHIPPED<br>    private LocalDateTime timestamp;<br>}</pre><h3>6. CQRS Pattern (Command Query Responsibility Segregation)</h3><h4>Problem</h4><p>Same model is used for both writes and reads, causing bloated code and scaling issues.</p><h4>Solution</h4><p>Separate models for <strong>commands (writes)</strong> and <strong>queries (reads)</strong>.</p><h4>Example</h4><ul><li>Write Model → PostgreSQL</li><li>Read Model → MongoDB</li><li>Events update read DB via Kafka</li></ul><pre>@RestController<br>public class OrderCommandController {<br>    @PostMapping(&quot;/orders&quot;)<br>    public ResponseEntity&lt;Void&gt; placeOrder(@RequestBody OrderRequest request) {<br>        // Publish ORDER_PLACED event to Kafka<br>    }<br>}</pre><h3>7. Saga Pattern</h3><h4>Problem</h4><p>How to maintain consistency across distributed services without 2PC (two-phase commit)?</p><h4>Solution</h4><p>Use a sequence of local transactions where each step publishes an event triggering the next.</p><h4>Types</h4><ul><li><strong>Orchestration</strong> → Central coordinator service</li><li><strong>Choreography</strong> → Services react to events</li></ul><h4>Choreography Example</h4><pre>Order Service → emits OrderCreated → <br>Inventory Service → reserves stock → emits StockReserved →<br>Payment Service → charges → emits PaymentCompleted</pre><p>Each service listens and responds:</p><pre>@KafkaListener(topics = &quot;order-events&quot;)<br>public void handleOrderCreated(OrderCreatedEvent event) {<br>    // reserve stock, then emit StockReservedEvent<br>}</pre><h4><strong>Orchestration Example</strong></h4><pre>@Service<br>public class OrderOrchestratorService {<br>    public void createOrder(Order order) {<br>        try {<br>            inventoryClient.reserve(order);<br>            paymentClient.pay(order);<br>            shippingClient.ship(order);<br>        } catch (Exception e) {<br>            compensate(order);<br>        }<br>    }<br><br>    public void compensate(Order order) {<br>        shippingClient.cancel(order);<br>        paymentClient.refund(order);<br>        inventoryClient.release(order);<br>    }<br>}</pre><h3>8. Strangler Fig Pattern</h3><h4>Problem</h4><p>Need to migrate a monolith to microservices gradually.</p><h4>Solution</h4><p>Route specific functionality to new microservices while retaining old system for others.</p><h4>Real-Life</h4><ul><li>Start replacing /users endpoint with new user service</li><li>Others like /orders still handled by monolith</li></ul><p>Use API Gateway to route selectively:</p><pre>routes:<br>  - id: user-service<br>    uri: lb://USER-SERVICE<br>    predicates:<br>      - Path=/users/**<br>  - id: monolith-app<br>    uri: http://localhost:8080<br>    predicates:<br>      - Path=/orders/**</pre><h3>9. Bulkhead Pattern</h3><h4><strong>Problem</strong></h4><p>One failing service can consume all resources and bring down the entire system.</p><h4>Solution</h4><p>Isolate resources (like thread pools or containers) between services to contain failures.</p><p><strong>Example using Resilience4j</strong></p><pre>@Bulkhead(name = &quot;inventoryService&quot;, type = Bulkhead.Type.THREADPOOL)<br>public String checkInventory() {<br>    return inventoryClient.check();<br>}</pre><h3>10. Sidecar Pattern</h3><h4>Problem</h4><p>You want to enhance a service with extra functionalities (e.g., logging, monitoring) without changing the service code.</p><h4>Solution</h4><p>Deploy helper components (sidecars) alongside each service instance.</p><p><strong>Real-Life</strong></p><ul><li>Service: app.jar</li><li>Sidecar: envoy/Fluentd container for logging/monitoring</li></ul><p>These two share the same pod (in Kubernetes), communicating via localhost.</p><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*v0dHrAmkD-ukJGG1Lf91pA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa816b0d04a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering SOLID Principles with a Real-World Notification Service (Java + Spring Boot)]]></title>
            <link>https://medium.com/@agamkakkar/mastering-solid-principles-with-a-real-world-notification-service-java-spring-boot-38c1982aa7e1?source=rss-c352c15536c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/38c1982aa7e1</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Agam Kakkar]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 06:13:53 GMT</pubDate>
            <atom:updated>2025-07-18T06:16:26.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2h6j2UmQOLvZRjMw" /></figure><h3>Introduction</h3><p>Design principles are the <strong>foundation of clean, maintainable, and scalable software</strong>. Among these, <strong>SOLID</strong> stands out as a timeless guide to writing better object-oriented code.</p><p>But while many tutorials explain SOLID with abstract shapes and birds, let’s bring it down to earth.</p><p>Imagine you’re building a <strong>Notification System</strong> for an enterprise app — something that can send emails, Slack messages, or even SMS alerts when a device overheats.</p><p>Let’s explore how each SOLID principle can be <strong>implemented, violated, and fixed</strong> using this real-world system.</p><h3>S — Single Responsibility Principle (SRP)</h3><p><strong>“A class should have only one reason to change.”</strong></p><p>❌ Violating SRP</p><pre>public class NotificationService {<br>    public void send(String message) { /* send email */ }<br>    public void log(String message) { /* log to file */ }<br>    public void saveToDatabase(String message) { /* insert into DB */ }<br>}</pre><p>Here, one class is handling <strong>messaging</strong>, <strong>logging</strong>, and <strong>persistence</strong> — three very different concerns.</p><p>✅ Fixing with SRP</p><pre>public class NotificationService {<br>    private final List&lt;NotificationSender&gt; senders;<br><br>    public NotificationService(List&lt;NotificationSender&gt; senders) {<br>        this.senders = senders;<br>    }<br><br>    public void sendAll(String message) {<br>        senders.forEach(sender -&gt; sender.send(message));<br>    }<br>}</pre><p>Now:</p><ul><li>NotificationService only sends notifications</li><li>Logging and persistence can be handled by separate services</li></ul><p><strong>🔁 Benefit:</strong> Focused classes, easier to test and maintain</p><h3>O — Open/Closed Principle (OCP)</h3><p><strong>“Software entities should be open for extension, but closed for modification.”</strong></p><p>Let’s say you want to support multiple notification channels (email, Slack, SMS).</p><p>❌ OCP Violation (if-else soup)</p><pre>public class NotificationService {<br>    public void send(String type, String message) {<br>        if (type.equals(&quot;email&quot;)) { /* send email */ }<br>        else if (type.equals(&quot;slack&quot;)) { /* send Slack */ }<br>    }<br>}</pre><p>Every new channel requires <strong>modifying</strong> this class — risky and error-prone.</p><p>✅ OCP with Polymorphism</p><pre>public interface NotificationSender {<br>    void send(String message);<br>}<br><br>@Component<br>public class EmailSender implements NotificationSender {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending Email: &quot; + message);<br>    }<br>}<br><br>@Component<br>public class SlackSender implements NotificationSender {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending Slack: &quot; + message);<br>    }<br>}</pre><p>Spring Boot will auto-inject them:</p><pre>@Service<br>public class NotificationService {<br>    private final List&lt;NotificationSender&gt; senders;<br><br>    public NotificationService(List&lt;NotificationSender&gt; senders) {<br>        this.senders = senders;<br>    }<br><br>    public void sendAll(String message) {<br>        senders.forEach(sender -&gt; sender.send(message));<br>    }<br>}</pre><p><strong>🔁 Benefit:</strong> Add new senders without touching existing code — rock-solid extensibility.</p><h3>L — Liskov Substitution Principle (LSP)</h3><p><strong>“Subtypes must be substitutable for their base types without breaking behavior.”</strong></p><p>❌ LSP Violation</p><pre>@Component<br>public class NullSender implements NotificationSender {<br>    public void send(String message) {<br>        throw new UnsupportedOperationException(&quot;Not implemented&quot;);<br>    }<br>}</pre><p>Calling send() here will <strong>crash your app</strong> — this class doesn’t behave like its parent.</p><p>✅ LSP Fix — Safe Substitution</p><pre>@Component<br>public class NoOpSender implements NotificationSender {<br>    public void send(String message) {<br>        System.out.println(&quot;NoOpSender: nothing to do.&quot;);<br>    }<br>}</pre><p>Now NotificationService can safely treat all senders the same, without surprises.</p><p><strong>🔁 Benefit:</strong> Ensures polymorphism works safely without runtime errors</p><h3>I — Interface Segregation Principle (ISP)</h3><p><strong>“Clients should not be forced to depend on methods they do not use.”</strong></p><p>❌ ISP Violation — Fat Interface</p><pre>public interface NotificationSender {<br>    void sendEmail(String msg);<br>    void sendSMS(String msg);<br>    void sendSlack(String msg);<br>}</pre><p>Now every implementing class has to provide all methods — even if it doesn’t need them.</p><p>✅ ISP Fix — Smaller Interfaces</p><pre>public interface EmailSender {<br>    void sendEmail(String msg);<br>}<br><br>public interface SmsSender {<br>    void sendSms(String msg);<br>}</pre><p>Now classes can implement <strong>only the interfaces they care about</strong>.</p><p><strong>🔁 Benefit:</strong> Cleaner, focused contracts and less boilerplate code</p><h3>D — Dependency Inversion Principle (DIP)</h3><p><strong>“High-level modules should not depend on low-level modules. Both should depend on abstractions.”</strong></p><p>❌ DIP Violation — Tightly Coupled</p><pre>public class NotificationService {<br>    private final EmailSender emailSender = new EmailSender();<br>}</pre><ul><li>Can’t mock it</li><li>Can’t replace it easily</li><li>Tied to one implementation</li></ul><p>✅ DIP Fix — Use Abstraction + DI</p><pre>public class NotificationService {<br>    private final NotificationSender sender;<br><br>    public NotificationService(NotificationSender sender) {<br>        this.sender = sender;<br>    }<br>}</pre><p>Spring Boot will inject the right implementation (Email, Slack, etc.):</p><pre>@Bean<br>public NotificationSender emailSender() {<br>    return new EmailSender();<br>}</pre><p>Or simply use @Component and Spring will do the wiring.</p><p><strong>🔁 Benefit:</strong> Better testability, easier to configure, more flexibility</p><h3>Recap Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*oMPCIVedA-ZxG8qSApk2Jw.png" /></figure><h3>Final Thoughts</h3><p><strong>SOLID isn’t just academic theory.</strong> It’s a practical guide that saves real dev teams from future pain. If your classes are small, your interfaces focused, and your code easy to extend — you’re already on the right track.</p><blockquote><em>Want to write testable, maintainable, and scalable software? Start with SOLID.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38c1982aa7e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>