<?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"><channel><title><![CDATA[Yash Bafna - Senior Engineer · Distributed Systems & LLM Infrastructure]]></title><description><![CDATA[Senior engineer with 7+ years building distributed systems at scale. Writing about LLM infrastructure, async architectures, and the design decisions behind production systems.]]></description><link>https://yashbafna.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 30 Nov 2026 21:35:48 GMT</lastBuildDate><atom:link href="https://yashbafna.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Building Routiq: a local-first LLM gateway that proves its savings]]></title><description><![CDATA[A local-first LLM gateway with semantic caching, complexity routing, and cost tracking. 84% cache hit, 9ms overhead. Prompts never leave your host.]]></description><link>https://yashbafna.hashnode.dev/building-routiq-local-first-llm-gateway</link><guid isPermaLink="true">https://yashbafna.hashnode.dev/building-routiq-local-first-llm-gateway</guid><category><![CDATA[llm]]></category><category><![CDATA[Python]]></category><category><![CDATA[System Design]]></category><category><![CDATA[distributed systems]]></category><category><![CDATA[infrastructure]]></category><category><![CDATA[chatgpt]]></category><category><![CDATA[Python 3]]></category><category><![CDATA[large language models]]></category><dc:creator><![CDATA[Yash Bafna]]></dc:creator><pubDate>Sat, 23 May 2026 14:01:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/60aa5b5020d1f45ceb7efc0d/224883e6-184f-4f29-a096-0d043bb47ded.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Your prompts shouldn't have to leave your machine to save you money.</p>
<p>That's the one-line pitch for Routiq, and it's also the constraint that made every other design decision harder. Most LLM cost-cutting tools are SaaS - you point your client at their endpoint, they proxy to OpenAI or Anthropic, they cache and route on their side, and your prompts (containing whatever code, customer data, or half-formed ideas you've typed) sit on their servers. The savings are real. The privacy cost is also real, and for a lot of teams it's a non-starter.</p>
<p>Routiq runs on your laptop or your server. You bring your own provider keys. Prompts never leave the host. And on repeated workloads it gets an <strong>84% cache hit rate, upto 88% cost savings, with 9ms p50 / 67ms p95 overhead</strong> before the provider call.</p>
<p>This post walks through how every piece works - caching, complexity routing, cost recording, security - what I chose, what I rejected, and what I got wrong on the first try.</p>
<hr />
<p><strong>Try it:</strong><br />Installation guide: <a href="https://github.com/yashbafna/routiq-feedback">github.com/yashbafna/routiq-feedback</a><br />PyPI: <a href="https://pypi.org/project/routiq">pypi.org/project/routiq</a> (v0.1.4)<br />Docker: <code>ghcr.io/yashbafna/routiq:latest</code></p>
<hr />
<h2>The problem</h2>
<p>Three things every developer using LLM APIs has seen:</p>
<p><strong>The same questions hit the same provider repeatedly.</strong> Your test suite asks "what's the capital of France" forty times across CI runs. Your team has six people who ask Claude how to write a regex for emails every other week. The API charges for every call.</p>
<p><strong>Trivial requests route to expensive models.</strong> "Format this JSON" and "design a multi-region failover strategy" go to the same <code>gpt-4o</code> or <code>claude-sonnet</code> because the SDK doesn't know the difference between them. You're paying premium token rates for jobs <code>gpt-4o-mini</code> or <code>gemini-flash-lite</code> would do for a fraction of the cost.</p>
<p><strong>The invoice is a black box.</strong> It arrives at month-end. It says $847. Nobody can tell you which feature, which user, or which week that came from.</p>
<p>There are tools that solve pieces of this - LiteLLM does multi-provider, Portkey and Helicone do observability, Bifrost does semantic caching - but most are either SaaS (your prompts leave your machine) or OSS that asks you to run Qdrant, Redis, Prometheus, and a dashboard server in production before the interesting features turn on. The slot for <em>runs on your machine, prompts stay local, BYOK, works in five minutes</em> was open.</p>
<p>Here's what's inside.</p>
<hr />
<h2>The pipeline, end to end</h2>
<p>Every request flows through eight stages before it goes to the provider, and through two more on the way back:</p>
<img src="https://cdn.hashnode.com/uploads/covers/60aa5b5020d1f45ceb7efc0d/553802eb-3c99-48c5-a7fb-6435f1bbf32d.png" alt="" style="display:block;margin:0 auto" />

<p>In one paragraph per stage:</p>
<p><strong>Alias resolution.</strong> Maps friendly names like <code>claude-latest</code> to canonical model IDs like <code>claude-sonnet-4-5-20250929</code>. Lets you write code that doesn't break when a new model version ships.</p>
<p><strong>Exact cache.</strong> SHA-256 over normalized messages, provider, and model. Redis lookup, sub-millisecond. The cheapest possible hit.</p>
<p><strong>Semantic cache.</strong> When the exact key misses, embed the prompt and search for cosine-similar entries above a threshold. ~48ms. Catches "how do I sort a list in Python" matching against "python list sort" - same intent, different bytes.</p>
<p><strong>Complexity analyzer.</strong> Heuristic classification - token count, keyword signals, tool presence - produces simple / medium / complex.</p>
<p><strong>Router.</strong> Maps complexity to a model tier, with multi-model fallback per tier. First registered provider wins, left-to-right on missing keys or open circuits.</p>
<p><strong>Adapter.</strong> Dispatches to OpenAI, Anthropic, DeepSeek, or Gemini with the right request shape. Connection pooling via <code>httpx</code> keeps TLS warm.</p>
<p><strong>Cache write.</strong> Stores the response + its embedding in Redis with a 1-hour TTL. Future similar prompts get the cached answer.</p>
<p><strong>Cost recording.</strong> Synchronous write to SQLite (WAL mode). Cost integrity beats tail latency.</p>
<p>The constraint that drove every algorithm choice downstream: <strong>9ms p50 for everything before the provider call</strong>. If a stage can't fit in its slice of that budget, it gets cut or made simpler.</p>
<hr />
<h2>Caching: exact, then semantic</h2>
<p>Cache is where 77–88% of the savings come from. Two layers, each tuned for a different failure mode.</p>
<h3>Exact cache</h3>
<p>The key is <code>SHA-256(normalized_messages + provider + model)</code>. Normalization strips whitespace and lowercases roles so <code>{"role": "User"}</code> and <code>{"role": "user"}</code> hash the same. Redis stores the response with a 1-hour TTL.</p>
<p>The interesting decision here is <strong>provider scoping</strong>. Anthropic and OpenAI behave differently:</p>
<ul>
<li><p>Anthropic responses are roughly portable across their models - a Sonnet response to "explain TCP" is reasonable for Haiku users too.</p>
</li>
<li><p>OpenAI responses are model-scoped - <code>gpt-4o</code> and <code>gpt-4o-mini</code> give meaningfully different answers to the same prompt and shouldn't share cache.</p>
</li>
</ul>
<p>So the cache key includes the model identifier for OpenAI / DeepSeek / Gemini and the provider identifier for Anthropic. Cross-model hits work where they're safe and don't where they aren't.</p>
<p><strong>Fail-open on Redis down.</strong> If Redis is unreachable, the cache stage logs the event and passes the request through to the provider with no caching. The alternative - return 503 because a cache layer blipped - punishes the user for an infrastructure issue they can't fix. Cache is a performance layer, not a correctness boundary. Fail-open is the right default for performance layers. (Cost recording, which is a correctness boundary, fails <em>closed</em> - more on that below.)</p>
<h3>Semantic cache</h3>
<p>Exact cache only hits identical bytes. The first time a user asks "how do I sort a list in Python" the bytes are different from the time their colleague asked "python list sort" yesterday, even though the answer is the same. Semantic cache is the fix.</p>
<img src="https://cdn.hashnode.com/uploads/covers/60aa5b5020d1f45ceb7efc0d/fdc9b261-e38c-4a2c-99e0-c8258043fdc5.png" alt="" style="display:block;margin:0 auto" />

<p>The choices:</p>
<p><strong>Model:</strong> <code>all-MiniLM-L6-v2</code><strong>.</strong> 22MB, CPU-only inference, ~40ms embed time on a laptop. Larger models give better semantic separation but cost startup time and memory the local-first promise can't afford. MiniLM is the floor that still works.</p>
<p><strong>Threshold: 0.82 cosine similarity.</strong> Tuned by hand against real traffic. The trade-off is brittle in both directions - too strict and you miss obvious matches, too loose and "sort a list" starts matching "sort a dictionary," which gives a wrong answer for a list-of-tuples question. The right number depends on your corpus; if you're using Routiq on a workload that's significantly different from general-purpose coding/QA prompts, this is the first knob to tune.</p>
<p><strong>Sub-50ms end-to-end</strong> because embedding cost dominates. Once you've paid ~40ms to embed, the Redis lookup is rounding error.</p>
<h3>What semantic cache will lie to you about</h3>
<p>Honest section. Semantic cache works great for <strong>short, intent-heavy prompts</strong> - "explain X," "what's the difference between Y and Z," "how do I do A in language B." Its failure mode is <strong>long conversations</strong>.</p>
<p>When a conversation has eight turns, the recent user message is buried under context. The embedding represents the <em>whole prompt</em>, which means two unrelated long conversations that share early context can look similar in vector space and produce a wrong cache hit. Routiq's current handling is conservative - the threshold and 1-hour TTL together make this rare in practice - but it's a real failure mode. For short interactive queries it's not a concern; for stateful agents with long history, treat semantic cache as opt-in per call and verify the matches on your workload.</p>
<hr />
<h2>Complexity routing: when "auto" makes sense</h2>
<p>The pitch is straightforward: not every request needs a frontier model. "Translate this to French" works on <code>gpt-4o-mini</code>. "Design a Raft consensus implementation for a multi-region key-value store" doesn't. If the SDK can tell the difference, you save real money.</p>
<h3>The classifier</h3>
<p>Heuristic, not ML. Three signals:</p>
<ol>
<li><p><strong>Token count.</strong> Long prompts skew complex. &gt;2000 tokens → bias toward complex tier.</p>
</li>
<li><p><strong>Keyword presence.</strong> A small list of words that empirically correlate with intent: <code>debug</code>, <code>implement</code>, <code>analyze</code>, <code>refactor</code>, <code>design</code>, <code>architecture</code> push toward complex; <code>format</code>, <code>summarize</code>, <code>translate</code>, <code>extract</code> push toward simple.</p>
</li>
<li><p><strong>Tool presence.</strong> Any tool definitions in the request → at least medium. Tool-using requests are almost always non-trivial.</p>
</li>
</ol>
<p>Why heuristic over a small ML classifier? The 9ms p50 budget. Loading even a tiny classifier costs RAM at startup and inference time per request, for marginal lift over rules. The heuristic is auditable (<code>grep</code> it), deterministic (same input → same tier), and free. When users hit the rare misclassification, they can override with <code>model="claude-latest"</code> and get exactly what they asked for.</p>
<h3>The router</h3>
<p>Maps complexity → tier → CSV of models, left-to-right fallback: simple: gemini-flash-lite-latest, gpt-4o-mini-latest, deepseek-chat medium: gpt-4o-latest, claude-haiku-latest, gemini-flash-latest complex: claude-latest, gpt-4o-latest, deepseek-reasoner-latest</p>
<p>First model whose provider has a key configured and an open circuit wins. If <code>claude-latest</code> is rate-limited, complex requests fall through to <code>gpt-4o-latest</code>. Configurable per deployment via env vars.</p>
<h3>The honest limitation</h3>
<p>A heuristic classifier is a coarse instrument. It will route some genuinely complex prompts to a cheap model. The mitigation is the escape hatch: <code>model="auto"</code> is opt-in. <code>model="claude-latest"</code> always wins, no routing happens, you pay full price for the model you asked for. Try <code>auto</code> on a workload where small precision loss is acceptable, watch the savings on the dashboard, decide.</p>
<hr />
<h2>Cost recording: the part most gateways get wrong</h2>
<p>Strong claim, then the receipts.</p>
<p>Most gateways record cost asynchronously - push the event to a queue, return the response, drain the queue in the background. This makes the hot path 1–2ms faster. It also means events get lost on crash, restart, or queue overflow. The result: the dashboard says you spent \(400 this month; the provider invoice says \)510. Now nobody trusts the dashboard, which was the whole reason you put a gateway in front of your LLM calls.</p>
<p>Routiq records synchronously. SQLite with WAL (write-ahead logging) mode for concurrent writes. Append-only writes are fast - under 1ms p50 - and the durability story is clean: the moment the response leaves the gateway, the cost row is on disk.</p>
<img src="https://cdn.hashnode.com/uploads/covers/60aa5b5020d1f45ceb7efc0d/006a5086-693f-465e-8644-c55b1b2658b2.png" alt="" style="display:block;margin:0 auto" />

<p>The explicit tradeoff: <strong>if the disk fills, the request 503s rather than silently dropping a cost event</strong>. Cost integrity wins over availability. This sounds harsh until you remember that the request still costs the user real money at the provider - losing the record means the user gets billed by OpenAI for a call they can't see in their dashboard. A 503 makes the problem loud and immediate; a silent drop makes it invisible until reconciliation.</p>
<p>Two more details:</p>
<p><strong>p50/p95/p99 are Routiq's overhead only, not provider latency.</strong> Mixing the two is a common dashboard mistake - a slow provider can hide a slow gateway, or a slow gateway can be blamed on the provider. The dashboard labels the metric explicitly: "Routiq overhead (excludes provider latency)."</p>
<p><strong>45-day retention with daily cleanup.</strong> Default rather than indefinite because nobody wants to debug a SQLite file that grew unbounded for a year. Configurable for users who want longer.</p>
<hr />
<h2>Security: the 22 fixes</h2>
<p>I ran the codebase through three rounds of security review and found 22 issues. Not all 22 are interesting - some are "rename this variable" - but six are worth a paragraph each.</p>
<p><strong>1. Constant-time API key comparison.</strong> The first version compared keys with <code>==</code>. That's a timing attack surface: the comparison short-circuits on the first mismatched byte, and over enough requests an attacker can recover the key one byte at a time. Fix: <code>hmac.compare_digest</code>, which is constant-time by construction. Cost of the fix: zero. Cost of skipping it: you have to explain it in a security review.</p>
<p><strong>2. SSRF protection on adapter URLs.</strong> Provider URLs come from configuration. An attacker who can write config - or who finds a config-injection bug - can point an adapter at <code>http://169.254.169.254/</code> (AWS metadata) or <code>http://localhost:6379</code> (your Redis) and exfiltrate. Fix: allowlist of host suffixes (<code>api.openai.com</code>, <code>api.anthropic.com</code>, etc.) and explicit block on private-IP ranges before the request goes out.</p>
<p><strong>3. Empty-key bypass.</strong> Found during audit: a request with <code>Authorization: Bearer</code> (header present, value empty) hit a code path that compared <code>""</code> to <code>""</code> and let the request through. Two-line fix: explicit length check before the constant-time compare. The lesson is that "constant-time comparison" doesn't help if you compare two empty strings.</p>
<p><strong>4. Startup guard for missing</strong> <code>ROUTIQ_API_KEY</code><strong>.</strong> Previous behavior: start the server with no auth key configured, fail every request at auth time. Real behavior should be: refuse to start, log loudly, exit. Failing fast at boot is cheaper than failing slowly at request time, and it's a clear signal in <code>docker compose up</code> output. Users who hit this stop hitting it after the first run.</p>
<p><strong>5. Auth on</strong> <code>/api/stats</code> <strong>and</strong> <code>/debug/semantic</code><strong>.</strong> These were unintentionally public on early builds - anyone on the network could pull dashboard data or query the semantic index. Now gated behind the same key as the proxy routes.</p>
<p><strong>6. Request scrubbing.</strong> Prompts never appear in logs. The implementation is <code>__repr__</code> overridden on the request model itself, not "remember to redact at every log site." Redaction discipline applied at the type boundary survives refactors; redaction discipline applied at log sites does not.</p>
<p>The other 16, in one line each:</p>
<ul>
<li><p>Security headers middleware (CSP, X-Content-Type-Options, Referrer-Policy)</p>
</li>
<li><p>PII regex scrubber on outbound logs</p>
</li>
<li><p><code>yaml.safe_load</code> everywhere, never <code>yaml.load</code></p>
</li>
<li><p>Non-root container user in the Dockerfile</p>
</li>
<li><p>Redis password required in default config</p>
</li>
<li><p>Dependency hash-pinning in <code>requirements.txt</code></p>
</li>
<li><p><code>pip-audit</code> in CI</p>
</li>
<li><p>TLS verification enforced on every adapter (no <code>verify=False</code>)</p>
</li>
<li><p>Rate limit on the auth endpoint to slow brute force</p>
</li>
<li><p>Idempotency keys to prevent double-billing on retries</p>
</li>
<li><p>Request size cap to bound memory</p>
</li>
<li><p>Backpressure: refuse new requests when in-flight count exceeds threshold</p>
</li>
<li><p>EdDSA signing on Docker images for integrity verification</p>
</li>
<li><p>Log rotation with size caps to prevent disk fill via log spam</p>
</li>
<li><p>Sanitized provider error messages (no prompt content in errors)</p>
</li>
<li><p><code>__repr__</code> override on the cost-record model as well as the request model</p>
</li>
</ul>
<p>Most of these are individually small. The aggregate is the point - security is a habit, not a milestone.</p>
<hr />
<h2>Two decisions I'd defend in a review</h2>
<p>The judgment section. Three picks, each with what I chose, what I rejected, and why.</p>
<p><strong>1. Synchronous cost recording.</strong> Rejected: async queue. The async version saves ~1ms p50 on the hot path. The failure mode - drift between dashboard and provider invoice - destroys the one number Routiq exists to surface. If your gateway can't tell you what you spent, why is it in front of your LLM calls?</p>
<p><strong>2. Heuristic complexity classifier.</strong> Rejected: small fine-tuned model. The 9ms p50 budget doesn't have room for inference, and the lift from an ML classifier over good heuristics is bounded - most requests are obvious from token count and keywords. Auditability beats marginal accuracy when the user can override anyway.</p>
<hr />
<h2>Try it</h2>
<p>Install path A - pip:</p>
<pre><code class="language-bash">pip install routiq
routiq start    # creates .env, then run again after adding keys
</code></pre>
<p>Install path B - Docker:</p>
<pre><code class="language-bash">curl -O https://raw.githubusercontent.com/yashbafna/routiq-feedback/main/docker-compose.yml
curl -O https://raw.githubusercontent.com/yashbafna/routiq-feedback/main/.env.example
mv .env.example .env
docker compose up -d
</code></pre>
<p>Using it from Python:</p>
<pre><code class="language-python">from routiq import RoutiqClient

client = RoutiqClient(
    api_key="your-key",
    base_url="http://localhost:8001"
)

# Auto-routing - complexity classifier picks the model
response = client.chat(model="auto", messages=[...])

# Pinned model - bypasses routing
response = await client.achat(
    model="gemini-flash-latest",
    messages=[...]
)
</code></pre>
<p>If you try it and something breaks, please file an issue (in github).</p>
]]></content:encoded></item><item><title><![CDATA[Design Principles -Contd.]]></title><description><![CDATA[To make design flexible, always try to program interface over concrete classes. This helps to extend code later very easily. Inheritance is the easiest way…]]></description><link>https://yashbafna.hashnode.dev/design-principles-contd</link><guid isPermaLink="true">https://yashbafna.hashnode.dev/design-principles-contd</guid><category><![CDATA[Design]]></category><category><![CDATA[design principles]]></category><category><![CDATA[design patterns]]></category><dc:creator><![CDATA[Yash Bafna]]></dc:creator><pubDate>Sun, 30 May 2021 16:00:25 GMT</pubDate><content:encoded><![CDATA[<h4 id="prefer-interface-over-concrete-class">Prefer interface over concrete class</h4>
<p>To make design flexible, always try to program interface over concrete classes.
This helps to extend code later very easily.</p>
<h4 id="favor-composition-over-inheritance">Favor composition over inheritance</h4>
<p>Inheritance is the easiest way to reuse the code. Just create a base class and inherit the same code in the child class. So simple, yes?</p>
<p>Unfortunately, inheritance has many disadvantages. If the child classes increases (which will be the common case for large applications), inheritance creates much coupling of classes.</p>
<p>Furthermore here is the list of other problems:</p>
<ol>
<li>If your parent class is having abstract methods, you need to inherit them to the child class, although it's not needed.</li>
<li>While overriding the parent method, one needs to be sure it is compatible with the parent method. Else it will break the code.</li>
<li>Inheritance exposes objects and methods to child classes. That is, child classes inherit objects from parents and as a result breaking the concept of encapsulation.</li>
<li>Tight coupling of the child classes. If any changes happen in parent class, that will affect child classes too.</li>
</ol>
<p>Phew!!! Though inheritance is a good concept to use but has many disadvantages.
But the good news is there is an alternative solution !!!
That is <strong>Composition</strong>.</p>
<p>Basically, inheritance is  '<em>is-a</em>' relation whereas composition is '<em>has-a</em>' relation.</p>
<p>Let's go to code.
Below is the simple inheritance:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Parent</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">print</span> <span class="hljs-string">'I am parent constructor'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">method</span> <span class="hljs-title">parent</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">print</span> <span class="hljs-string">'This is method of parent'</span>


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child</span>(<span class="hljs-params">Parent</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">print</span> <span class="hljs-string">'I am child constructor'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">methodChild</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">print</span> <span class="hljs-string">'This is method of child'</span>

<span class="hljs-comment">#calling child function</span>
obj = Child()
<span class="hljs-comment">#parent can be accessible as child inherits it</span>
obj.methodParent()
obj.methodChild()
</code></pre><p>Output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622382059229/UuPK9-xFu.png" alt="image.png" /></p>
<p>Now let's break this into the composition relationship.</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SmallFeature</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(<span class="hljs-keyword">self</span>)</span></span>:
        print <span class="hljs-string">'I am small feature class constructor'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">methodSmallFeature</span><span class="hljs-params">(<span class="hljs-keyword">self</span>)</span></span>:
        print <span class="hljs-string">'This is method of small feature class'</span>


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainApplication</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(<span class="hljs-keyword">self</span>)</span></span>:
        <span class="hljs-keyword">self</span>.obj = SmallFeature()
        print <span class="hljs-string">'I am main application constructor'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">methodOfMainApplication</span><span class="hljs-params">(<span class="hljs-keyword">self</span>)</span></span>:
        <span class="hljs-keyword">self</span>.obj.methodSmallFeature()

<span class="hljs-comment">#calling MainApplication object</span>
obj = MainApplication()
obj.methodOfMainApplication()
</code></pre><p>Output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622382363540/lQFgnfJQ4.png" alt="image.png" /></p>
<p>But if we try to access 'SmallFeature Class', methodSmallFeature() from the object of MainApplication, the code will crash.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622382459582/Pv69a80Bv.png" alt="image.png" /></p>
<p>That's a lot of stuff!!</p>
<p>Let's move to the end of this article and see when to use inheritance and composition.</p>
<ul>
<li>If someone wants to <strong>change the behavior of the methods</strong> of a class then <strong>inheritance</strong> is favorable.</li>
<li>If someone wants to just <strong>use the methods without changing their behavior</strong> of them,  then the <strong>composition</strong> is favorable.</li>
</ul>
<hr />
<p>That's all for this article now. Hope you like the article.</p>
<p>Thanks for reading!!😀</p>
<p>Stay Tuned for more.</p>
]]></content:encoded></item><item><title><![CDATA[Design principles]]></title><description><![CDATA[Let's discuss some of the good software design principles]]></description><link>https://yashbafna.hashnode.dev/design-principles</link><guid isPermaLink="true">https://yashbafna.hashnode.dev/design-principles</guid><category><![CDATA[design principles]]></category><category><![CDATA[design patterns]]></category><dc:creator><![CDATA[Yash Bafna]]></dc:creator><pubDate>Sun, 30 May 2021 15:57:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1622564938792/nVML306r-.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="favor-encapsulation-for-the-items-that-varies">Favor encapsulation for the items that varies</h3>
<p>If there are certain part of the application that varies a lot, identify them and separate them. This way it will minimize the effect caused by changes.</p>
<h4 id="encapsulate-the-method">Encapsulate the method</h4>
<p>Let's take the example of calculating library charges based on the age of the student.</p>
<p>Below is the code snippet for the same in Python.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calculateLibraryCharges</span>(<span class="hljs-params">name, age</span>):</span>
    libraryCharge=<span class="hljs-number">0</span>
    <span class="hljs-keyword">if</span> age &lt; <span class="hljs-number">20</span>:
        libraryCharge=<span class="hljs-number">200</span>
    <span class="hljs-keyword">elif</span> age &gt;=<span class="hljs-number">20</span> <span class="hljs-keyword">and</span> age &lt;=<span class="hljs-number">22</span>:
        libraryCharge=<span class="hljs-number">300</span>
    <span class="hljs-keyword">else</span>:
        libraryCharge=<span class="hljs-number">400</span>
    print(name,<span class="hljs-string">' your library charges is Rs.'</span>,libraryCharge)

calculateLibraryCharges(<span class="hljs-string">'Yash'</span>,<span class="hljs-number">25</span>)
</code></pre><p>It will output as:</p>
<pre><code>Yash  your <span class="hljs-keyword">library</span> charges <span class="hljs-keyword">is</span> Rs. <span class="hljs-number">400</span>
</code></pre><p>Here if we want to modify the logic for calculating charges then it would be difficult. One can say, hey Yash it's easy to keep logic for the above code snippet. Generally, this is small code but in enterprise applications, code is much big. It cannot be good to maintain like above.</p>
<p>Instead, we should break the code further and separate the logic, like below.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">chargesBasedOnAge</span>(<span class="hljs-params">age</span>):</span>
    <span class="hljs-keyword">if</span> age &lt; <span class="hljs-number">20</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">200</span>
    <span class="hljs-keyword">elif</span> age &gt;=<span class="hljs-number">20</span> <span class="hljs-keyword">and</span> age &lt;=<span class="hljs-number">22</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">300</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">400</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calculateLibraryCharges</span>(<span class="hljs-params">name, age</span>):</span>
    print(name,<span class="hljs-string">' your library charges is Rs.'</span>,chargesBasedOnAge(age))
</code></pre><p>Output:</p>
<pre><code>Yash your <span class="hljs-keyword">library</span> charges <span class="hljs-keyword">is</span> Rs. <span class="hljs-number">400</span>
</code></pre><p>So with the separation of the logic, code is quite maintainable and readable.</p>
<p>Let's see the second principle- <em>Encapsulation over class</em></p>
<hr />
<h6 id="encapsulation-over-class-level"><strong>Encapsulation over class level</strong></h6>
<p>Over the time of the application, one might feel to add more responsibilities to it. It will be better to separate the helper methods into separate classes.</p>
<p>Taking our previous example. We can separate out calculating library charges and main function into separate classes.</p>
<p>Below is the Library charges class in Python which will calculate library charges based on age.</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LibraryCharges</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(<span class="hljs-keyword">self</span>, age)</span></span>:
        <span class="hljs-keyword">self</span>.__age = age

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calculateLibraryCharges</span><span class="hljs-params">(<span class="hljs-keyword">self</span>)</span></span>:
        libraryCharge = <span class="hljs-number">0</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">self</span>.__age &lt; <span class="hljs-number">20</span>:
            libraryCharge = <span class="hljs-number">200</span>
        elif <span class="hljs-number">20</span> &lt;= <span class="hljs-keyword">self</span>.__age &lt;= <span class="hljs-number">22</span>:
            libraryCharge = <span class="hljs-number">300</span>
        <span class="hljs-symbol">else:</span>
            libraryCharge = <span class="hljs-number">400</span>
        <span class="hljs-keyword">return</span> libraryCharge
</code></pre><p>And the main function as:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">mainFunction</span>(<span class="hljs-params">name, age</span>):</span>
    libObj = LibraryCharges(age)
    print(<span class="hljs-string">"Hi, {0} your library charges is Rs.{1}"</span>.format
    (name,libObj.calculateLibraryCharges()))
</code></pre><p>Running it as :</p>
<pre><code><span class="hljs-selector-tag">mainFunction</span>(<span class="hljs-string">'Yash'</span>, <span class="hljs-number">25</span>)
</code></pre><p>It will output as:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622279792994/eXl5BRUh7.png" alt="image.png" /></p>
<p>This way we have maintained objects separately and hence it is quite easy to maintain the logic of the application.</p>
<hr />
<p>That's all for this article now. Hope you like the article.</p>
<p>Thanks for reading!!😀</p>
<p>Stay Tuned for more.</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to Design Pattern]]></title><description><![CDATA[In this article, we will see what we mean by design patterns.]]></description><link>https://yashbafna.hashnode.dev/introduction-to-design-pattern</link><guid isPermaLink="true">https://yashbafna.hashnode.dev/introduction-to-design-pattern</guid><category><![CDATA[design patterns]]></category><category><![CDATA[Design]]></category><category><![CDATA[design principles]]></category><dc:creator><![CDATA[Yash Bafna]]></dc:creator><pubDate>Sun, 30 May 2021 15:49:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1622564328696/fO7e5Ug0S.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="what-are-design-patterns"><strong>What are design patterns?</strong></h3>
<p>Design patterns are typical solutions to commonly occurring problems in software design. They are predefined blueprints to solve a commonly occurring problem.</p>
<p><em>Please note</em>- There is a difference between design patterns and algorithms. Basically, an algorithm is a set of clearly defined instructions whereas a design pattern is a more high-level description of the solution.</p>
<p>In general, a design pattern has 4 essential elements:</p>
<ol>
<li><em>Pattern Name</em>- It describes the vocabulary of the pattern (i.e., pattern name)</li>
<li><em>Problem statement</em> - It describes when to apply the pattern.</li>
<li><em>Solution</em> - It describes the elements that make up the design, relationships, responsibilities, and collaboration.</li>
<li><em>Consequences</em> - They are the result of trade-offs of applying the pattern. </li>
</ol>
<h3 id="classification-of-design-patterns"><strong>Classification of design patterns</strong></h3>
<p>Design patterns are mainly classified into 3 broader categories.</p>
<ul>
<li><strong>Creational pattern</strong>:- It relates to how objects are created and can be reused.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622002277721/UZKn9sSCg.png" alt="Creational.png" /></li>
<li><strong>Structural pattern</strong>:- It explains how to assemble objects and classes into larger structures.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622002303980/9qoPvliJM.png" alt="structural.png" /></li>
<li><strong>Behavioral pattern</strong>:- It dictates the interaction of classes and objects amongst each other and assignment of the responsibility.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622002319032/C9gVdDE1d.png" alt="Behavioral.png" /></li>
</ul>
<hr />
<p><em>Fun Fact</em></p>
<p>The concept of patterns was first coined and described by Christopher Alexander in  <a target="_blank" href="https://www.amazon.in/Pattern-Language-Buildings-Construction-Environmental/dp/0195019199/ref=sr_1_1?crid=34Y95R971R7LJ&amp;dchild=1&amp;keywords=a+pattern+language+towns%2C+buildings%2C+construction&amp;qid=1622002947&amp;sprefix=a+pttern%2Caps%2C338&amp;sr=8-1"><em>A Pattern Language: Towns, Buildings, Construction</em></a>
The idea was picked up by four authors: Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm. In 1995 they published <a target="_blank" href="https://www.amazon.in/Design-Patterns-Erich-Gamma/dp/9332555400/ref=sr_1_1_sspa?dchild=1&amp;keywords=design+pattern&amp;qid=1622003073&amp;sr=8-1-spons&amp;psc=1&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEzUEU4UktGSzNLMUlQJmVuY3J5cHRlZElkPUEwNzM4NTc4MjRSRE0yVTc5TlQ3UyZlbmNyeXB0ZWRBZElkPUEwNTA2MzkzQTVRRlAzRE82MDFSJndpZGdldE5hbWU9c3BfYXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ=="><em>Design Patterns</em></a> in which they applied the concept of design pattern in software design. <em>They are generally known as GoF (gang of four).</em></p>
<hr />
<p>That's all for this article now.
Hope you like the article. </p>
<p>Thanks for reading!!😀</p>
<p>Stay Tuned for more.</p>
]]></content:encoded></item></channel></rss>