<?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 harsh_singh on Medium]]></title>
        <description><![CDATA[Stories by harsh_singh on Medium]]></description>
        <link>https://medium.com/@harshhub.414?source=rss-62af0852f2f6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CfTdrJXOHvwb9Pc6NI9_yQ.jpeg</url>
            <title>Stories by harsh_singh on Medium</title>
            <link>https://medium.com/@harshhub.414?source=rss-62af0852f2f6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:56:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harshhub.414/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[How Apps “Understand” You Without Reading Your Mind]]></title>
            <link>https://medium.com/@harshhub.414/how-apps-understand-you-without-reading-your-mind-4936dd41f0e3?source=rss-62af0852f2f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4936dd41f0e3</guid>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[data-privacy]]></category>
            <dc:creator><![CDATA[harsh_singh]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 09:13:10 GMT</pubDate>
            <atom:updated>2025-12-30T09:18:46.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Va1oO7fNVjJ98AjYkGQttA.png" /></figure><p>Have you ever felt like an app knows you a little too well?</p><p>You open it, and the content feels familiar.<br> The recommendations feel timely.<br> The interface seems to adapt to you.</p><p>It’s easy to assume this comes from personal data — name, age, location, contacts.</p><p>But in reality, something far more powerful is at work.</p><p><strong>Patterns.</strong></p><p>Apps don’t need to know <em>who you are</em>.<br> They only need to know <em>how you behave</em>.</p><h3>Behavior Is the Most Honest Data</h3><p>Every interaction you make leaves a small signal:</p><ul><li>What you tap</li><li>What you scroll past</li><li>How long you stay on a screen</li><li>When you open the app</li><li>Which features you never touch</li><li>When you abandon an action halfway</li></ul><p>Individually, these signals are meaningless.</p><p>But when combined over time, they form something incredibly precise:</p><p><strong>A behavioral fingerprint.</strong></p><p>Unlike profile data, behavior is:</p><ul><li>Hard to fake</li><li>Continuously updated</li><li>Context-rich</li><li>Predictive</li></ul><p>You might change your username.<br> You might hide your location.<br> But your patterns stay consistent.</p><h3>Why Behavior Reveals More Than Personal Data</h3><p>Let’s compare:</p><p><strong>Personal data says:</strong></p><ul><li>Age: 22</li><li>Location: India</li><li>Job: Student</li></ul><p><strong>Behavior says:</strong></p><ul><li>Opens the app late at night</li><li>Skips tutorials</li><li>Uses advanced features</li><li>Ignores notifications</li><li>Engages deeply with long-form content</li></ul><p>Which one tells you more about a person?</p><p>This is why modern recommendation systems, ad platforms, and product teams prioritize <strong>behavioral signals over static data</strong>.</p><h3>The Silent Problem: Inference Without Awareness</h3><p>The real concern isn’t that apps collect behavior.</p><p>The concern is <strong>how silently it happens</strong>.</p><p>Most users never realize:</p><ul><li>How much can be inferred</li><li>How small actions compound</li><li>How long this data lives</li><li>How it’s shared across systems</li></ul><p>You didn’t explicitly say:</p><p><em>“I like this type of content.”</em></p><p>But your behavior said it repeatedly.</p><p>And behavior doesn’t need consent dialogs to be powerful.</p><h3>How Platforms Responded: Limiting Visibility</h3><p>As systems became better at inference, platform owners noticed a pattern:</p><p>Even without permissions, apps could:</p><ul><li>Infer interests</li><li>Predict intent</li><li>Fingerprint users across sessions</li><li>Correlate behavior across apps</li></ul><p>So modern platforms began to change the rules.</p><p>Not because apps are evil.<br> But because <strong>unbounded visibility leads to silent profiling</strong>.</p><p>That’s why today:</p><ul><li>Apps are restricted from freely inspecting the environment</li><li>Cross-app visibility is limited</li><li>Background inference is discouraged</li><li>Explicit user intent is prioritized</li></ul><p>The goal isn’t to break apps.<br> The goal is to <strong>restore balance</strong>.</p><h3>Privacy Isn’t About Hiding</h3><p>This is where privacy is often misunderstood.</p><p>Privacy does <strong>not</strong> mean:</p><ul><li>Being anonymous</li><li>Using apps less</li><li>Hiding everything</li></ul><p>Privacy means:</p><p><em>Having control over </em>how<em> and </em>when<em> you are understood.</em></p><p>There’s a difference between:</p><ul><li>An app responding to your explicit action</li><li>An app silently modeling you over time</li></ul><p>One respects agency.<br> The other removes it.</p><h3>Why This Matters More Than Ever</h3><p>As AI systems improve, behavioral data becomes even more valuable.</p><p>Patterns don’t just explain the past — <br> they <strong>predict the future</strong>.</p><p>What you’ll click.<br> What you’ll buy.<br> When you’re likely to leave.<br> When you’re most persuadable.</p><p>Without guardrails, behavior becomes destiny.</p><p>That’s why privacy discussions today are shifting away from:</p><p><em>“What data is collected?”</em></p><p>Toward:</p><p><em>“What can be inferred?”</em></p><h3>A Better Mental Model</h3><p>Think of it this way:</p><ul><li><strong>Data</strong> is what you give</li><li><strong>Behavior</strong> is what you reveal</li><li><strong>Inference</strong> is what systems conclude</li></ul><p>Privacy lives in the space between revelation and inference.</p><h3>Final Thought</h3><p>Apps don’t know you because they spy on you.</p><p>They know you because <strong>patterns don’t lie</strong>.</p><p>And the future of privacy isn’t about stopping data collection — <br> it’s about ensuring we’re not <strong>silently understood without consent</strong>.</p><p>That’s the real challenge of modern software.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4936dd41f0e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IndexedStack, ShellRoute, and StatefulShellRoute in Flutter (GoRouter) — The Complete Guide to…]]></title>
            <link>https://medium.com/@harshhub.414/indexedstack-shellroute-and-statefulshellroute-in-flutter-gorouter-the-complete-guide-to-759b2975808c?source=rss-62af0852f2f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/759b2975808c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-navigation]]></category>
            <dc:creator><![CDATA[harsh_singh]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 20:36:14 GMT</pubDate>
            <atom:updated>2025-12-01T20:36:14.604Z</atom:updated>
            <content:encoded><![CDATA[<h3>IndexedStack, ShellRoute, and StatefulShellRoute in Flutter (GoRouter)The Complete Guide to Bottom Navigation + State Preservation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnrv44oP3pDvmGTaljs3Ag.png" /></figure><p>Bottom navigation is simple — until you want to <strong>keep state</strong>, support <strong>deep links</strong>, and handle <strong>multiple navigation stacks</strong>.</p><p>Most beginners start with a basic BottomNavigationBar, and quickly face these problems:</p><ul><li>“Why does my page rebuild every time I switch tabs?”</li><li>“Why does the counter reset?”</li><li>“Why does scrolling go back to the top?”</li><li>“Why do I lose state when navigating with GoRouter?”</li><li>“Why are some bottom navigation setups preserving state, and others not?”</li></ul><p>To answer this, we need to understand <strong>three different approaches</strong>:</p><ol><li>IndexedStack-based bottom navigation (pure Flutter)</li><li>ShellRoute with GoRouter</li><li>StatefulShellRoute.indexedStack (GoRouter’s advanced solution)</li></ol><p>This article explains each one in depth — what it is, how it works, how memory is managed, and when to use which.</p><h3><strong>IndexedStack — The Foundation of State-Preserving Bottom Navigation</strong></h3><p>IndexedStack is the <strong>simplest</strong>, pure-Flutter way to create bottom navigation with state preservation.</p><h3>What is IndexedStack?</h3><p>Think of IndexedStack like multiple pages stacked on top of each other:</p><pre>Layer 2 — SettingsPage()<br>Layer 1 — HomePage() ← visible<br>Layer 0 — NotificationPage()</pre><p>When you change the index:</p><p>Flutter does not rebuild other pages</p><p>Flutter does not dispose other pages</p><p>Flutter only changes which page is visible</p><p>This means: State is preserved across tabs<br>Your counter, scroll positions, forms — everything stays alive.</p><p>IndexedStack Example</p><pre>class MainNavigationShell extends StatefulWidget {<br>  const MainNavigationShell({super.key});<br><br>  @override<br>  State&lt;MainNavigationShell&gt; createState() =&gt; _MainNavigationShellState();<br>}<br><br>class _MainNavigationShellState extends State&lt;MainNavigationShell&gt; {<br>  int _currentIndex = 0;<br><br>  final List&lt;Widget&gt; _pages = const [<br>    HomePage(),<br>    SettingsPage(),<br>  ];<br><br>  @override<br>  Widget build(BuildContext context) {<br>    print(&#39;MainNavigationShell build, index=$_currentIndex&#39;);<br><br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Main Navigation Shell (IndexedStack)&#39;)),<br>      body: IndexedStack(<br>        index: _currentIndex,<br>        children: _pages,<br>      ),<br>      bottomNavigationBar: BottomNavigationBar(<br>        currentIndex: _currentIndex,<br>        onTap: (index) =&gt; setState(() =&gt; _currentIndex = index),<br>        items: const [<br>          BottomNavigationBarItem(icon: Icon(Icons.home), label: &#39;Home&#39;),<br>          BottomNavigationBarItem(icon: Icon(Icons.settings), label: &#39;Settings&#39;),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p><strong>MEMORY BEHAVIOR IN INDEXEDSTACK</strong></p><pre>| Action                   | What Happens in Memory                       |<br>| ------------------------ | -------------------------------------------- |<br>| Open App                 | Both pages are built **once**                |<br>| Switch to Settings       | Home remains alive; Settings becomes visible |<br>| Switch to Home           | Settings remains alive; Home becomes visible |<br>| Navigate away from shell | Both pages get disposed                      |</pre><p><strong>initState() called once</strong></p><p><strong>dispose() called only when the shell is completely removed</strong></p><p><strong>Builds happen only when state changes, not on tab switching</strong></p><h3><strong>Limitations of IndexedStack Navigation</strong></h3><p>While IndexedStack is powerful, it has limitations:</p><ul><li>You cannot give each tab its own internal navigation stack.</li><li>URL routing (/home, /settings) isn’t tied to the tab.</li><li>Deep linking becomes difficult.</li><li>Back button behavior is messy.</li></ul><p>This is where GoRouter’s ShellRoute comes in.</p><h3><strong>ShellRoute — GoRouter’s First Attempt at a Bottom Navigation Shell</strong></h3><p>ShellRoute allows you to wrap multiple routes inside a common UI shell:</p><pre>AppBar  <br>Body (child from GoRouter)  <br>BottomNavigationBar</pre><p>It looks like this:</p><pre>ShellRoute(<br>  builder: (context, state, child) {<br>    return MainNavigationShell(child: child);<br>  },<br>  routes: [<br>    GoRoute(path: &#39;/home&#39;, builder: ...),<br>    GoRoute(path: &#39;/settings&#39;, builder: ...),<br>  ],<br>),</pre><h3>The Problem with ShellRoute: It does NOT preserve state</h3><p>Because ShellRoute works like this:</p><ul><li>When you navigate to /home, GoRouter builds HomePage()</li><li>When you navigate to /settings, GoRouter builds SettingsPage()</li><li>When you come <em>back</em> to /home, GoRouter <strong>builds Home again</strong></li></ul><p>It <strong>does not keep</strong> HomePage or SettingsPage mounted in memory.</p><h3>Result:</h3><ul><li>dispose() called every time</li><li>initState() called every time</li><li>Counter resets</li><li>Scroll resets</li><li>UI state is lost</li></ul><h3>Memory Model of ShellRoute</h3><pre>Only one page is alive at a time.<br><br>HomePage → disposed<br>SettingsPage → constructed</pre><p>This is NOT ideal for bottom navigation, where users expect tabs to maintain their state.</p><h3><strong>StatefulShellRoute.indexedStack — GoRouter’s Best Solution for Bottom Navigation</strong></h3><p>To solve all problems with ShellRoute, GoRouter introduced:</p><h3>StatefulShellRoute.indexedStack</h3><p>This is GoRouter’s version of IndexedStack, with <strong>navigation support</strong> and <strong>state preservation</strong>.</p><p><strong>How It Works</strong></p><ul><li>Each tab becomes a <em>branch</em></li><li>Each branch has its own Navigator and its own stack</li><li>All branches stay alive</li><li>Switching tabs simply switches visibility, NOT rebuilding UI</li></ul><pre>StatefulShellRoute.indexedStack(<br>  builder: (context, state, navigationShell) {<br>    return MainNavigationShell(navigationShell: navigationShell);<br>  },<br>  branches: [<br>    StatefulShellBranch(<br>      routes: [<br>        GoRoute(<br>          path: &#39;/home&#39;,<br>          builder: (context, state) =&gt; const HomePage(),<br>        ),<br>      ],<br>    ),<br>    StatefulShellBranch(<br>      routes: [<br>        GoRoute(<br>          path: &#39;/settings&#39;,<br>          builder: (context, state) =&gt; const SettingsPage(),<br>        ),<br>      ],<br>    ),<br>  ],<br>)</pre><pre>class MainNavigationShell extends StatelessWidget {<br>  final StatefulNavigationShell navigationShell;<br><br>  const MainNavigationShell({super.key, required this.navigationShell});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: navigationShell,<br>      bottomNavigationBar: BottomNavigationBar(<br>        currentIndex: navigationShell.currentIndex,<br>        onTap: (index) =&gt; navigationShell.goBranch(<br>          index,<br>          initialLocation: index == navigationShell.currentIndex,<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h4><strong>MEMORY BEHAVIOR OF STATEFULSHELLROUTE</strong></h4><p>✔ Each tab has its own Navigator</p><p>✔ Each tab maintains its stack</p><pre>Dashboard Stack:<br>  /home<br>  /home/details<br><br>Settings Stack:<br>  /settings</pre><p>Switch tabs → nothing is disposed.</p><p>initState() runs once per page</p><p>dispose() only runs when the entire shell is removed</p><p>You can deep link to /home/details and tab switches still work</p><p>Back button works independently inside each tab</p><p>This is <strong>the most powerful bottom navigation architecture</strong> in Flutter today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=759b2975808c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Flutter’s Three Trees: Widget, Element, and Render Object]]></title>
            <link>https://medium.com/@harshhub.414/understanding-flutters-three-trees-widget-element-and-render-object-5e3f8d840eab?source=rss-62af0852f2f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e3f8d840eab</guid>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-tree]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <dc:creator><![CDATA[harsh_singh]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 09:31:57 GMT</pubDate>
            <atom:updated>2025-10-20T09:32:17.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoSd7ttKuvXqonpwL0pRfw.png" /></figure><p>Flutter uses <strong>three core trees</strong> to construct, manage, and render your app’s UI:</p><ul><li><strong>Widget Tree</strong> — the declarative blueprint of the UI</li><li><strong>Element Tree</strong> — the runtime representation that connects widgets to render objects</li><li><strong>Render Object Tree</strong> — the low-level objects that handle layout, painting, and interactions</li></ul><p>Each tree plays a unique role in Flutter’s rendering system, and understanding how they work together is key to building efficient and scalable Flutter apps.</p><h3>1. Widget Tree</h3><h3>What It Is</h3><p>The Widget Tree is the <strong>declarative structure</strong> of your UI — what you define in your Dart code. Every component, from buttons to text fields, is a widget. Widgets describe <strong>what</strong> should be displayed, not <strong>how</strong> or <strong>where</strong> it appears.</p><h3>Example</h3><pre>Widget build(BuildContext context) {<br>  return Scaffold(<br>    appBar: AppBar(title: Text(&#39;Widget Tree&#39;)),<br>    body: Center(child: Text(&#39;Hello World&#39;)),<br>  );<br>}</pre><h3>Key Points</h3><ul><li>Widgets are <strong>immutable</strong>; Flutter creates a new widget whenever the state changes.</li><li>Widgets act as <strong>configuration objects</strong> or blueprints, not the actual rendered UI.</li></ul><h3>2. Element Tree</h3><h3>What It Is</h3><p>The Element Tree is the <strong>runtime representation</strong> of widgets. Flutter creates an Element for every widget in your app during the build phase. Elements keep track of:</p><ul><li>The current widget</li><li>Its state (for stateful widgets)</li><li>Its position in the hierarchy</li></ul><h3>How It Works</h3><p>When setState() is called, Flutter <strong>does not rebuild the entire UI</strong>. Instead, it compares new widgets with the existing ones in the Element Tree and updates only what has changed. This process is called <strong>widget reconciliation</strong>.</p><h3>Types of Elements</h3><ul><li><strong>StatelessElement</strong> — for StatelessWidget</li><li><strong>StatefulElement</strong> — for StatefulWidget</li><li><strong>RenderObjectElement</strong> — for widgets that affect layout and painting (e.g., Container, Padding)</li></ul><h3>3. Render Object Tree</h3><h3>What It Is</h3><p>The Render Object Tree is the <strong>lowest-level tree</strong>, responsible for:</p><ul><li>Layout (size and position)</li><li>Painting (drawing on the screen)</li><li>Hit testing (touch detection)</li></ul><p>RenderObjects (like RenderBox) handle the actual rendering on the GPU.</p><h3>Example</h3><ul><li>Text widget → RenderParagraph</li><li>Container widget → RenderDecoratedBox</li></ul><p>Simplified flow:</p><pre>Widget Tree → Element Tree → Render Object Tree → GPU Rendering</pre><h3>How the Trees Work Together</h3><p>StageTreeDescriptionBuildWidget TreeDefine what the UI should look likeMountElement TreeCreate live instances and link widgets to render objectsLayout &amp; PaintRender Object TreeHandle layout, painting, and user interactions</p><h3>Visualization Example</h3><pre>Widget Tree<br> └── Center<br>      └── Text(&quot;Hello&quot;)</pre><pre>Element Tree<br> └── CenterElement<br>      └── StatelessElement(Text)</pre><pre>Render Object Tree<br> └── RenderPositionedBox<br>      └── RenderParagraph</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e3f8d840eab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How the Actor Model Scales to Millions of Users]]></title>
            <link>https://medium.com/@harshhub.414/how-the-actor-model-scales-to-millions-of-users-246378de838e?source=rss-62af0852f2f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/246378de838e</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[paypal]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[harsh_singh]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 20:45:30 GMT</pubDate>
            <atom:updated>2025-07-17T05:52:22.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CyAToKsIBPv3Zj8X-r3Y0A.jpeg" /></figure><p>This article explains how the <strong>Actor Model</strong>, particularly with <strong>Akka in Java</strong>, helps build highly scalable, non-blocking systems compared to traditional thread-based architectures.</p><p>Imagine you’re the <strong>mayor of a growing city</strong>. At first, things are great — everyone lives close to the center, where all services (hospitals, water, transport) are located.</p><p>But as the population grows, you expand the city outward, building more houses across 100 km. Now, people have to travel hours every day just to reach the city center. Services are overloaded, traffic is terrible, and things start to break. This was the problem <strong>PayPal</strong> for suffering we have to handle millions of transaction everyday, there were using 1000 virtual machines to handle this..which was very complex to maintain and error prone.</p><p>Now suppose,Instead of spreading out, you start building <strong>apartment towers</strong> — compact, vertical zones with their own water, clinics, and shops. Everything is local. People don’t need to go to the city center anymore.</p><p>Suddenly, your city runs smoother, faster, and serves more people with fewer roads and less chaos. This what we called Actor-based(AKKA) model which helped paypal to come from <strong>1000 Virtual machines to just 8</strong>.</p><h3>What Is an Actor?</h3><p>In the <strong>Actor Model of computation</strong>, an <strong>actor</strong> is the <strong>fundamental unit of work</strong>.</p><p>You can think of an actor as a <strong>self-contained micro-service</strong> that:</p><ul><li><strong>Receives messages</strong></li><li><strong>Sends messages</strong> to other actors</li><li><strong>Creates new actors</strong></li><li><strong>Maintains private, internal state.</strong></li></ul><p><strong><em>Actors are not threads.</em></strong><em>They are </em><strong><em>lightweight objects</em></strong><em>, and many can </em><strong><em>share the same few threads</em></strong></p><p>Imagine This:</p><p>You have:</p><ul><li>1,000 actors (one per user or task)</li><li>Only 32 threads in your thread pool</li></ul><p>Each actor:</p><ul><li>Only <strong>needs a thread</strong> for a few milliseconds</li><li>Then <strong>gives it back</strong></li></ul><p>In traditional method you were only able to handle 32 concurrent requests with 32 threads..</p><p>But with Actor you now have a whole big team of 1000 actors for same 32 threads.</p><p>This is because Actor does not keep the thread with itself whole duration of request instead it frees it between the request which help to create multiple actors using same number of threads.</p><h3>Traditional System (Thread-per-Request)</h3><blockquote><em>User clicks “Add to Cart” on the website.</em></blockquote><ul><li><strong>A thread is assigned</strong> from the thread pool.</li><li>Thread <strong>queries the database</strong> to fetch the cart (blocking).</li><li>Thread <strong>updates the cart</strong> in memory.</li><li>Thread <strong>writes the updated cart</strong> back to the DB (blocking again).</li><li>Thread <strong>sends HTTP response</strong> and releases.</li></ul><blockquote><em>Total time: 150ms<br> Thread is held for entire 150ms<br> 10,000 users = 10,000 threads = system overload</em></blockquote><h3>Actor-Based System (Akka)</h3><blockquote><em>👤 Same user clicks “Add to Cart”</em></blockquote><ul><li>A message is sent to the <strong>CartActor[user123]</strong>.</li><li>Actor is <strong>already alive</strong> and has <strong>cart in memory</strong> (no DB hit).</li><li>Actor <strong>processes the message</strong> using a shared thread.</li><li>Actor makes <strong>non-blocking async call</strong> to save update to DB.</li><li>Thread is <strong>freed immediately</strong> (no blocking).</li><li>When DB write completes, <strong>Akka schedules callback</strong>, actor sends response.</li></ul><p><em>Total time: still 150ms.</em></p><p><em>Thread held: only 2ms total</em></p><p><em>10,000 users = 10,000 actors, but still need ~32 threads</em></p><h3>What Is Actor State?</h3><p>An <strong>actor’s state</strong> is the data it keeps inside itself — like a user’s cart, balance, or session.</p><ul><li>It’s <strong>private</strong>: only the actor can access it</li><li>It’s <strong>in-memory</strong>: fast to read/write</li><li>It’s <strong>safe</strong>: no other thread or actor can touch it</li></ul><h3>Why It’s Helpful</h3><ul><li>No need for locks — no shared memory</li><li>No race conditions — one message at a time</li><li>Faster — no DB call needed for every request</li><li>Scales well — each actor handles its own data</li></ul><p>In actor-based systems like Akka, the actor keeps the user’s state (like a cart or balance) in memory, so it doesn’t hit the database on every action. Instead, it loads the state from the database only once when the actor is first created (cold start). After that, all updates happen in-memory, which is much faster. To ensure data safety, the actor periodically saves changes to the database using event sourcing or snapshots. When the actor becomes idle and is passivated (shut down to save memory), it persists its final state, so it can restore (rehydrate) it later. This way, you get the speed of memory with the reliability of durable storage — without overwhelming the database with frequent reads and writes.</p><h3>How Actor State Is Cleared</h3><ul><li>If the actor becomes <strong>idle</strong> (no messages for a while), Akka may <strong>passivate</strong> (stop) it to save memory.</li><li>Before passivating, it <strong>persists the latest state</strong> to the database.</li><li>When needed again (e.g., user comes back), the actor is <strong>restarted and rehydrated</strong> from the saved state.</li></ul><h3>Imagine a Simple DB Operation:</h3><blockquote><em>User clicks “Get My Orders” → System fetches order history from DB.</em></blockquote><h3>Traditional Blocking System (Spring MVC, Thread-per-request)</h3><ul><li>A user request comes in.</li><li>Server assigns a <strong>dedicated thread</strong> to that request.</li><li>The thread starts the DB call → waits 200ms for DB to respond.</li><li>During that time, the thread <strong>does nothing</strong> — just sits and waits.</li><li>After response, it sends the result back and ends.</li></ul><h3>Problem:</h3><p>Even though the thread only did <strong>1ms</strong> of useful work and waited <strong>199ms</strong>, it was <strong>blocked the whole time</strong> — and unavailable to serve others.</p><ul><li>If 10,000 users do this:</li><li>You need 10,000 thread</li><li>~2GB of RAM (each thread ~2MB)</li><li>Risk of thread pool exhaustion, high context switching</li></ul><h3>Actor-Based / Async System (Akka / Netty / NIO)</h3><ul><li>A user request arrives as a <strong>message</strong> to their actor.</li><li>Actor gets a thread for 1ms → sends async DB request.</li><li>The thread is immediately <strong>released</strong> (not blocked).</li><li>DB responds after 200ms → the system gets a signal (event).</li><li>Actor processes the response using a thread for 1ms again → done.</li></ul><h3>Benefit:</h3><ul><li>During the 199ms DB wait, <strong>no thread is held</strong></li><li>That thread is <strong>serving others in the meantime</strong></li></ul><p>If 10,000 users do this:</p><ul><li>You still only need ~32–50 threads</li><li>Tiny RAM usage</li><li>Zero blocking, highly efficient.</li></ul><p>Now u might be confused it’s still making DB call in Actor model that must be using some thread ..so let’s clear that too..</p><p><strong>How threads are used differently for a database call</strong> in:</p><ul><li>Traditional (Blocking I/O)</li><li>Actor-Based / Async (Non-blocking I/O)</li></ul><h3>What Is the “I/O Thread” in Async Systems?</h3><p>It’s a <strong>lightweight, event-driven thread</strong> that’s part of a <strong>dedicated thread pool</strong> used <strong>only</strong> for handling <strong>I/O operations</strong> like:</p><ul><li>Reading/writing to databases</li><li>Calling external APIs</li><li>Network communication (sockets)</li></ul><h3>Technically, It Comes From:</h3><ul><li><strong>Netty’s event loop group</strong> (used by Akka HTTP, Play, etc.)</li><li><strong>Async DB driver’s internal I/O pool</strong> (e.g., R2DBC, PostgreSQL async client)</li><li><strong>Java NIO Selector threads</strong> (react to I/O readiness using OS signals)</li><li><strong>Operating system’s kernel-backed non-blocking I/O</strong></li></ul><h3>How It Works:</h3><ul><li>Actor wants to fetch something from DB.</li><li>It initiates an <strong>asynchronous request</strong> using an async driver.</li><li>The <strong>I/O thread (not the actor thread)</strong> monitors the DB socket using NIO/event loop.</li><li>When the DB responds, the I/O thread <strong>fires a callback or event</strong>.</li><li>That event is sent back to the <strong>actor</strong> as a message for processing.</li></ul><blockquote><em>Imagine a </em><strong><em>valet team</em></strong><em> that just watches for car arrivals and hands off keys. They’re not driving the cars — they just respond when one shows up.</em></blockquote><p>Similarly, I/O threads <strong>don’t “do” the work</strong> — they <strong>watch and notify</strong> when something (like DB response) is ready.</p><p>Here come’s the last and most important topic which help to manage complexity</p><h3>What is a Parent-Child Actor?</h3><p>In the <strong>Actor Model</strong>, every actor can <strong>create other actors</strong>.</p><ul><li>The one that creates is the <strong>parent</strong>.</li><li>The one that’s created is the <strong>child</strong>.</li></ul><p>This forms a <strong>tree-like hierarchy</strong> of actors.</p><h3>Role of the Parent Actor:</h3><p><strong>Creation &amp; Supervision</strong>:</p><ul><li>The parent creates child actors for handling sub-tasks.</li><li>It supervises them — decides what to do if they fail (restart, stop, escalate).</li></ul><p><strong>Delegation</strong>:</p><ul><li>Instead of doing all work, the parent delegates parts to child actors.</li></ul><p><strong>Lifecycle Control</strong>:</p><ul><li>If the parent stops, all its children are also stopped automatically.</li></ul><h3>Role of the Child Actor:</h3><p><strong>Focused Work</strong>:</p><ul><li>Handles a specific task or user/session independently.</li></ul><p><strong>Reports Back (Optional)</strong>:</p><ul><li>Can send results, errors, or updates to the parent.</li></ul><p>So next time you think about using threads, locks, and shared state — imagine 10,000 people fighting over one bathroom key. Painful, right? Now imagine each one has their own little actor with its own toilet… uh, I mean, logic and state. Much better!</p><p>Actors don’t get into race conditions, don’t need therapy for deadlocks, and don’t hog threads like a drama queen on stage. They just do their job, one message at a time.</p><p>If software was theatre, Actors would win an Oscar for best performance under load.</p><p>The curtain drops… but the messages keep flowing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=246378de838e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Spring Cloud? A Beginner’s Guide to Microservices Made Easy]]></title>
            <link>https://medium.com/@harshhub.414/spring-cloud-explained-simplifying-microservices-architecture-in-the-cloud-era-1aec0d4f2cfb?source=rss-62af0852f2f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aec0d4f2cfb</guid>
            <category><![CDATA[spring-cloud-gateway]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[harsh_singh]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 20:02:22 GMT</pubDate>
            <atom:updated>2025-06-25T09:03:10.263Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lm9npyXjzRNs924VzzBCDQ.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>What is Spring Cloud, and how does it simplify microservices in Java? If you’re struggling to manage distributed systems, Spring Cloud is a powerful framework that helps build scalable, cloud-native microservices. Built on top of Spring Boot, it streamlines configuration management, service discovery, load balancing, and more — all while keeping your architecture clean and modular. In this article, you’ll learn how Spring Cloud works, why it matters, and when to use it in your projects.</p><p>Imagine walking into a large, modern shopping mall filled with dozens of stores that specialize in various products, such as clothing, electronics, food, and cosmetics. As a visitor, you don’t need to know the location of each store, their opening hours, or how they restock their shelves. Simply enter through the main entrance, consult the mall directory, and let the security personnel and information desk guide you to your desired destination.</p><p>Think of the mall as your backend system, with each store representing a microservice—such as one for users, one for orders, and one for products. Just as the mall requires infrastructure to help visitors navigate, communicate, and function effectively, your system needs tools and patterns to manage all these services reliably.</p><p>This is where <strong>Spring Cloud</strong> comes in.</p><p>Managing a <strong>microservices architecture</strong> is like managing a busy mall. It’s not enough to just have separate services — you need coordination, communication, and control.</p><p>Some of the common problems teams face when scaling microservices are:</p><ul><li><strong>How do services find each other</strong> without hardcoding IPs?</li><li><strong>How do you change config in one place and reflect it everywhere?</strong></li><li><strong>How do you handle failures</strong> in one service without crashing the whole flow?</li><li><strong>How do you trace a request</strong> that goes through 5 services?</li></ul><p>“Managing a microservices architecture at scale isn’t easy. Spring Cloud brings production-grade solutions to the table — from service discovery to distributed tracing — to help you build robust cloud-native applications.”</p><p>Built on top of <strong>Spring Boot</strong>, <strong>Spring Cloud</strong> provides tools like:</p><ul><li><strong>Eureka</strong> for service discovery (the mall directory)</li><li><strong>Spring Cloud Config</strong> for centralized configuration (the mall management office)</li><li><strong>Spring Cloud Gateway</strong> for routing (the main entrance/security desk)</li><li><strong>Sleuth + Zipkin</strong> for distributed tracing (CCTV to trace visitor paths)</li><li><strong>Resilience4j</strong> for fault tolerance (emergency response systems)</li></ul><p>In this article, we’ll explore how Spring Cloud components solve real-world problems in distributed systems, and how you can use them to build reliable, scalable cloud-native apps.</p><h3><strong>Why Spring Cloud?</strong></h3><p>When people shift from monolithic(Each Service in different SpringBoot application) apps to <strong>microservices</strong>, they expect flexibility. But soon they run into unexpected issues like hardcoded URLs, messy configs, and broken flows when a single service fails.</p><h3>1. Hardcoded URLs — Services Can’t Find Each Other</h3><p>Let’s say your order-service needs data from product-service. Without service discovery, you might write something like this:</p><pre>// order-service<br>RestTemplate restTemplate = new RestTemplate();<br>String productInfo = restTemplate.getForObject(&quot;http://localhost:8081/products/101&quot;, String.class);</pre><p>Problem:</p><ul><li>What if product-service is deployed on a different port tomorrow?</li><li>What if there are 3 instances of product-service running?</li><li>You’ll have to change the code everywhere.</li></ul><p>✅ Spring Cloud Solution:<br> Use <strong>Eureka (Service Registry)</strong> + <strong>LoadBalanced RestTemplate</strong>:</p><pre>// Enable service discovery<br>@LoadBalanced<br>@Bean<br>public RestTemplate restTemplate() {<br>    return new RestTemplate();<br>}<br><br>// Now just use the service name instead of the URL<br>String productInfo = restTemplate.getForObject(&quot;http://product-service/products/101&quot;, String.class);</pre><p>Now Spring Cloud will <strong>auto-discover the service</strong>, load balance it, and route the request.</p><h4>Spring Cloud’s Solution Using Eureka and LoadBalanced RestTemplate</h4><p>1. <strong>Eureka (Service Registry)</strong></p><p>Think of Eureka as a <strong>phonebook</strong> for your services.</p><ul><li>When each service (like product-service) starts up, it <strong>registers itself</strong> with Eureka</li><li>Eureka keeps track of <strong>where each service is located</strong> (its address and port).</li><li>If you have multiple instances of product-service, Eureka knows about all of them.</li></ul><p>2. <strong>LoadBalanced RestTemplate</strong></p><p>RestTemplate is a simple tool in Spring Boot that lets you call other services by making HTTP requests.</p><ul><li>When you add @LoadBalanced to RestTemplate, you are telling Spring:<br> <strong>&quot;Hey, instead of using a fixed URL, please ask Eureka where the service is.&quot;</strong></li></ul><p>3. <strong>Using Service Name Instead of URL</strong></p><p>Now, you don’t call the product-service by its address or port. Instead, you call it by its <strong>service name</strong> registered in Eureka-</p><pre>String productInfo = restTemplate.getForObject(&quot;http://product-service/products/101&quot;, String.class);</pre><p>Spring Cloud will:</p><ul><li>Ask Eureka <strong>“Where can I find product-service right now?”</strong></li><li>Eureka responds with the list of all available instances.</li><li>Spring Cloud picks one instance automatically (load balancing).</li><li>The request is routed to that instance.</li></ul><h3>🛠 Problem 2: Updating Config Across All Services</h3><h3>👎 The Old Way (Without Spring Cloud)</h3><p>In a typical microservices setup:</p><ul><li>Each service has its own application.properties or application.yml.</li><li>If you need to change something (e.g., an API key), you must <strong>manually update</strong> every service’s config file.</li><li>Then, you have to <strong>restart all those services</strong> for the changes to take effect.</li></ul><p>This is error-prone and doesn’t scale well.</p><h3>Spring Cloud Fix: Centralized Config with Spring Cloud Config Server</h3><p>Spring Cloud gives us a <strong>central config server</strong>. Think of it like a <strong>shared settings panel</strong> that all services can access.</p><p>All your service configurations live in one place — like a <strong>GitHub repo</strong> — and your services fetch their config from there at runtime.</p><h3><strong>Problem 3: Crashes and Failures</strong></h3><p>Let’s say your order-service wants to call product-service to get product info. But what if:</p><ul><li>product-service is down?</li><li>Or it takes too long to respond?</li><li>Or the network has issues?</li></ul><p>In these cases, your app might crash or hang — which is bad for users. 😞</p><h3>Spring Cloud Fix: Resilience4j</h3><p>Spring Cloud uses a tool called <strong>Resilience4j</strong> to protect your service. It gives you:</p><ul><li><strong>Retry</strong> → Try again if it fails</li><li><strong>Fallback</strong> → Show a default response if it still doesn’t work</li><li><strong>Circuit Breaker</strong> → Stop calling the failing service after a few tries, and try again later</li></ul><h3>Simple Example with Retry + Fallback</h3><pre>@Retry(name = &quot;productService&quot;, fallbackMethod = &quot;fallback&quot;)<br>public String getProduct() {<br>    return restTemplate.getForObject(&quot;http://product-service/products&quot;, String.class);<br>}</pre><pre>// This method runs if getProduct() keeps failing<br>public String fallback(Exception e) {<br>    return &quot;Sorry! We’re showing a default product for now.&quot;;<br>}</pre><h3>What’s Happening?</h3><p>You try to call <a href="http://product-service/products.">http://product-service/products.</a></p><p>If it fails (maybe the service is down), Spring will <strong>retry</strong> a few times.</p><p>If it <strong>still fails</strong>, it will call the fallback() method.’</p><p>The user still gets a nice response like:<br> &quot;Sorry! We’re showing a default product for now.&quot;<br> instead of a scary error.</p><h3>Problem 4: Debugging is a Nightmare</h3><p>When you have just <strong>one service</strong>, finding bugs is easy — you check the logs and see what went wrong.</p><p>But in <strong>microservices</strong>, a single user request might go through 4–5 services like this:</p><pre>User ➝ Gateway ➝ Order Service ➝ Product Service ➝ Payment Service ➝ Notification Service</pre><p>Now imagine something breaks. You look at your logs and think:</p><p>“Which service failed?”<br>“Where did the request go?”<br>“How long did each service take?”<br> “What was the actual flow?”</p><p>It becomes <strong>really hard</strong> to understand what happened. This is where <strong>Spring Cloud Sleuth + Zipkin</strong> come to the rescue.</p><h3>Spring Cloud Fix: Sleuth + Zipkin</h3><h3>🔍 What is Sleuth?</h3><p><strong>Spring Cloud Sleuth</strong> automatically adds a <strong>unique ID</strong> (called a <strong>trace ID</strong>) to every request. This trace ID:</p><ul><li>Is the same across <strong>all services</strong> the request touches.</li><li>Appears in your <strong>logs</strong>, so you can <strong>search using that ID</strong>.</li></ul><p>You’ll also see <strong>span IDs</strong>, which are like mini-IDs for each step along the way.</p><h3>What is Zipkin?</h3><p><strong>Zipkin</strong> is a tool that collects those trace IDs and shows them in a <strong>visual timeline</strong> like this:</p><pre>➤ Gateway: 5ms  <br>➤ Order Service: 30ms  <br>➤ Product Service: 80ms  <br>➤ Payment Service: 200ms ❌ ← Something went wrong here  <br>➤ Notification Service: Not Reached</pre><p>If you’re just getting started with microservices like me, <strong>Spring Cloud might seem overwhelming at first</strong> — but once you understand the pieces, you’ll realize it solves a lot of the hard stuff for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aec0d4f2cfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use of Beans in spring vs. Other frameworks]]></title>
            <link>https://medium.com/@harshhub.414/use-of-beans-in-spring-vs-other-frameworks-1027f7a3304a?source=rss-62af0852f2f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1027f7a3304a</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[beans]]></category>
            <dc:creator><![CDATA[harsh_singh]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 08:35:25 GMT</pubDate>
            <atom:updated>2024-12-01T08:35:25.241Z</atom:updated>
            <content:encoded><![CDATA[<p>You might need clarification about the use case of creating beans using a constructor and setter injection vs. directly assigning objects during development. I will explain how these beans enhance the scalability and flexibility of your project, unlike other frameworks that require tedious tasks.</p><p>First, let’s begin with what is constructor and setter injection so that it might get easy for you to know better:</p><p><strong>Constructor injection and setter injection using beans-</strong></p><pre>package com.example;<br><br>public class Engine {<br>    private String type;<br><br>    public String getType() {<br>        return type;<br>    }<br><br>    public void setType(String type) {<br>        this.type = type;<br>    }<br>}</pre><p>This is simple engine class having single parameter…</p><pre>package com.example;<br><br>public class Car {<br>    private Engine engine; // Constructor injection<br>    private String color;  // Setter injection<br>    private String model;  // Setter injection<br><br>    // Constructor for Constructor Injection<br>    public Car(Engine engine) {<br>        this.engine = engine;<br>    }<br><br>    // Setter for Color<br>    public void setColor(String color) {<br>        this.color = color;<br>    }<br><br>    // Setter for Model<br>    public void setModel(String model) {<br>        this.model = model;<br>    }<br><br>    public void displayDetails() {<br>        System.out.println(&quot;Car Model: &quot; + model);<br>        System.out.println(&quot;Car Color: &quot; + color);<br>        System.out.println(&quot;Engine Type: &quot; + engine.getType());<br>    }<br>}</pre><p>This is another class Car which depends on Engine class and means Car class is dependent on Engine class and we are passing object of Engine class through constructor injection and have some setters and for parameters of Car class.</p><pre>&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;<br>       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans<br>       http://www.springframework.org/schema/beans/spring-beans.xsd&quot;&gt;<br><br>    &lt;!-- Bean for Engine Dependency --&gt;<br>    &lt;bean id=&quot;engine&quot; class=&quot;com.example.Engine&quot;&gt;<br>        &lt;property name=&quot;type&quot; value=&quot;V8 Engine&quot; /&gt;<br>    &lt;/bean&gt;<br><br>    &lt;!-- Bean for Car --&gt;<br>    &lt;bean id=&quot;car&quot; class=&quot;com.example.Car&quot;&gt;<br>        &lt;!-- Constructor Injection --&gt;<br>        &lt;constructor-arg ref=&quot;engine&quot; /&gt;<br>        &lt;!-- Setter Injection --&gt;<br>        &lt;property name=&quot;color&quot; value=&quot;Red&quot; /&gt;<br>        &lt;property name=&quot;model&quot; value=&quot;Tesla Model S&quot; /&gt;<br>    &lt;/bean&gt;<br><br>&lt;/beans&gt;</pre><p>This is our config.xml, which specifies the configuration of our code, including bean creation and assigning values to bean parameters. Additionally, beans can be considered as objects of any class.</p><p>Beans are defined using the bean tag, and the Spring IoC container manages the creation and parameter assignment for all these beans. You can think of it as the all-rounder of a company, responsible for managing tasks and other essential information.</p><pre>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.support.ClassPathXmlApplicationContext;<br><br>public class SpringDemo {<br>    public static void main(String[] args) {<br>        ApplicationContext context = new ClassPathXmlApplicationContext(&quot;config.xml&quot;);<br>        Car car = (Car) context.getBean(&quot;car&quot;);<br>        car.displayDetails();<br>    }<br>}</pre><p>Application context can be considered as a tool used by our all rounder IOC container for doing all the stuffs related to beans injection and their lifecyle.</p><p>Here’s is the output:</p><pre>Car Model: Tesla Model S<br>Car Color: Red<br>Engine Type: V8 Engine</pre><p>Now you might be thinking we can all do this with manually creating object, it such a confusing to do using beans, but it’s not true for large scale application even for small it is very helpfull. You might not find this beans of any use because you have got used to your code of :</p><p>Car c=new Car();</p><p>like this and it seems to simple and familiar to you…but in development if things seem to be easy means you can optimize it too and learn more..</p><p>Well now let me take you to a practical example of this to get better understanding:</p><p>We are creating a e-commerce platform and we are using some services like :</p><ol><li><strong>Order Service</strong>: Handles placing customer orders.</li><li><strong>Payment Service</strong>: Processes customer payments.</li><li><strong>Notification Service</strong>: Sends notifications (email, SMS) to customers.</li><li><strong>Inventory Service</strong>: Updates stock after an order is placed.</li></ol><h3>Without IoC and Beans (Manual Object Creation)</h3><pre>public class OrderService {<br>    private PaymentService paymentService;<br>    private NotificationService notificationService;<br>    private InventoryService inventoryService;<br><br>    public OrderService() {<br>        // Dependencies are created directly here.<br>        this.paymentService = new PaymentService(&quot;PAYMENT_KEY&quot;);<br>        this.notificationService = new NotificationService(&quot;EMAIL_API_KEY&quot;);<br>        this.inventoryService = new InventoryService();<br>    }<br><br>    public void placeOrder(Order order) {<br>        paymentService.processPayment(order);<br>        notificationService.sendOrderConfirmation(order);<br>        inventoryService.updateStock(order.getProductId(), -order.getQuantity());<br>    }<br>}</pre><p><strong>Problems in above approach-</strong></p><ul><li>OrderService is tightly coupled to PaymentService, NotificationService, and InventoryService.</li><li>Any change in the constructor of PaymentService (e.g., adding a new API key) requires changes in OrderService.</li><li>Whenever you need payment services you will reintialize it and if API’s key changes you need to change it all instances.</li><li>Sometimes suppose for payment services you requires two APIs keys one for customer and one for retailer then you will get confused in which part of code what to assign but you can this all do in a single xml in spring.</li><li>If you expand to hundreds of services, manually creating and managing these objects becomes unmanageable and error-prone.</li></ul><h3>With IoC and Beans (Using Spring Framework)</h3><pre>public class OrderService {<br>    private PaymentService paymentService;<br>    private NotificationService notificationService;<br>    private InventoryService inventoryService;<br><br>    // Dependencies injected by the IoC container<br>    public void setPaymentService(PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br><br>    public void setNotificationService(NotificationService notificationService) {<br>        this.notificationService = notificationService;<br>    }<br><br>    public void setInventoryService(InventoryService inventoryService) {<br>        this.inventoryService = inventoryService;<br>    }<br><br>    public void placeOrder(Order order) {<br>        paymentService.processPayment(order);<br>        notificationService.sendOrderConfirmation(order);<br>        inventoryService.updateStock(order.getProductId(), -order.getQuantity());<br>    }<br>}</pre><pre>&lt;beans&gt;<br>    &lt;!-- Define beans for services --&gt;<br>    &lt;bean id=&quot;paymentService&quot; class=&quot;com.example.PaymentService&quot;&gt;<br>        &lt;constructor-arg value=&quot;PAYMENT_KEY&quot; /&gt;<br>    &lt;/bean&gt;<br><br>    &lt;bean id=&quot;notificationService&quot; class=&quot;com.example.NotificationService&quot;&gt;<br>        &lt;constructor-arg value=&quot;EMAIL_API_KEY&quot; /&gt;<br>    &lt;/bean&gt;<br><br>    &lt;bean id=&quot;inventoryService&quot; class=&quot;com.example.InventoryService&quot; /&gt;<br><br>    &lt;bean id=&quot;orderService&quot; class=&quot;com.example.OrderService&quot;&gt;<br>        &lt;property name=&quot;paymentService&quot; ref=&quot;paymentService&quot; /&gt;<br>        &lt;property name=&quot;notificationService&quot; ref=&quot;notificationService&quot; /&gt;<br>        &lt;property name=&quot;inventoryService&quot; ref=&quot;inventoryService&quot; /&gt;<br>    &lt;/bean&gt;<br>&lt;/beans&gt;</pre><ul><li>Dependencies (PaymentService, NotificationService, InventoryService) are injected into OrderService by the IoC container.</li><li>OrderService no longer &quot;knows&quot; how these services are created, making it easy to replace them with alternative implementations (e.g., StripePaymentService).</li><li>All configurations are centralized in config.xml (or annotations in modern Spring setups).</li><li>Changing PaymentService API keys or replacing the NotificationService implementation requires a single update in the configuration file, not in multiple classes.</li><li>In large-scale systems, managing hundreds of dependencies becomes manageable.</li><li>The IoC container handles the creation, initialization, and lifecycle of beans.</li></ul><h3>Real-Life Analogy</h3><ul><li><strong>Without Beans:</strong> Imagine you’re a manager manually hiring and assigning employees for every task in your office. You need to interview each person and onboard them individually.</li><li><strong>With Beans:</strong> You hire an HR agency (IoC container). The HR agency recruits, assigns roles, and manages employee lifecycles. You just use the employees when needed, focusing on tasks instead of recruitment.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1027f7a3304a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Client and Server-Side Rendering]]></title>
            <link>https://medium.com/@harshhub.414/flutter-client-and-server-side-rendering-f67334feab68?source=rss-62af0852f2f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f67334feab68</guid>
            <category><![CDATA[app-performance]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[client-side-rendering]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[harsh_singh]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 07:46:38 GMT</pubDate>
            <atom:updated>2024-11-10T07:46:38.097Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmFTPBPq7oLcaO247jvjBg.png" /></figure><p>When developing mobile applications, one of the key decisions you’ll need to make is how to construct the user interface (UI). Should the UI be primarily built on the server and delivered to the client, or should the client be responsible for rendering and managing the UI? In this article, we’ll explore the difference between <strong>Server-Driven UI</strong> and <strong>Client-Driven UI</strong> in Flutter.</p><h3><strong>Client-Driven UI</strong></h3><p>In a <strong>Client-Driven UI</strong>, the client (Flutter app) is responsible for building the UI. The server sends data such as text, images, or other content, and the app is in charge of rendering the UI components.</p><h4>How it Works</h4><p>The server provides content data, but the structure and layout of the UI are predefined in the app. The client app retrieves the data and displays it in the appropriate layout.</p><h4>Example:</h4><p>Here is a sample JSON response from the server that contains only content data:</p><pre>{<br>  &quot;title&quot;: &quot;Welcome to Client-Driven UI&quot;,<br>  &quot;buttonLabel&quot;: &quot;Click Me&quot;<br>}</pre><p>In this case, the Flutter app will render a simple UI with the title and a button:</p><pre>void main() {<br>  runApp(MyApp());<br>}</pre><pre>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: ClientDrivenPage(),<br>    );<br>  }<br>}</pre><pre>class ClientDrivenPage extends StatelessWidget {<br>  final String jsonResponse = &#39;&#39;&#39;<br>    {<br>      &quot;title&quot;: &quot;Welcome to Client-Driven UI&quot;,<br>      &quot;buttonLabel&quot;: &quot;Click Me&quot;<br>    }<br>  &#39;&#39;&#39;;</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    final Map&lt;String, dynamic&gt; parsedJson = json.decode(jsonResponse);</pre><pre>    return Scaffold(<br>      appBar: AppBar(title: Text(parsedJson[&#39;title&#39;])),<br>      body: Center(<br>        child: ElevatedButton(<br>          onPressed: () {},<br>          child: Text(parsedJson[&#39;buttonLabel&#39;]),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Server-Driven UI</h3><p>In a <strong>Server-Driven UI</strong>, the server dictates what the UI should look like. The Flutter app receives data from the server, which includes details about the UI layout and components. Based on this data, the app dynamically builds and renders the UI.</p><h4>How it Works</h4><p>The server sends a structured response (often in JSON format) that describes the layout of the UI, such as which widgets should be displayed, their properties, and how they are styled. The client app then parses this data and renders the UI based on the received instructions.</p><h4>Example:</h4><p>Consider this sample JSON response from the server:</p><pre>{<br>  &quot;type&quot;: &quot;column&quot;,<br>  &quot;children&quot;: [<br>    {<br>      &quot;type&quot;: &quot;text&quot;,<br>      &quot;content&quot;: &quot;Welcome to Server-Driven UI&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;button&quot;,<br>      &quot;content&quot;: &quot;Click Me&quot;<br>    }<br>  ]<br>}</pre><p>The Flutter app will parse this JSON and render a Column containing a Text widget and a Button widget.</p><pre>void main() {<br>  runApp(MyApp());<br>}</pre><pre>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: ServerDrivenPage(),<br>    );<br>  }<br>}</pre><pre>class ServerDrivenPage extends StatelessWidget {<br>  final String jsonResponse = &#39;&#39;&#39;<br>    {<br>      &quot;type&quot;: &quot;column&quot;,<br>      &quot;children&quot;: [<br>        {<br>          &quot;type&quot;: &quot;text&quot;,<br>          &quot;content&quot;: &quot;Welcome to Server-Driven UI&quot;<br>        },<br>        {<br>          &quot;type&quot;: &quot;button&quot;,<br>          &quot;content&quot;: &quot;Click Me&quot;<br>        }<br>      ]<br>    }<br>  &#39;&#39;&#39;;</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    final Map&lt;String, dynamic&gt; parsedJson = json.decode(jsonResponse);</pre><pre>    return Scaffold(<br>      appBar: AppBar(title: Text(&quot;Server-Driven UI&quot;)),<br>      body: _buildWidget(parsedJson),<br>    );<br>  }</pre><pre>  Widget _buildWidget(Map&lt;String, dynamic&gt; json) {<br>    if (json[&#39;type&#39;] == &#39;column&#39;) {<br>      List&lt;Widget&gt; children = [];<br>      for (var child in json[&#39;children&#39;]) {<br>        if (child[&#39;type&#39;] == &#39;text&#39;) {<br>          children.add(Text(child[&#39;content&#39;]));<br>        } else if (child[&#39;type&#39;] == &#39;button&#39;) {<br>          children.add(ElevatedButton(<br>            onPressed: () {},<br>            child: Text(child[&#39;content&#39;]),<br>          ));<br>        }<br>      }<br>      return Column(<br>        mainAxisAlignment: MainAxisAlignment.center,<br>        children: children,<br>      );<br>    }<br>    return Container();<br>  }<br>}</pre><h3><strong>What to Choose?</strong></h3><p>Choosing between <strong>Server Driven UI</strong> and the approach of <strong>extracting data from a GET API and displaying it using predefined widgets</strong> depends on the use case, project complexity, and maintenance requirements. Here are key factors to consider:</p><h3>1. Flexibility and Dynamic Updates:</h3><p><strong>Server Driven UI</strong>:</p><ul><li><strong>Pros</strong>: Allows the server to dictate the UI structure, making it easy to push UI changes, experiments, or updates without releasing a new app version or web deployment.</li><li><strong>Cons</strong>: Requires a more complex server-side implementation and parsing logic on the client side.</li></ul><p><strong>GET API with Predefined Widgets</strong>:</p><ul><li><strong>Pros</strong>: Easier to implement, as you only fetch data and display it using widgets that are already part of the app’s codebase.</li><li><strong>Cons</strong>: UI changes require updates to the app’s code and redeployment. This means longer update cycles and delays in reflecting design changes.</li></ul><h3>2. Use Case Complexity:</h3><p><strong>Server Driven UI</strong>:</p><ul><li><strong>Ideal for</strong>: Applications where UI needs to change frequently, such as e-commerce platforms, news apps, or content-driven services where different users may see different UIs.</li><li><strong>Not ideal for</strong>: Apps with simple, static UI structures where the UI doesn’t change often.</li></ul><p><strong>GET API with Predefined Widgets</strong>:</p><ul><li><strong>Ideal for</strong>: Applications with relatively fixed UI components that only need to display varying content (e.g., user profiles, static forms, or dashboards).</li><li><strong>Not ideal for</strong>: Apps needing dynamic UI changes without frequent updates.</li></ul><h3>3. Development and Maintenance:</h3><p><strong>Server Driven UI</strong>:</p><ul><li><strong>Pros</strong>: Easier to maintain and update UI/UX centrally, leading to faster rollouts for design and layout changes.</li><li><strong>Cons</strong>: Requires more effort in initial development to create a parsing system that converts JSON (or other formats) to widgets. Also, more complex debugging and error handling might be needed.</li></ul><p><strong>GET API with Predefined Widgets</strong>:</p><ul><li><strong>Pros</strong>: Simple to develop and maintain because the UI structure is hardcoded, and the data just needs to be fetched and displayed.</li><li><strong>Cons</strong>: Changes in UI structure or layout require updating the app’s source code and redeploying the app, which can be time-consuming and disrupt users.</li></ul><h3>4. Performance:</h3><p><strong>Server Driven UI</strong>:</p><ul><li><strong>Potential Drawback</strong>: Initial rendering might be slower due to JSON parsing and dynamic widget building, especially for complex layouts.</li><li><strong>Optimization</strong>: Good caching strategies and efficient parsing logic can mitigate performance issues.</li></ul><p><strong>GET API with Predefined Widgets</strong>:</p><ul><li><strong>Better Performance</strong>: Rendering predefined widgets based on fetched data is generally faster since the layout is hardcoded and requires less runtime parsing.</li><li><strong>Fewer Overheads</strong>: The structure is already compiled, so the app can directly populate the UI with data, leading to faster rendering.</li></ul><h3>5. Control and Customization:</h3><p><strong>Server Driven UI</strong>:</p><ul><li><strong>Pros</strong>: The server has complete control over the app’s UI, which is beneficial for running A/B tests, theming, or quickly responding to business needs.</li><li><strong>Cons</strong>: Limits the client-side’s ability to control the UI, which might be less ideal for apps needing local customization or offline functionality.</li></ul><p><strong>GET API with Predefined Widgets</strong>:</p><ul><li><strong>Pros</strong>: Gives developers more control over UI customization and user interactions on the client side.</li><li><strong>Cons</strong>: Lacks the centralized flexibility of server-driven updates.</li></ul><h3>Conclusion:</h3><p><strong>Choose Server Driven UI</strong> if:</p><ul><li>Your app needs to frequently change the UI or conduct experiments.</li><li>You want centralized control over the layout and user experience.</li><li>Your team is comfortable with the added complexity of server-side and client-side logic.</li></ul><p><strong>Choose GET API with Predefined Widgets</strong> if:</p><ul><li>Your app’s UI structure is relatively stable and doesn’t need constant updates.</li><li>You want a simpler implementation with a straightforward development process.</li><li>Quick performance and direct data display are more important than flexibility.</li></ul><p>In my next article i’m will share 3 traditional methods to implement client side rendering..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f67334feab68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DTO Pattern Use Case in Spring Boot]]></title>
            <link>https://medium.com/@harshhub.414/dto-pattern-use-case-in-spring-boot-0feb060f008d?source=rss-62af0852f2f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0feb060f008d</guid>
            <category><![CDATA[data-transfer-object]]></category>
            <category><![CDATA[spring-boot-project]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[harsh_singh]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 16:59:10 GMT</pubDate>
            <atom:updated>2024-10-01T16:59:10.712Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is DTO?</strong></h3><p>The <strong>DTO (Data Transfer Object) pattern</strong> is a design pattern used to transfer data between different layers of an application, particularly in scenarios where data needs to be exchanged between a client and a server. The primary purpose of a DTO is to encapsulate data and reduce the number of method calls, especially when dealing with remote services</p><p>In a user profile management application, there is a <strong>User</strong> entity that contains fields such as id, username, email, password, dateOfBirth, address, and profilePicture. The application allows users to create and manage their profiles, but when exposing user data through an API for a mobile app, the frontend only needs the id, username, email, and profilePicture to display user information.</p><p>If we don’t use a Data Transfer Object (DTO) in a user profile management application, we risk exposing sensitive data, such as passwords and addresses, when returning the entire User entity in API responses. This can lead to security vulnerabilities and data breaches. Additionally, the payload size will increase, causing slower response times and higher data usage for mobile users who only need specific fields like id, username, email, and profilePicture.</p><h3><strong>Example When we don’t use DTO:</strong></h3><p>When you don’t use a DTO, the incoming request body is directly mapped to your <strong>entity class.</strong></p><p>Entity: Todo</p><pre>@Entity<br>@Table(name = &quot;t_todos&quot;)<br>@Getter<br>@Setter<br>@AllArgsConstructor<br>@NoArgsConstructor<br>public class Todo {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.AUTO)<br>    private int id;  // Auto-generated, should not be modified by clients<br><br>    private String title;<br><br>    private String description;<br><br>    @Temporal(TemporalType.TIMESTAMP)<br>    private Date dateCreated = new Date();  // Set automatically by the server<br><br>    private boolean status = false;  // Default is false<br><br>    @Enumerated(EnumType.STRING)<br>    private StatusType statusType = StatusType.INACTIVE;  // Default is INACTIVE<br><br>    @Enumerated(EnumType.STRING)<br>    private Priority priority = Priority.Low;  // Default is Low<br>}</pre><p>Controller: Directly Using the Entity</p><pre>@RestController<br>@RequestMapping(&quot;/todos&quot;)<br>public class TodoController {<br><br>    @Autowired<br>    private TodoService todosService;<br><br>    // Save new Todo<br>    @PostMapping(&quot;/save&quot;)<br>    public ResponseEntity&lt;Todo&gt; saveTodo(@RequestBody Todo todo) {<br>        // Set dateCreated if not provided<br>        if (todo.getDateCreated() == null) {<br>            todo.setDateCreated(new Date());<br>        }<br><br>        // Save the todo entity directly<br>        todosService.save(todo);<br><br>        return ResponseEntity.status(HttpStatus.CREATED).body(todo);<br>    }<br>}</pre><p>Example of Request (Without DTO)</p><pre>{<br>    &quot;id&quot;: 5,<br>    &quot;title&quot;: &quot;Learn Spring Boot&quot;,<br>    &quot;description&quot;: &quot;Learn about DTOs in Spring Boot&quot;,<br>    &quot;dateCreated&quot;: &quot;2024-09-30T10:00:00.000Z&quot;,<br>    &quot;status&quot;: true,<br>    &quot;statusType&quot;: &quot;ACTIVE&quot;,<br>    &quot;priority&quot;: &quot;High&quot;<br>}</pre><p>Drawback:</p><p>The client is able to provide the id, dateCreated, and even the status. These fields should not be modifiable by the client (e.g., id should be auto-generated, dateCreated should be set by the server).</p><h3><strong>Example Using DTO</strong>(Data Transfer Object)<strong>:</strong></h3><p>A DTO is a separate object that is used to transfer data between layers. When using a DTO, you control which fields are exposed to the client and which fields can be modified by the request. This separates the internal database structure from the client interface.</p><p>Create a DTO: TodoRequest</p><pre>//Invoke necessary annotations.<br>public class TodoRequest {<br>    <br>    @NotBlank(message = &quot;Title is required&quot;)<br>    private String title;<br><br>    private String description;<br><br>    private boolean status = false;<br><br>    private StatusType statusType = StatusType.INACTIVE;<br><br>    private Priority priority = Priority.Low;<br><br>}</pre><h4>Updated Controller Using DTO</h4><pre>@RestController<br>@RequestMapping(&quot;/todos&quot;)<br>public class TodoController {<br><br>    @Autowired<br>    private TodoService todosService;<br><br>    // Save new Todo using DTO<br>    @PostMapping(&quot;/save&quot;)<br>    public ResponseEntity&lt;Todo&gt; saveTodo(@Valid @RequestBody TodoRequest todoRequest) {<br><br>        // Manually create a new Todo entity from the DTO<br>        Todo todo = new Todo();<br>        todo.setTitle(todoRequest.getTitle());<br>        todo.setDescription(todoRequest.getDescription());<br>        todo.setStatus(todoRequest.isStatus());<br>        todo.setStatusType(todoRequest.getStatusType());<br>        todo.setPriority(todoRequest.getPriority());<br>        todo.setDateCreated(new Date());  // Set by server<br><br>        // Save the todo entity<br>        todosService.save(todo);<br><br>        return ResponseEntity.status(HttpStatus.CREATED).body(todo);<br>    }<br>}</pre><p>Example of Request (With DTO)</p><pre>{<br>    &quot;title&quot;: &quot;Learn Spring Boot&quot;,<br>    &quot;description&quot;: &quot;Learn about DTOs in Spring Boot&quot;,<br>    &quot;status&quot;: true,<br>    &quot;statusType&quot;: &quot;ACTIVE&quot;,<br>    &quot;priority&quot;: &quot;High&quot;<br>}</pre><p>Benefits:</p><p>You can <strong>control which fields are exposed</strong> to the client and which fields can be modified. In this case, the client can only modify title, description, status, statusType, and priority. Fields like id and dateCreated are managed by the server.</p><p>You can apply validation rules to the DTO, ensuring that only valid data is passed through. For example, the title is marked as required using the @NotBlank annotation.</p><h3>Summary:</h3><ul><li><strong>Without DTO</strong>: Directly mapping request data to the entity is faster and more convenient but can expose sensitive fields, increase security risks, and tightly couple your API with your database schema.</li><li><strong>With DTO</strong>: Using a DTO adds an extra layer of abstraction, which improves security, separates concerns, and gives you better control over the data flow between the client and server. It also simplifies validation and enhances the overall design of your API.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0feb060f008d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide to Securing URLs in Spring Boot Applications]]></title>
            <link>https://medium.com/@harshhub.414/step-by-step-guide-to-securing-urls-in-spring-boot-applications-1c77d9a12019?source=rss-62af0852f2f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c77d9a12019</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[harsh_singh]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 17:25:18 GMT</pubDate>
            <atom:updated>2024-09-28T17:25:18.379Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Spring Security</strong> is a framework that helps protect your application by handling things like login, user roles, and access to different parts of your site. It makes sure only the right people can access certain information or features. With built-in support for common security practices like password management and user permissions, Spring Security is widely used in many Java-based applications.</p><p>For example, imagine you have an online store. You would want everyone to access product pages, but only admins to access the page where they can add new products. Spring Security makes this easy by allowing you to protect URLs based on user roles.</p><h3>Setting Up Spring Security</h3><p>Before you start securing URLs in your application, you first need to add Spring Security to your project. This is done by including the necessary dependencies in your pom.xml (for Maven) or build.gradle (for Gradle).</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Reference: <a href="https://docs.spring.io/spring-security/reference/getting-spring-security.html">Getting Spring Security :: Spring Security</a></p><p>After you add the Spring Security dependency to your project, all URLs in your application become secured by default. This means that when you try to access any link, you will be prompted to log in with a username and password.</p><p>By default, Spring Security creates a user with the following credentials:</p><ul><li><strong>Username:</strong> user</li><li><strong>Password:</strong> The password is generated automatically and can be found in the console output when you run your application.</li></ul><h3>Changing Default Username and Password</h3><p>Instead of using the default user and the generated password, you can specify your own credentials by adding properties in the application.properties or application.yml file</p><h4>Using application.properties</h4><p>In your src/main/resources/application.properties, add the following lines:</p><pre>spring.security.user.name=yourUsername<br>spring.security.user.password=yourPassword</pre><p>To secure specific URLs in your Spring Boot application, you can use the HttpSecurity object in your security configuration class. Below is an example of how to set this up in your SecurityConfig class.</p><pre>package com.scm.scm20.config;<br><br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.web.SecurityFilterChain;<br><br><br>@Configuration<br>public class SecurityConfig {<br> <br>    // Configure security filter chain<br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {<br>        httpSecurity.authorizeHttpRequests(authorized -&gt; {<br>            authorized.requestMatchers(&quot;/user/**&quot;).authenticated(); // Secure /user/** URLs<br>            authorized.anyRequest().permitAll(); // Allow all other requests<br>        });<br>        return httpSecurity.build();<br>    }<br>}</pre><p>In the provided SecurityConfig class, the securityFilterChain method configures the security settings for the application using the HttpSecurity object. The method starts by calling authorizeHttpRequests, which allows you to define rules for URL access. In this setup, the line authorized.requestMatchers(&quot;/user/**&quot;).authenticated(); secures all URLs that begin with /user/, meaning that only authenticated users will be able to access these endpoints. Conversely, the line authorized.anyRequest().permitAll(); allows all other URLs to be accessed without authentication, making them open to the public.</p><p><strong>Problem</strong>-</p><p>When integrating Spring Security into your web application, you may notice that your UI elements, such as CSS and JavaScript files, are not displaying correctly. This issue typically arises because Spring Security secures all resources by default, which means that any requests to CSS or JS files are also subject to authentication.</p><pre>@Bean<br>public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {<br>    httpSecurity.authorizeHttpRequests(authorized -&gt; {<br>        authorized.requestMatchers(&quot;/user/**&quot;).authenticated(); // Secure /user/** URLs<br>        authorized.requestMatchers(&quot;/css/**&quot;, &quot;/js/**&quot;).permitAll(); // Allow access to CSS and JS files<br>        authorized.anyRequest().permitAll(); // Allow all other requests<br>    });<br>    return httpSecurity.build();<br>}</pre><p><strong>authorized.requestMatchers(&quot;/css/**&quot;, &quot;/js/**&quot;).permitAll();</strong>: This line permits all requests to URLs starting with /css/ and /js/, allowing unauthenticated users to access your CSS and JavaScript files. This ensures that your web application&#39;s UI is displayed correctly, as users can now load the necessary styles and scripts without authentication issues.</p><h3>Customizing Security for Specific Roles</h3><p>Spring Security enables role-based access control, allowing you to customize user access levels based on roles such as admins, moderators, or regular users. This enhances security by restricting access to specific functionalities or areas of your application according to user roles.</p><p><strong>Define User Roles</strong>: First, define the roles you want to use in your application. Common examples include:</p><ul><li>ROLE_USER for regular users</li><li>ROLE_ADMIN for administrators</li><li>ROLE_MODERATOR for moderator</li></ul><p><strong>Modify the User Details Service</strong>: Ensure your SecurityCustomUserDetailService (or equivalent user details service) provides the user roles during authentication. Here’s an example of how this might look:</p><pre>@Service<br>public class SecurityCustomUserDetailService implements UserDetailsService {<br><br>    @Autowired<br>    private UserRepository userRepository; // Assume this is your user repository<br><br>    @Override<br>    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<br>        User user = userRepository.findByUsername(username);<br>        if (user == null) {<br>            throw new UsernameNotFoundException(&quot;User not found&quot;);<br>        }<br>        return new org.springframework.security.core.userdetails.User(<br>            user.getUsername(),<br>            user.getPassword(),<br>            getAuthorities(user) // Get roles as authorities<br>        );<br>    }<br><br>    private Collection&lt;? extends GrantedAuthority&gt; getAuthorities(User user) {<br>        return user.getRoles().stream()<br>            .map(role -&gt; new SimpleGrantedAuthority(role.getName()))<br>            .collect(Collectors.toList());<br>    }<br>}</pre><p><strong>Update the Security Configuration</strong>: Modify your SecurityConfig class to restrict access based on user roles. Here’s how to configure it:</p><pre>@Configuration<br>public class SecurityConfig {<br><br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {<br>        httpSecurity.authorizeHttpRequests(authorized -&gt; {<br>            authorized.requestMatchers(&quot;/admin/**&quot;).hasRole(&quot;ADMIN&quot;); // Only admins can access /admin/**<br>            authorized.requestMatchers(&quot;/user/**&quot;).hasAnyRole(&quot;USER&quot;, &quot;ADMIN&quot;); // Users and admins can access /user/**<br>            authorized.anyRequest().permitAll(); // Allow all other requests<br>        });<br>        return httpSecurity.build();<br>    }<br>}</pre><h3><strong>Method-Level Security:</strong></h3><p><strong>Method-Level Security</strong> in Spring Security allows you to secure individual methods in your application based on user roles or authorities. This approach offers fine-grained control over access to specific business logic, enabling you to enforce security rules directly at the method level rather than just at the URL or controller level.</p><pre>import org.springframework.security.access.prepost.PreAuthorize;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class ProductService {<br><br>    // Only admins can add a product<br>    @PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;)&quot;)<br>    public void addProduct(Product product) {<br>        // Logic to add a product<br>    }<br><br>    // Users with USER or ADMIN role can view products<br>    @PreAuthorize(&quot;hasAnyRole(&#39;USER&#39;, &#39;ADMIN&#39;)&quot;)<br>    public List&lt;Product&gt; getProducts() {<br>        // Logic to fetch products<br>        return productRepository.findAll();<br>    }<br>}</pre><p>Let’s consider a simple e-commerce application where you want to restrict access to certain methods based on user roles.</p><h4>User Roles</h4><ul><li><strong>ADMIN</strong>: Can manage products and users.</li><li><strong>USER</strong>: Can view products and place orders.</li></ul><h4>Explanation of Annotations</h4><ul><li><strong>@PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;)&quot;)</strong>: This annotation on the addProduct method ensures that only users with the role ADMIN can access this method. If a user without this role tries to invoke this method, an access denied error will be thrown.</li><li><strong>@PreAuthorize(&quot;hasAnyRole(&#39;USER&#39;, &#39;ADMIN&#39;)&quot;)</strong>: This annotation on the getProducts method allows both USER and ADMIN roles to access the method. Users without either of these roles will not be able to call this method.</li></ul><h3>Example of Role-Based Access Control</h3><p>Here’s an example of another service class, OrderService, demonstrating the use of @Secured for restricting access:</p><pre>import org.springframework.security.access.annotation.Secured;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class OrderService {<br><br>    // Only users with ROLE_USER can place an order<br>    @Secured(&quot;ROLE_USER&quot;)<br>    public void placeOrder(Order order) {<br>        // Logic to place an order<br>    }<br><br>    // Only admins can cancel an order<br>    @Secured(&quot;ROLE_ADMIN&quot;)<br>    public void cancelOrder(Long orderId) {<br>        // Logic to cancel an order<br>    }<br>}</pre><h3>Benefits of Method-Level Security</h3><ol><li><strong>Fine-Grained Control</strong>: Allows for detailed control over who can access specific business logic, improving security.</li><li><strong>Clearer Code</strong>: Keeps security concerns close to the logic they protect, making the codebase easier to understand.</li><li><strong>Flexibility</strong>: Easy to modify security rules by changing annotations without affecting the overall URL security configuration.</li></ol><h3>Conclusion</h3><p>Securing URLs in Spring Boot applications using Spring Security significantly enhances security and flexibility, as demonstrated in our example:</p><p><strong>Role-Based Access Control</strong>: With the @PreAuthorize annotation in the ProductService, we restrict access to specific methods based on user roles, such as allowing only admins to add products. This ensures that sensitive actions are protected and only accessible to authorized users.</p><p><strong>Streamlined Integration</strong>: By configuring the SecurityConfig class, we can easily set up security for specific URL patterns. For instance, we secured the /admin/** endpoints for admins and allowed both users and admins access to /user/**, showcasing straightforward URL protection.</p><p><strong>Customizable Policies</strong>: The flexibility to define security rules allows us to adjust access controls based on evolving application needs, making it easier to manage user permissions effectively.</p><p><strong>Robust Security Features</strong>: Spring Security not only protects URLs but also provides comprehensive security features, safeguarding the application against common threats</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c77d9a12019" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Compare Dart Objects by Value: Custom Equality and Hash Code Techniques]]></title>
            <link>https://medium.com/@harshhub.414/how-to-compare-dart-objects-by-value-custom-equality-and-hash-code-techniques-f6e4ec5f25bd?source=rss-62af0852f2f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6e4ec5f25bd</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[codeoptimisation]]></category>
            <category><![CDATA[efficiency]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <dc:creator><![CDATA[harsh_singh]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 18:33:46 GMT</pubDate>
            <atom:updated>2024-09-04T19:11:58.755Z</atom:updated>
            <content:encoded><![CDATA[<p>When comparing two instances of the same class, you may find yourself manually comparing each individual member to determine if the objects are equivalent. For example, consider the following code, which demonstrates how to compare the properties of two instances of a Car class by checking each field:</p><pre><br>// Creating a basic class<br>class Car {<br>  int modelNumber;<br>  String company;<br>  String color;<br>  String gearType;<br><br>  // Marking all fields as required<br>  Car({<br>    required this.modelNumber,<br>    required this.company,<br>    required this.color,<br>    required this.gearType,<br>  });<br>}<br><br>void main() {<br>  // Creating instances of the Car class<br>  Car car1 = Car(modelNumber: 123, company: &quot;Skoda&quot;, color: &quot;SmokyWhite&quot;, gearType: &quot;AutoGear&quot;);<br>  Car car2 = Car(modelNumber: 123, company: &quot;Skoda&quot;, color: &quot;SmokyWhite&quot;, gearType: &quot;AutoGear&quot;);<br><br>  // Comparing each member of the two instances<br>  if (car1.modelNumber == car2.modelNumber &amp;&amp;<br>      car1.company == car2.company &amp;&amp;<br>      car1.color == car2.color &amp;&amp;<br>      car1.gearType == car2.gearType) {<br>    print(&quot;Two classes are equal&quot;);<br>  } else {<br>    print(&quot;Two classes are not equal&quot;);<br>  }<br>}</pre><p>Manually comparing each member of two class instances is not an optimized approach, especially when the class has many fields. As the number of members grows, the code becomes more verbose, harder to maintain, and prone to errors. This approach is inefficient because it requires writing repetitive comparison logic for each field, making the code less readable and harder to manage.</p><p>But what if you do this:</p><pre>print(car1==car2); // Output: False</pre><p>Each time you create an instance of a class, Dart allocates a new memory address for that object.</p><p>In this example, even though car1 and car2 have identical field values, the comparison car1 == car2 returns false. This is because, by default, Dart compares objects based on their memory addresses. Each instance of Car is allocated a unique memory address, so the comparison checks if these two addresses are the same, which they are not.</p><p>What will happen when we assign one object to another, will they be equal?</p><pre>Car car1=new Car(modelNumber: 123, company: &quot;Skoda&quot;, color: &quot;SmokyWhite&quot;, gearType: &quot;AutoGear&quot;);<br>Car car2=car1;<br>print(car1==car2);// Output:true</pre><p>In Dart, when you assign one object to another, you are not creating a new instance but rather assigning a reference to the same instance. This means that both variables point to the same memory location. As a result, the two variables will be considered equal in terms of reference equality, as they refer to the same object.</p><p>Any comparison of fields between car1 and car2 will also be true since they are the same object. For example, car1.modelNumber == car2.modelNumber will be true</p><p>This approach is problematic because modifying car2 will also affect car1, as both variables point to the same memory address. Consequently, any changes made through one reference are reflected in the other.</p><p>So, what to do next… 🤔</p><pre>class Car {<br>  int modelNumber;<br>  String company;<br>  String color;<br>  String gearType;<br><br>  Car({<br>    required this.modelNumber,<br>    required this.company,<br>    required this.color,<br>    required this.gearType,<br>  });<br><br>  // CopyWith method to create a new Car instance with modified fields<br>  Car copyWith({<br>    int? modelNumber,<br>    String? company,<br>    String? color,<br>    String? gearType,<br>  }) {<br>    return Car(<br>      modelNumber: modelNumber ?? this.modelNumber,<br>      company: company ?? this.company,<br>      color: color ?? this.color,<br>      gearType: gearType ?? this.gearType,<br>    );<br>  }<br>}<br><br>void main() {<br>  // Creating an instance of Car<br>  Car car1 = Car(modelNumber: 123, company: &quot;Skoda&quot;, color: &quot;SmokyWhite&quot;, gearType: &quot;AutoGear&quot;);<br>  <br>  // Creating a new instance by copying car1 and modifying the color<br>  Car car2 = car1.copyWith(color: &quot;Black&quot;);<br><br>  print(&quot;Car1 color: ${car1.color}&quot;); // Output: Car1 color: SmokyWhite<br>  print(&quot;Car2 color: ${car2.color}&quot;); // Output: Car2 color: Black<br>}</pre><p>The copyWith method provides a mechanism to create a new instance of a class with specific fields modified while preserving the values of other fields from the original instance. This approach ensures that the new instance resides at a different memory location than the original object, thereby avoiding unintended side effects due to shared references as discussed above.</p><p>It is generally used when comparing objects, especially in scenarios where you need to ensure that two instances have the same values, using copyWith allows you to create a new instance that mirrors the original object except for the specified change.</p><p>So, the problem is how to compare two classes based on their values.</p><p>Here is the answer…</p><pre>class Car {<br>  int modelNumber;<br>  String company;<br>  String color;<br>  String gearType;<br><br>  Car({<br>    required this.modelNumber,<br>    required this.company,<br>    required this.color,<br>    required this.gearType,<br>  });<br><br>  // CopyWith method to create a new Car instance with modified fields<br>  Car copyWith({<br>    int? modelNumber,<br>    String? company,<br>    String? color,<br>    String? gearType,<br>  }) {<br>    return Car(<br>      modelNumber: modelNumber ?? this.modelNumber,<br>      company: company ?? this.company,<br>      color: color ?? this.color,<br>      gearType: gearType ?? this.gearType,<br>    );<br>  }<br><br>  @override<br>  bool operator ==(Object other) {<br>    if (identical(this, other)) return true;<br>    return other is Car &amp;&amp;<br>        other.modelNumber == modelNumber &amp;&amp;<br>        other.company == company &amp;&amp;<br>        other.color == color &amp;&amp;<br>        other.gearType == gearType;<br>  }<br><br>  @override<br>  int get hashCode {<br>    return modelNumber.hashCode ^<br>        company.hashCode ^<br>        color.hashCode ^<br>        gearType.hashCode;<br>  }<br>}</pre><p>By overriding the <strong><em>==</em> </strong>and “hashcode” method from the base Object class.</p><p>The == operator override in Dart allows you to define custom equality logic for instances of the Car class. It begins by using identical(this, other) to quickly check if both references point to the same memory location. If they do, the method returns true, indicating that both references are to the exact same object. If they are not identical, the method then checks if other is also an instance of the Car class. It proceeds by comparing each relevant field (modelNumber, company, color, and gearType) of the other object with the corresponding fields of the current instance (this). The two instances are considered equal if all these fields match. This implementation ensures that two Car objects are deemed equal only when their field values are identical, providing a robust way to compare complex objects.</p><p>The hashCode getter in Dart is designed to provide a unique integer value for instances of the Car class, which is essential for using objects in hash-based collections like HashSet or HashMap. This implementation combines the hash codes of the Car&#39;s fields—modelNumber, company, color, and gearType—using the bitwise XOR operator (^). By XORing these hash codes together, it creates a composite hash code that reflects the values of these fields. This ensures that two Car instances with identical field values will have the same hash code, aligning with the equality logic defined by the overridden == operator. This approach is crucial for maintaining consistency in collections that rely on hash codes for object identification and storage.</p><p>If you don’t override the hashCode method in your class and only override the == operator to compare values, you can still check if two objects are equal based on their content. However, there are important limitations and potential problems, especially when using hash-based collections like HashSet, HashMap, or HashTable.</p><p>Let me show by an example why hashCode is important:</p><p>Problems will arise if you use hash-based collections like HashSet or HashMap.</p><pre>class Car {<br>  int modelNumber;<br>  String company;<br>  String color;<br>  String gearType;<br><br>  Car({<br>    required this.modelNumber,<br>    required this.company,<br>    required this.color,<br>    required this.gearType,<br>  });<br><br>  // CopyWith method to create a new Car instance with modified fields<br>  Car copyWith({<br>    int? modelNumber,<br>    String? company,<br>    String? color,<br>    String? gearType,<br>  }) {<br>    return Car(<br>      modelNumber: modelNumber ?? this.modelNumber,<br>      company: company ?? this.company,<br>      color: color ?? this.color,<br>      gearType: gearType ?? this.gearType,<br>    );<br>  }<br><br>  @override<br>  bool operator ==(Object other) {<br>    if (identical(this, other)) return true;<br>    return other is Car &amp;&amp;<br>        other.modelNumber == modelNumber &amp;&amp;<br>        other.company == company &amp;&amp;<br>        other.color == color &amp;&amp;<br>        other.gearType == gearType;<br>  }<br><br>} <br>void main(){<br>// Creating instances of the Car class<br>  Car car1 = Car(modelNumber: 123, company: &quot;Skoda&quot;, color: &quot;SmokyWhite&quot;, gearType: &quot;AutoGear&quot;);<br>  Car car2 = Car(modelNumber: 123, company: &quot;Skoda&quot;, color: &quot;SmokyWhite&quot;, gearType: &quot;AutoGear&quot;);<br>  Set&lt;Car&gt; carset = {car1, car2};<br>  print(carset.length); // Output: 2 (without overriding `hashCode`)<br>}</pre><p>Even though car1 and car2 are logically equal (==), they may still be treated as two distinct entries in the HashSet. This happens because HashSet relies on both the == operator and the hashCode to determine if two objects are equal. If two objects are equal but have different hash codes, they will be treated as different entries in the set.</p><p>In the Car class, the hashCode is calculated by combining the hash codes of the modelNumber, company, color, and gearType fields. This is done using the XOR operator (^), which combines the individual hash codes into a single hash code for the Car instance.</p><p>With “hashCode”:</p><pre>class Car {<br>  int modelNumber;<br>  String company;<br>  String color;<br>  String gearType;<br><br>  Car({<br>    required this.modelNumber,<br>    required this.company,<br>    required this.color,<br>    required this.gearType,<br>  });<br><br>  // CopyWith method to create a new Car instance with modified fields<br>  Car copyWith({<br>    int? modelNumber,<br>    String? company,<br>    String? color,<br>    String? gearType,<br>  }) {<br>    return Car(<br>      modelNumber: modelNumber ?? this.modelNumber,<br>      company: company ?? this.company,<br>      color: color ?? this.color,<br>      gearType: gearType ?? this.gearType,<br>    );<br>  }<br><br>  @override<br>  bool operator ==(Object other) {<br>    if (identical(this, other)) return true;<br>    return other is Car &amp;&amp;<br>        other.modelNumber == modelNumber &amp;&amp;<br>        other.company == company &amp;&amp;<br>        other.color == color &amp;&amp;<br>        other.gearType == gearType;<br>  }<br><br>@override<br>  int get hashCode {<br>    return modelNumber.hashCode ^<br>        company.hashCode ^<br>        color.hashCode ^<br>        gearType.hashCode;<br>  }<br><br>} <br>void main(){<br>// Creating instances of the Car class<br>  Car car1 = Car(modelNumber: 123, company: &quot;Skoda&quot;, color: &quot;SmokyWhite&quot;, gearType: &quot;AutoGear&quot;);<br>  Car car2 = Car(modelNumber: 123, company: &quot;Skoda&quot;, color: &quot;SmokyWhite&quot;, gearType: &quot;AutoGear&quot;);<br>  Set&lt;Car&gt; carset = {car1, car2};<br>  print(carset.length); // Output: 1(with overriding `hashCode`)<br>}</pre><p>This is how you can compare two instances of a class based on their values. Alternatively, you can achieve similar functionality more efficiently using the Equatable package, which I will discuss in my next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6e4ec5f25bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>