<?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 Swarnim Gupta on Medium]]></title>
        <description><![CDATA[Stories by Swarnim Gupta on Medium]]></description>
        <link>https://medium.com/@guptaswarnim.14?source=rss-26704fb0baad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*TWVo-BjYbwpOF6b5</url>
            <title>Stories by Swarnim Gupta on Medium</title>
            <link>https://medium.com/@guptaswarnim.14?source=rss-26704fb0baad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:38:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guptaswarnim.14/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[Keeping the Conversation Alive: Communication Techniques for Modern Web Apps]]></title>
            <link>https://medium.com/@guptaswarnim.14/keeping-the-conversation-alive-communication-techniques-for-modern-web-apps-631221bf3fde?source=rss-26704fb0baad------2</link>
            <guid isPermaLink="false">https://medium.com/p/631221bf3fde</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[server-sent-events]]></category>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <dc:creator><![CDATA[Swarnim Gupta]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 14:35:21 GMT</pubDate>
            <atom:updated>2025-09-28T14:35:21.405Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s web-driven world, <strong>how your application communicates with the server</strong> can make or break the user experience. From refreshing dashboards to instant chat messages, users expect information to be delivered <strong>fast, seamless, and in real-time</strong>.</p><p>But not all communication techniques are created equal. Some are simple to implement but put extra load on servers, while others are more efficient yet require additional infrastructure.</p><p>In this blog, we’ll break down such techniques with simple explanations and code snippets so you know exactly when to reach for which technique.</p><p><strong>Short polling:</strong></p><p>Short polling is a method where the client (e.g., a web browser) periodically sends requests to the server to check for new data or updates.</p><ul><li>Each request opens a <strong>short-lived connection</strong> with the server.</li><li>Once the server responds (even with “no updates”), the connection is closed.</li><li>After a fixed interval, the client sends another request.</li></ul><p>This approach avoids keeping long-lived connections open (as in WebSockets or Server-Sent Events) and keeps resource utilization relatively lower per connection.</p><p>However, there’s a trade-off:</p><ul><li>If there are no updates, the client is still making repeated requests, which may lead to <strong>unnecessary load</strong> on both server and network at scale.</li></ul><p><strong>Where is short polling useful ?</strong></p><p>Short polling is commonly used when:</p><ul><li>You want near real-time updates without complex infrastructure.</li><li>Systems don’t need millisecond accuracy but should feel responsive.</li></ul><p>Typical use cases:</p><ul><li>Notifications (e.g., new message indicator)</li><li>Dashboard analytics refreshes</li><li>Lightweight monitoring systems</li></ul><p><strong>Things to keep in mind:</strong></p><p>When implementing short polling:</p><ol><li>Set a reasonable polling interval — Too frequent polling can overwhelm your server; too slow reduces responsiveness.</li><li>Handle exceptions — Network failures, timeouts, or invalid responses must be caught gracefully.</li><li>Stop polling when unnecessary — For example, clear the polling interval when the user navigates away from the page.</li></ol><p><strong>Example: Short Polling in JavaScript</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;title&gt;Short Polling Example&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h2&gt;Notifications&lt;/h2&gt;<br>  &lt;div id=&quot;updates&quot;&gt;No updates yet...&lt;/div&gt;<br>  &lt;script&gt;<br>    let pollingInterval;<br>    function startPolling() {<br>      pollingInterval = setInterval(async () =&gt; {<br>        try {<br>          const response = await fetch(&quot;/api/updates&quot;);<br>          if (!response.ok) throw new Error(&quot;Network response error&quot;);<br>          const data = await response.json();<br>          if (data.hasUpdate) {<br>            document.getElementById(&quot;updates&quot;).innerText = data.message;<br>          }<br>        } catch (error) {<br>          console.error(&quot;Polling error:&quot;, error);<br>        }<br>      }, 5000); // poll every 5 seconds<br>    }<br>    function stopPolling() {<br>      clearInterval(pollingInterval);<br>    }<br>    startPolling();<br>    // Stop polling when user leaves<br>    window.addEventListener(&quot;beforeunload&quot;, stopPolling);<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Long polling:</strong></p><p>Long polling is a technique where the client sends a request to the server, but instead of responding immediately, the server <strong>keeps the connection open</strong> until:</p><ul><li>New data is available — When new data is ready, the server sends it to the client and closes the connection.</li><li>Timeout occurs — If no new data becomes available within a certain period, the server sends an empty response and closes the connection</li></ul><p>After receiving a response, the client immediately sends another request, effectively creating a chain of persistent checks.</p><p>This way, you avoid constant “empty” requests like in short polling, but you end up with <strong>long-lived connections</strong>. If you have a large number of clients, this can still mean significant load on your server.</p><p><strong>Where is long polling useful ?</strong></p><p>Long polling works well when you want near-instant delivery of updates but can’t or don’t want to use WebSockets.</p><p>Common use cases:</p><ul><li>Real-time collaboration tools (e.g., Google Docs style editing)</li><li>Live feeds (comments, activity streams)</li><li>Messaging/chat apps (before WebSockets became mainstream)</li></ul><p><strong>Things to keep in mind:</strong></p><ul><li>Each client keeps a connection open, so scaling to many users can be heavy.</li><li>The server should be optimized to handle many idle connections.</li><li>You still need to reconnect after each response (either with new data or after timeout).</li></ul><p><strong>Example: Long Polling in JavaScript</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;title&gt;Long Polling Example (Simple Stop)&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h2&gt;Chat Updates&lt;/h2&gt;<br>  &lt;div id=&quot;messages&quot;&gt;Waiting for messages...&lt;/div&gt;<br>  &lt;button onclick=&quot;stopLongPolling()&quot;&gt;Stop Polling&lt;/button&gt;<br>  &lt;script&gt;<br>    let pollingActive = true;<br>    async function startLongPolling() {<br>      if (!pollingActive) return;<br>      try {<br>        const response = await fetch(&quot;/api/messages&quot;); <br>        if (!response.ok) throw new Error(&quot;Network response error&quot;);<br>        const data = await response.json();<br>        if (data.message) {<br>          document.getElementById(&quot;messages&quot;).innerText = data.message;<br>        }<br>      } catch (error) {<br>        console.error(&quot;Long polling error:&quot;, error);<br>      } finally {<br>        if (pollingActive) startLongPolling();<br>      }<br>    }<br>    function stopLongPolling() {<br>      pollingActive = false;<br>    }<br>    startLongPolling();<br>    window.addEventListener(&quot;beforeunload&quot;, stopLongPolling);<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>WebSocket:</strong></p><p>WebSockets enable <strong>full-duplex communication</strong> between client and server over a <strong>single, long-lived TCP connection.</strong></p><ul><li>The client initiates a <strong>handshake</strong> using an HTTP request with an Upgrade header.</li><li>The server responds and upgrades the connection.</li><li>After that, both client and server can <strong>send messages to each other at any time</strong> until the connection is closed.</li></ul><p>This makes WebSockets perfect for scenarios where you need <strong>instant, two-way communication</strong>.</p><p><strong>Where are WebSockets useful ?</strong></p><p>Some classic use cases include:</p><ul><li>Online gaming (fast updates, low latency)</li><li>Financial trading platforms (live stock/crypto prices)</li><li>Real-time analytics dashboards</li><li>Chat applications and live support</li></ul><p><strong>Challenges with WebSockets:</strong></p><ul><li>Resource usage — Each open connection consumes memory and sockets</li><li>Connection limits — Browsers, servers, and proxies often cap concurrent connections</li><li>Sticky sessions — Load balancers may need to keep clients connected to the same server</li><li>Authentication — Tokens or cookies must be securely handled at connection time</li><li>Firewalls<strong> — </strong>Some environments block non-HTTP traffic</li><li>Scaling<strong> — </strong>Handling thousands (or millions) of concurrent connections can be tricky</li><li>Testing/debugging — More complex than plain HTTP</li><li>Cleanup<strong> — </strong>Always close unused connections</li><li>Connection drops<strong> — </strong>Clients should auto-reconnect when a connection is lost</li></ul><p><strong>Example: WebSocket in JavaScript</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;title&gt;WebSocket Example&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h2&gt;Live Chat&lt;/h2&gt;<br>  &lt;div id=&quot;messages&quot;&gt;&lt;/div&gt;<br>  &lt;input type=&quot;text&quot; id=&quot;input&quot; placeholder=&quot;Type a message...&quot; /&gt;<br>  &lt;button onclick=&quot;sendMessage()&quot;&gt;Send&lt;/button&gt;<br>  &lt;script&gt;<br>    const socket = new WebSocket(&quot;ws://localhost:8080&quot;);<br>    socket.addEventListener(&quot;open&quot;, () =&gt; {<br>      console.log(&quot;Connected to WebSocket server&quot;);<br>    });<br>    socket.addEventListener(&quot;message&quot;, (event) =&gt; {<br>      const msgDiv = document.getElementById(&quot;messages&quot;);<br>      const newMsg = document.createElement(&quot;p&quot;);<br>      newMsg.innerText = &quot;Server: &quot; + event.data;<br>      msgDiv.appendChild(newMsg);<br>    });<br>    function sendMessage() {<br>      const input = document.getElementById(&quot;input&quot;);<br>      if (input.value) {<br>        socket.send(input.value);<br>        input.value = &quot;&quot;;<br>      }<br>    }<br>    socket.addEventListener(&quot;error&quot;, (error) =&gt; {<br>      console.error(&quot;WebSocket error:&quot;, error);<br>    });<br>    socket.addEventListener(&quot;close&quot;, () =&gt; {<br>      console.log(&quot;Disconnected from server&quot;);<br>    });<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Server Side Events (SSE):</strong></p><p>SSE uses a <strong>long-lived unidirectional HTTP connection</strong> from the server to the client.</p><ul><li>The client opens a connection using the EventSource API.</li><li>The server responds with <strong>text/event-stream</strong> content type and keeps the connection open.</li><li>The server can then <strong>continuously send messages</strong> in a simple format (eg. {event, data ,id})</li><li>The browser automatically handles reconnection if the connection drops.</li></ul><p>This makes SSE great for <strong>lightweight, server-to-client streaming</strong>.</p><p><strong>Where are SSEs useful ?</strong></p><p>Some classic use cases:</p><ul><li>News feeds or live score updates</li><li>Social media notifications (e.g., Facebook/Twitter updates)</li><li>Monitoring dashboards</li><li>Lightweight pub-sub style broadcasting</li></ul><p><strong>Challenges with SSE:</strong></p><p>Like all real-time techniques, SSE comes with trade-offs —</p><ul><li>Browser compatibility — Supported by most modern browsers, but not in IE</li><li>Connection limits<strong> — </strong>Browsers limit the number of open connections per domain</li><li>Timeouts<strong> — </strong>Proxies or servers may kill idle connections</li><li>Background tabs <strong>— </strong>Browsers throttle background activity</li><li>Resource usage<strong> — </strong>Each client holds a persistent connection</li><li>Load balancers &amp; firewalls<strong> — </strong>May drop long-lived connections</li><li>Testing/debugging <strong>— </strong>Streams can be tricky to inspect</li><li>Broadcasting <strong>— </strong>Efficient fan-out requires server optimization.</li></ul><p><strong>Example: SSE in JavaScript</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;title&gt;SSE Example&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h2&gt;Live Notifications&lt;/h2&gt;<br>  &lt;div id=&quot;updates&quot;&gt;Waiting for updates...&lt;/div&gt;<br>  &lt;script&gt;<br>    const eventSource = new EventSource(&quot;/api/stream&quot;);<br>    eventSource.onmessage = (event) =&gt; {<br>      const updatesDiv = document.getElementById(&quot;updates&quot;);<br>      const newUpdate = document.createElement(&quot;p&quot;);<br>      newUpdate.innerText = &quot;Update: &quot; + event.data;<br>      updatesDiv.appendChild(newUpdate);<br>    };<br>    eventSource.addEventListener(&quot;news&quot;, (event) =&gt; {<br>      console.log(&quot;News Event:&quot;, event.data);<br>    });<br>    eventSource.onerror = (error) =&gt; {<br>      console.error(&quot;SSE error:&quot;, error);<br>    };<br>    function stopSSE() {<br>      eventSource.close();<br>    }<br>    window.addEventListener(&quot;beforeunload&quot;, stopSSE);<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Webhooks:</strong></p><p>A webhook is a way for one application to send <strong>real-time data to another application</strong> as soon as an event occurs.</p><ul><li>The receiving system exposes a <strong>REST API endpoint</strong> (usually POST).</li><li>The sending system calls this endpoint whenever an event happens.</li><li>The payload (often JSON) usually includes data about the event and is secured using an <strong>authorization mechanism</strong> (like a secret key or HMAC signature).</li></ul><p>This makes webhooks a <strong>push model</strong> — no need to poll or keep a connection open.</p><p><strong>Where are Webhooks Useful?</strong></p><p>Webhooks are everywhere in modern integrations:</p><ul><li>Notification systems (e.g., Stripe → send payment success notifications)</li><li>Data synchronization (e.g., CMS pushing updates to a search index)</li><li>Automation (e.g., GitHub sending events to CI/CD pipelines)</li></ul><p><strong>Challenges with Webhooks:</strong></p><ul><li>Retry mechanism<strong> — </strong>What happens if the receiving server is down? The sender must retry delivery</li><li>Verification &amp; security <strong>— </strong>You must validate that the webhook really came from the trusted source</li><li>Idempotency<strong> — </strong>Handling duplicate events gracefully</li><li>Error handling<strong> — </strong>Ensuring failures don’t silently break integrations</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=631221bf3fde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Method Overloading and null: How the Compiler Really Picks a Method]]></title>
            <link>https://medium.com/@guptaswarnim.14/java-method-overloading-and-null-how-the-compiler-really-picks-a-method-7d469ce50d05?source=rss-26704fb0baad------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d469ce50d05</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java-tips]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[method-overloading]]></category>
            <dc:creator><![CDATA[Swarnim Gupta]]></dc:creator>
            <pubDate>Sat, 10 May 2025 17:55:06 GMT</pubDate>
            <atom:updated>2025-05-10T17:55:06.859Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wondered how Java decides which overloaded method to call when you pass null? This guide breaks down method selection rules, specificity, and common pitfalls — with practical examples and clear reasoning.</p><p>Let’s start by understanding what is method selection and ambiguity.</p><p><strong>Method selection</strong></p><ul><li>Method selection is the process of finding the correct method to use in a given situation.</li><li>Correct method selection is essential for code reliability, efficiency, and maintainability.</li></ul><p><strong>Ambiguity</strong></p><ul><li>Ambiguity occurs when multiple methods are potentially applicable, making it unclear which one should be used.</li><li>This can arise from multiple definitions of a method, overloading, or ambiguous contexts.</li></ul><p><strong>Resolving ambiguity — priority and selection rules:</strong></p><ul><li><strong>Tighter first argument:</strong> In some programming languages, the method with the “tighter” or more specific first argument is often selected in case of ambiguity.</li><li><strong>Priority:</strong> Some systems assign priority to methods, with the higher-priority method being chosen in case of ambiguity.</li></ul><p>Java method overloading can get confusing when null is involved. The compiler chooses the most specific applicable method, but sometimes the call becomes ambiguous. Here&#39;s a series of examples — from basic to tricky — to deepen your understanding.</p><p><strong>Overloading with Object, char[] and Integer :</strong></p><pre>public class Test {<br><br>  public void doSomething(Object obj) { ... }<br>  <br>  public void doSomething(char[] obj) { ... }<br><br>  public void doSomething(Integer obj) { ... }<br><br>  public void testMethodSelection() {<br>    doSomething(null);<br>  }<br>}</pre><ul><li>Java will always try to use the most specific applicable version of a method that is available.</li><li>For <em>Object</em> and <em>char[]</em>, array version is more specific since Object is supertype. So, <em>char[]</em> version is chosen.</li><li>For <em>char[]</em> and <em>Integer</em>, none is more specific than the other. So, Java compiler throws ambiguous method error.</li></ul><p><strong>Overloading with Integer and int[] :</strong></p><pre>public class Test {<br><br>  public void doSomething(Integer obj) { ... }<br>  <br>  public void doSomething(int[] obj) { ... }<br><br>  public void testMethodSelection() {<br>    doSomething(null);<br>  }<br>}</pre><ul><li><em>null</em> can match both as both are reference types.</li><li>Since neither is more specific than the other, the complier throws ambiguous method error.</li></ul><p><strong>Overloading with Integer and int… :</strong></p><pre>public class Test {<br><br>  public void doSomething(Integer obj) { ... }<br>  <br>  public void doSomething(int... obj) { ... }<br><br>  public void testMethodSelection() {<br>    doSomething(null);<br>  }<br>}</pre><ul><li><em>int…</em> is syntactic sugar for <em>int[].</em> It is treated as <em>int[]</em> but marked as varargs.</li><li>Varargs methods are always lower priority than fixed-arity methods (ones that take fixed number of arguments).</li><li>Hence, the <em>Integer</em> version is selected.</li></ul><p><strong>Overloading with Serializable and String :</strong></p><pre>public class Test {<br><br>  public void doSomething(Serializable obj) { ... }<br>  <br>  public void doSomething(String obj) { ... }<br><br>  public void testMethodSelection() {<br>    doSomething(null);<br>  }<br>}</pre><ul><li><em>Serializable</em> is an interface (more generic).</li><li><em>String</em> implements <em>Serializable</em> and is a concrete class. So, this version is chosen.</li></ul><p><strong>Overloading of generics with same raw type :</strong></p><pre>public class Test {<br><br>  public void doSomething(List&lt;String&gt; obj) { ... }<br><br>  public void doSomething(List&lt;Integer&gt; obj) { ... }<br>  <br>  public void doSomething(List obj) { ... }<br><br>  public void testMethodSelection() {<br>    doSomething(null);<br>  }<br>}</pre><ul><li>Java implements generics at compile time using type erasure. Type erasure means that the compiler removes all generic type information during compilation and replaces it with raw types or bounds. This allows generic code to run on the JVM, which doesn’t understand generics.<br>So, <em>List&lt;String&gt;</em> and <em>List&lt;Integer&gt;</em> are both compiled as <em>List</em>.</li><li>Since all methods now have same signature, the compiler throws ambiguous method error.</li></ul><p><strong>Overloading with List&lt;?&gt; and Set&lt;?&gt; :</strong></p><pre>public class Test {<br><br>  public void doSomething(List&lt;Integer&gt; obj) { ... }<br>  <br>  public void doSomething(Set&lt;Integer&gt; obj) { ... }<br><br>  public void testMethodSelection() {<br>    doSomething(null);<br>  }<br>}</pre><ul><li><em>List</em> and <em>Set</em> are siblings; neither is a subtype of other. So, the compiler throws ambiguous method error.</li></ul><p><strong>Overloading with interface and superclass :</strong></p><pre>public interace I {}<br>public class A {}<br>public class B extends A implements I {}<br><br>public class Test {<br><br>  public void doSomething(A obj) { ... }<br>  <br>  public void doSomething(I obj) { ... }<br><br>  public void testMethodSelection() {<br>    B b = null;<br>    doSomething(b);<br>  }<br>}</pre><ul><li><em>B </em>matches both overloads, as it extends <em>A</em> and implements <em>I</em>.</li><li>Since neither <em>A</em> nor <em>I</em> is more specific than the other, the compiler throws ambiguous method error.</li></ul><p><strong>Overloading with Interface in Superclass Chain :</strong></p><pre>public interface I {}<br>public class A implements I {}<br>public class B extends A {}<br><br>public class Test {<br>    public void doSomething(A obj) { ... }<br>    public void doSomething(I obj) { ... }<br><br>    public void testMethodSelection() {<br>        B b = null;<br>        doSomething(b);<br>    }<br>}</pre><ul><li><em>doSomething(A obj)</em> is valid as <em>B</em> extends <em>A</em>.</li><li><em>doSomething(A obj) </em>is valid as <em>B</em> inherits from <em>A</em>, which implements <em>I</em>.</li><li>So, now compiler compares between <em>A</em> and <em>I</em>. Since <em>A</em> is more specific, <em>doSomething(A obj)</em> is chosen.</li></ul><p><strong>Overloading with subclass :</strong></p><pre>public class A {}<br>public class B extends A {}<br><br>public class Test {<br><br>  public void doSomething(A obj) { ... }<br>  <br>  public void doSomething(B obj) { ... }<br><br>  public void testMethodSelection() {<br>    doSomething(null);<br>  }<br>}</pre><ul><li><em>B</em> is a subclass of <em>A</em>. So, this version is chosen.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d469ce50d05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Design Principles]]></title>
            <link>https://medium.com/@guptaswarnim.14/solid-design-principles-75a19aeb2369?source=rss-26704fb0baad------2</link>
            <guid isPermaLink="false">https://medium.com/p/75a19aeb2369</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Swarnim Gupta]]></dc:creator>
            <pubDate>Sat, 03 May 2025 18:04:38 GMT</pubDate>
            <atom:updated>2025-05-03T18:04:38.116Z</atom:updated>
            <content:encoded><![CDATA[<p>SOLID is the acronym for the five design principles that form the basis of object-oriented design(OOD). As a Java developer, I’ll be discussing why the knowledge of these principles is important while designing applications, and try to explain each principle by mapping them as close as possible to real-life scenarios.</p><p><strong>Importance of SOLID principles as a developer:</strong></p><ul><li>Most logical approach to build and maintain growing applications if you understand the nuances of an object-oriented environment.</li><li>Common pattern followed by most developers while working on projects. So, it is easy to understand and adapt to the coding practices followed by an organisation.</li><li>If followed correctly, they make your code easy to read and work on in the future. In addition, they make it easier to add functionalities to existing code without much reorganisation.</li></ul><p><strong>S.O.L.I.D principles:</strong></p><ul><li>Single Responsibility</li><li>Open/Closed</li><li>Liskov Substitution</li><li>Interface Segregation</li><li>Dependency Inversion</li></ul><p><strong>Single Responsibility:</strong></p><blockquote>Each class should only have one responsibility. <br>Each class should have only one reason to change.</blockquote><ul><li>Let’s take the example of a service responsible for managing Student entity.</li></ul><pre>public class StudentService {<br><br>  public void saveStudentDetails(Student student) {...}<br>  public Student getStudentById(int id) {...}<br>  public void sendNotification(Student student) {...}<br><br>}</pre><ul><li>Here, the methods to save and get student details make sense. But the method of sending notification is only partially related. It would make more sense to form the notification payload with student details in our service and have a separate NotificationService send the notification. Some other reasons are<br>- Reusability of sendNotification method since the process of sending <br> notification would be same for an application.<br>- If you create methods for sending notification in each entity and there <br> is a change in, say, the authKey added in notification provider, you will <br> have to go in each entity’s service and make the changes.</li><li>Advantages — <br>- Each class has a well-defined purpose, leading to better code <br> organization.<br>- We can modify any class without affecting others, reducing <br> complexity.</li></ul><p><strong>Open / Closed:</strong></p><blockquote>Software entities (classes, objects, etc.) should be open for extension but closed for modification.</blockquote><ul><li>Suppose you manage a gift card store where there are departments handling different functions of the card generating process. There is a department that gets user details required for the card; another for processing the card; another for packaging the card. All of them handle different types of gift cards in different ways.<br>Now, if there is a new gift card introduced, you would have to go to each department and tell them how to handle that new card. This is required every time a new gift card is introduced, or even when an existing one is discontinued. It will be tedious and there can be errors if you forgot to update even one department about the changes.</li><li>Taking the same example —</li></ul><pre>public class GiftCardGenerator {<br>  public void getUserDetails(Card card) {<br>    if(Card.BIRTHDAY == card) {<br>      //get details for birthday gift card<br>    } else if (Card.ANNIVERSARY == card){<br>      //get details for anniversary gift card<br>    } else ...<br>  }<br>  <br>  public void processCard(Card card) {<br>    if(Card.BIRTHDAY == card) {<br>      //process birthday gift card<br>    } else if (Card.ANNIVERSARY == card){<br>      //process anniversary gift card<br>    } else ...<br>  }<br><br>  public void packageCard(Card card) {<br>    if(Card.BIRTHDAY == card) {<br>      //package birthday gift card<br>    } else if (Card.ANNIVERSARY == card){<br>      //package anniversary gift card<br>    } else ...<br>  }<br>}</pre><ul><li>It would be much easier if there is a central checkpoint for all processes that have to be done for each card, and if the departments are organised by card type. So, each department would just be responsible to adhere to the checklist and process the respective card accordingly.</li></ul><pre>public interface GiftCardGenerator {<br>  void getUserDetails();<br>  void processCard();<br>  void packageCard();<br>}<br><br>public class BirthdayCardGenerator implements GiftCardGenerator {<br>  //implement all methods<br>}<br><br>public class AnniversaryCardGenerator implements GiftCardGenerator {<br>  //implement all methods<br>}</pre><ul><li>Advantages — <br>- We can add new functionality without introducing bugs to existing <br> working functionality.<br>- This makes the code flexible and adaptable.</li></ul><p><strong>Liskov’s substitution:</strong></p><blockquote>If a class A is subtype of class B, we should be able to replace B with A without disrupting the behaviour of the program.</blockquote><ul><li>The example of rectangle and square makes understanding the proper implementation of this principle clear. We all know that square is a type of rectangle having same width and height values. <br>So, if we were to make Square a subclass of Rectangle, would it be right?</li></ul><pre>public class Rectangle {<br>  private int width;<br>  private int height;<br><br>  public void setWidth(int width) {<br>    this.width = width;<br>  }<br><br>  public void setHeight(int height) {<br>    this.height = height;<br>  }<br><br>  public void printArea() {<br>    System.out.println(width * height);<br>  }<br>}<br><br>public class Square extends Rectangle {<br>  @Override<br>  public void setWidth(int width) {<br>    this.width = width;<br>    this.height = width;<br>  }<br><br>  @Override<br>  public void setHeight(int height) {<br>    this.width = height;<br>    this.height = height;<br>  }<br>}<br><br>public class LSPTest {<br>  Rectangle r1 = new Rectangle();<br>  r1.setWidth(2);<br>  r1.setHeight(3);<br>  r1.printArea(); //prints 6<br><br>  Square s = new Square();<br>  s.setWidth(5);<br>  s.printArea(); //prints 25<br><br>  Rectangle r2 = new Square();<br>  r1.setWidth(2);<br>  r1.setHeight(3);<br>  r1.printArea(); //prints 9(wrong)<br>}</pre><ul><li>This looks ok at first glance but it violates Liskov’s principle as we cannot substitute Rectangle class with Square class. This is because Square changes the fundamental behaviour of Rectangle (width and height cannot be different). This also violates OCP as the subclass is modifying the parent class.<br>We can instead define a Shape interface and use it to implement Rectangle and Square classes independently.</li></ul><pre>public interface Shape {<br>    void printArea();<br>} <br><br>public class Rectangle implements Shape {<br>  private int width;<br>  private int height;<br><br>  public void setWidth(int width) {<br>    this.width = width;<br>  }<br><br>  public void setHeight(int height) {<br>    this.height = height;<br>  }<br><br>  @Override<br>  public void printArea() {<br>    System.out.println(width * height);<br>  }<br>}<br><br>public class Square implements Shape {<br>  private int side;<br><br>  public void setSide(int side) {<br>    this.side = side;<br>  }<br><br>  @Override<br>  public void printArea() {<br>    System.out.println(side * side);<br>  }<br>}</pre><ul><li>Advantages — <br>- It ensures that subclasses maintain the functionality of their parent <br> class (supporting OCP)</li></ul><p><strong>Interface segregation:</strong></p><blockquote>Larger interfaces should be split into smaller ones, such that implementing classes only need to be concerned about the methods that interest them.</blockquote><ul><li>The best example would be of the bird kingdom. There are different type of birds — some can fly, while some can only float in water. <br>To say all birds can implement flying and floating on a broader level would be misleading. So, we further categorise them into flying birds and floating birds respectively.</li><li>Taking the same example for code demonstration, wrong implementation would be something like below —</li></ul><pre>public interface Bird {<br>  void hasBeak();<br>  void hasWings();<br>  void fly();<br>  void float();<br>}<br><br>public class Eagle implements Bird{<br>  ...<br>  @Override <br>  public void fly() {<br>    //implement flying<br>  }<br><br>  @Override <br>  public void float() {<br>    System.out.println(&quot;Action not allowed&quot;);<br>  }<br>}<br><br>public class Penguin implements Bird{<br>  ...<br>  @Override <br>  public void fly() {<br>    System.out.println(&quot;Action not allowed&quot;);<br>  }<br><br>  @Override <br>  public void float() {<br>    //implement floating<br>  }<br>}</pre><ul><li>The methods defined in the interface are misleading, and you wouldn’t know if any of these methods are not implemented unless you check each of the implementing classes.<br>A better implementation where only concerned methods are overridden would be</li></ul><pre>public interface Bird {<br>  void hasBeak();<br>  void hasWings();<br>}<br><br>public interface FlyingBird {<br>  void fly();<br>}<br><br>public interface FloatingBird {<br>  void float();<br>}<br><br>public class Eagle implements Bird, FlyingBird{<br>  ...<br>  @Override <br>  public void fly() {<br>    //implement flying<br>  }<br>}<br><br>public class Penguin implements Bird, FloatingBird{<br>  ...<br>  @Override <br>  public void float() {<br>    //implement floating<br>  }<br>}</pre><ul><li>Advantages — <br>- Interfaces are more focused, making the code more understandable.<br>- Classes can implement only the interfaces they need, promoting code <br> reuse and reducing redundancy.</li></ul><p><strong>Dependancy inversion:</strong></p><blockquote>Instead of high-level modules depending on low-level modules, both should depend on abstractions.</blockquote><ul><li>Say, we want to order pizza in a restaurant. Different restaurants have different systems for maintaining and processing customer orders. To learn how to use such systems in each restaurant will be tiring and time-consuming. So, instead, we have an abstraction layer of waiters who take customer orders and feed the data for processing according to the restaurant’s system.<br>So, the “customer” layer is only concerned about placing their orders and receiving them, while the logic of storing and processing these orders is done by the “waiter” layer.</li><li>Now, let’s take the example of a service which makes call to the database for fetching some data.</li></ul><pre>public class UserService {<br><br>  private UserRepository userRepository;<br><br>  public void printActiveUsers() {<br>    String query = &quot;SELECT * FROM USER WHERE ACTIVE=1;&quot;;<br>    List&lt;User&gt; activeUsers = userRepository.executeCommand(query);<br>    for(User user: activeUsers) {<br>      System.out.println(&quot;UID: &quot; + user.getId());<br>      System.out.println(&quot;Name: &quot; + user.getName());<br>    }<br>  }<br><br>}</pre><ul><li>Here, the service is tightly coupled with the repository. If we want to migrate to another type of database, we would have to make changes in the service layer. <br>It also doesn’t make sense for the service layer to be concerned about the logic for interacting with the database. It should only know that it has to call a certain method and expected data would be received from the repository layer.</li><li>Instead, we can add an abstraction for the repository layer and implement the required methods in its implementing class. This way, even if we migrate to another database, we would just have to change the implementing class without any changes in the service layer.</li></ul><pre>public class UserService {<br><br>  private UserRepository userRepository;<br><br>  public void printActiveUsers() {<br>    List&lt;User&gt; activeUsers = userRepository.getActiveUsers();<br>    for(User user: activeUsers) {<br>      System.out.println(&quot;UID: &quot; + user.getId());<br>      System.out.println(&quot;Name: &quot; + user.getName());<br>    }<br>  }<br>}<br><br>public interface UserRepository {<br>  List&lt;User&gt; getActiveUsers();<br>}<br><br>public class UserRepositoryImpl implements UserRepository {<br>  <br>  @Override<br>  public List&lt;User&gt; getActiveUsers() {<br>    String query = &quot;SELECT * FROM USER WHERE ACTIVE=1;&quot;;<br>    return executeCommand(query);<br>  }<br>}</pre><ul><li>Advantages — <br>- Loose coupling between classes makes the code more modular and <br> reusable.<br>- Makes it easier to test and modify code.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75a19aeb2369" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>