<?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 Rupen Anjaria on Medium]]></title>
        <description><![CDATA[Stories by Rupen Anjaria on Medium]]></description>
        <link>https://medium.com/@rupen-anjaria?source=rss-fb4ba040f2fd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1_a7cEZlnANvbCsg.</url>
            <title>Stories by Rupen Anjaria on Medium</title>
            <link>https://medium.com/@rupen-anjaria?source=rss-fb4ba040f2fd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:52:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rupen-anjaria/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[Advanced Change Detection & Zone Optimization in Angular]]></title>
            <link>https://rupen-anjaria.medium.com/advanced-change-detection-zone-optimization-in-angular-1a0c6a5662f9?source=rss-fb4ba040f2fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a0c6a5662f9</guid>
            <category><![CDATA[zonejs-in-angular]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Rupen Anjaria]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 20:13:18 GMT</pubDate>
            <atom:updated>2026-07-26T20:13:18.084Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding What Actually Triggers Your UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4uERM-Te3nknkfvKP8VTQA.png" /></figure><h3>The Hidden Cost of “It Just Works”</h3><p>One of Angular’s greatest strengths is also one of its biggest performance traps <em>Angular automatically updates the UI for you.</em></p><p>What we miss to ask:</p><ul><li><em>When does Angular decide to update?</em></li><li><em>How often does it check components?</em></li><li><em>What triggered the render?</em></li><li><em>How expensive was it?</em></li></ul><p>In small applications, this abstraction is helpful.</p><p>In enterprise systems with:</p><ul><li>complex dashboards,</li><li>real-time updates,</li><li>massive component trees,</li><li>and 50+ concurrent interactions,</li></ul><p>…it becomes critical to understand the runtime model.</p><h3>First Principles: Angular Does Not “Watch Variables”</h3><p>This is one of the biggest misconceptions in Angular. Angular does <strong>not</strong> observe variable changes directly.</p><p>Instead:</p><ol><li>Something asynchronous happens</li><li>Angular gets notified</li><li>Angular runs change detection</li><li>Angular compares template expressions</li><li>The DOM updates if values changed</li></ol><p>The key question becomes:</p><blockquote><strong><em>Who tells Angular that something happened?</em></strong></blockquote><p>The answer is: <strong>Zone.js</strong></p><h3>What Zone.js Actually Do</h3><h4>The Simplified Mental Model</h4><p>Under the hood, Zone.js monkey-patches asynchronous browser APIs such as:</p><ul><li>setTimeout</li><li>Promise</li><li>DOM events</li><li>XHR/fetch</li><li>requestAnimationFrame</li></ul><p>When async work completes, Zone.js informs Angular that <em>“Something might have changed.” </em>Angular then triggers change detection.</p><p><strong>Visualizing the Flow</strong></p><pre>User Click<br>   ↓<br>Browser Event<br>   ↓<br>Zone.js intercepts event<br>   ↓<br>Angular notified<br>   ↓<br>Change Detection Runs<br>   ↓<br>DOM updates</pre><p>This is why Angular “magically” updates the screen.</p><h3>The Real Performance Problem</h3><p>Angular’s default strategy historically has been <em>“When in doubt, check everything.” </em>This is fine for small apps, but expensive for enterprise applications.</p><p><strong>Why Large Component Trees Become Slow</strong></p><p>Imagine:</p><ul><li>5,000 bindings</li><li>Nested reusable widgets</li><li>Real-time streams</li><li>Charts updating every second</li></ul><p>Each async event can trigger:</p><ul><li>full component tree traversal</li><li>expression evaluation</li><li>DOM comparison</li></ul><p>Even if nothing visible changed.</p><h3>Change Detection Strategies</h3><p>Angular provides two primary strategies:</p><p><strong>1. Default Strategy:</strong> Every async event can re-check the entire subtree</p><h4>Pros</h4><ul><li>Easy mental model</li><li>Beginner-friendly</li></ul><h4>Cons</h4><ul><li>Expensive at scale</li><li>Harder to predict rendering cost</li></ul><p>2. <strong>OnPush Strategy: </strong>Angular skips checks unless</p><ul><li>Input reference changes</li><li>Event occurs inside component</li><li>Observable emits via async pipe</li><li>Manual trigger happens</li></ul><h3>The Biggest OnPush Misunderstanding</h3><p>Many developers believe <em>“OnPush means Angular only updates when inputs change.”. </em>That’s not true. Events inside the component still trigger checks.</p><p>Example:</p><pre>&lt;button (click)=&quot;increment()&quot;&gt;+&lt;/button&gt;</pre><p>This still schedules change detection.</p><h3>Mutation vs Immutability</h3><p>This is where many teams accidentally break OnPush.</p><pre>this.user.name = &#39;John&#39;;</pre><p>Reference did not change. Angular may skip update.</p><pre>this.user = {<br>  ...this.user,<br>  name: &#39;John&#39;<br>};</pre><p>New reference so, Angular detects change.</p><h3>Micro-Tasks vs Macro-Tasks</h3><p>This is where performance discussions become truly interesting.</p><h3>Macro-Tasks</h3><p>Examples:</p><ul><li>setTimeout</li><li>setInterval</li><li>DOM events</li></ul><p>Scheduled through browser task queue.</p><h3>Micro-Tasks</h3><p>Examples:</p><ul><li>Promise.then</li><li>queueMicrotask</li><li>async/await continuations</li></ul><p>Micro-tasks execute immediately after current execution finishes, before rendering.</p><h3>Why This Matters in Angular</h3><p>Zone.js patches both.</p><p>But micro-tasks can flood change detection much faster.</p><h3>Example Problem</h3><pre>Promise.resolve().then(() =&gt; {<br>  this.updateUI();<br>});</pre><p>Now imagine:</p><ul><li>websocket stream</li><li>RxJS chains</li><li>dozens of micro-task emissions</li></ul><p>You may accidentally trigger:</p><ul><li>excessive CD cycles</li><li>UI thrashing</li><li>frame drops</li></ul><h3>Production Insight</h3><p>Many enterprise Angular performance issues are not caused by:</p><ul><li>DOM size</li><li>bundle size</li></ul><p>…but by excessive asynchronous churn.</p><h3>Zone Pollution: A Silent Performance Killer</h3><p>Third-party libraries often trigger unnecessary change detection.</p><p>Examples:</p><ul><li>scrolling libraries</li><li>charting libraries</li><li>mouse movement listeners</li><li>resize handlers</li></ul><p>These can generate:</p><ul><li>hundreds of events per second</li><li>unnecessary Angular checks</li></ul><h3>Solution: Run Outside Angular Zone</h3><p>Angular provides:</p><pre>constructor(private ngZone: NgZone) {}</pre><h3>Example</h3><pre>this.ngZone.runOutsideAngular(() =&gt; {<br>  window.addEventListener(&#39;scroll&#39;, () =&gt; {<br>    // expensive logic<br>  });<br>});</pre><p>Now Angular will not trigger change detection on every scroll event.</p><h3>Re-entering Angular Only When Necessary</h3><pre>this.ngZone.run(() =&gt; {<br>  this.isVisible = true;<br>});</pre><p>This pattern is extremely valuable for:</p><ul><li>animations</li><li>canvas rendering</li><li>chart updates</li><li>drag/drop systems</li></ul><h3>Real-World Example: Chart Performance</h3><p>A common enterprise issue:</p><p>Dashboard with:</p><ul><li>12 charts</li><li>live refresh every second</li><li>mouse hover interactions</li></ul><p>Symptoms:</p><ul><li>CPU spikes</li><li>frame drops</li><li>laggy UI</li></ul><h3>Root Cause</h3><p>Chart library generated:</p><ul><li>mousemove events</li><li>resize events</li><li>animation callbacks</li></ul><p>Each triggered Angular change detection.</p><h3>Fix</h3><p>Move chart rendering outside Angular zone.</p><p>Result:</p><ul><li>dramatically reduced CD cycles</li><li>smoother interaction</li><li>lower CPU usage</li></ul><h3>Zone-Less Angular</h3><p>Angular is moving toward a future where Zone.js becomes <a href="https://angular.dev/guide/zoneless">optional</a>. This is one of the most important architectural shifts in modern Angular.</p><h4>Why Go Zone-Less?</h4><p>Benefits:</p><ul><li>predictable rendering</li><li>reduced overhead</li><li>better scalability</li><li>explicit control</li></ul><p>Trade-off:</p><ul><li>developer must manually signal updates</li></ul><h4>Example Configuration</h4><pre>bootstrapApplication(AppComponent, {<br>  providers: [<br>    provideZoneChangeDetection({<br>      eventCoalescing: true<br>    })<br>  ]<br>});</pre><p>Or fully disable zones:</p><pre>ngZone: &#39;noop&#39;</pre><p>If you chose to go zone less then make sure to uninstall zone.js to reduce bundle size.</p><h3>Reality Check: Should You Go Zone-Less?</h3><h4>Good Candidates</h4><ul><li>highly interactive dashboards</li><li>financial trading systems</li><li>visualization-heavy apps</li><li>performance-critical enterprise systems</li></ul><h4>Bad Candidates</h4><ul><li>small CRUD apps</li><li>junior-heavy teams</li><li>fast-moving projects without performance issues</li></ul><h4>Profiling Angular Applications in Production</h4><p>Most teams profile incorrectly.</p><p>They focus only on:</p><ul><li>Lighthouse</li><li>bundle size</li></ul><p>But runtime performance matters equally.</p><h3>What to Measure</h3><h4>1. Change Detection Frequency</h4><p>Ask:</p><ul><li>How often is CD running?</li><li>Which components rerender most?</li></ul><h4>2. Long Tasks</h4><p>Use Chrome Performance panel.</p><p>Look for:</p><ul><li>scripting spikes</li><li>layout thrashing</li><li>excessive event handlers</li></ul><h4>3. Frame Drops</h4><p>Target:</p><ul><li>60 FPS</li><li>under 16ms/frame</li></ul><h4>Angular DevTools</h4><p>Angular DevTools provides:</p><ul><li>component profiler</li><li>change detection analysis</li><li>runtime insights</li></ul><p>This is vastly underused in enterprise teams.</p><h3>Advanced Production Technique: Event Coalescing</h3><p>Angular can merge multiple events into fewer change detection runs.</p><p>Example:</p><pre>provideZoneChangeDetection({<br>  eventCoalescing: true<br>})</pre><p>This can significantly reduce rendering pressure.</p><h3>Important Trade-Off</h3><p>Optimization is not free. Every optimization introduces:</p><ul><li>Complexity</li><li>Debugging difficulty</li><li>Onboarding cost</li></ul><p>The goal is not: <em>“Use every performance trick.”</em></p><p>The goal is: <em>“Use the minimum complexity required.”</em></p><h3>A Practical Decision Framework</h3><h4>Use Default Strategy When:</h4><ul><li>App is small</li><li>Performance is acceptable</li><li>Simplicity matters more</li></ul><h4>Use OnPush When:</h4><ul><li>App scales significantly</li><li>Component trees grow large</li><li>Rendering becomes measurable bottleneck</li></ul><h4>Use Zone-Less When:</h4><ul><li>Performance profiling proves zones are bottleneck</li><li>Your team understands rendering mechanics deeply</li></ul><h3>Final Thoughts</h3><p>Angular performance optimization is fundamentally about controlling unnecessary work. The best Angular engineers are not those who memorize APIs.</p><p>They understand:</p><ul><li>rendering mechanics</li><li>async behavior</li><li>browser event loops</li><li>scheduling costs</li><li>architectural trade-offs</li></ul><p>That understanding is what allows large Angular systems to remain fast — even under enterprise-scale complexity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a0c6a5662f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro frontends in Angular: When They Work and When They Fail]]></title>
            <link>https://rupen-anjaria.medium.com/micro-frontends-in-angular-when-they-work-and-when-they-fail-9b43a73cbc6d?source=rss-fb4ba040f2fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b43a73cbc6d</guid>
            <category><![CDATA[google-developer-expert]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-microfrontend]]></category>
            <dc:creator><![CDATA[Rupen Anjaria]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 20:07:23 GMT</pubDate>
            <atom:updated>2026-06-28T20:07:23.580Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pM98JxsF_bfNqOMAvHSRLw.png" /></figure><p>Over the last few years, micro frontends have become one of the most discussed architectural patterns in enterprise Angular applications. Conference talks, blog posts, and vendor presentations often describe them as the natural evolution of frontend architecture, promising independent deployments, autonomous teams, and faster delivery.</p><p>The reality is more complexed.</p><p>Micro frontends solve specific organizational problems, not technical ones. Many enterprises adopt them hoping to improve scalability, only to discover increased complexity, dependency conflicts, slower debugging, and difficult operational challenges.</p><p>This article cuts through the hype and examines where Angular micro frontends create real value, where they introduce unnecessary complexity, and how to recognize the warning signs before a project becomes difficult to maintain.</p><p><strong>Understanding Micro frontends</strong></p><p>A micro frontend architecture breaks a large frontend application into multiple independently developed and deployed applications.</p><p>Instead of a single Angular application owned by one team, multiple teams own separate applications that are assembled at runtime into a unified user experience.</p><p>A common enterprise structure might look like:</p><ul><li>Shell Application</li><li>Customer Management Application</li><li>Billing Application</li><li>Reporting Application</li><li>Administration Application</li></ul><p>Each application can be built, tested, and deployed independently.</p><p>The promise may sounds compelling:</p><ul><li><em>Faster team autonomy: </em>One team focuses on Billing and another on Reporting.</li><li><em>Independent deployments:</em> Billing can go without impacting Reporting.</li><li><em>Better scalability:</em> If Reporting has more demand then we can just focus on scaling that app.</li></ul><p>However, there are challenges.</p><h3><strong>Module Federation Architecture</strong></h3><p>Angular micro frontends are generally implemented using <a href="https://webpack.js.org/concepts/module-federation/">Webpack Module Federation</a>.</p><p>Module Federation allows one application to dynamically load modules from another application at runtime.</p><p>A typical architecture consists of:</p><h3>Host (Shell)</h3><p>The shell application acts as the entry point.</p><p>Its responsibilities include:</p><ul><li>Authentication</li><li>Navigation</li><li>Layout</li><li>Shared state orchestration</li><li>Loading remote applications</li></ul><h3>Remote Applications</h3><p>Each business domain becomes a remote application.</p><p>Examples:</p><ul><li>Customer Portal</li><li>Orders</li><li>Payments</li><li>Analytics</li></ul><p>The shell downloads remote bundles only when needed.</p><p>Instead of deploying one massive application, multiple deployable artifacts exist across different teams.</p><p>This architecture enables deployment independence but introduces runtime dependencies that do not exist in a traditional Angular monolith.</p><h3>Where it works?</h3><p>Many discussions focus on technical scalability. The bigger advantage is organizational scalability.</p><p>Imagine a company with:</p><ul><li>5 frontend teams</li><li>80 developers</li><li>Multiple release schedules</li></ul><p>Without micro frontends:</p><ul><li>All the team members have to be in releases</li><li>Shared code creates bottlenecks and error prone.</li><li>Large builds slow delivery</li><li>Production deployment surprises/miscommunications etc.</li></ul><p>With micro frontends:</p><ul><li>Teams release independently (we don’t need everyone to be awake till 2 AM)</li><li>Ownership boundaries become clearer</li><li>Faster deployment</li><li>No surprises as long as team knows the business.</li></ul><p>Note that the the problem being solved is non-technical. If team coordination is smooth then micro frontends may provide little value.</p><h3>Problem: Deployment Independence vs Architectural Complexity</h3><p>Every independent deployment creates additional operational complexity. However, complexity increases in several areas:</p><h3>Runtime Failures</h3><p>Traditional Angular applications fail during <em>build </em>time.</p><p>Micro frontends can fail during <em>runtime — more serious incident</em>. This includes:</p><ul><li>Remote application unavailable</li><li>Incorrect federation configuration (when an app’s build tools or runtime scripts are misaligned)</li><li>CDN deployment delay (the time it takes for new updates to a micro frontend to become visible to end-users.)</li><li>Version mismatch</li></ul><p>Users may encounter failures that passed all CI/CD validations.</p><h3>Distributed Debugging</h3><p>A production bug might involve:</p><ul><li>Shell application</li><li>Authentication application</li><li>Shared library</li><li>Remote application</li></ul><p>Identifying root cause becomes significantly harder.</p><p>What once required debugging a single application now requires understanding an entire distributed frontend ecosystem.</p><h3>Monitoring Challenges</h3><p>Traditional monitoring becomes insufficient.</p><p>Teams must monitor:</p><ul><li>Remote availability</li><li>Federation loading failures</li><li>Shared dependency conflicts</li><li>Cross-application communication</li></ul><p>Operational maturity becomes a prerequisite.</p><h3>Shared Dependencies: The Hidden Challenge</h3><p>Most micro frontend failures originate from shared dependencies. At first glance, sharing Angular packages appears simple.</p><p>Common shared libraries include:</p><ul><li>Angular Core</li><li>Angular Router</li><li>RxJS</li><li>Angular Material</li><li>Design Systems</li></ul><p>The problem emerges as teams evolve independently.</p><p>Consider:</p><p>Team A upgrades to Angular 21.</p><p>Team B remains on Angular 20.</p><p>Team C introduces a breaking change in a shared UI library.</p><p>Everything may compile successfully.</p><p>The failure appears only after deployment.</p><p>These runtime conflicts are among the most frustrating problems in micro frontend environments because they often escape traditional testing pipelines.</p><h3>The Duplicate Framework Problem</h3><p>One of the most <em>expensive </em>mistakes is loading multiple framework versions.</p><p>Imagine:</p><ul><li>Shell loads Angular 20</li><li>Remote loads Angular 21</li></ul><p>Without proper federation configuration, both frameworks may be downloaded.</p><p>Consequences include:</p><ul><li>Larger bundles</li><li>Increased memory usage</li><li>Slower startup times</li><li>Unexpected runtime behavior</li></ul><p>Organizations sometimes adopt micro frontends expecting performance improvements and accidentally ship significantly larger applications.</p><p>Performance budgets become harder to enforce because responsibility is distributed across multiple teams.</p><h3>Versioning Strategies That Actually Work</h3><p>Successful micro frontend platforms treat versioning as a <em>first-class</em> architectural concern.</p><h3>Strategy 1: Platform Governance</h3><p>Establish a platform team responsible for:</p><ul><li>Angular upgrades</li><li>Shared library versions</li><li>Dependency policies</li></ul><p>This reduces autonomy slightly but prevents architectural chaos.</p><h3>Strategy 2: Shared Design System</h3><p>A centrally managed design system ensures:</p><ul><li>Visual consistency</li><li>Component reuse</li><li>Accessibility compliance</li></ul><p>Without this, applications begin to look like separate products stitched together.</p><h3>Strategy 3: Controlled Upgrade Windows</h3><p>Instead of allowing every team to upgrade independently:</p><ul><li>Define quarterly upgrade windows</li><li>Coordinate framework changes</li><li>Validate federation compatibility</li></ul><p>Many large organizations eventually adopt this model after experiencing dependency fragmentation.</p><p>Let’s discuss some failure scenarios.</p><h3>Failure Scenario #1: The Enterprise Portal Collapse</h3><p>A global enterprise adopted micro frontends across 15 teams. Initially, deployment speed improved dramatically.</p><p>After two years:</p><ul><li>Angular versions diverged</li><li>Shared libraries forked</li><li>Design systems drifted</li><li>Runtime errors increased</li></ul><p>Eventually, nearly every release required cross-team validation.</p><p>The architecture that was intended to reduce coordination created more coordination than the original monolith.</p><p>The root cause was not technology.</p><p>It was lack of governance.</p><h3>Failure Scenario #2: The Small Team Anti-Pattern</h3><p>A company with six frontend developers adopted micro frontends because it was considered a modern architecture.</p><p>They created:</p><ul><li>Shell</li><li>Customer application</li><li>Orders application</li><li>Reporting application</li></ul><p>Within six months:</p><ul><li>Build pipelines tripled</li><li>Deployment processes multiplied</li><li>Testing complexity increased</li><li>Team productivity declined</li></ul><p>The organization spent more time maintaining architecture than delivering business value. The original Angular monolith would have scaled comfortably for years. This is one of the most common micro frontend failures.</p><p>The architecture solves a problem that does not exist.</p><h3>Failure Scenario #3: The Shared Library Explosion</h3><p>A large organization created dozens of shared packages:</p><ul><li>Shared UI</li><li>Shared Utilities</li><li>Shared Services</li><li>Shared Components</li><li>Shared State</li></ul><p>Over time every application depended on everything. The result was a distributed monolith. Teams appeared independent but remained tightly coupled through shared packages.</p><p>A single breaking change triggered organization-wide releases.</p><p>Micro frontends existed only on paper.</p><p>Architecturally, the system behaved like a monolith with additional complexity.</p><h3>When Micro frontends Work Extremely Well</h3><p>Micro frontends often succeed when all of the following conditions exist:</p><h3>Large Engineering Organizations</h3><p>Typically:</p><ul><li>Multiple frontend teams</li><li>Independent business domains</li><li>Different release schedules</li></ul><h3>Strong Domain Boundaries</h3><p>Examples:</p><ul><li>Commerce</li><li>Billing</li><li>Analytics</li><li>Customer Management</li></ul><p>Each domain can evolve independently.</p><h3>Mature DevOps Practices</h3><p>Organizations already possess:</p><ul><li>CI/CD automation</li><li>Observability</li><li>Distributed monitoring</li><li>Platform engineering expertise</li></ul><p>Micro frontends are strategic infrastructure. The payoff appears over years, not months.</p><h3>When NOT to Use Micro frontends</h3><p>Avoid micro frontends when:</p><h3>You Have One Team</h3><p>A modular Angular monolith is almost always simpler.</p><h3>Your Application Is Small</h3><p>Premature architectural distribution creates unnecessary complexity.</p><h3>Teams Share Most Features</h3><p>Heavy collaboration usually indicates weak domain boundaries.</p><h3>You Lack Platform Engineering Resources</h3><p>Someone must own:</p><ul><li>Federation infrastructure</li><li>Dependency governance</li><li>Upgrade coordination</li><li>Monitoring</li></ul><p>Without this ownership, complexity accumulates rapidly.</p><h3>Your Motivation Is Trend Adoption</h3><p>The most dangerous reason to adopt micro frontends is:</p><p>“Everyone else is doing it.”</p><p>Architecture should solve business problems, not follow industry fashion.</p><h3>A Practical Decision Framework</h3><p>Ask these questions before adopting micro frontends:</p><ol><li>Do multiple teams need independent deployments?</li><li>Are business domains clearly separable?</li><li>Will team count continue growing?</li><li>Can we invest in platform governance?</li><li>Is coordination currently our biggest bottleneck?</li></ol><p>If most answers are “No,” a modular Angular monolith is usually the better choice.</p><p>If most answers are “Yes,” micro frontends may provide significant long-term value.</p><h3><strong>Micro frontends Are an Evolution, Never a Starting Point</strong></h3><p>The best micro frontend architectures usually begin as well-designed modular monoliths (this is crutial, if monolith is poorly design then migrating may be time/resource consuming). Organizations first establish clear domain boundaries, shared design systems, and disciplined dependency management. Only when independent deployments become a business necessity do they extract those domains into separate frontend applications. Companies that start with micro frontends too early often optimize for a future they may never reach, while those that start with a modular monolith preserve the flexibility to evolve without paying the upfront complexity cost.</p><h3>Conclusion</h3><p>Micro frontends are neither the future of frontend development nor an architectural mistake.</p><p>They are a specialized solution for a specific organizational challenge: enabling large teams to scale independently.</p><p>When applied to the right problem, they can dramatically improve deployment flexibility and team autonomy.</p><p>When applied to the wrong problem, they create distributed complexity, runtime failures, dependency conflicts, and operational overhead that far outweigh their benefits.</p><p>The most successful Angular architects do not ask, “How can we implement micro frontends?”</p><p>They ask, “Do we actually need them?”</p><p>That question often determines whether a system remains maintainable five years later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b43a73cbc6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signals vs RxJS: The Architectural Decision Every Angular Team Must Make]]></title>
            <link>https://rupen-anjaria.medium.com/signals-vs-rxjs-the-architectural-decision-every-angular-team-must-make-128bc621f22c?source=rss-fb4ba040f2fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/128bc621f22c</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[signal]]></category>
            <dc:creator><![CDATA[Rupen Anjaria]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 23:48:26 GMT</pubDate>
            <atom:updated>2026-06-23T23:48:26.507Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_R-hBZNKoGvB6K8zZLp7g.png" /></figure><p>Understanding distinction between RxJS and Signals is one of the most important architectural decisions in modern Angular.</p><p>Angular 16 introduced Signals and it immediately spark controversy. Many assumed that it will replace RxJS or RxJS will become obsolete and we have to rewrite all the functionalities using Signals. This is because RxJS was used heavily. (remember AngularJS 1 to Angular?)</p><p>However, in reality, Signals solves different problem and is not a replacement of RxJS. Let’s discuss in this article.</p><h3>What are they — brief introduction</h3><p>RxJS (Reactive Extensions for JavaScript) is a library for working with asynchronous data streams. <em>A stream represents values that arrive over time.</em> These values might come from an HTTP request, user interactions, WebSocket messages, timers, or any other asynchronous source.</p><p>Imagine an e-commerce application where a customer places an order. The order status changes over time from “Order Placed” to “Processing,” then “Shipped,” and finally “Delivered.” Each status update is an event that occurs at different moments. RxJS is designed to model and process these kinds of event streams.</p><p>A simplified example might look like this:</p><pre>orderStatus$ = this.orderService.getOrderStatus(orderId);<br>orderStatus$.subscribe(status =&gt; { console.log(status); });</pre><p>Here, we may get multiple values over time as the order progresses through different stages.</p><p>Signals, on the other hand, are Angular’s reactive functionality for managing state. A Signal always represents the current value of something. Instead of describing a sequence of events over time, a Signal describes the latest state.</p><p>Using the same e-commerce example, suppose a user selects a product from a product list. The currently selected product is not a stream of events. It is simply the current state of the UI. Signals are ideal for this scenario.</p><pre>selectedProduct = signal&lt;Product | null&gt;(null);<br>selectProduct(product: Product) {<br>  this.selectedProduct.set(product);<br>}</pre><p>At any moment, the signal holds the current selected product. Components can read it synchronously and Angular automatically updates the UI whenever the value changes.</p><p>This leads to an important distinction.</p><p>RxJS answers the question: “What values might arrive over time?”</p><p>Signals answer the question: “What is the current value right now?”</p><p>That single difference explains most of the architectural decisions we make when choosing between them.</p><h3>The Evolution of Reactivity in Angular</h3><p>In the early days, Angular applications relied heavily on change detection that traversed large portions of the component tree whenever something changed. As applications grew larger, developers increasingly adopted RxJS to manage asynchronous operations and application state.</p><p>RxJS became the foundation of many Angular applications. Developers used Observables for HTTP requests, component communication, state management, user events, and nearly every reactive scenario imaginable.</p><p>While RxJS is extremely powerful, it also comes with complexity. Developers must understand operators such as <em>switchMap</em>, <em>mergeMap</em>, <em>concatMap</em>, <em>combineLatest</em>, <em>debounceTime</em>, and many others. While these operators provide tremendous flexibility, they can also make code difficult to understand and maintain when used for simple state management scenarios.</p><p>Signals were introduced to simplify reactive state management inside Angular applications. They provide a more intuitive way to represent state while allowing Angular to perform more efficient updates.</p><p><em>Signals were not created to replace RxJS. They were created to eliminate unnecessary RxJS usage where state management was the primary goal.</em></p><h3>Why Signals Feel Faster</h3><p>One reason Signals have generated so much excitement is their performance characteristics.</p><p>Traditional Angular applications often rely on <em>Observables </em>combined with the async pipe. When data changes, Angular performs change detection to determine what needs to be updated.</p><p>Signals take a more granular approach.</p><p>When a template reads a signal, Angular automatically tracks that dependency. If the signal changes later, Angular knows exactly which parts of the UI depend on that value.</p><p>Instead of checking large portions of the component tree, Angular can update only the affected areas.</p><p>For example:</p><pre>userName = signal(&#39;John&#39;);<br>changeName() {<br>  this.userName.set(&#39;David&#39;);<br>}</pre><p>If only one section of the template uses userName, Angular updates only that section.</p><h3>The Biggest Mistake Teams Are Making</h3><p>Many teams hear that Signals are the future and immediately begin wrapping everything in signals.</p><p>Consider this pattern:</p><pre>products$ = this.http.get&lt;Product[]&gt;(&#39;/api/products&#39;);<br>products = toSignal(products$);</pre><p>Technically, this works. However, many teams stop here and assume they have adopted Signal-based architecture.</p><p>In reality, they have simply converted an Observable into a Signal and the underlying architecture remains unchanged.</p><p>Signals should not be viewed as a decorative layer placed on top of existing RxJS code. Instead, developers should identify which parts of their applications represent <em>state </em>and which parts represent <em>streams</em>.</p><p>Only then can Signals be used effectively.</p><h3>When Signals Are the Better Choice</h3><p>Signals excel at representing UI state.</p><p>Consider a product details page. The application may need to track whether data is loading, which product is selected, which tab is active, and whether a modal dialog is open.</p><p>These values all represent current state.</p><pre>loading = signal(false);<br>selectedProduct = signal&lt;Product | null&gt;(null);<br>activeTab = signal(&#39;details&#39;);<br>isReviewDialogOpen = signal(false);</pre><p>Signals make this code straightforward and easy to understand. They also shine when creating derived state through computed signals. Suppose an e-commerce application displays only products currently in stock.</p><pre>products = signal&lt;Product[]&gt;([]);<br>availableProducts = computed(() =&gt;<br>  this.products().filter(p =&gt; p.inStock)<br>);</pre><p>The computed signal automatically updates whenever the products list changes.</p><p>The resulting code is concise, readable, and requires minimal boilerplate.</p><h3>When RxJS Remains the Right Tool</h3><p>Despite the excitement around Signals, RxJS remains indispensable.</p><p>HTTP requests are naturally asynchronous streams.</p><pre>this.http.get&lt;Product[]&gt;(&#39;/api/products&#39;);</pre><p>WebSocket communication is a stream.</p><p>Server-Sent Events are streams.</p><p>User interactions such as typing, scrolling, and clicking generate streams of events.</p><p>Search functionality provides a perfect example.</p><pre>searchControl.valueChanges.pipe(<br>  debounceTime(300),<br>  distinctUntilChanged(),<br>  switchMap(query =&gt;<br>    this.productService.search(query)<br>  )<br>);</pre><p>Here, RxJS provides powerful operators that allow developers to debounce user input, cancel previous requests, and process asynchronous responses efficiently.</p><p>Signals cannot replace these capabilities.</p><p>Whenever the problem involves events occurring over time, RxJS remains the superior solution.</p><h3>The Enterprise Sweet Spot: A Hybrid Architecture</h3><p>In my experience, the best architecture for modern Angular applications combines both technologies.</p><p>The service layer should continue using RxJS because APIs, WebSockets, and asynchronous workflows naturally produce streams.</p><pre>@Injectable()<br>export class ProductService {<br>  getProducts() {<br>      return this.http.get&lt;Product[]&gt;(&#39;/api/products&#39;);<br>    }<br>}</pre><p>The component layer should primarily use Signals because components are concerned with rendering state.</p><pre>products = toSignal(<br>  this.productService.getProducts(),<br>  { initialValue: [] }<br>);</pre><p>This creates a clean separation of responsibilities. RxJS handles asynchronous workflows. Signals handle UI state.</p><p>The resulting architecture is easier to understand, easier to maintain, and aligns closely with Angular’s future direction.</p><h3>Signals and OnPush: A Powerful Combination</h3><p>For years, Angular performance optimization often revolved around OnPush change detection.</p><pre>@Component({<br>  changeDetection:<br>    ChangeDetectionStrategy.OnPush<br>})</pre><p>Signals complement this strategy beautifully.</p><p>Because Angular can track exactly which signals are used within a template, updates become highly targeted and efficient.</p><p>Combining Signals with OnPush creates a performance baseline that would previously require significantly more effort to achieve.</p><p>Large applications benefit from fewer unnecessary renders, improved responsiveness, and reduced change detection overhead.</p><h3>Should Signals Replace NgRx?</h3><p>This is another question that frequently appears in architectural discussions.</p><p>For smaller applications, Signals can often eliminate the need for NgRx entirely. Simple state management becomes much easier using signals, computed values, and effects.</p><p>However, enterprise applications frequently require capabilities beyond state storage.</p><p>Features such as time-travel debugging, action logging, event sourcing, audit trails, and predictable state transitions remain valuable. In these scenarios, NgRx still offers significant benefits.</p><p>The future is more likely “NgRx powered by Signals.”</p><h3>Final Thoughts</h3><p>The debate between Signals and RxJS is based on a false assumption. The question is not which one should win.</p><p>Signals and RxJS are complementary technologies.</p><p>RxJS is a general-purpose reactive programming library capable of managing state, events, and asynchronous data streams. Angular Signals focus <em>specifically</em> on application and component state, providing a simpler and more efficient mechanism for UI reactivity inside Angular.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=128bc621f22c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thinking Angular Way]]></title>
            <link>https://rupen-anjaria.medium.com/thinking-angular-way-bd15c31f57b5?source=rss-fb4ba040f2fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd15c31f57b5</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Rupen Anjaria]]></dc:creator>
            <pubDate>Fri, 15 May 2026 23:33:31 GMT</pubDate>
            <atom:updated>2026-05-15T23:35:15.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDK-FqhFMlOFRVwOJlvQRg.png" /></figure><h3>A Practical Guide to Performance, Scalability, and Real-World Trade-offs</h3><p>Most Angular performance problems are architectural, not framework-related. This guide goes beyond best practices into <strong>decision-making, trade-offs, and production lessons.</strong></p><h3>Why This Article Is Different</h3><p>There’s no shortage of Angular “best practices” online. Most are like:</p><ol><li><a href="https://medium.com/@sivakishore.teru/lazy-loading-in-angular-c44d71b7aa85">Use lazy loading</a></li><li><a href="https://medium.com/angular-in-depth/deep-dive-into-the-onpush-change-detection-strategy-in-angular-fab5e4da1d69">Use OnPush</a></li><li><a href="https://medium.com/@dragos.atanasoae_62577/angular-project-structure-guide-small-medium-and-large-projects-e17c361b2029">Organize your folders</a></li></ol><p>But in real enterprise systems, the questions are harder:</p><ul><li><em>When NOT to use OnPush?</em></li><li><em>When should you break domain isolation?</em></li><li><em>Is NgRx helping or slowing your team down?</em></li><li><em>How do you design for 50+ developers, not just performance benchmarks?</em></li></ul><p>This article focuses on <strong>above questions</strong>. Let’s begin.</p><h3><strong>Think Angular as a Composition Engine</strong></h3><p>We know that Angular is <em>framework, </em>but for this point<em> let’s say </em>it’s a <strong>composition engine for UI + state + data flows</strong>.</p><p>Your job is to control:</p><ol><li><strong>Boundaries</strong> (what loads together)</li><li><strong>Change propagation</strong> (what re-renders upon other control)</li><li><strong>Dependencies</strong> (who knows about whom)</li></ol><p>If you know Rreact the Angular = React++. If you get these right, performance follows naturally.</p><h3>Domain-Driven Structure (and Where It Breaks)</h3><p>The ideal structure would be:</p><pre>-- feature<br>  -- orders<br>  -- payments<br>  -- billing</pre><p>Each domain own UI, state and API interaction. (Similar to <a href="https://rupen-anjaria.medium.com/refactoring-a-fat-asp-net-core-controller-into-vertical-slice-architecture-5340b3f21dba">Vertical slice architecture</a>). It gets broken when we have common functionality, for example, checkout touching orders + payments + billing and you can’t duplicate your code to satisfy the domain-driven approach. So, what should be done?</p><p>The solution would be to introduce an orchestration layer. Like</p><pre>-- features<br>  -- checkout (orchestration layer)</pre><h3>Think Lazy Loading from performance perspective</h3><p>Many developers think lazy loading as merely a routing mechanism, however, in reality it is more for performance. So, instead of route base splitting, use lazy loading by identifying <strong>user intention</strong> and <strong>timing.</strong></p><p>For example, if it is a dashboard item then it should be eager loading however for reports use lazy loading. Further, if there is a chart in a report then defer for more time.</p><h3>Change Detection: What Actually Happens</h3><p>Do you know what triggers change detection in <em>OnPush</em>? It’s beyond <em>ChangeDetectionStrategy.OnPush. Here are the key triggers:</em></p><ol><li>Input reference change: User changes a value in text box and the value is being used somewhere else in the screen. For example, changing quantity of products to reflect total price.</li><li>Events (click, HTTP, timers): Click on buttons, HTTP call etc.</li><li>Observable emissions (async pipe): Response from an asyn call.</li></ol><p>If we update a dependent object silently then it can break UI. At the same time overusing async pipes can flood rendering. We need to find balance approach and design UI in that consideration. Just using OnPush won’t do any magic.</p><h3>Trade-off: OnPush vs Developer Experience</h3><p>Predictable rendering and performance gain are obvious when using <em>OnPush</em>, however, it can make debugging harder. So, we need to allow exceptions in highly interactive components.</p><p>For example:</p><ul><li>A large dashboard with many mostly-static widgets is a good candidate for OnPush.</li><li>For a highly interactive search/filter component, OnPush can become annoying during debugging and rapid UI updates.</li></ul><h3>RxJS vs Signals vs NgRx — A Decision Framework</h3><p>Here is the decision tree about what to use.</p><pre>if state shared globally then<br>  use NgRx<br>else<br>  use RxJS (Stay local)<br><br>if debugging then use NgRx (Prefer structured state) <br><br>if performance critical at micro-level then Signals can reduce overhead</pre><h3>Production Insight: Overusing Global State</h3><p>Do not put everything in global state. Why? it will slower development, more code (more bugs) and tight coupling of features. Best approach is to go local state and use global only when it is absolutely necessary.</p><h3>Hidden Performance Killer: Template Complexity</h3><p>You might have seen some code like:</p><pre>&lt;div *ngFor=&quot;let item of items&quot;&gt;<br> {{ computeHeavy(item) }} <br>&lt;/div&gt;</pre><p>This is bad a approach because <em>computeHeavy(item)</em> gets call on every change detection cycle, which can get expensive fast. A <em>pure pipe</em> avoids that by only recalculating when the input actually changes. (it’s more code, but the advantage wins)</p><pre>import { Pipe, PipeTransform } from &#39;@angular/core&#39;;<br><br>@Pipe({<br>  name: &#39;computeHeavy&#39;,<br>  pure: true<br>})<br>export class ComputeHeavyPipe implements PipeTransform {<br>  transform(item: any): any {<br>    // move your heavy logic here<br>    return /* result of heavy computation */;<br>  }<br>}<br><br>&lt;div *ngFor=&quot;let item of items&quot;&gt;<br>  {{ item | computeHeavy }}<br>&lt;/div&gt;</pre><h3>Scaling Teams, Not Just Code (non-technical and important)</h3><p>Architecture must support <strong>people</strong>, not just performance. At 5 or less developers almost any structure works. At 20+ developers, boundaries become critical, merge conflicts explode and inconsistent patterns emerge. At 50+ developers you must establish strict coding conventions, code ownership per domain and enforced architecture (lint rules, schematics).</p><h3>Mistakes I’ve Seen in Real Systems</h3><p><strong>Shared module: </strong>This one becomes dumping ground. Code review must check and ensure only necessary and non-repetive code exist here.</p><p><strong>Early Micro-Frontends: </strong>Avoid in early phase as it can lead to complexity and delay feature release.</p><p><strong>No Bundle Analysis:</strong> Perform this regardless of what stage the product is in.</p><p><strong>Too much open-source:</strong> Just because something is available in Github, don’t include in your project. Try to build/code natively if possible. What if the npm package has security risk? becomes outdated with new version?</p><h3>What Great Angular Architecture Feels Like</h3><p>When you work with a well-architected Angular codebase, you will observe (among many):</p><ul><li>You can locate any feature in seconds</li><li>Changes don’t ripple unexpectedly</li><li>Performance issues are predictable</li><li>Teams work independently without collisions</li></ul><h3>Final Take</h3><p>The difference between a good Angular developer and a recognized expert is not knowledge of APIs, but it’s <strong>judgment</strong>.</p><ul><li>Knowing when to isolate vs integrate</li><li>When to optimize vs keep it simple</li><li>When to introduce tools vs avoid them</li></ul><p>That judgment comes from understanding <strong>trade-offs</strong>, not rules.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd15c31f57b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Resilient APIs in .NET Using Polly — With Before/After Scenario]]></title>
            <link>https://rupen-anjaria.medium.com/building-resilient-apis-in-net-using-polly-52eb5844b59e?source=rss-fb4ba040f2fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/52eb5844b59e</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[polly]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Rupen Anjaria]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 21:15:21 GMT</pubDate>
            <atom:updated>2026-03-15T21:21:50.290Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*K4URi3xZeZIpRcJ-HdIQsQ.jpeg" /></figure><p>Modern APIs rarely operate in isolation.</p><p>A typical API might depend on:</p><ul><li>External payment services</li><li>Third-party APIs</li><li>Microservices in other environments</li><li>Cloud services such as storage or messaging</li></ul><p>The problem is simple: <strong>networks fail</strong>. Requests timeout. Services restart. Temporary spikes overload dependencies. Without resilience strategies, a small failure can cause a system-wide outage. This is where <strong>Polly</strong> becomes extremely valuable in .NET applications.</p><h3>What Is Polly?</h3><p>As we know, a resilience API (or a resilient API design) ensures services remain functional, reliable, and secure despite network disruptions, high traffic, or service outages.</p><p>Polly is a popular .NET library that helps developers implement <strong>resilience and transient fault handling (recover automatically after failure)</strong>.</p><p>It allows you to define policies such as:</p><ul><li>Retry</li><li>Circuit breaker</li><li>Timeout</li><li>Fallback</li><li>Bulkhead isolation</li></ul><p>These policies help your application <strong>handle temporary failures gracefully instead of crashing or propagating errors immediately</strong>.</p><h3>Why Resilience Matters (Rather Why not?)</h3><p>Imagine your API calls a payment service.</p><p>If the payment service temporarily fails for 2 seconds, your API could:</p><ol><li>Fail immediately (bad user experience)</li><li>Retry a few times (better)</li><li>Stop calling the failing service temporarily (best)</li></ol><p>Polly helps implement these strategies with minimal code.</p><h3>Installing Polly</h3><p>Install the package:</p><pre>dotnet add package Polly</pre><p>For HTTP APIs, the integration package is also common:</p><pre>dotnet add package Microsoft.Extensions.Http.Polly</pre><p>This allows Polly policies to integrate directly with <em>HttpClient</em>.</p><h3>Implementing a Simple Retry Policy</h3><p>A retry policy handles <strong>temporary failures</strong> such as network glitches.</p><pre>using Polly;<br><br>var retryPolicy = Policy<br>    .Handle&lt;Exception&gt;()<br>    .Retry(3);</pre><p>Using it</p><pre>retryPolicy.Execute(() =&gt;<br>{<br>    CallExternalService();<br>});</pre><p>If the operation fails, Polly retries up to <strong>three times</strong>.</p><h3>Retry With Delay (More Realistic)</h3><p>Immediate retries may overwhelm a struggling service.</p><p>A better approach is to add delay.</p><pre>var retryPolicy = Policy<br>    .Handle&lt;HttpRequestException&gt;()<br>    .WaitAndRetry(3, attempt =&gt; TimeSpan.FromSeconds(2));</pre><p>Meaning:</p><ul><li>Retry 3 times</li><li>Wait 2 seconds between attempts</li></ul><p>This gives the downstream service time to recover.</p><h3>Circuit Breaker Pattern</h3><p>Retries alone can make things worse if a service is completely down.</p><p>The <strong>circuit breaker</strong> stops repeated calls to a failing dependency.</p><pre>var circuitBreaker = Policy<br>    .Handle&lt;HttpRequestException&gt;()<br>    .CircuitBreaker(<br>        handledEventsAllowedBeforeBreaking: 3,<br>        durationOfBreak: TimeSpan.FromSeconds(30));</pre><p>Behavior:</p><ol><li>If 3 consecutive failures occur → circuit opens</li><li>Requests fail immediately for 30 seconds</li><li>After 30 seconds → system tries again</li></ol><p>This prevents flooding a failing service.</p><h3>Combining Retry and Circuit Breaker</h3><pre>var retry = Policy<br>    .Handle&lt;HttpRequestException&gt;()<br>    .WaitAndRetry(3, _ =&gt; TimeSpan.FromSeconds(2));<br><br>var circuitBreaker = Policy<br>    .Handle&lt;HttpRequestException&gt;()<br>    .CircuitBreaker(3, TimeSpan.FromSeconds(30));<br><br>var policy = Policy.Wrap(retry, circuitBreaker);</pre><p>Now your API will:</p><ol><li>Retry transient failures</li><li>Stop calling the service if failures continue</li></ol><p>This greatly improves stability.</p><h3>But we use HttpClient</h3><pre>builder.Services.AddHttpClient(&quot;PaymentService&quot;)<br>    .AddPolicyHandler(<br>        Policy<br>            .Handle&lt;HttpRequestException&gt;()<br>            .WaitAndRetryAsync(3, retryAttempt =&gt;<br>                TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))<br>    );</pre><p>This uses <strong>exponential backoff</strong>:</p><p>Retry delays increase:</p><pre>2s → 4s → 8s</pre><p>This prevents retry storms during outages.</p><h3>Timeout Policy</h3><p>Sometimes services hang instead of failing.</p><p>A timeout policy ensures requests don’t run forever.</p><pre>var timeoutPolicy = Policy<br>    .Timeout(TimeSpan.FromSeconds(5));</pre><p>If the request exceeds 5 seconds, Polly cancels it. This protects your API threads and resources.</p><h3>Fallback Policy</h3><p>A fallback policy provides an <strong>alternative</strong> when everything else fails.</p><pre>var fallbackPolicy = Policy&lt;string&gt;<br>    .Handle&lt;Exception&gt;()<br>    .Fallback(() =&gt; &quot;Service temporarily unavailable&quot;);</pre><p>Now your API returns a safe response instead of throwing errors.</p><h3>Putting it all together</h3><p>Let’s understand with a Before/After scenario. Here is a typical ASP.NET CORE API:</p><p>Services/PricingService.cs</p><pre>public class PricingService<br>{<br>    private readonly HttpClient _httpClient;<br><br>    public PricingService(HttpClient httpClient)<br>    {<br>        _httpClient = httpClient;<br>    }<br><br>    public async Task&lt;decimal&gt; GetPriceAsync(int productId)<br>    {<br>        var response = await _httpClient.GetAsync($&quot;/price/{productId}&quot;);<br><br>        response.EnsureSuccessStatusCode();<br><br>        var price = await response.Content.ReadFromJsonAsync&lt;decimal&gt;();<br><br>        return price;<br>    }<br>}</pre><p>Program.cs</p><pre>builder.Services.AddHttpClient&lt;PricingService&gt;(client =&gt;<br>{<br>    client.BaseAddress = new Uri(&quot;https://pricing-api.company.com&quot;);<br>});</pre><p>After installing Polly and making below changes:</p><p>Program.cs</p><pre>using Polly;<br>using Polly.Extensions.Http;<br><br>builder.Services.AddHttpClient&lt;PricingService&gt;(client =&gt;<br>{<br>    client.BaseAddress = new Uri(&quot;https://pricing-api.company.com&quot;);<br>})<br>.AddPolicyHandler(GetRetryPolicy())<br>.AddPolicyHandler(GetCircuitBreakerPolicy())<br>.AddPolicyHandler(GetTimeoutPolicy());<br><br>//Retry 2, 4 and 8 seconds<br>static IAsyncPolicy&lt;HttpResponseMessage&gt; GetRetryPolicy()<br>{<br>    return HttpPolicyExtensions<br>        .HandleTransientHttpError()<br>        .WaitAndRetryAsync(<br>            3,<br>            retryAttempt =&gt; TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),<br>            onRetry: (outcome, timespan, retryAttempt, context) =&gt;<br>            {<br>                Console.WriteLine(<br>                    $&quot;Retry {retryAttempt} after {timespan.TotalSeconds}s due to {outcome.Exception?.Message}&quot;);<br>            });<br>}<br><br>//3 failures then circuit opens<br>//30 seconds then no calls allowed<br>//then system tests service again<br>static IAsyncPolicy&lt;HttpResponseMessage&gt; GetCircuitBreakerPolicy()<br>{<br>    return HttpPolicyExtensions<br>        .HandleTransientHttpError()<br>        .CircuitBreakerAsync(<br>            handledEventsAllowedBeforeBreaking: 3,<br>            durationOfBreak: TimeSpan.FromSeconds(30),<br>            onBreak: (result, breakDelay) =&gt;<br>            {<br>                Console.WriteLine(&quot;Circuit opened due to failures.&quot;);<br>            },<br>            onReset: () =&gt;<br>            {<br>                Console.WriteLine(&quot;Circuit closed. Service healthy again.&quot;);<br>            });<br>}<br><br>//If the service takes more than 5 seconds, the request is cancelled.<br>static IAsyncPolicy&lt;HttpResponseMessage&gt; GetTimeoutPolicy()<br>{<br>    return Policy.TimeoutAsync&lt;HttpResponseMessage&gt;(5);<br>}</pre><p>Services/PricingService.cs (<em>We can use Polly and choose to keep our PricingService as it is, but here is the modified code</em>)</p><pre>public class PricingService<br>{<br>    private readonly HttpClient _httpClient;<br>    private readonly ILogger&lt;PricingService&gt; _logger;<br><br>    public PricingService(HttpClient httpClient, ILogger&lt;PricingService&gt; logger)<br>    {<br>        _httpClient = httpClient;<br>        _logger = logger;<br>    }<br><br>    public async Task&lt;decimal&gt; GetPriceAsync(int productId)<br>    {<br>        try<br>        {<br>            var response = await _httpClient.GetAsync($&quot;/price/{productId}&quot;);<br><br>            response.EnsureSuccessStatusCode();<br><br>            var price = await response.Content.ReadFromJsonAsync&lt;decimal&gt;();<br><br>            return price ?? 0;<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogWarning(ex, &quot;Pricing service unavailable. Using fallback price.&quot;);<br><br>            // Fallback value<br>            return 0;<br>        }<br>    }<br>}</pre><h3>Conclusion</h3><p>Distributed systems fail in unpredictable ways.</p><p>Resilience patterns such as:</p><ul><li>Retry</li><li>Circuit breaker</li><li>Timeout</li><li>Fallback</li></ul><p>allow your API to <strong>recover automatically from transient failures</strong>.</p><p>With Polly integrated into ASP.NET Core, implementing these patterns requires only a few lines of code but can dramatically improve the reliability of production systems. You can make your APIs resilient <strong>without </strong>touching your service code and by placing resilience policies in the <em>HttpClient</em> pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52eb5844b59e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring Using Advanced C# Pattern Matching]]></title>
            <link>https://rupen-anjaria.medium.com/refactoring-using-advanced-c-pattern-matching-d52c70b56574?source=rss-fb4ba040f2fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d52c70b56574</guid>
            <dc:creator><![CDATA[Rupen Anjaria]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 14:57:49 GMT</pubDate>
            <atom:updated>2026-03-01T14:57:49.913Z</atom:updated>
            <content:encoded><![CDATA[<p>Pattern matching in <strong>C#</strong> is a way to <strong>check what something is and get information from it in one simple step.</strong></p><p>Instead of writing a lot of if statements and type checks, C# lets you match a value against a “pattern.”. The before and after code will blow your mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*vk-vMGyNgENlTLDrVPatjg.jpeg" /></figure><p>On the surface, the pattern matching looks like just syntactic changes. However, it’s a shift towards declarative logic, safer null check, reduced casting and branching. When used well, it makes your code feel smaller. The code becomes easy to understand — like you are reading plain English.</p><p>Additional reasons to use pattern matching is in a large systems includes, growth of conditional logic, business rules multiply, validation becomes complex.</p><p>What began as simple is checks has evolved into a powerful language feature that can replace:</p><ul><li>Long if/else chains</li><li>Complex switch statements</li><li>Type casting blocks</li><li>Null checks</li><li>Guard clauses</li></ul><p>Modern C# (9–13) turned pattern matching into one of the most expressive features in the language.</p><p>Let’s walk through <strong>advanced pattern matching</strong> using simple, practical examples.</p><h3>Type Patterns</h3><p>Before pattern matching:</p><pre>if (obj is Order)<br>{<br>    var order = (Order)obj;// Typecast<br>    Console.WriteLine(order.Total);<br>}</pre><p>Now:</p><pre>if (obj is Order order) // Typecast and null check in one statement<br>{<br>    Console.WriteLine(order.Total);<br>}</pre><p>The cast and null check are combined into one safe expression. Basically, if <em>obj </em>is of type <em>Order</em> then cast and create variable <em>order</em>. If <em>obj</em> is null then skip.</p><h3>Switch Expressions</h3><p>Old style:</p><pre>string GetStatusText(OrderStatus status)<br>{<br>    switch (status)<br>    {<br>        case OrderStatus.Pending:<br>            return &quot;Waiting&quot;;<br>        case OrderStatus.Completed:<br>            return &quot;Done&quot;;<br>        default:<br>            return &quot;Unknown&quot;;<br>    }<br>}</pre><p>Modern switch expression:</p><pre>string GetStatusText(OrderStatus status) =&gt;<br>    status switch<br>    {<br>        OrderStatus.Pending   =&gt; &quot;Waiting&quot;,<br>        OrderStatus.Completed =&gt; &quot;Done&quot;,<br>        _                     =&gt; &quot;Unknown&quot; // default<br>    };</pre><p><strong>Note: </strong><em>=&gt;</em> denotes <em>return</em> statement.</p><h3>Relational Patterns: To reduce if..else.</h3><pre>string category;<br><br>if (age &lt; 18){<br><br> category = &quot;Minor&quot;;<br><br>}<br>else if (age &gt;= 18 &amp;&amp; age &lt; 65){<br><br> category = &quot;Adult&quot;;<br><br>} else {<br><br> category = &quot;Senior&quot;;<br><br>}</pre><p>New style:</p><pre>string category = age switch<br>{<br>    &lt; 18        =&gt; &quot;Minor&quot;,<br>    &gt;= 18 and &lt; 65 =&gt; &quot;Adult&quot;, // Note &quot;and&quot; operator for simple english, impress??<br>    _           =&gt; &quot;Senior&quot;<br>};</pre><h3>Property Patterns: For Clean Validation</h3><p>Old code:</p><pre>if (order != null &amp;&amp;<br>    order.Customer != null &amp;&amp;<br>    order.Customer.IsActive &amp;&amp;<br>    order.Total &gt; 100)<br>{<br>    Console.WriteLine(&quot;Eligible for discount&quot;);<br>}</pre><p>New code:</p><pre>if (order is { Customer.IsActive: true, Total: &gt; 100 })<br>{<br>    Console.WriteLine(&quot;Eligible for discount&quot;);<br>}</pre><p>If you have an object with good number of properties then it becomes easy to check this way. Null check included.</p><h3>Positional Patterns (With Records)</h3><p>If you’re using records:</p><pre>public record Point(int X, int Y);</pre><p>You can match like this:</p><pre>var result = point switch<br>{<br>    (0, 0) =&gt; &quot;Origin&quot;,<br>    (0, _) =&gt; &quot;Y Axis&quot;,<br>    (_, 0) =&gt; &quot;X Axis&quot;,<br>    _      =&gt; &quot;Somewhere else&quot;<br>};</pre><p>This works because records support deconstruction.</p><p>Very useful in geometry, rules engines, parsing logic, etc.</p><h3>Combining Patterns (Real-World Example)</h3><p>Let’s say you’re evaluating a payment:</p><pre>public record Payment(decimal Amount, string Method, bool IsVerified);</pre><pre>string Evaluate(Payment payment) =&gt;<br>    payment switch<br>    {<br>        { Amount: &lt;= 0 } =&gt;<br>            &quot;Invalid amount&quot;,<br><br>        { Method: &quot;CreditCard&quot;, IsVerified: true } =&gt;<br>            &quot;Approved&quot;,<br><br>        { Method: &quot;CreditCard&quot;, IsVerified: false } =&gt;<br>            &quot;Verification required&quot;,<br><br>        { Method: &quot;Cash&quot; } =&gt;<br>            &quot;Accepted&quot;,<br><br>        _ =&gt;<br>            &quot;Unknown payment type&quot;<br>    };</pre><ul><li>Property matching</li><li>Relational pattern</li><li>Constant matching</li><li>No nested if blocks</li></ul><h3>List Patterns (Modern C# Feature)</h3><p>Old style:</p><pre>if (numbers.Length == 3 &amp;&amp;<br>    numbers[0] == 1 &amp;&amp;<br>    numbers[1] == 2 &amp;&amp;<br>    numbers[2] == 3)</pre><p>New style: — The power of <em>is</em></p><pre>if (numbers is [1, 2, 3])<br>{<br>    Console.WriteLine(&quot;Exact match&quot;);<br>}<br><br>//OR<br><br>if (numbers is [1, .., 5])<br>{<br>    Console.WriteLine(&quot;Starts with 1, ends with 5&quot;);<br>}</pre><h3>Null Pattern (Stop Writing == null)</h3><p>Instead of:</p><pre>if (order == null)</pre><p>You can write:</p><pre>if (order is null)</pre><p>Why does this matter? Because is null bypasses overloaded equality operators. It’s safer in domain-heavy codebases.</p><h3>Pattern Matching in ASP.NET Core (Practical Use)</h3><p>Inside an endpoint:</p><pre>public IActionResult Process(object request)<br>{<br>    return request switch<br>    {<br>        CreateOrderCommand cmd =&gt; Ok(HandleCreate(cmd)),<br>        CancelOrderCommand cmd =&gt; Ok(HandleCancel(cmd)),<br>        _ =&gt; BadRequest(&quot;Unknown request&quot;)<br>    };<br>}</pre><p>This removes fragile type-checking blocks.</p><h3>Conclusion</h3><p>We should use pattern matching when we are replacing nested if/else, evaluating rules, mapping states, you want declarative logic, you’re working with records or immutable types.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d52c70b56574" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring a Fat ASP.NET Core Controller into Vertical Slice Architecture]]></title>
            <link>https://rupen-anjaria.medium.com/refactoring-a-fat-asp-net-core-controller-into-vertical-slice-architecture-5340b3f21dba?source=rss-fb4ba040f2fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5340b3f21dba</guid>
            <dc:creator><![CDATA[Rupen Anjaria]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 03:58:21 GMT</pubDate>
            <atom:updated>2026-02-24T03:58:21.807Z</atom:updated>
            <content:encoded><![CDATA[<p>Enterprise APIs never start messy. They <em>become</em> messy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40QE7nHeE5KVDOjmkSdSbQ.png" /></figure><p>What begins as a clean OrdersController slowly turns into a 1,200-line file handling validation, business rules, logging, transactions, authorization checks, and mapping. :)</p><p>Let’s walk through how to refactor a bloated controller into a clean <strong>Vertical Slice Architecture</strong> — without introducing unnecessary abstraction or complexity.</p><h3>The Problem: The “Fat Controller”</h3><p>I am sure you have seem something like below either when you join a new team or just Friday browsing your legacy code:</p><pre>[ApiController]<br>[Route(&quot;api/orders&quot;)]<br>public class OrdersController : ControllerBase<br>{<br>    private readonly AppDbContext _context;<br>    private readonly ILogger&lt;OrdersController&gt; _logger;<br><br>    public OrdersController(AppDbContext context, ILogger&lt;OrdersController&gt; logger)<br>    {<br>        _context = context;<br>        _logger = logger;<br>    }<br><br>    [HttpPost]<br>    public async Task&lt;IActionResult&gt; Create(CreateOrderRequest request)<br>    {<br>        if (request.Items == null || !request.Items.Any())<br>            return BadRequest(&quot;Order must have at least one item.&quot;);<br><br>        var customer = await _context.Customers.FindAsync(request.CustomerId);<br>        if (customer == null)<br>            return NotFound(&quot;Customer not found.&quot;);<br><br>        var order = new Order<br>        {<br>            CustomerId = request.CustomerId,<br>            CreatedAt = DateTime.UtcNow,<br>            TotalAmount = request.Items.Sum(x =&gt; x.Price * x.Quantity)<br>        };<br><br>        _context.Orders.Add(order);<br>        await _context.SaveChangesAsync();<br><br>        _logger.LogInformation(&quot;Order created with ID {OrderId}&quot;, order.Id);<br><br>        return Ok(order.Id);<br>    }<br>}</pre><p>At first glance, this seems fine.</p><p>But then requirements grow:</p><ul><li>Inventory validation</li><li>Loyalty discount calculation</li><li>Audit logging</li><li>Domain events</li><li>Payment processing</li><li>Transaction management</li></ul><p>Soon your controller becomes a coordination monster.</p><h3>Why This Is a Problem</h3><ul><li>Hard to unit test</li><li>Violates Single Responsibility</li><li>Business logic tied to web layer</li><li>Every change risks breaking unrelated functionality</li></ul><p>The controller should orchestrate — not implement business logic.</p><h3>Our Refactoring Goal</h3><ul><li>Each feature isolated</li><li>Minimal coupling</li><li>Business logic outside controllers</li><li>Easier testability</li><li>Clear boundaries</li></ul><p>Enter <strong>Vertical Slice Architecture</strong>.</p><p><strong>Step 1 — Move Logic into a Feature Folder</strong></p><p>Instead of organizing by layer:</p><pre>Controllers/<br>Services/<br>Repositories/<br>Models/</pre><p>Organize by <strong>feature</strong>:</p><pre>Features/<br>  Orders/<br>    Create/<br>      CreateOrderCommand.cs<br>      CreateOrderHandler.cs<br>      CreateOrderValidator.cs</pre><p><em>Each feature owns everything it needs. That’s the core principle.</em></p><p><strong>Step 2 — Introduce a Command + Handler</strong></p><p>CreateOrderCommand.cs</p><pre>public record CreateOrderCommand(<br>    int CustomerId,<br>    List&lt;OrderItemDto&gt; Items<br>);</pre><p>CreateOrderHandler.cs</p><pre>public class CreateOrderHandler<br>{<br>    private readonly AppDbContext _context;<br>    private readonly ILogger&lt;CreateOrderHandler&gt; _logger;<br><br>    public CreateOrderHandler(AppDbContext context, ILogger&lt;CreateOrderHandler&gt; logger)<br>    {<br>        _context = context;<br>        _logger = logger;<br>    }<br><br>    public async Task&lt;int&gt; Handle(CreateOrderCommand command)<br>    {<br>        var customer = await _context.Customers.FindAsync(command.CustomerId);<br>        if (customer == null)<br>            throw new InvalidOperationException(&quot;Customer not found.&quot;);<br><br>        var order = new Order<br>        {<br>            CustomerId = command.CustomerId,<br>            CreatedAt = DateTime.UtcNow,<br>            TotalAmount = command.Items.Sum(x =&gt; x.Price * x.Quantity)<br>        };<br><br>        _context.Orders.Add(order);<br>        await _context.SaveChangesAsync();<br><br>        _logger.LogInformation(&quot;Order created with ID {OrderId}&quot;, order.Id);<br><br>        return order.Id;<br>    }<br>}</pre><p><strong>Step 3 — Slim Down the Controller</strong></p><pre>[HttpPost]<br>public async Task&lt;IActionResult&gt; Create(<br>    [FromBody] CreateOrderCommand command,<br>    [FromServices] CreateOrderHandler handler)<br>{<br>    var orderId = await handler.Handle(command);<br>    return Ok(orderId);<br>}<br>//[FromServices] tells framework to <br>//“Resolve this parameter from the Dependency Injection container — not from the request.”</pre><p>That’s it. The controller delegates. The feature owns its logic.</p><p>What are the advantages?</p><ol><li><strong>Better Testability: </strong>You can now test <em>CreateOrderHandler</em> without spinning up ASP.NET Core.</li><li><strong>Clear Ownership: </strong>All “Create Order” logic lives together.</li><li><strong>Reduced Merge Conflicts: </strong>Teams working on different features don’t collide in the same controller file.</li><li><strong>Natural Scalability: </strong>Adding a new feature doesn’t modify existing code — it adds a new slice/a group of folders.</li></ol><h3><strong>Other changes and concepts:</strong></h3><ol><li>You Must Register the Handler. Standard DI thing.</li></ol><pre>//Program.cs<br>builder.Services.AddScoped&lt;CreateOrderHandler&gt;();<br>//Otherwise ASP.NET cannot resolve it.</pre><p>2. How is command parameter passed to the controller?</p><p>By default in an [ApiController], complex types are automatically bound from the request body. So, as our command looks like this:</p><pre>public record CreateOrderCommand(<br>    int CustomerId,<br>    List&lt;OrderItemDto&gt; Items<br>);</pre><p>You call the endpoint like this:</p><pre>POST /api/orders<br>Content-Type: application/json<br>body:<br>{<br>  &quot;customerId&quot;: 10,<br>  &quot;items&quot;: [<br>    { &quot;productId&quot;: 1, &quot;price&quot;: 100, &quot;quantity&quot;: 2 }<br>  ]<br>}</pre><p>ASP.NET Core:</p><ul><li>Deserializes the JSON into CreateOrderCommand</li><li>Injects CreateOrderHandler from DI</li><li>Calls the method</li></ul><h3>Conclusion</h3><p>Most architectural problems in .NET applications don’t come from lack of patterns — they come from patterns applied too late.</p><p>Refactoring a fat controller into vertical slices:</p><ul><li>Improves clarity</li><li>Reduces risk</li><li>Encourages cohesion</li><li>Aligns code with business capabilities</li></ul><p>And most importantly — it makes your codebase feel calm again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5340b3f21dba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring a Membership Calculator in C# Using SOLID Principles]]></title>
            <link>https://rupen-anjaria.medium.com/refactoring-a-membership-calculator-in-c-using-solid-principles-7006f27639ee?source=rss-fb4ba040f2fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7006f27639ee</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[csharp-programming]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Rupen Anjaria]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 01:43:14 GMT</pubDate>
            <atom:updated>2026-02-23T01:43:14.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*7pUTu1oK7XggWYDZWT0wdQ.png" /></figure><p>From instanceof / if chains to Clean OOP Design</p><p>Let’s say we have a <strong>membership system</strong> with three types:</p><ul><li>Standard</li><li>Gold</li><li>Platinum</li></ul><p>We’ll start with a problematic implementation, then refactor it step by step using SOLID principles, and finally present a clean production-ready version.</p><h3><strong>Step 0 — The Original Problematic Design</strong></h3><p>This is standard implementation we see:</p><pre>public class StandardMembership { }<br>public class GoldMembership { }<br>public class PlatinumMembership { }<br><br>public class MembershipCalculator<br>{<br>    public double CalculateDiscount(object membership)<br>    {<br>        if (membership is StandardMembership)<br>            return 0.05;<br>        else if (membership is GoldMembership)<br>            return 0.10;<br>        else if (membership is PlatinumMembership)<br>            return 0.20;<br>        else<br>            return 0;<br>    }<br>}</pre><p>What’s Wrong Here?</p><h4>Open/Closed Principle (OCP) — Broken</h4><p>If we add DiamondMembership, we must modify MembershipCalculator.</p><h4>Single Responsibility Principle (SRP) — Weak</h4><p>There will be <strong>two</strong> reasons to change the class <em>MembershipCalculator</em>. One to add new class <em>DiamondMembership</em> and another to change the discount price.</p><h4>Dependency Inversion Principle (DIP) — Broken</h4><p>They depend on concrete classes instead of abstractions.</p><h4>Polymorphism is ignored</h4><p>Using is instead of virtual behavior is a major code smell.</p><p>Now, let’s fix the code by refactoring step-by-step. Focus on <strong>MembershipCalculator </strong>class.</p><h3><strong>Step 1 — Fix Open/Closed Principle (OCP) by moving behavior to the types themselves.</strong></h3><p>The principle states: <em>The class should be open for extension, but close for modification.</em></p><pre>//Creating Abstraction by interface<br>public interface IMembership<br>{<br>    double GetDiscount();<br>}<br><br>//Concrete implementations<br>public class StandardMembership : IMembership<br>{<br>    public double GetDiscount() =&gt; 0.05;<br>}<br><br>public class GoldMembership : IMembership<br>{<br>    public double GetDiscount() =&gt; 0.10;<br>}<br><br>public class PlatinumMembership : IMembership<br>{<br>    public double GetDiscount() =&gt; 0.20;<br>}<br><br>//Update calculator<br>public class MembershipCalculator<br>{<br>    public double CalculateDiscount(IMembership membership)<br>    {<br>        return membership.GetDiscount();<br>    }<br>}</pre><p><strong><em>Result:</em></strong> If we add new Diamond Membership then:</p><pre>public class Diamond: IMembership<br>{<br>    public double GetDiscount() =&gt; 0.15;<br>}</pre><p>Now, the class <em>MembershipCalculator</em> is closed for modification but open for extention. We do <strong>NOT</strong> modify MembershipCalculator.</p><h3><strong>Step 2 — Fix Dependency Inversion Principle (DIP)</strong></h3><p>Now:</p><ul><li>High-level module: MembershipCalculator</li><li>Depends on: IMembership</li><li>Not on: StandardMembership, GoldMembership, etc.</li></ul><p>This removes tight coupling and improves testability.</p><p>Example of mocking in tests:</p><pre>public class FakeMembership : IMembership<br>{<br>    public double GetDiscount() =&gt; 0.99;<br>}</pre><h3>Step 3 — Improve Single Responsibility (SRP)</h3><p>Currently:</p><ul><li>Each membership type owns its own discount logic.</li><li>The calculator simply delegates.</li></ul><p>Each class now has <strong>one reason to change</strong>:</p><ul><li>If discount rules change → update the specific membership.</li><li>If calculation orchestration changes → update calculator.</li></ul><p><em>SRP is achieved.</em></p><h3><strong>Step 4— Improve Single Responsibility Further (Strategy Pattern) — Final version</strong></h3><p>If discount rules become complex (date-based, purchase-based, etc.), use <em>Strategy Pattern</em>.</p><p>Here is the example:</p><pre>//Introduce new interface<br>public interface IDiscountStrategy<br>{<br>    double CalculateDiscount();<br>}<br><br>public class StandardDiscountStrategy : IDiscountStrategy<br>{<br>    public double CalculateDiscount() =&gt; 0.05;<br>}<br><br>public class GoldDiscountStrategy : IDiscountStrategy<br>{<br>    public double CalculateDiscount() =&gt; 0.10;<br>}<br><br>public class PlatinumDiscountStrategy : IDiscountStrategy<br>{<br>    public double CalculateDiscount() =&gt; 0.20;<br>}</pre><p>Use Strategy Pattern.</p><pre>public class Membership<br>{<br>    private readonly IDiscountStrategy _discountStrategy;<br><br>    public Membership(IDiscountStrategy discountStrategy)<br>    {<br>        _discountStrategy = discountStrategy;<br>    }<br><br>    public double GetDiscount()<br>    {<br>        return _discountStrategy.CalculateDiscount();<br>    }<br>}</pre><p>Now discount behavior is:</p><ul><li>Replaceable at runtime</li><li>Testable</li><li>Extendable</li><li>Fully compliant with OCP and DIP</li></ul><p>But wait.. what will happen to my <em>MembershipCalculator </em>class after strategy pattern. The answer is “<em>It’s not useful and should be gone</em>” and this is how you will use:</p><pre>class Program<br>{<br>    static void Main()<br>    {<br>        var goldMembership = new Membership(new GoldDiscountStrategy());<br><br>        double discountRate = goldMembership.GetDiscount();<br><br>        Console.WriteLine($&quot;Gold discount rate: {discountRate * 100}%&quot;);<br>    }<br>}</pre><p>Basically, we can switch discount category at runtime. Here is another scenario. Let’s say we would like to offer Black Friday discount (separate then Normal)</p><pre>// Black Friday discount<br>public class GoldBlackFridayStrategy : IDiscountStrategy<br>{<br>    public double CalculateDiscount() =&gt; 0.15;<br>}<br><br><br>class Program<br>{<br>    static void Main()<br>    {<br>        var membership = new Membership(new GoldDiscountStrategy());<br>        Console.WriteLine($&quot;Gold: {membership.GetDiscount() * 100}%&quot;);<br><br>        // Dynamically switch to Black Friday strategy<br>        // note that we are using the same memberhip object<br>        membership.ChangeStrategy(new GoldBlackFridayStrategy());<br>        Console.WriteLine($&quot;Black Friday Gold: {membership.GetDiscount() * 100}%&quot;);<br>    }<br>}</pre><h3>Conclusion</h3><p>In this article we have learned SOLID principles by example. Stating merely definition may not get us this far by practicing refactoring of an existing scenario. To learn more, inspect your existing code and try refactoring as shown above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7006f27639ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factors that can affect costs in Azure]]></title>
            <link>https://rupen-anjaria.medium.com/factors-that-can-affect-costs-in-azure-42d8942873e8?source=rss-fb4ba040f2fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/42d8942873e8</guid>
            <dc:creator><![CDATA[Rupen Anjaria]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 19:57:31 GMT</pubDate>
            <atom:updated>2026-02-19T19:57:31.076Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-O0ly3UbsXHhm5tToWMZug.jpeg" /></figure><p>Let’s discusses various factors affecting costs in Microsoft Azure, transitioning the financial model from capital expenses (CapEx) associated with traditional infrastructure to operational expenses (OpEx) based on usage. Key influencing factors include resource type, consumption patterns, maintenance requirements, geographical location, subscription type, and Azure Marketplace offerings. Each of these elements can significantly impact the overall expenses incurred by users, necessitating careful consideration and management of resources.</p><h3>Highlights</h3><p>- <strong>Cost Model Transition:</strong> Azure shifts costs from CapEx to OpEx, allowing users to pay only for what they use.<br>- <strong>Resource Types Matter</strong>: Different resource types, settings, and regions can lead to varied costs.<br>- <strong>Flexible Consumption:</strong> Pay-as-you-go model provides flexibility, with options for reserved resources offering significant discounts.<br>- <strong>Maintenance is Key</strong>: Proper management of resources is essential to avoid unnecessary costs.<br>- <strong>Regional Pricing Variability</strong>: Costs can differ based on geographical factors, including local economic conditions.<br>- <strong>Subscription Benefits</strong>: Certain Azure subscriptions come with usage allowances that can help lower costs.<br>- <strong>Marketplace Offerings</strong>: Azure Marketplace allows users to purchase third-party solutions that may add to total expenditure.</p><h3>Key Insights</h3><p>- <strong>Transition to OpEx</strong>: The move from CapEx to OpEx in Azure signifies a fundamental shift in how organizations budget for IT resources. Instead of investing heavily in infrastructure, companies can now scale their expenses based on actual usage, allowing for greater financial agility. This model is particularly beneficial for startups and small businesses that may not have the capital to invest in large-scale infrastructure.</p><p>- <strong>Impact of Resource Types on Costs</strong>: The cost of provisioning resources in Azure is not uniform. It varies based on the type of resource chosen (e.g., storage accounts, virtual machines) and specific configurations like performance tiers and redundancy settings. Organizations must analyze their needs carefully to select the optimal resource configurations to avoid inflated costs.</p><p>- <strong>Pay-as-you-go vs. Reserved Capacity</strong>: Azure’s pay-as-you-go model offers straightforward pricing that aligns expenses with usage patterns. However, for businesses with predictable workloads, committing to reserved capacity can lead to substantial savings — up to 72%. This dual pricing model offers flexibility and cost-effectiveness, catering to varying business needs.</p><p>- <strong>Importance of Maintenance</strong>: Regular maintenance of cloud resources is crucial for cost control. Unused or over-provisioned resources can lead to unnecessary expenses. Effective resource management practices, such as regularly auditing deployed resources and deprovisioning what isn’t needed, can help organizations optimize their Azure spending.</p><p>- <strong>Geographical Cost Differences</strong>: The geographical location of Azure resources can greatly influence costs due to variations in local economic conditions, including power costs and labor. Additionally, network traffic costs differ by region, with some areas offering cheaper data transfer rates. Organizations should consider these factors when planning their cloud architecture to minimize costs.</p><p>- <strong>Subscription Types and Their Implications</strong>: Different Azure subscription types provide various allowances and benefits that can affect costs. For example, the Azure free trial offers a limited number of services for free for the first year, making it a great entry point for businesses testing the waters of cloud computing. Understanding the nuances of subscription types can help organizations choose the most cost-effective options.</p><p>- <strong>Azure Marketplace Costs</strong>: Azure Marketplace offers third-party solutions that can complement Azure services. However, users should be aware that purchasing from the Marketplace may involve additional costs beyond Azure services, including vendor fees. Understanding the total cost of ownership for solutions acquired through the Marketplace is crucial for accurate budgeting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42d8942873e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extension Members in C# 14: Helping Large Solution]]></title>
            <link>https://rupen-anjaria.medium.com/extension-members-in-c-14-helping-large-solution-0e1cc108da38?source=rss-fb4ba040f2fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e1cc108da38</guid>
            <dc:creator><![CDATA[Rupen Anjaria]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 01:27:27 GMT</pubDate>
            <atom:updated>2026-02-15T01:27:27.150Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uLzGgH6WqPZ9VbkBTP0Ww.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>Before understanding Extension Members, let me quickly explain what is Extension Methods are. Extension methods were introduced in C# 3.0, which was released as part of the .NET Framework 3.5 in 2007. The ideas was to give ability to add custom methods to an existing class. For example, we need to capitalize first letter of a string. Natively, no such method available, so we can write custom method and then use in any string object.</p><p>Big .NET projects slowly collect lots of helper code. Example includes things like logging helpers, validation helpers, and other convenience methods. Over time, these helpers get spread out across many static classes as extension methods, which makes the codebase harder to find your way around and harder to understand.</p><p>C# 14 solves this problems with Extension <em>Methods </em>by introducing Extension <em>Members (or extension blocks)</em>.</p><p><strong>Why Extension Member?</strong></p><p>Extension members were introduce to address the limitation of Extension Methods:</p><ul><li>They only support methods, not properties or operators: Basically, you can only create function, but what if you need custom properties? For example, string contains “A” then it should set “containsA” as true. Further, you cannot overload operators (like +, — , * , / etc.) if you don’t own the type.</li><li>You cannot extend the <em>type</em>. For example, you can add extension method for string class, but you can only use it with instance of string. You cannot call “string.myMethod”. You have to create an instance of string and then call your method.</li><li>It is hard to find “everything that extends this type” when you are working on a big codebase.</li></ul><p>For example, consider below code written in previous version to extend String class:</p><pre>public static class StringExtensions<br>{<br>    <br>    public static string AddExclamation(this string value)<br>        =&gt; value + &quot;!&quot;;<br><br>    public static string Repeat(this string value, int count)<br>        =&gt; string.Concat(Enumerable.Repeat(value, count));<br>}</pre><p>Usage:</p><pre>string text = &quot;Hello&quot;;<br><br>Console.WriteLine(text.AddExclamation()); // Hello!<br>Console.WriteLine(text.Repeat(3));        // HelloHelloHello</pre><p>This works, but if your solution has many String helpers, they can easily be spread across multiple static classes and even different projects, which makes finding relevant method difficult and may result in writing duplicate methods.</p><p>With new version, you can write it as:</p><pre>public static class StringExtensions<br>{<br>    extension(string value)<br>    {<br>        public string AddExclamation() =&gt; value + &quot;!&quot;;<br>        public int WordCount() =&gt; value.Split(&#39; &#39;).Length;<br>    }<br>}</pre><p><em>Note that C# 14 doesn’t </em><strong><em>enforce</em></strong><em> to combine all the methods in one class. Once can still write multiple classes, but the new syntax makes it clean and readable - so I encourage to utilize the new format and place all relevant methods in one place.</em></p><p><strong>Extension Properties</strong></p><p>Imagine you frequently work with IEnumerable&lt;T&gt; and want clear methods for emptiness checks:</p><pre>public static class EnumerableExtensions<br>{<br>    extension&lt;T&gt;(IEnumerable&lt;T&gt; source)<br>    {<br>        public bool IsEmpty =&gt; !source.Any();<br><br>        public bool IsNotEmpty =&gt; source.Any();<br>    }<br>}</pre><p>Usage:</p><pre>var numbers = new[] { 1, 2, 3 };<br><br>if (numbers.IsNotEmpty)<br>{<br>    Console.WriteLine(&quot;We have data&quot;);<br>}<br>if (numbers.IsEmpty)<br>{<br>    Console.WriteLine(&quot;We have no data&quot;);<br>}</pre><p>Compared to !numbers.Any(), the extension properties <em>IsEmpty</em> and <em>IsNotEmpty</em> are easier to read in business rules and validation code. This wasn’t available in earlier C# version.</p><p><strong>Extension Operators</strong></p><p>You can also define operators for types you don’t own, which is especially useful for value types and collections.</p><pre>public static class StringOperators<br>{<br>    extension(string left)<br>    {<br>        public static string operator +(string right)<br>            =&gt; $&quot;{left} {right}&quot;;<br>    }<br>}</pre><p>Usage:</p><pre>string first = &quot;Hello&quot;;<br>string second = &quot;World&quot;;<br><br>string result = first + second;<br><br>Console.WriteLine(result); // Hello World</pre><h3>Closing Thoughts</h3><p>Extension members in C# 14 go beyond simple extension methods and give you a <em>structured</em> way to attach behavior to existing types. By grouping methods, properties, and operators into extension blocks, you can keep your cross‑cutting APIs cohesive, discoverable, and easier to maintain in large .NET solutions.</p><p>If you are already using extension methods extensively, C# 14&#39;s extension members are a natural next step to modernize your codebase and better reflect your domain model in the language itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e1cc108da38" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>