<?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 Shivanshu Goyal on Medium]]></title>
        <description><![CDATA[Stories by Shivanshu Goyal on Medium]]></description>
        <link>https://medium.com/@shivanshugoyal0111?source=rss-bad57cfd891d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JwXzgxq2H1mI5La_MltgUw.png</url>
            <title>Stories by Shivanshu Goyal on Medium</title>
            <link>https://medium.com/@shivanshugoyal0111?source=rss-bad57cfd891d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 20:50:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivanshugoyal0111/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[Reactive Programming with Spring Boot & Tomcat]]></title>
            <link>https://medium.com/geekculture/reactive-programming-with-spring-boot-tomcat-3406e7311ca6?source=rss-bad57cfd891d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3406e7311ca6</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[tomcat]]></category>
            <dc:creator><![CDATA[Shivanshu Goyal]]></dc:creator>
            <pubDate>Sun, 18 Jan 2026 21:12:34 GMT</pubDate>
            <atom:updated>2026-01-18T21:12:34.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*88JsseO7ltGWQui3ZE_8xg.png" /></figure><blockquote><em>A beginner‑friendly explanation of reactive programming using </em><strong><em>Spring Boot</em></strong><em>, </em><strong><em>Tomcat</em></strong><em>, and </em><strong><em>Project Reactor</em></strong><em>, focused on </em>how it really works<em>, </em>what runs where<em>, and </em>when you should (or should not) use it<em>.</em></blockquote><h3>1. Why Reactive Programming Exists</h3><p>Traditional server applications follow a <strong>thread‑per‑request</strong> model:</p><ul><li>One request</li><li>One server thread</li><li>That thread waits (blocks) during I/O</li></ul><p>This works well at low to moderate load, but breaks down when:</p><ul><li>You have <strong>many concurrent requests</strong></li><li>Most of the time is spent <strong>waiting on I/O</strong> (HTTP calls, DB, file systems)</li></ul><p>Reactive programming exists to:</p><blockquote><strong><em>Use fewer threads to handle more concurrent I/O‑bound requests efficiently.</em></strong></blockquote><h3>2. Reactive ≠ Async ≠ Non‑Blocking (Important Distinction)</h3><p>Before code, align on terminology:</p><ul><li><strong>Async</strong>: Work happens later, possibly on another thread</li><li><strong>Non‑blocking</strong>: Threads are not parked waiting for I/O</li><li><strong>Reactive</strong>: A <em>data pipeline</em> that is lazy, event‑driven, and back‑pressure aware</li></ul><p>Reactive programming is not just about threads — it is about <strong>controlling data flow and execution boundaries</strong>.</p><h3>3. Mono &amp; Flux: Pipelines, Not Executions</h3><p>In Project Reactor:</p><ul><li>Mono&lt;T&gt; → 0 or 1 value</li><li>Flux&lt;T&gt; → 0 to N values</li></ul><p>A critical rule:</p><blockquote><strong><em>Without subscription, nothing executes.</em></strong></blockquote><pre>Mono&lt;String&gt; mono = Mono.just(&quot;A&quot;)<br>        .map(v -&gt; v + &quot;B&quot;);</pre><p>At this point:</p><ul><li>No thread is used</li><li>No work is done</li><li>This is only a <em>definition</em></li></ul><p>Execution starts <strong>only when someone subscribes</strong>.</p><h3>4. Who Subscribes in a Spring Boot App?</h3><p>When you return a Mono from a controller:</p><pre>@GetMapping(&quot;/data&quot;)<br>public Mono&lt;String&gt; getData() {<br>    return serviceMethod();<br>}</pre><p>👉 <strong>Spring Framework subscribes for you</strong>.</p><ul><li>In Spring MVC: subscription is managed by async adapters</li><li>In Spring WebFlux: subscription is native</li></ul><p>You should <strong>never call </strong><strong>subscribe() manually</strong> in controllers.</p><h3>5. A Complete Controller → Service → Repository Example</h3><p>Let’s look at a realistic flow.</p><h4>Controller</h4><pre>public Mono&lt;String&gt; controllerMethod() {<br>    return serviceMethod()<br>            .doOnSubscribe(s -&gt; System.out.println(&quot;Controller: subscribed&quot;))<br>            .map(result -&gt; result + &quot; | Controller&quot;)<br>            .doOnNext(v -&gt; System.out.println(&quot;Controller received: &quot; + v));<br>}</pre><h4>Service</h4><pre>public Mono&lt;String&gt; serviceMethod() {<br>    return repositoryMethod()<br>            .doOnSubscribe(s -&gt; System.out.println(&quot;Service: subscribed&quot;))<br>            .flatMap(result -&gt; asyncEnhance(result))<br>            .doOnNext(v -&gt; System.out.println(&quot;Service processed: &quot; + v));<br>}<br><br><br>public Mono&lt;String&gt; asyncEnhance(String input) {<br>    return Mono.fromCallable(() -&gt; {<br>        System.out.println(&quot;AsyncEnhance: running&quot;);<br>        return input + &quot; | ServiceAsync&quot;;<br>    });<br>}</pre><h4>Repository (Data Source)</h4><pre>public Mono&lt;String&gt; repositoryMethod() {<br>    return Mono.fromCallable(() -&gt; {<br>        System.out.println(&quot;Repository: producing data&quot;);<br>        return &quot;RepoData&quot;;<br>    }).doOnSubscribe(s -&gt; System.out.println(&quot;Repository: subscribed&quot;))<br>      .doOnNext(v -&gt; System.out.println(&quot;Repository: doOnNext -&gt; &quot; + v));<br>}</pre><h4>Data execution flow along with subscription (logs) 📁</h4><pre>Controller: subscribed<br>Service: subscribed<br>Repository: subscribed<br><br><br>Repository: producing data<br>Repository: doOnNext -&gt; RepoData<br>AsyncEnhance: running<br>Service processed: RepoData | ServiceAsync<br>Controller received: RepoData | ServiceAsync | Controller</pre><h3>6. Subscription Flow vs Data Flow</h3><p>This is where most confusion comes from.</p><h4>Subscription Flow (Top → Down)</h4><pre>Controller → Service → Repository</pre><p>Spring subscribes at the controller boundary, and the subscription travels <strong>down</strong> to the data source.</p><h4>Data Flow (Bottom → Up)</h4><pre>Repository → Service → Controller → HTTP Response</pre><p>Data is produced only at the <strong>source</strong> (repository), then flows upward through the pipeline.</p><blockquote><em>Subscription goes </em>down<em>. Data comes </em>up<em>.</em></blockquote><h3>7. What Is the Source of Data?</h3><p>A source is any operator that <strong>creates data</strong>:</p><ul><li>Mono.fromCallable(...) → CPU / blocking source</li><li>WebClient.retrieve() → non‑blocking I/O source</li><li>Mono.just(...) → in‑memory source</li></ul><p>Everything else (map, flatMap, doOnNext) <strong>does not create data</strong> — it only reacts to it.</p><h3>8. map vs flatMap: Sync vs Async Transformation</h3><h4>map — synchronous transformation</h4><pre>.map(v -&gt; v + &quot;X&quot;)</pre><ul><li>Executes immediately when data is available</li><li>Must not block</li><li>Returns a value</li></ul><h4>flatMap — asynchronous transformation</h4><pre>.flatMap(v -&gt; asyncCallReturningMono(v))</pre><ul><li>Used when the transformation itself is async</li><li>Returns a Mono</li><li>Flattens Mono&lt;Mono&lt;T&gt;&gt; into Mono&lt;T&gt;</li></ul><p>Use rule:</p><blockquote><em>If the lambda returns a value → </em><em>map<br>If it returns a </em><em>Mono → </em><em>flatMap</em></blockquote><h3>9. Threads in Tomcat + Reactive Applications</h3><h4>Threads Involved</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNcjzw1mtwwVAwo-0IOrcw.png" /></figure><p>Tomcat threads <strong>do not stay blocked</strong> when using reactive return types.</p><h3>10. Blocking vs Non‑Blocking (Critical Section)</h3><h4>Blocking operations</h4><ul><li>JDBC</li><li>File I/O</li><li>Synchronous REST calls</li><li>Thread.sleep()</li><li>Heavy CPU serialization</li></ul><p>Blocking means:</p><blockquote><em>A thread is occupied while waiting</em></blockquote><p>Blocking on reactor threads reduces throughput and scalability.</p><h3>11. publishOn: When and Why</h3><p>publishOn changes <strong>where downstream operators execute</strong>.</p><h4>Use publishOn when:</h4><ul><li>Data arrives on a non‑blocking thread</li><li>You must run blocking or CPU‑heavy work next</li></ul><pre>return webClientCall()<br>    .publishOn(Schedulers.boundedElastic())<br>    .map(resp -&gt; blockingParsing(resp));</pre><h4>What this code is trying to achieve</h4><ul><li>webClientCall() → <strong>non-blocking I/O</strong> (Netty event-loop thread)</li><li>blockingParsing(resp) → <strong>CPU-heavy or blocking work</strong> (JSON parsing, JAXB, file IO, crypto, etc.)</li><li>publishOn(boundedElastic) → <strong>move blocking work off the event loop</strong></li></ul><p>This is <strong>correct usage</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7K8Rve89e-cKszuh2nn1g.png" /></figure><h4>Why is this a BIG problem?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVyo9csFYEOA7mqBIOfjmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OaxYc1o6feq_hSX5OqlDfQ.png" /></figure><h4>What publishOn actually fixes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BI72w-8tZB36Aww5nt-xCQ.png" /></figure><h3>12. subscribeOn vs publishOn (Mental Model)</h3><ul><li>subscribeOn → controls where the <strong>source</strong> runs</li><li>publishOn → controls where <strong>downstream</strong> runs</li></ul><p>Most applications need publishOn more than subscribeOn.</p><h3>13. API Caller Experience</h3><p>From the API caller’s perspective:</p><ul><li>Response is still synchronous HTTP</li><li>Latency depends on downstream services</li><li>Server scales better under load</li></ul><p>Reactive changes <strong>server internals</strong>, not the HTTP contract.</p><p><strong>With Tomcat, the API caller experience is still blocking</strong>, even if your server-side code is reactive.</p><h4>a) What “blocking” means for an API caller</h4><p>From an <strong>API caller’s point of view</strong> (browser, mobile app, another service):</p><ul><li>They send an HTTP request</li><li>They <strong>wait</strong> until: the server sends a response <strong>or </strong>a timeout occurs</li></ul><p>There is <strong>no such thing as a “non-blocking HTTP call” for the caller</strong>.</p><p>👉 <strong>HTTP is request–response</strong><br> 👉 The caller is always waiting for the response</p><p>So even if:</p><ul><li>You use <strong>Reactive programming</strong></li><li>You use <strong>WebClient</strong></li><li>You use <strong>virtual threads</strong></li></ul><p><strong>The caller still blocks waiting for the response</strong>.</p><h4>b) What changes with reactive programming is NOT the caller</h4><p>Reactive programming <strong>does NOT change the caller experience</strong>.</p><p>What it changes is:</p><blockquote><strong><em>How the server uses threads while the caller is waiting</em></strong></blockquote><h4>c) Tomcat + traditional (Servlet MVC) model</h4><h4>Thread model</h4><ul><li>Tomcat accepts the request</li><li>Assigns <strong>one Tomcat worker thread</strong></li><li>That thread: executes controller; calls service; waits for DB / HTTP / IO</li><li>Thread stays <strong>blocked</strong> until response is ready</li></ul><h4>Result</h4><ul><li>Caller waits (blocking) ❌</li><li><strong>Tomcat thread also waits (blocked)</strong> ❌</li><li>Limited scalability</li></ul><pre>Caller ----waits----&gt; [ Tomcat Thread BLOCKED ]</pre><h4>d) Tomcat + Reactive (Spring WebFlux on Tomcat)</h4><p>This is where confusion usually starts.</p><h4>Important fact</h4><blockquote><strong><em>Tomcat is still a Servlet container</em></strong></blockquote><p>Even with WebFlux:</p><ul><li>Tomcat thread receives the request</li><li>Spring subscribes to your Mono / Flux</li><li>Response is written <strong>only when data arrives</strong></li></ul><h4>What changes?</h4><ul><li><strong>Tomcat thread is NOT blocked during IO</strong></li><li>It is released back to the pool</li><li>Reactor threads handle async signals</li></ul><h4>Result</h4><ul><li>Caller waits (blocking) ❌ (same as before)</li><li><strong>Tomcat thread is freed</strong> ✅</li><li>Better thread utilization</li></ul><pre>Caller ----waits----&gt; [ Response pending ]<br>                   Tomcat thread: FREE<br>                   Reactor threads: working</pre><h4>e) Why the caller still feels blocking</h4><p>Because:</p><ul><li>HTTP connection stays open</li><li>Caller cannot proceed until response arrives</li><li>TCP socket is held open</li></ul><p>Reactive does <strong>not</strong> mean:</p><ul><li>Streaming response instantly (unless you use SSE/Flux)</li><li>Fire-and-forget (unless async messaging)</li></ul><h4>f) What reactive actually optimizes</h4><p>Reactive optimizes <strong>server-side scalability</strong>, not caller behavior.</p><h4>Without reactive</h4><ul><li>200 concurrent callers</li><li>200 Tomcat threads blocked</li></ul><h4>With reactive</h4><ul><li>200 concurrent callers</li><li>Maybe: 20 Tomcat threads; Few Reactor threads</li><li>Threads are reused efficiently</li></ul><h4>g) When does caller experience change?</h4><p>Only in these cases:</p><h4>1️⃣ Streaming APIs (Flux)</h4><ul><li>Server sends partial data</li><li>Caller processes chunks</li><li>Still waiting, but <strong>progressively</strong></li></ul><h4>2️⃣ Async fire-and-forget</h4><ul><li>Caller gets 202 Accepted</li><li>Actual work happens later</li></ul><h4>3️⃣ WebSockets / SSE</h4><ul><li>Persistent connection</li><li>Event-driven communication</li></ul><p>👉 <strong>Normal REST </strong><strong>Mono&lt;T&gt; → still blocking for caller</strong></p><h3>14. When Should You Use Reactive Programming?</h3><p>Use it when:</p><ul><li>Workload is I/O‑heavy</li><li>High concurrency is required</li><li>You use non‑blocking clients (WebClient)</li></ul><p>Avoid it when:</p><ul><li>Work is CPU‑heavy</li><li>Codebase is simple CRUD</li><li>Team is unfamiliar with reactive concepts</li></ul><blockquote><em>In many cases, </em><strong><em>virtual threads are a simpler alternative</em></strong><em>.</em></blockquote><h3>Final Thought</h3><p>Reactive programming is powerful, but unforgiving.</p><blockquote><em>It rewards correctness and punishes misunderstanding.</em></blockquote><p>If you understand:</p><ul><li>Subscription vs data flow</li><li>Blocking vs non‑blocking</li><li>Thread boundaries</li></ul><p>Then reactive programming becomes a <strong>scalable, elegant tool</strong> — not magic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3406e7311ca6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/reactive-programming-with-spring-boot-tomcat-3406e7311ca6">Reactive Programming with Spring Boot &amp; Tomcat</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Model Context Protocol: Connecting AI to Everything That Matters]]></title>
            <link>https://shivanshugoyal0111.medium.com/the-model-context-protocol-connecting-ai-to-everything-that-matters-8258eafcf343?source=rss-bad57cfd891d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8258eafcf343</guid>
            <category><![CDATA[mcp-client]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[ai-agent-development]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Shivanshu Goyal]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 06:25:59 GMT</pubDate>
            <atom:updated>2025-10-03T06:34:33.804Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>The LLM Revolution: From Text Generation to Action</strong></h4><p>Large Language Models (LLMs) have evolved dramatically since their inception. What began as sophisticated text generators have become reasoning engines capable of understanding complex instructions, analyzing data, and even writing code. But for all their linguistic brilliance, early LLMs had a fundamental limitation: <strong>they existed in isolation</strong>.</p><p>These models could tell you how to book a flight, but they couldn’t actually book one. They could write SQL queries, but couldn’t execute them against your database. They could suggest fixes to your code, but couldn’t apply the changes. The AI lived in a bubble, disconnected from the digital world we wanted it to help us navigate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38pPZAwCMbdWBgRSCkPtig.png" /><figcaption>LLM generates text based only on input — no external data used</figcaption></figure><h4>The Tool Calling Breakthrough</h4><p>The introduction of <strong>tool calling</strong> (also known as function calling) changed everything. Suddenly, LLMs could:</p><ol><li>Execute Python functions to perform calculations</li><li>Make API calls to retrieve real-time data</li><li>Interact with databases and file systems</li><li>Control external applications and services</li></ol><pre># Example: LLM can now call functions<br>def get_weather(city: str) -&gt; dict:<br>  return {&quot;city&quot;: city, &quot;temp&quot;: 72, &quot;condition&quot;: &quot;sunny&quot;}<br><br># AI model invokes: get_weather(&quot;Seattle&quot;)<br># Result: {&quot;city&quot;: &quot;Seattle&quot;, &quot;temp&quot;: 72, &quot;condition&quot;: &quot;sunny&quot;}</pre><p>This breakthrough transformed LLMs from mere text processors into <strong>agents</strong> capable of taking real-world action. But with great power came great complexity.</p><p><strong>The Tool Calling Integration Nightmare</strong></p><p>As tool calling gained adoption, developers quickly ran into the dreaded <strong>“N×M integration problem”</strong>:</p><ol><li><strong>Every AI system</strong> needs to integrate with <strong>every external service.</strong></li><li>Each integration requires custom connectors and authentication</li><li>Different tools use different data formats and error handling</li><li>Maintenance overhead scales exponentially</li></ol><p><strong>Picture building an AI assistant for your company that needs to:</strong></p><ol><li>Access your CRM (Salesforce API)</li><li>Query your database (custom SQL connector)</li><li>Read files from Google Drive (Google APIs)</li><li>Send Slack messages (Slack SDK)</li><li>Monitor system logs (custom log parsers)</li></ol><p><strong>Each integration demands:</strong></p><ul><li>✅ Custom API clients and authentication flows</li><li>✅ Unique error handling and retry logic</li><li>✅ Different data serialization formats</li><li>✅ Separate documentation and testing</li><li>✅ Individual maintenance overhead</li></ul><p>The result? A tangled web of integrations that’s expensive to build, painful to maintain, and nearly impossible to scale across multiple AI applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMiUpnpI0VPy714SxyXC3g.png" /><figcaption>N AI agents are talking to M external systems via tools</figcaption></figure><p>Each agent currently requires its own integration (tool or function) to connect to an external service or system. This means we end up building <strong>N separate integrations for N agents</strong>, even if they all need access to the same GitHub functionality. The proposed idea is to create a <strong>single GitHub integration</strong> that can be shared and reused by any agent worldwide, eliminating duplication and ensuring consistency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NpqZ-LHXusjOwl3WQ7M6eQ.png" /></figure><p>Server does the heavy lifting instead of every client writting the integration for same functionality again and again.</p><ul><li>Authentication with github</li><li>API rate limiting</li><li>Error handling</li><li>Data format translation</li></ul><p>Client should be just connecting to the server using the same language.</p><h4>Enter the Model Context Protocol: The Universal Solution</h4><p>This is where the <strong>Model Context Protocol (MCP)</strong> comes in. Introduced by Anthropic in November 2024, MCP is an open standard that solves the tool calling integration crisis by providing a <strong>universal interface</strong> between AI systems and external tools.</p><p>Think of MCP as “USB-C for AI integrations” — one protocol to connect them all.</p><p><strong>What is the Model Context Protocol?</strong></p><p>The <strong>Model Context Protocol (MCP)</strong> is a <strong>protocol (set of rules and standards)</strong> that defines how AI models (like LLMs) can <strong>connect to external tools, data sources, and services</strong> in a consistent and standardized way</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yDXSqeGD8FlHRC6VuXfQdA.png" /><figcaption>Model Context Protocol</figcaption></figure><h4>MCP Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*jQk49hj1BBoy9_E-fZH4Lw.png" /><figcaption>MCP Architecture</figcaption></figure><p>MCP follows a client-server architecture where an MCP host — an AI application like <a href="https://www.claude.ai/download">Claude Desktop</a> — establishes connections to one or more MCP servers. The MCP host accomplishes this by creating one MCP client for each MCP server. Each MCP client maintains a dedicated <strong>one-to-one connection</strong> with its corresponding MCP server. The key participants in the MCP architecture are:</p><ul><li><strong>MCP Host </strong>🏠<strong>:</strong> The AI application that coordinates and manages one or multiple MCP clients</li><li><strong>MCP Client </strong>👤<strong>: </strong>A component that maintains a connection to an MCP server and obtains context from an MCP server for the MCP host to use</li><li><strong>MCP Server </strong>🗄️<strong>:</strong> A program that provides context to MCP clients</li></ul><h4>MCP Primitives</h4><p>MCP primitives are the most important concept within MCP. They define what clients and servers can offer each other. These primitives specify the types of contextual information that can be shared with AI applications and the range of actions that can be performed.</p><p>MCP Server has 3 core primitives — think of them as the basic building blocks that make everything work:</p><h4>1. Resources 📁 (Things to Read)</h4><p>Static information that AI can access and read from:</p><ul><li>Files (documents, spreadsheets, code)</li><li>Database records</li><li>Web pages or API responses</li><li>Documentation or knowledge bases</li></ul><blockquote><strong><em>Simple analogy: Like books on a shelf — the AI can read them but they don’t change.</em></strong></blockquote><h4>2. Tools 🔧 (Things to Do)</h4><p>Dynamic actions that AI can perform:</p><ul><li>Run calculations or execute code</li><li>Send emails or Slack messages</li><li>Query databases or APIs</li><li>Create/update/delete records</li></ul><blockquote><strong><em>Simple analogy: Like tools in a toolbox — the AI can pick them up and use them to accomplish tasks.</em></strong></blockquote><h4>3. Prompts 💬 (Templates for Instructions)</h4><p>Reusable instruction templates that provide context:</p><ul><li>Pre-written prompts for common scenarios</li><li>Context about how to use specific tools</li><li>Guidelines for handling certain types of data</li><li>Best practices for specific domains</li></ul><blockquote><strong><em>Simple analogy: Like recipe cards — they tell the AI the right way to approach different situations.</em></strong></blockquote><p><strong>In essence:</strong></p><ul><li>Resources = “What can I read?”</li><li>Tools = “What can I do?”</li><li>Prompts = “How should I do it?”</li></ul><p>These three primitives work together to let AI systems interact with the world in a standardized way, rather than each AI needing custom code for every single integration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wSFfz0ncXtJBb9Gtz8m6Qg.png" /><figcaption>Primitives → Standard Operations</figcaption></figure><h4>The MCP client is equally important, sharing its core features with the server.</h4><h4>1. Sampling</h4><p><strong>What it is / Purpose</strong></p><ul><li><strong>Sampling</strong> is a mechanism whereby an MCP server can ask the client to invoke the language model (LLM) on its behalf. In other words, servers can send a request for the client to generate completions or reasoning.</li><li>This allows <strong>agentic workflows</strong>: the server can rely on the client’s access to AI capabilities without needing to integrate directly with a language model.</li></ul><p><strong>How it works / Flow</strong></p><ul><li>The server sends a sampling request, including the “messages” (prompt/context), model preferences, system prompt, and other parameters.</li><li>The client then performs the LLM call in its own environment, respecting user permissions, security boundaries, etc.</li><li>Because sampling is invoked inside the broader tool or operation context, it helps keep <strong>clear boundaries</strong> between operations and avoids polluting context windows.</li></ul><p><strong>User Interaction &amp; Safety</strong></p><ul><li>Clients typically allow <strong>human-in-the-loop</strong> controls. A sampling request may require user approval. The client can show the prompt, model choice, and token limits for transparency.</li><li>Users might have options to <strong>pre-approve</strong>, <strong>deny</strong>, or <strong>modify</strong> sampling requests.</li><li>The client may also redact sensitive content, enforce rate limits, or validate input to maintain security.</li></ul><h4>2. Roots</h4><p><strong>What it is / Purpose</strong></p><ul><li><strong>Roots</strong> define <strong>filesystem boundaries</strong> that the client exposes to servers. They tell servers “these are the directories you may work within.”</li><li>By using roots, the client guides server behavior so that servers only see relevant files/folders and do not overstep into unrelated or sensitive file areas.</li></ul><p><strong>Details &amp; Behavior</strong></p><ul><li>Roots are represented using <strong>file URIs</strong> (e.g. file:///Users/agent/travel-planning) and a <strong>name</strong> (a label or title).</li><li>The client can update the roots list dynamically (e.g. when the user opens or closes certain folders), and notify servers via a roots/list_changed event.</li><li>Servers operate within these roots by using relative paths or file search techniques, but <strong>actual access is mediated by the client</strong> (the client enforces security). In other words, roots are guidance, not unconditional permissions.</li></ul><p><strong>User Interaction</strong></p><ul><li>Roots are often exposed automatically — for example, when a user opens a workspace or folder in the host application, the client will make those directories available as roots.</li><li>Advanced users may also manually configure roots, e.g. exposing certain directories while excluding others.</li></ul><h4><strong>3. Elicitation</strong></h4><p><strong>What it is / Purpose</strong></p><ul><li><strong>Elicitation</strong> lets MCP servers ask the client to <strong>prompt the user</strong> for particular information during a workflow. Instead of requiring all data up front, servers can pause and request missing details at the right time.</li><li>This supports more flexible, interactive workflows (e.g. a travel-booking server asking for seat preference, insurance, etc.).</li></ul><p><strong>Mechanics &amp; Flow</strong></p><ul><li>The server issues a request like elicitation/requestInput along with a <strong>schema</strong> defining what input it needs (fields, types, validation rules) and a <strong>message</strong> to explain the question.</li><li>The client’s UI prompts the user, collects the input, validates it against the schema, then returns it to the server.</li><li>Users may <em>decline</em>, <em>cancel</em>, or <em>partially answer</em> if allowed by the schema. The client shows which server is asking and why, to maintain transparency.</li></ul><p><strong>Safety &amp; UX Considerations</strong></p><ul><li>Elicitation requests should avoid asking permission-sensitive info like passwords or API keys.</li><li>The client may warn users of suspicious requests and allow users to inspect data before sending.</li><li>Elicitation interactions are designed to be contextual, clear, and respectful of user control. The schema and message should explain <em>why</em> the server needs the data</li></ul><h3>Layers</h3><p>No discussion about MCP would be complete without touching on its layers. There are two key layers that deserve our attention and exploration.</p><h4><strong>Data Layer</strong></h4><p>The data layer is the language and grammar of the MCP ecosystem that everyone agrees upon to communicate.</p><ol><li>In MCP, <strong>JSON RPC 2.0</strong> serves as the foundation of the data layer.</li><li><strong>JSON-RPC</strong> stands for <strong>JavaScript Object Notation — Remote Procedure Call</strong>.</li><li>A <strong>Remote Procedure Call (RPC)</strong> allows a program to execute a function on another computer as if it were local, hiding the details of network communication and data transfer. This abstraction makes it easier to build distributed applications.</li><li><strong>JSON-RPC</strong> combines the concept of <strong>Remote Procedure Calls</strong> with the simplicity of <strong>JSON</strong>, allowing developers to structure RPC requests and responses in a standardized JSON format.</li></ol><p><strong>Why JSON-RPC 2.0?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nrTdCUx3LHDU4tr8ljLp6Q.png" /><figcaption>⚡ Notifications + batching + transport-agnostic design are basically the <strong>killer combo</strong> that makes JSON-RPC so suitable for MCP.</figcaption></figure><h4>Transport Layer</h4><p>The <strong>Transport Layer</strong> is the mechanism that moves JSON-RPC messages between the Client and Server.</p><p>The choice of transport depends on the type of server.</p><p><strong>Local MCP Server — STDIO</strong></p><ol><li><strong>STDIO</strong> refers to the built-in streams every program has.<br>- <strong>stdin</strong> (input the program reads)<br>- <strong>stdout</strong> (output the program writes)</li><li>In MCP, these streams are used as transport layer between the client and server.</li></ol><p><strong>How does STDIO work?</strong></p><ul><li>The host starts the server as a subprocess. <em>[Subprocess = I run the server program as my child process and talk to it through pipes (stdin/stdout), instead of over the network]</em></li><li>Host writes JSON-RPC messages to the server’s <strong>stdin</strong>.</li><li>Server reads from <strong>stdin</strong>, processes, and writes responses to <strong>stdout</strong>.</li><li>Host reads responses from the subprocess’s <strong>stdout</strong>.</li><li><strong>stderr</strong> is usually just for logs/errors.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUBI76M9soia5sQFKFZhfw.png" /><figcaption>Benefits of using STDIO as transport layer</figcaption></figure><p><strong>Remote MCP Server — HTTP Streamable (earlier HTTP + SSE (optional) )</strong></p><ul><li>Using HTTP allows the host to reach servers running anywhere.</li><li>Host sends JSON RPC requests using POST requests with a JSON payload</li><li>The transport supports standard HTTP auth methods(like API keys)</li><li>SSE stands for Server Sent Events, and it’s an extension of HTTP</li><li>Using SSE the server sends multiple messages to client over a single open connection</li><li>Instead of sending one large JSON blob, the server can stream chunks of data as they are ready. Ideal for long running tasks or incremental updates</li></ul><h4>🔎 SSE vs HTTP Streamable in MCP</h4><p><strong>Server-Sent Events (SSE):</strong></p><ul><li>One-way stream (server → client).</li><li>Client opens a connection; server pushes events.</li><li>Good for simple “updates” (like logs, stock prices, chat messages).</li><li>Limitation: <strong>client cannot stream data to server</strong>, only receives.</li></ul><p><strong>HTTP Streamable (full-duplex streaming over HTTP):</strong></p><ul><li>Both <strong>client → server</strong> and <strong>server → client</strong> streams are possible.</li><li>Messages can be framed incrementally (no need to wait for full payload).</li><li>Perfect for MCP, where host and server may <strong>both stream JSON-RPC messages</strong>.</li></ul><h4>🚀 Why HTTP Streamable is better for MCP</h4><ul><li>MCP requires <strong>bidirectional streaming</strong> (host sends requests, server streams results back).</li><li>SSE is only <strong>unidirectional</strong>, so the host would need another channel (like POST + SSE combo).</li><li>With HTTP Streamable, <strong>one connection is enough</strong>: the client can send messages and get streamed responses without reopening connections.</li></ul><pre># server_streamable.py - Server (FastAPI, async streaming)<br>from fastapi import FastAPI, Request<br>from fastapi.responses import StreamingResponse<br>import asyncio<br>import json<br><br>app = FastAPI()<br><br>@app.post(&quot;/mcp&quot;)<br>async def mcp_endpoint(request: Request):<br>    async def response_stream():<br>        async for chunk in request.stream():  # read client chunks<br>            msg = json.loads(chunk)<br>            # Stream partial responses back<br>            yield json.dumps({&quot;id&quot;: msg[&quot;id&quot;], &quot;partial&quot;: &quot;Hello&quot;}) + &quot;\n&quot;<br>            await asyncio.sleep(1)<br>            yield json.dumps({&quot;id&quot;: msg[&quot;id&quot;], &quot;result&quot;: &quot;World&quot;}) + &quot;\n&quot;<br><br>    return StreamingResponse(response_stream(), media_type=&quot;application/json&quot;)</pre><pre># client_streamable.py - Client (incremental request + reading response)<br>import requests, json<br><br>def request_stream():<br>    # Stream request incrementally<br>    yield json.dumps({&quot;id&quot;: 1, &quot;method&quot;: &quot;greet&quot;, &quot;params&quot;: {&quot;name&quot;: &quot;Shivanshu&quot;}}).encode() + b&quot;\n&quot;<br>    yield json.dumps({&quot;id&quot;: 2, &quot;method&quot;: &quot;greet&quot;, &quot;params&quot;: {&quot;name&quot;: &quot;Pavan&quot;}}).encode() + b&quot;\n&quot;<br><br>with requests.post(&quot;http://localhost:8000/mcp&quot;, data=request_stream(), stream=True) as r:<br>    for line in r.iter_lines():<br>        if line:<br>            print(&quot;Got:&quot;, line.decode())</pre><p>Lets see the similar example with SSE</p><pre># server_sse.py - Server (FastAPI with SSE)<br>from fastapi import FastAPI<br>from fastapi.responses import StreamingResponse<br>import asyncio<br><br>app = FastAPI()<br><br>@app.get(&quot;/events&quot;)<br>async def sse_endpoint():<br>    async def event_stream():<br>        # Stream messages to client<br>        yield &quot;data: {\&quot;partial\&quot;: \&quot;Hello\&quot;}\n\n&quot;<br>        await asyncio.sleep(1)<br>        yield &quot;data: {\&quot;partial\&quot;: \&quot;World\&quot;}\n\n&quot;<br>        await asyncio.sleep(1)<br>        yield &quot;data: {\&quot;result\&quot;: \&quot;Done\&quot;}\n\n&quot;<br>    <br>    return StreamingResponse(event_stream(), media_type=&quot;text/event-stream&quot;)</pre><pre># client_sse.py - Client (listening to SSE)<br>import requests<br><br>with requests.get(&quot;http://localhost:8000/events&quot;, stream=True) as r:<br>    for line in r.iter_lines():<br>        if line and line.startswith(b&quot;data:&quot;):<br>            print(&quot;Got:&quot;, line.decode()[6:])</pre><h4>🔄 What happens:</h4><ul><li>The client opens /events and passively <strong>receives server messages</strong>:</li></ul><pre>Got: {&quot;partial&quot;: &quot;Hello&quot;} Got: {&quot;partial&quot;: &quot;World&quot;} Got: {&quot;result&quot;: &quot;Done&quot;}</pre><ul><li><strong>But the client cannot send JSON requests back over the same channel.</strong></li><li>If the host wants to request something, it must open a <strong>separate POST</strong> endpoint.</li><li>That breaks the nice bidirectional JSON-RPC model MCP expects.</li></ul><h3>MCP Lifecycle</h3><p>The <strong>MCP Life Cycle</strong> describes the <strong>complete sequence of steps</strong> that govern how a Host (client) and a Server establish, use, and end a connection during a session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1cdWD0WPHiucH3V67BTfQ.png" /><figcaption>MCP Lifecycle</figcaption></figure><h4>Initialization Phase</h4><ol><li><strong>[Step 1] Host → Server: </strong><strong>initialize</strong></li></ol><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: 1,<br>  &quot;method&quot;: &quot;initialize&quot;,<br>  &quot;params&quot;: {<br>    &quot;protocolVersion&quot;: &quot;2024-05-01&quot;,<br>    &quot;capabilities&quot;: {  //capabilities of mcp client, offered to mcp server<br>      &quot;streaming&quot;: true,<br>      &quot;batching&quot;: true,<br>      &quot;roots&quot;: { &quot;listChanged&quot;: true},<br>      &quot;sampling&quot;: {}<br>    },<br>    &quot;clientInfo&quot;: {<br>      &quot;name&quot;: &quot;MyMCPHost&quot;,<br>      &quot;version&quot;: &quot;1.0.0&quot;<br>    }<br>  }<br>}</pre><p>2. [Step 2] Server → Host: initialize Response</p><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: 1,<br>  &quot;result&quot;: {<br>    &quot;serverInfo&quot;: {<br>      &quot;name&quot;: &quot;MyMCPServer&quot;,<br>      &quot;version&quot;: &quot;2.1.0&quot;<br>    },<br>    &quot;capabilities&quot;: {  //capabilities of MCP server, offered to client<br>      &quot;tools&quot;: true,<br>      &quot;streaming&quot;: true,<br>      &quot;notifications&quot;: true<br>    }<br>  }<br>}</pre><p>3. [Step 3] <strong>Host → Server: </strong><strong>initialized Notification</strong></p><ul><li>Host notifies the server that initialization is complete.</li><li>This is a <strong>notification</strong> (no response expected).</li></ul><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;method&quot;: &quot;initialized&quot;,<br>  &quot;params&quot;: {}<br>}</pre><p>There are a few <strong>important rules 🤝</strong> for initialization phase:</p><ul><li>The client <strong>SHOULD NOT</strong> send requests other than <a href="https://modelcontextprotocol.io/specification/2025-06-18/basic/utilities/ping"><strong>pings</strong></a> before the server has responded to the <em>initialize</em> request.</li><li>The server <strong>SHOULD NOT</strong> send requests other than <a href="https://modelcontextprotocol.io/specification/2025-06-18/basic/utilities/ping"><strong>pings</strong></a> and <a href="https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/logging"><strong>logging</strong></a> before receiving the <em>initialized</em> notification.</li></ul><h4>Error Handling</h4><p>Error handling in MCP is how the Host (client) and Server signal that <strong>something went wrong</strong> with a request.</p><p><strong>MCP </strong>inherits JSON RPC’s standard error object format.</p><p><strong>Causes of Error:</strong></p><ul><li>Unsupported or mismatched protocol version.</li><li>Invalid arguments to a tool</li><li>Calling a method for a capability that wasn’t negotiated.</li><li>Malformed JSON-RPC messages.</li></ul><p><strong>Error Object Structure</strong></p><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: 1, <br>  &quot;error&quot;: {<br>    &quot;code&quot;: -32601,<br>    &quot;message&quot;: &quot;Method not found&quot;,<br>    &quot;data&quot;: {<br>      &quot;hint&quot;: &quot;The requested method &#39;fetchQuote&#39; is not supported by this server&quot;<br>    }<br>  }<br>}<br><br>🔎 Error codes:<br>-32700 → Parse error (invalid JSON)<br>-32600 → Invalid request<br>-32601 → Method not found<br>-32602 → Invalid params<br>-32603 → Internal error<br>-32000 to -32099 → Server-defined errors</pre><h4>MCP Inspector ✅</h4><p>MCP Inspector streamlines development by letting you inspect, test, and troubleshoot your MCP tools in real time.</p><p>npx @modelcontextprotocol/inspector is a <strong>developer’s debugging console for MCP servers</strong> — like Postman/Swagger UI, but for MCP.</p><pre>//command to start the inspector for your mcp server<br>npx @modelcontextprotocol/inspector python my_mcp_server.py</pre><h4>🔎 What happens:</h4><ol><li>Inspector starts up.</li><li>It <strong>spawns your server as a subprocess</strong> (here python my_mcp_server.py).</li><li>It automatically wires the server’s <strong>stdio</strong> to the Inspector proxy.</li><li>You open the UI at: <a href="http://localhost:6274/">http://localhost:6274</a></li><li>From the UI, you can list tools, send test requests, and watch messages.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJube0bAXipCrgcBQJCUGA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8258eafcf343" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[11. Design Pattern: Flyweight]]></title>
            <link>https://levelup.gitconnected.com/11-design-pattern-flyweight-bf3fbc41fa8c?source=rss-bad57cfd891d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf3fbc41fa8c</guid>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[text-editor]]></category>
            <category><![CDATA[flyweight-design-pattern]]></category>
            <category><![CDATA[game-design]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <dc:creator><![CDATA[Shivanshu Goyal]]></dc:creator>
            <pubDate>Sat, 29 Jul 2023 12:18:25 GMT</pubDate>
            <atom:updated>2023-07-30T16:47:51.225Z</atom:updated>
            <content:encoded><![CDATA[<p>It is one of the <strong>structural design patterns</strong> that is used to reduce the number of objects created to improve the <strong>memory footprint</strong> of an application. It is usually employed whenever we have limited memory or we can <strong>reuse the already existing similar kind</strong> of objects. It also helps in improving performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*D9CS6Ptv8DJAPD_R" /></figure><p>Let’s take an example of an application where the Flyweight pattern can be applied to improve its memory footprint. <strong>Notepad++, A Text Editor</strong> which we want to implement. For simplicity, Assume we can write anything in the notepad++ using A-Z, a-z, and 0–9, space characters.</p><p>A Client writes a paragraph using the mentioned characters. The same character would be repeating a couple of times. Can we create an object for those characters just once in the first use and reuse the same object in future uses?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgulvTMZ-0by0i4WvtF3Xg.png" /></figure><p>From the above image, it is clear for every letter to print, it requires 3 things:</p><ol><li>x coordinate</li><li>y coordinate</li><li>character itself. <strong>(it is a common property that can be reused across multiple letters)</strong></li></ol><pre>public class Letter {<br>  <br>    private int xCoordinate;<br>    private int yCoordinate;<br>    private char character;<br>}</pre><p>If we go with this object, we need to create as many objects of the Letter class as we want to write in Notepad++. What It means is if there are 1000 letters in a paragraph, 1K objects of this class would be created which is an expensive operation. <strong>How do we solve this issue with the Flyweight pattern?</strong></p><h3>How to implement Flyweight Pattern?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*el5W_yUuJmjS1T1bJTLHcA.png" /></figure><p>Few things to keep in mind while implementing the Flyweight pattern:</p><ol><li><strong>Remove the properties</strong> from the class which vary for different instances to make the class flyweight. For example. x and y coordinates must not be part of the Letter class as they vary for every letter instance.</li><li>These <strong>extrinsic properties</strong> must be passed to the flyweight class’s method at runtime.</li><li>The Flyweight class is an <strong>immutable class</strong>. Once its object is created, must not be edited.</li><li>We need to <strong>cache the flyweight class objects</strong> once created to be reused as and when needed.</li></ol><p>To understand it better, we will implement the Text Editor using the Flyweight pattern.</p><p>1. Create an Interface</p><pre>public interface Letter {<br><br>    public void display(int row, int column);<br>}</pre><p>2. Have a concrete implementation for the interface.</p><pre>public class EditorCharacter implements Letter {<br><br>    private char character;<br>    private String fontType;<br><br>    public EditorCharacter(char character, String fontType){<br>        this.character = character;<br>        this.fontType = fontType;<br>    }<br><br>    public char getCharacter() {<br>        return this.character;<br>    }<br><br>    public String getFontType() {<br>        return this.fontType;<br>    }<br><br>    //no need to create setters as this object needs to be immutable<br><br>    @Override<br>    public void display(int row, int column) {<br><br>        //display the character of particular font and size<br>        //at given location<br>    }<br>}</pre><p>3. There will be a factory that takes care of creating and caching these EditorCharacter objects.</p><pre>public class LetterFactor {<br><br>    //cache to store the letter for which object is already created or requested<br>    private static Map&lt;String, Letter&gt; characterCache = new HashMap&lt;&gt;();<br><br>    public static Letter crateLetter(char characterValue, String fontType){<br><br>        String key = fontType + &quot;_&quot; + characterValue;<br><br>        //returns from the cache if available<br>        if(characterCache.containsKey(key)) {<br>            return characterCache.get(key);<br><br>        } else {<br><br>            EditorCharacter characterObject = new EditorCharacter(characterValue, fontType);<br>            characterCache.put(key, characterObject);<br>            return characterObject;<br>        }<br>    }<br>}</pre><p>4. Client</p><pre>public class Client {<br>    <br>    public static void main(String[] args) {<br>        <br>        /*<br>         * Let&#39; say my text is &quot;Hello, this is Flyweight article!!&quot;<br>         *<br>        */<br><br>        <br>        //to add letter l at 3 position <br>        addLetter(&#39;l&#39;, &quot;Arial&quot;, 0, 2);<br><br>        //to add letter l at 4position <br>        addLetter(&#39;l&#39;, &quot;Arial&quot;, 0, 3);<br><br>        //only one object for character &#39;l&#39; of Arial type will be created<br>        //regardless of how many times it is being used.<br><br>    }<br>}<br><br><br>private static void addLetter(char characterValue, String fontType, int x, int y) {<br>    <br>    Letter letter = LetterFactory.createLetter(&quot;l&quot;, &quot;Arial&quot;);<br>    letter.display(x, y);<br>}</pre><h4>Famous Applications</h4><ol><li><strong>Text Editor</strong></li><li><strong>E-Game</strong> where we create the same type of player at different locations.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1l3q9v65GZMbk7KjGlEMxw.png" /><figcaption>A player of an E-Game can have these properties where an object can be created based on body and type</figcaption></figure><p>Thanks for reading!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf3fbc41fa8c" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/11-design-pattern-flyweight-bf3fbc41fa8c">11. Design Pattern: Flyweight</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10. Design Pattern:- State & Vending Machine Example]]></title>
            <link>https://levelup.gitconnected.com/10-design-pattern-state-vending-machine-example-676c1b8c1563?source=rss-bad57cfd891d------2</link>
            <guid isPermaLink="false">https://medium.com/p/676c1b8c1563</guid>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[vending-machines]]></category>
            <category><![CDATA[state-design-pattern]]></category>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Shivanshu Goyal]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 17:36:15 GMT</pubDate>
            <atom:updated>2023-08-03T14:06:46.493Z</atom:updated>
            <content:encoded><![CDATA[<p>The State Design Pattern is one of the most useful <strong>behavioral</strong> design patterns that is used to change the behavior of the class based on its state. In this pattern, A state interface is implemented by multiple concrete states and a context object changes its behavior as its state object changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*b08B0syGTakWxD1K" /></figure><p>This design pattern is useful when we want to <strong>avoid primitive if/else statements</strong>, Here we extract the logic to separate classes and the context object delegates the behavior to the methods (<strong>operations</strong>) of the state class. Little confused? Let’s take an example to understand it better.</p><h3>Television</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMcjGZ3u7OtcrNtfAWm0wA.png" /><figcaption>This image shows which operations are possible in a state of TV. Example: TV can be turned on when it is OFF.</figcaption></figure><h4>How to implement State Pattern?</h4><p>The state interface will have all the operations which can be executed by any concrete state object. The<strong> default behavior for each operation must throw an exception or do nothing</strong>. Then each concrete state class will implement the operations which are possible in the given state of the context. Now, context is the one whose behavior changes based on the state it holds. The below image might help you to understand how we implement State design patterns at a low level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzHQSwhPQk3bArpt8e-JCA.png" /></figure><h3>Vending Machine</h3><p>It is a very <strong>known low-level design interview question</strong>. When you are asked to design a vending machine, your interviewer is interested to know how much you know about the State Design Pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GfhrGumacxT0vfPHfFrinQ.png" /><figcaption>Vending Machine</figcaption></figure><p>Let’s see how a Vending machine can be designed using the State pattern. <strong>In order to design a vending machine, we need to do the following steps:</strong></p><ol><li>Identify all the states possible in a vending machine</li><li>Identify which all operations are possible in which state</li><li>Identify other objects required in a Vending machine</li><li>Identify the flow for any request to the Vending machine. <strong>Happy path + error scenario + cancel scenario</strong></li></ol><h4>States</h4><ol><li>Idle State</li><li>Accepting Coin State</li><li>Product Selection State</li><li>Dispensing State</li></ol><h4>Operations</h4><ol><li>Insert coins</li><li>Select product</li><li>Cancel request</li><li>Get change</li><li>Collect product</li><li>Press the insert coin button</li><li>Press the select product button</li></ol><h4>Other Objects</h4><ol><li>Item</li><li>ItemType</li><li>ItemShelf</li><li>ItemBox -&gt; An array of ItemShelf</li><li>VendingMachine (or Context)</li></ol><h4>Flow</h4><p>All outbound arrow indicates an operation possible in the given state of the vending machine. For example: <strong>Accepting coin state</strong> has 3 operations possible:</p><ol><li>Insert coins</li><li>Press the <strong>select product</strong> button</li><li>Cancel request</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCawjhVurDC0jBefvcxrlA.png" /></figure><pre>public interface State {<br>    //operations possible by any concrete state<br><br>    default void insertCoin(VendingMachine machine, Coin coin) throws Exception {<br>        throw new UnsupportedException(&quot;Method not supported&quot;);<br>    }<br><br>    default void selectProduct(VendingMachine machine, Integer codeNum) throws Exception {<br>        throw new UnsupportedException(&quot;Method not supported&quot;);<br>    }<br><br>    default List&lt;Coin&gt; cancelReqeust(VendingMachine machine) throws Exception {<br>        <br>    }<br><br>    default int getChange(int returnChangeMoney) throws Exception {<br>        throw new UnsupportedException(&quot;Method not supported&quot;);<br>    }<br><br>    default Item collectProduct(VendingMachine machine, int codeNumber) throws Exception {<br>        throw new UnsupportedException(&quot;Method not supported&quot;);<br>    }<br><br>    default void pressInsertCoinButton(VendingMachine machine) throws Exception {<br>        throw new UnsupportedException(&quot;Method not supported&quot;);<br>    }<br><br>    default void pressSelectProductButton(VendingMachine machine) throws Exception {<br>        throw new UnsupportedException(&quot;Method not supported&quot;);<br>    }<br><br>}</pre><p>We will implement two concrete state classes and other classes can be implemented in the same manner.</p><h4>Accepting Coin State Concrete class</h4><pre>public class AcceptingCoinState implements State {<br>    <br>    public AcceptingCoinState() {<br>    <br>    }<br><br>    //override operations possible by this concrete state<br><br>    public void insertCoin(VendingMachine machine, Coin coin) throws Exception {<br>        System.out.println(&quot;Accepted the coin&quot;);<br>        machine.getCoinList().add(coin);<br>    }<br><br>    public List&lt;Coin&gt; cancelReqeust(VendingMachine machine) throws Exception {<br>        System.out.println(&quot;Returned the full amount back in the Coin Dispense Tray&quot;);<br>        machine.setVendingMachineState(new IdleState(machine));<br>        return machine.getCoinList();<br>    }<br><br>    public void pressSelectProductButton(VendingMachine machine) throws Exception {<br>        machine.setVendingMachineState(new ProductSelectionState());<br>    }<br><br>}</pre><h4>Product Selection State Concrete class</h4><pre>public class ProductSelectionState implements State {<br>    <br>    public ProductSelectionState() {<br>    <br>    }<br><br>    //override operations possible by this concrete state<br><br>    public void selectProduct(VendingMachine machine, Integer codeNum) throws Exception {<br>        //1. get item of this codeNum<br>        Item item = machine.getInventory().getItem(codeNum);<br><br>        //2. total amount paid by Customer<br>        int paidByCustomer = 0;<br>        for(Coin coin : machine.getCoinList()){<br>            paidByCustomer = paidByCustomer + coin.value;<br>        }<br><br>        //3. compare product price and amount paid by customer<br>        if(paidByCustomer &lt; item.getPrice()) {<br>            cancelReqeust(machine);<br>            throw new Exception(&quot;insufficient money&quot;);<br>        } else if(paidByCustomer &gt;= item.getPrice()) {<br><br>            if(paidByCustomer &gt; item.getPrice()) {<br>                getChange(paidByCustomer-item.getPrice());<br>            }<br>            machine.setVendingMachineState(new DispensingState(machine, codeNumber));<br>        }<br>    }<br><br>    public int getChange(int returnChangeMoney) throws Exception {<br>        return returnChangeMoney;<br>    }<br><br>    public List&lt;Coin&gt; cancelReqeust(VendingMachine machine) throws Exception {<br>        System.out.println(&quot;Returned the full amount back in the Coin Dispense Tray&quot;);<br>        machine.setVendingMachineState(new IdleState(machine));<br>        return machine.getCoinList();<br>    }<br><br>}</pre><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=676c1b8c1563" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/10-design-pattern-state-vending-machine-example-676c1b8c1563">10. Design Pattern:- State &amp; Vending Machine Example</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[9. Design Pattern:- Chain of Responsibility]]></title>
            <link>https://levelup.gitconnected.com/9-design-pattern-chain-of-responsibility-2f370311a7e9?source=rss-bad57cfd891d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f370311a7e9</guid>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[logger]]></category>
            <category><![CDATA[chain-of-responsibility]]></category>
            <dc:creator><![CDATA[Shivanshu Goyal]]></dc:creator>
            <pubDate>Wed, 26 Jul 2023 15:26:23 GMT</pubDate>
            <atom:updated>2023-07-27T13:37:13.729Z</atom:updated>
            <content:encoded><![CDATA[<p>It is a <strong>behavioral design</strong> pattern that allows us to pass a request through a <strong>chain of request handlers</strong>. Each handler has the next handler with it and it passes the request to the next handler if it is not able to fulfill that request. We always try to put the most obvious or used handler first. If you are confused about what I meant by the most used handler, keep reading the article, it will be clear in the below paragraphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-ySkIQtJmmLylOUOuVWQA.png" /><figcaption>Chain of Responsibility Design Pattern</figcaption></figure><h4>How to implement the Chain of Responsibility pattern?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1ekDrNoIvX5zndnRZz0CQ.png" /></figure><p>It is a renowned design pattern that is used in many real-world applications. Let’s talk about those examples to understand it better. These examples are very common <strong>low-level design</strong> questions asked in software engineer interviews.</p><ol><li>Design a Logger</li><li>Design an ATM machine</li></ol><h3>Logger</h3><p>A logger is a utility used to log something into a file/console for an application. Now, we can have different types of log messages to log.</p><ol><li>Info Log (most application logs belong to the Info category) → <strong>Most used one</strong></li><li>Debug Log</li><li>Error Log</li></ol><blockquote><strong>The most used LogProcessor comes first and the least used comes last</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyotPI2_ebD_e5Djfz2N-Q.png" /><figcaption>Chain of Log Processors</figcaption></figure><h4>Log Processor → Abstract class</h4><pre>public abstract class LogProcessor {<br><br>    private LogProcessor nextProcessor;<br><br>    public LogProcessor(LogProcessor nextProcessor) {<br>        this.nextProcessor = nextProcessor;<br>    }<br><br>    public void logMessage(LogLevel logLevel, String message) {<br>        if(nextProcessor != null) {<br>            nextProcessor.logMessage(logLevel, message);<br>        } else {<br>            throw new IllegalArgumentException(&quot;LogLevel is not correct!!&quot;);<br>        }<br>    }<br>}</pre><h4>Error Log Processor</h4><pre>public class ErrorLogProcessor extends LogProcessor {<br><br>    public ErrorLogProcessor(LogProcessor nextProcessor) {<br>        super(nextProcessor);<br>    }<br><br>    public void logMessage(LogLevel logLevel, String message) {<br>        //print if it is error logLevel else let super handle it <br>        if(LogLevel.Error.equals(logLevel)) {<br>            System.out.println(&quot;Error message %s&quot;, message);<br>        } else {<br>            super.logMessage(logLevel, message);<br>        }<br>    }<br>}</pre><h4>Debug Log Processor</h4><pre>public class DebugLogProcessor extends LogProcessor {<br><br>    public ErrorLogProcessor(LogProcessor nextProcessor) {<br>        super(nextProcessor);<br>    }<br>    <br>    public void logMessage(LogLevel logLevel, String message) {<br>        //print if it is error logLevel else let super handle it <br>        if(LogLevel.Debug.equals(logLevel)) {<br>            System.out.println(&quot;Error message %s&quot;, message);<br>        } else {<br>            super.logMessage(logLevel, message);<br>        }<br>    }<br>}</pre><h4>Info Log Processor</h4><pre>public class InfoLogProcessor extends LogProcessor {<br>  <br>    public ErrorLogProcessor(LogProcessor nextProcessor) {<br>        super(nextProcessor);<br>    }<br>    public void logMessage(LogLevel logLevel, String message) {<br>        //print if it is error logLevel else let super handle it <br>        if(LogLevel.Error.equals(logLevel)) {<br>            System.out.println(&quot;Error message %s&quot;, message);<br>        } else {<br>            super.logMessage(logLevel, message);<br>        }<br>    }<br>}</pre><h4>Logger Factory</h4><pre>public class LoggerFactory {<br>  <br>    public static LogProcessor getLogger() {<br><br>        //the most used logProcessor comes first and the least used comes last<br>        new InfoLogProcessor(new DebugLogProcessor(new ErrorLogProcessor(null)));<br>    }<br>}</pre><h4>Client</h4><pre>public class Client {<br>  <br>    public static void main(String[] args) {<br>        <br>        //in production code, we dont need to create multiple instances of logProessor<br>        LogProcessor logger = LoggerFactory.getLogger();<br>        <br>        logger.logMessage(LogLevel.Error, &quot;this is my error message&quot;);<br>        logger.logMessage(LogLevel.Info, &quot;this is my info message&quot;);<br>    }<br>}</pre><h3>ATM Machine</h3><p>Whenever a customer withdraws an amount from an ATM machine. It always starts with the highest supported note handler to fulfill the request. If the requested handler is not able to fulfill, it further requests to the next note handler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80vD2ywsidp_LVVCVXJ2aQ.png" /></figure><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f370311a7e9" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/9-design-pattern-chain-of-responsibility-2f370311a7e9">9. Design Pattern:- Chain of Responsibility</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8. Design Pattern:- Composite]]></title>
            <link>https://shivanshugoyal0111.medium.com/8-design-pattern-composite-bd3cd2b60b21?source=rss-bad57cfd891d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd3cd2b60b21</guid>
            <category><![CDATA[filesystem]]></category>
            <category><![CDATA[arithmetic-operations]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[composite-design-pattern]]></category>
            <dc:creator><![CDATA[Shivanshu Goyal]]></dc:creator>
            <pubDate>Wed, 26 Jul 2023 11:30:25 GMT</pubDate>
            <atom:updated>2023-08-05T01:56:05.761Z</atom:updated>
            <content:encoded><![CDATA[<p>The Composite design pattern is a <strong>structural design pattern</strong> where we have an object inside an object. This pattern creates a <strong>tree structure</strong> of a group of objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JEFEg1x0X5QcmULkCF1tg.png" /><figcaption>Composite Design Pattern</figcaption></figure><h4>How to implement Composite Pattern?</h4><p>It is super easy to implement the Composite design pattern. Each Composite object (non-leaf only) will have a list of objects of its own base type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pQVvwPm7dwY9OqCjNXlcg.png" /></figure><p>The leaf class does not have any child object whereas the non-leaf class is having a list of composite objects (leaf + non-leaf).</p><h4>Applications</h4><p>Let’s take some real-world examples to understand it better. This pattern can be applied to the application where we have an object having another object of the same base type inside it.</p><ol><li><strong>File System: </strong>A folder can have a list of files + subfolders inside it.</li><li><strong>Arithmetic Expression (or Calculator): </strong>It can be a combination of one or more expressions.</li></ol><h4>File System:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6j5PJiNGpsRMU2lWB8ryDg.png" /><figcaption>File System: Red boxes are indicating files whereas black boxes are folders</figcaption></figure><pre>public interface FileSystem {<br><br>    //method to list the directory or file name<br>    void list();<br>}</pre><p>Directory or Folder</p><pre>public class Directory implements FileSystem {<br>    <br>    private List&lt;FileSystem&gt; filesystems;<br>    private String name;<br><br>    public Directory(String name) {<br>        this.name = name;<br>        this.filesystems = new ArrayList&lt;&gt;();<br>    }<br>    <br>    public void add(FileSystem fileSystem) {<br>      this.fileSystems.add(fileSystem);<br>    }<br>    <br>    public void list() {<br>        System.out.println(&quot;Directory name: %s&quot;, name);<br><br>        //printing all child file sytems<br>        for(FileSystem filesystem: filesystems) {<br>            filesystem.list();<br>        }<br>    }<br>}</pre><p>File</p><pre>public class File implements FileSystem {<br>    <br>    private String name;<br><br>    public File(String name) {<br>        this.name = name;<br>    }<br>    <br>    public void list() {<br>        System.out.println(&quot;File name: %s&quot;, name);<br>    }<br>}</pre><p>How does the client use this file system?</p><pre>public class Client {<br>    <br>    public void static main(String[] args) {<br><br>        FileSystem rootDirectory = new Directory(&quot;Apartments&quot;);<br>        <br>        FileSystem 1bhk = new Directory(&quot;1BHK&quot;);<br>        FileSystem 2bhk = new Directory(&quot;2BHK&quot;);<br>        FileSystem 3bhk = new Directory(&quot;3BHK&quot;);<br><br>        FileSystem flat204 = new File(&quot;flat204&quot;);<br>        FileSystem flat202 = new File(&quot;flat202&quot;);<br><br>        2bhk.add(flat202);<br>        2bhk.add(flat204);<br><br>        rootDirectory.add(1bhk);<br>        rootDirectory.add(2bhk);<br>        rootDirectory.add(3bhk);<br><br>        rootDirectory.list();<br><br>    }<br>}</pre><h4>Arithmetic Expression:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oeDQqtCkULNJ0f3vO1Vu2Q.png" /><figcaption>The Composite Object having one or more child object(s)</figcaption></figure><p>Arithmetic Expression Interface</p><pre>public interface ArithmeticExpression {<br><br>    //method to evaluate its value<br>    int evaluate();<br>}</pre><p>Number (Simple Object)</p><pre>public class Number implements ArithmeticExpression {<br><br>    private int number;<br><br>    public Number(int number) {<br>        this.number = number;<br>    }<br><br>    public int evaluate() {<br>        return number;<br>    }<br>}</pre><p>Expression (Composite Object)</p><pre>public class Expression implements ArithmeticExpression {<br><br>    private Operator operator;<br>    private ArithmeticExpression left;<br>    private ArithmeticExpression right;<br><br>    public Expression(Operator operator, ArithmeticExpression left, ArithmeticExpression right) {<br>        this.operator = operator;<br>        this.left = left;<br>        this.right = right;<br>    }<br><br>    public int evaluate() {<br>        <br>        int result = 0;<br>        switch (operator) {<br>            case ADD:<br>                result = left.evaluate() + right.evaluate();<br>                break;<br>            case MINUS:<br>                result = left.evaluate() - right.evaluate();<br>                break;<br>            case MULTIPLY:<br>                result = left.evaluate() * right.evaluate();<br>                break;<br>            case DIVIDE:<br>                int right = right.evaluate();<br>                result = right == 0? throw new InvalidValue(): (left.evaluate() / right);<br>                break;<br>            default:<br>                throw new IllegalArgumentException();            <br>        }<br>        return result;<br>    }<br>}</pre><p>Thanks for reading!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd3cd2b60b21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7. Design Pattern:- Strategy]]></title>
            <link>https://shivanshugoyal0111.medium.com/7-design-pattern-strategy-84a31d4b41ce?source=rss-bad57cfd891d------2</link>
            <guid isPermaLink="false">https://medium.com/p/84a31d4b41ce</guid>
            <category><![CDATA[strategy-design-pattern]]></category>
            <category><![CDATA[single-responsibility]]></category>
            <category><![CDATA[open-closed-principle]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <dc:creator><![CDATA[Shivanshu Goyal]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 11:55:08 GMT</pubDate>
            <atom:updated>2023-07-24T11:55:08.649Z</atom:updated>
            <content:encoded><![CDATA[<p>The strategy design pattern is a <strong>behavioral design pattern</strong> that is used to change the behavior of an object dynamically by injecting a particular strategy based on the requirements. This design pattern enables us to choose from multiple strategies at runtime rather than depending on a single static dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6UIlRGWN62mSeYzigELyQ.png" /><figcaption>Strategy Design Pattern</figcaption></figure><h4>Components of Strategy Pattern</h4><p>There are 3 main components while implementing the Strategy pattern.</p><ol><li><strong>Client</strong>: It will contain the reference of the Strategy object and will interact with it using the common strategy interface.</li><li><strong>Strategy Interface:</strong> It is an interface to define the behavior of the strategy and concrete strategy implementations will have their specific implementation for the interface methods.</li><li><strong>Concrete strategies:</strong> Implementations of the Strategy interface which will be used by the client. The client can choose among all the strategies at runtime.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1mz1THmojEEnCCcj3Fjecw.png" /></figure><h4>Let’s take an example to understand what is the problem if we don’t use the strategy pattern.</h4><p>We have an Order service that needs to talk to different order repositories based on the given database type from the client to interact with the target database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YO96QtGFLJdjmed-F9g4Xw.png" /></figure><pre>public class OrderService {<br><br>    public OrderService() {}<br><br>    //returns the price for the given product<br>    public double getPrice(String databaseType, String productId) {<br>        <br>        switch (databaseType) {<br><br>            case &quot;ORACLE&quot;:<br>                return new OracleOrderRepository().getPrice(productId);<br>            case &quot;MYSQL&quot;:<br>                return new MysqlOrderRepository().getPrice(productId);<br>            default:<br>                throw new IllegalArgumentException(&quot;The given databaseType is not supported!!&quot;);<br>        }<br>    }<br>} </pre><h4>Problems with the above design</h4><ol><li>It is <strong>not unit testable</strong> as the specific repository objects are created inside the getPrice method.</li><li>It does not follow the <strong>Open-Closed principle</strong>. How do we add a new database in the future?</li><li>It <strong>violates the single responsibility principle.</strong> Order service is not supposed to take responsibility for repository object creation.</li></ol><h4>Fix the problems using the Strategy pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d0J8A26V-G3KP6Ck.jpg" /></figure><ol><li>Have an OrderRepository interface (Strategy interface)</li></ol><pre>public interface OrderRepository {<br><br>    double getPrice(String productId);<br>}</pre><p>2. Implement the OrderRepository for each database available today. A new implementation can be added later when a new database is available.</p><pre>public class OracleOrderRepository implements OrderRepository {<br><br>    public OracleOrderRepository() {}<br><br>    //returns the price for the given product<br>    public double getPrice(String productId) {<br>        System.out.println(&quot;Returning price from oracle database&quot;);<br>        return 10.0;<br>    }<br>}</pre><pre>public class MySqlOrderRepository implements OrderRepository {<br><br>    public MySqlOrderRepository() {}<br><br>    //returns the price for the given product<br>    public double getPrice(String productId) {<br>        System.out.println(&quot;Returning price from Mysql database&quot;);<br>        return 20.0;<br>    }<br>}</pre><p>3. Let the OrderService have the reference of a specific Order repository through the OrderRepository interface. The client of the order service can decide at runtime which database he wants to interact with.</p><pre>public class OrderService {<br><br>    private OrderRepository orderRepository;<br><br>    //client can inject a particular strategy (orderRepository) at runtime<br>    public OrderService(OrderRepository orderRepository) {<br>        this.orderRepository = orderRepository;<br>    }<br><br>    //returns the price for the given product<br>    public double getPrice(String productId) {<br>        <br>        return orderRepository.getPrice(productId);<br>    }<br>}</pre><p>Now, OrderService is not responsible for OrderRepository object creation. It is clearly scalable as it does not require any modification if we add or delete any implementation for the OrderRepository interface.</p><p>Thanks for reading!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84a31d4b41ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6. Design Pattern:- Adapter]]></title>
            <link>https://medium.com/geekculture/6-design-pattern-adapter-f0b2e50f56e9?source=rss-bad57cfd891d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0b2e50f56e9</guid>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[adapter-vs-proxy]]></category>
            <category><![CDATA[adapter-design-pattern]]></category>
            <dc:creator><![CDATA[Shivanshu Goyal]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 10:33:07 GMT</pubDate>
            <atom:updated>2023-07-24T10:33:07.358Z</atom:updated>
            <content:encoded><![CDATA[<p>An adapter Design Pattern is a structural design pattern that is used to have a bridge between 2 incompatible interfaces so that they can collaborate with each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVCTo-aM6RMP2OpUJV2WIQ.png" /></figure><p>Let’s take a real-world example to understand it better. We have a socket with 3 squares and the power adapter has oval shape pins. Clearly, they are not compatible with each other and we would need an adapter in between to make them work together. In this example, the power adapter becomes the client, the socket is our existing functionality and a new adapter which is introduced in between is the adapter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QLfWDIlGKqoNaHe0ijKxQ.png" /></figure><h4>How to implement the Adapter Pattern?</h4><p>We will implement the adapter pattern for a pricing service that returns the price for a given product in USA currency ($). We got a client who needs to use the price service for its Indian customers who would like to see the product price in Indian rupees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oEYBOh0Fj9yYjvSIlS2GA.png" /><figcaption>PriceServiceAdapter to return the price in the given country’s currency (Indian rupees in our case).</figcaption></figure><pre>public interface PriceService {<br><br>    //returns the price for the given product in dollars<br>    double getPriceInDollar(String productId);<br>}</pre><p>PriceServiceAdapter to adapt the price currency from the dollar to the given currency.</p><pre>public interface PriceServiceAdapter {<br><br>    //returns the price for the given product<br>    double getPrice(String productId);<br>}</pre><p>Implementation of the PriceServiceAdapter to get the price of the given product in Indian currency.</p><pre>public class PriceServiceAdapterInd implements PriceServiceAdapter {<br><br>    private PriceService priceService; //has-a<br><br>    public PriceServiceAdapterInd() {<br>        priceService = new ConsumablePriceService();<br>    }<br><br>    //returns the price for the given product in Indian currency<br>    @Override<br>    public double getPrice(String productId) {<br>        <br>        double price = priceService.getPriceInDollar(productId);<br><br>        return price * 82.0;<br>    }<br>}</pre><p><strong>How does the client make use of PriceServiceAdapter?</strong></p><pre>public class Client {<br><br>    private PriceServiceAdapter priceServiceAdapter; //has-a<br><br>    public static void main(String[] args) {<br>        priceServiceAdapter = new PriceServiceAdapterInd();<br><br>        String productId = &quot;sampleProductId&quot;;    <br>        double priceInRup = priceServiceAdapter.getPrice(productId);<br>        <br>        System.out.println(&quot;Product price is {}&quot;, priceInRup);<br>    }<br>}</pre><p>Now, we are clear on how the Adapter pattern can be implemented. You might be wondering, <strong>isn’t an Adapter pattern very much similar to the </strong><a href="https://medium.com/@shivanshugoyal0111/5-design-pattern-proxy-ea1a40a014ec"><strong>Proxy pattern</strong></a><strong>?</strong></p><h4>Adapter vs Proxy Design Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xmqqbWqM-4f_O26VYCIS5w.png" /><figcaption>Adapter vs Proxy</figcaption></figure><blockquote>Adapter provides a different interface to its subject. Proxy provides the same interface.</blockquote><p>In practice, the concepts <em>wrapper</em>, <em>adapter,</em> and <em>proxy</em> are so closely related that the terms are used interchangeably.</p><ol><li>As the name suggests, <strong>a wrapper</strong> is literally something that <strong>wraps</strong> around another object.</li><li>An <strong>adapter pattern</strong> is used when the client is not compatible with the existing functionality. It wraps the existing functionality into the new interface which is what the client wants.</li><li>Now a <strong>Proxy</strong> is an object of the same interface. It only “pretends” to be the actual object, but instead forwards the actual behavior (calculations, processing, data access, etc.) to an underlying referenced object.</li></ol><p>Thanks for reading!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0b2e50f56e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/6-design-pattern-adapter-f0b2e50f56e9">6. Design Pattern:- Adapter</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection: Constructor vs Field]]></title>
            <link>https://levelup.gitconnected.com/dependency-injection-constructor-vs-field-96035a78fdc0?source=rss-bad57cfd891d------2</link>
            <guid isPermaLink="false">https://medium.com/p/96035a78fdc0</guid>
            <category><![CDATA[setter-injection]]></category>
            <category><![CDATA[dependency-inversion]]></category>
            <category><![CDATA[constructor-injection]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[field-injection]]></category>
            <dc:creator><![CDATA[Shivanshu Goyal]]></dc:creator>
            <pubDate>Sun, 23 Jul 2023 12:48:03 GMT</pubDate>
            <atom:updated>2023-07-23T17:21:54.569Z</atom:updated>
            <content:encoded><![CDATA[<p>Dependency injection is an elementary concept that says giving an object things it needs, rather than having it create them itself. It is useful as it follows the <strong>Single Responsibility Principle</strong>. The object is no longer responsible to create the things on which it is dependent. It also makes our code easy to test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4YplrqCdloYyy1u0cx06Q.png" /><figcaption>Dependency Injection</figcaption></figure><h4>What is dependency?</h4><p>The below image explains OrderService class uses OrderRepository class’s methods which makes OrderService a dependent class and OrderRepository becomes a <strong>dependency</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_HwYZ8z5xi7WAO3pAS6LA.png" /><figcaption>OrderService has an OrderRepository dependency</figcaption></figure><h4>Types of Dependency Injection</h4><p>There are 3 ways using which a dependency can be injected.</p><ol><li>Constructor Injection (<strong><em>Most recommended</em></strong>)</li><li>Setter Injection</li><li>Field Injection</li></ol><h4>Constructor Injection</h4><p>It is the most recommended way to inject a dependency.</p><pre>@Component<br>public class OrderService {<br><br>    private final OrderRepository orderRepository;<br><br>    //dependency is injected using constructor    <br>    @Autowired<br>    public OrderService(OrderRepository orderRepository) {<br>        this.orderRepository = orderRepository;<br>    }<br>} </pre><h4>Setter Injection</h4><p>Dependency is injected using the setter method of the dependent class. There is a problem as <strong>we cannot make our dependency variable final</strong>.</p><pre>@Component<br>public class OrderService {<br><br>    private final OrderRepository orderRepository;<br><br>    public OrderService(OrderRepository orderRepository) {<br>        this.orderRepository = orderRepository;<br>    }<br><br>    //dependency is injected using setter<br>    @Autowired<br>    public void setOrderRepository(OrderRepository orderRepository) {<br>        this.orderRepository = orderRepository;<br>    }<br>}</pre><h4>Field Injection</h4><p>It is the easiest way to inject a dependency. It has been always a contentious topic to decide between field and constructor injection. We will see what are the problems with field injection and <strong>why Constructor injection is the correct and recommended way for dependency injection.</strong></p><pre>@Component<br>public class OrderService {<br><br>    //field injection<br>    @Autowired<br>    private OrderRepository orderRepository;<br><br>    public OrderService(OrderRepository orderRepository) {<br>        this.orderRepository = orderRepository;<br>    }<br>}</pre><h4>Problems with Field Injection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*aLiq9UJ4R88YnTXx" /></figure><ol><li>We cannot make the dependency variable <strong>final</strong>. It means dependency is injected into the OrderRepository variable after the OrderService instance is created.</li><li>It <strong>violates the basic Java principle</strong>. Any private variable must be accessed within the class. Spring tries to inject the dependency into the private variable <strong>using reflection</strong>.</li><li>[Assumption: We don’t want to use the reflection] There is <strong>no way</strong> to inject the <strong>mock</strong> dependency in a unit test. If the dependency is injected using a constructor, the test can pass any bean of its choice for the dependency while writing the test for the dependent class.</li></ol><p>After looking at all these issues, it is quite clear that we must not use field injection even if it is a very clear and simple way to achieve injection.</p><h4>Is there any place where we can use Field injection?</h4><p>Yes, Field injection can be used while writing the test which is using SpringBootTest annotation (basically an application test). It would be required to fetch the bean for the class we want to test.</p><h4>Dependency Inversion vs Dependency Injection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1eERLKIOv8k02yYBKVqbA.png" /></figure><p>The Dependency Inversion Principle says the dependent class should not be dependent on the dependencies directly but instead depend upon the abstraction (interface) of the dependency. This aims to reduce the coupling between the classes is achieved by introducing abstraction between the layer, thus doesn’t care about the real implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LOczo3tI_ZeMr1koUtfo6Q.png" /><figcaption>National Park needs to know about all types of birds</figcaption></figure><p>This is NOT a good design as all the lower classes functionality is exposed to the higher class. Tomorrow, when there is a need to add a new type of bird, National Park would need to make that change in its class. Let’s see how we fix these issues using Dependency Inversion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDpvnPFFhdcmS23W19WKcg.png" /><figcaption>National Park has Bird dependency (abstraction not the concrete classes)</figcaption></figure><p>Thanks for reading!</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🧠 AI Tools ⇒ <a href="https://www.aimind.so/">View Now</a></li></ul><p>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></p><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96035a78fdc0" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/dependency-injection-constructor-vs-field-96035a78fdc0">Dependency Injection: Constructor vs Field</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5. Design Pattern:- Proxy]]></title>
            <link>https://shivanshugoyal0111.medium.com/5-design-pattern-proxy-ea1a40a014ec?source=rss-bad57cfd891d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea1a40a014ec</guid>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[proxy-pattern]]></category>
            <category><![CDATA[spring-bean]]></category>
            <dc:creator><![CDATA[Shivanshu Goyal]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 06:57:37 GMT</pubDate>
            <atom:updated>2023-07-26T11:27:52.592Z</atom:updated>
            <content:encoded><![CDATA[<p>Proxy Design Pattern is another structural design pattern that is used to provide a substitute for another object in order to control access to it. it basically allows us to create an intermediary that acts as an interface to another resource. For example, <strong><em>A debit card acts as a proxy for the funds available in a bank account</em></strong>. The card can be swiped in place of cash for making purchases for something from the market. The intent is to use an extra level of indirection to support distributed, controlled, or intelligent access to the target resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Edu8bVmYY6nYOc8BpVawWQ.png" /><figcaption>Proxy Design Pattern</figcaption></figure><p>You might be wondering how is it different from the <a href="https://shivanshugoyal0111.medium.com/4-design-pattern-facade-a6410fb35afa">Facade Design Pattern</a>. Implementation for many design patterns is quite similar. We can not easily distinguish which design pattern is being implemented in the given system. However, their intents are distinctive.</p><ol><li>The facade pattern defines a new interface for existing objects, whereas the Proxy pattern makes use of the existing subject’s interface.</li><li>The Facade Design Pattern also provides an interface to hide complexity from the client, but the Proxy acts as a proxy for a given resource. It can not be a proxy for multiple resources and it is not supposed to hide any complexity from the client.</li><li>The proxy pattern keeps the client&#39;s experience seamless as it defines an interface that will make the proxy and the original resource interchangeable whereas Facade creates a new wrapper to hide all the internal subsystems of the complex system.</li></ol><h4>How to implement the Proxy Pattern?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HaTrLMFs-NawRTsiikEwhQ.png" /></figure><p>The client always interacts with the proxy implementation which internally talks to the original implementation. Looks like we are not convinced why we need this proxy pattern. Why can’t the client directly invoke the original resource?</p><p>Let’s discuss some of the commonly known applications where the Proxy pattern is employed.</p><ol><li>You are an employee in your company. Any request made to the outside web goes through the proxy. None of the servers will get to know you are the real client requesting something. Having this proxy in between helps in access restrictions to some resources on the internet and also provides a level of security to the clients. This type of proxy is known as <strong>Protection Proxy</strong>.</li><li>The proxy can be also used to <strong>cache</strong> the static data to serve the client instead of making a new request for the same data. <strong>Logging</strong> can also be done as part of the proxy before and after the actual work.</li><li>The <strong>Virtual Proxy </strong>is used to delay the instantiation of <strong>resource-hungry</strong> objects until they are actually requested by the client.</li><li>It can also be used to <strong>change the behavior of existing beans</strong> without changing the original code.</li></ol><p>I will take an example of the Proxy Pattern where we need to add a layer or security before invoking the actual resource.</p><p><strong>Banker Interface</strong></p><pre>public interface Banker {<br><br>    //method to deposit the given amount to the given account<br>    void deposit(accountId, amount);<br><br>    //method to withdraw the given amount from the given account<br>    Long withdraw(accountId, amount);<br>}</pre><p><strong>Banker Interface Actual implementation</strong></p><pre>public class BankerImpl implements Banker {<br><br>    public void deposit(accountId, amount) {<br>        System.out.println(&quot;Depositing the amount %d to the account %s&quot;,<br>                           amount, accountId);<br>    }<br><br>    public Long withdraw(accountId, amount) {<br>        System.out.println(&quot;Withdrawing the amount %d from the account %s&quot;,<br>                           amount, accountId);<br>        return amount;<br>    }<br>}</pre><p><strong>Banker Interface Proxy implementation</strong></p><pre>public class BankerProxy implements Banker {<br><br>    //BankerProxy implements Banker interface<br>    //And it also has an actual implementation object<br>    private Banker banker; <br><br>    public BankerProxy() {<br>        banker = new BankerImpl();<br>    }<br><br>    public void deposit(accountId, amount) {<br>        //allow deposit only if the request is coming from banker<br>        if(request.userId is &quot;banker&quot;) {<br>            banker.deposit(accountId, amount);<br>        } else {<br>            throw new RuntimeException(&quot;Current user is not authorized to deposit&quot;);<br>        }<br>    }<br><br>    public Long withdraw(accountId, amount) {<br>        <br>        return banker.withdraw(accountId, amount);<br>    }<br>}</pre><h4>The Proxy Pattern is heavily used in Spring/SpringBoot for bean creation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NShjbYUkiRP8GpKS.jpg" /></figure><p>Whenever we define a bean in the Spring project <strong>ApplicationConfig</strong>, Spring creates a proxy for that <strong>ApplicationConfig</strong> using <strong>CGLIB</strong> and when the client needs a bean defined in the configuration, it always goes through the proxy bean which wrapped the actual bean creation method inside it.</p><p><strong>Why is it required?</strong></p><p>It is required as this bean is supposed to be a singleton bean and Proxy makes sure that the bankerBean() method is not called more than once. The request goes to the <strong>proxy of the ApplicationConfig</strong> instead of directly invoking the ApplicationConfig method and it checks whether the method is already called or not.</p><pre>@ComponentScan<br>@Configuration<br>public class ApplicationConfig {<br><br>    @Bean <br>    public BankerBean bankerBean() {<br>        System.out.println(&quot;Creating BankerBean!!&quot;);<br>        return new BankerImpl();<br>    }<br>}</pre><p>Thanks for reading!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea1a40a014ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>