<?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 Sidharth Ram on Medium]]></title>
        <description><![CDATA[Stories by Sidharth Ram on Medium]]></description>
        <link>https://medium.com/@sidharth.ram2001?source=rss-cf6835731c32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Lr73hdJ2TsgauuGiKoQ9Vg.jpeg</url>
            <title>Stories by Sidharth Ram on Medium</title>
            <link>https://medium.com/@sidharth.ram2001?source=rss-cf6835731c32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 09:15:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sidharth.ram2001/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[Redis for Beginners: What It Is and Why Your App Probably Needs It]]></title>
            <link>https://medium.com/@sidharth.ram2001/redis-for-beginners-what-it-is-and-why-your-app-probably-needs-it-59aef562cc73?source=rss-cf6835731c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/59aef562cc73</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Sidharth Ram]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 03:18:21 GMT</pubDate>
            <atom:updated>2026-11-17T03:18:21.502Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why I started looking at Redis</h3><p>I kept seeing Redis in job descriptions for backend roles. For a while I nodded along like I knew exactly what it did.</p><p>So I sat down and actually set it up. Turns out the core idea is simple, and once it clicks, you start noticing places in your own apps where it would help.</p><p>Here’s the beginner-friendly version I wish I’d read first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7PDJKiaG5aGQ-IqW7ze8w.jpeg" /></figure><h3>So what is Redis?</h3><p>Redis is an in-memory data store. It keeps data in RAM instead of on disk, which is why reads and writes are so fast.</p><p>At its simplest, it’s a giant key-value map. You store something under a key, and you get it back by that key. Think of a HashMap that lives outside your application and that many services can share.</p><p>It’s more than plain strings, though. Redis supports lists, sets, sorted sets, and hashes, and you can give any key an expiry time so it deletes itself.</p><p>A simple way to picture it: your database is the filing cabinet in the back room. Redis is the sticky note on your monitor with the things you look up ten times a day.</p><h3>Where it’s actually used</h3><p>• <strong>Caching.</strong> Store the result of a slow database query or API call, and serve it from memory next time. This is the most common use by far.</p><p>• <strong>Session storage.</strong> Keep logged-in user sessions in Redis so any server behind a load balancer can read them.</p><p>• <strong>Rate limiting.</strong> Count requests per user per minute with a key that expires. Block them once they cross the limit.</p><p>• <strong>Leaderboards.</strong> Sorted sets keep scores ranked automatically, which is handy for games or “top products” lists.</p><p>• <strong>Simple queues and pub/sub.</strong> Lightweight messaging between services, when something like Kafka would be overkill.</p><p>In an e-commerce app, for example, the product catalog barely changes but gets read constantly. That’s a perfect candidate for caching.</p><h3>Setting it up in five minutes</h3><p>The quickest way is Docker. No installers, nothing to clean up afterwards.</p><p><strong>1. Start Redis</strong></p><p>docker run -d — name redis -p 6379:6379 redis:7</p><p><strong>2. Open the Redis CLI</strong></p><p>docker exec -it redis redis-cli</p><p><strong>3. Try a few commands</strong></p><p>PING<br> # PONG<br> <br> SET user:1:name “john”<br> GET user:1:name<br> # “john”<br> <br> SET otp:1234 “839201” EX 60<br> TTL otp:1234<br> # 57 (seconds left before it deletes itself)<br> <br> INCR page:views<br> INCR page:views<br> # 2</p><p>That EX 60 part is the bit that made Redis click for me. An OTP that disappears after a minute, with zero cleanup code.</p><p>From here, most frameworks have a client ready to go. In Spring Boot it’s one starter dependency, which I’ll cover properly next week.</p><h3>Why it’s worth it (and when it isn’t)</h3><p><strong>The benefits:</strong></p><p>• <strong>Speed.</strong> Reading from memory is far faster than a database round trip with query planning and joins.</p><p>• <strong>Less load on your database.</strong> Repeat reads hit Redis, so your database can focus on writes and the queries that really need it.</p><p>• <strong>Built-in expiry.</strong> TTLs handle cleanup for OTPs, sessions, and cached data automatically.</p><p>• <strong>Shared across services.</strong> Multiple app instances read the same cache, unlike an in-process HashMap.</p><p>• <strong>Easy to start.</strong> One Docker command and you’re running.</p><p><strong>When to think twice:</strong></p><p>• Data that changes every second, or must always be 100% current, like stock levels during checkout.</p><p>• As your only source of truth. Redis can persist to disk, but treat it as a fast layer in front of your real database.</p><ul><li>Tiny apps with low traffic. Sometimes the database is fast enough, and Redis is one more thing to run.</li></ul><p>If you’ve used Redis in production, what was the first thing you cached?<br>write to me …</p><p>#Redis #Java #SpringBoot #BackendDevelopment #LearningInPublic</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59aef562cc73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Use Claude to Reverse Engineer and Document a Codebase Without Burning Through Tokens]]></title>
            <link>https://medium.com/@sidharth.ram2001/how-i-use-claude-to-reverse-engineer-and-document-a-codebase-without-burning-through-tokens-6cb984b60d8e?source=rss-cf6835731c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cb984b60d8e</guid>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[ai-token-reduction]]></category>
            <dc:creator><![CDATA[Sidharth Ram]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 03:21:02 GMT</pubDate>
            <atom:updated>2026-11-10T03:21:31.153Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>By Sidharth Ram</em></h4><p>The fastest way I’ve found to understand an unfamiliar codebase with Claude is a three-step loop: map the system, test my understanding, then turn what I’ve learned into documentation.</p><p>Done carelessly, this process can burn through tokens. Here’s how I keep it focused.</p><p>As a Java full stack developer, I’ve worked on several production projects, mostly Spring Boot backends with frontends on top. Whenever I picked up a new module, I ran into the same problem: the code worked, but the reasons behind its design lived in a few people’s heads.</p><p>Reading hundreds of files line by line is slow. Constantly asking teammates for context takes their time. So I started using Claude Code as a research partner and built a workflow around a few Claude skills.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*sUCsoRT-jgB3FZqKjtA4GQ.jpeg" /></figure><h3>1. Map the codebase before diving into the files</h3><p>I start with a reverse engineering skill that tells Claude how to explore a codebase systematically. Rather than asking it to “explain the project,” I ask it to build a map of:</p><ul><li><strong>Modules:</strong> the main packages, what they own, and how they depend on each other</li><li><strong>Entry points:</strong> REST controllers, scheduled jobs, message listeners, and startup configuration</li><li><strong>Data flow:</strong> how a request moves through the system, from controller to service to repository and back</li><li><strong>Integrations:</strong> external APIs, queues, caches, and databases</li><li><strong>Open questions:</strong> anything unusual, duplicated, or unclear</li></ul><p>I treat Claude’s map as a hypothesis, not as fact. I open the files it points to and trace one or two real requests end to end. If the map is wrong, I correct it before moving on. The next steps depend on getting this one right.</p><h3>2. Let Claude interview you</h3><p>This is the step that changed how I work. Instead of asking Claude questions, I ask it to interview me.</p><p>After the initial exploration, I might say: <em>“Grill me on how the order service handles a failed payment.”</em> Claude asks one question at a time, probing for gaps in my understanding:</p><ul><li>What happens if the downstream call times out halfway through?</li><li>Is the operation idempotent, or could a retry create a duplicate record?</li><li>Where’s the transaction boundary, and what gets rolled back?</li><li>Why is this cached here, and when does the cache get invalidated?</li></ul><p>When I can’t answer, I’ve found something worth investigating. Maybe I haven’t understood the code yet. Or maybe the code doesn’t have a clear answer. The first sends me back to the source; the second may become a documentation note or a question for the team.</p><p>It can feel uncomfortable at first, in a useful way. It’s also good interview practice: design trade-offs, failure modes, and edge cases are exactly the kinds of things technical interviews explore.</p><h3>3. Turn the map and answers into documentation</h3><p>At this point, I have a verified map and answers to the questions that matter. That’s a strong foundation for documentation.</p><p>I ask Claude to draft from those notes rather than from the raw code. This keeps the output focused and makes it easier to check. Depending on the module, I might produce:</p><ol><li><strong>An architecture overview</strong> of the main components, how they connect, and why they’re structured that way</li><li><strong>Module READMEs</strong> covering purpose, key classes, configuration, and common pitfalls</li><li><strong>Request flow walkthroughs</strong> tracing one or two critical paths step by step</li><li><strong>An onboarding guide</strong> explaining how to run the project locally and where to start reading</li><li><strong>A list of known gaps</strong> for questions the code couldn’t answer</li></ol><p>I review every line before sharing the docs. AI-written documentation can sound confident and still be subtly wrong. My rule is simple: if I can’t point to the code that supports a sentence, I fix or remove it.</p><h3>How I keep token usage under control</h3><p>The biggest source of wasted tokens is letting Claude read and retain more context than the task needs. Exploring a large codebase makes that easy to do. These habits help me stay focused:</p><ul><li><strong>Keep </strong><strong>CLAUDE.md short.</strong> I use it for project rules, build commands, and conventions. Longer background belongs in separate docs that Claude can read when needed.</li><li><strong>Point to specific files.</strong> Referencing OrderService.java is more focused than asking Claude to search the whole repository for “the order logic.”</li><li><strong>Clear context between unrelated tasks.</strong> I use /clear when switching tasks. For long sessions, /compact summarizes the conversation and frees up context.</li><li><strong>Delegate broad exploration to subagents.</strong> They work in their own context and return a summary, keeping the main conversation focused.</li><li><strong>Use skills for repeatable workflows.</strong> A skill’s short description stays in context until it’s needed, so skills can be a more efficient way to reuse a process than pasting a long prompt each time.</li><li><strong>Plan before coding.</strong> A plan can expose a wrong direction before it turns into several rounds of edits.</li><li><strong>Match the model to the task.</strong> A simple lookup or boilerplate task may not need the largest model.</li></ul><h3>Skills that make the workflow repeatable</h3><p>Two other skills round out the process.</p><p><strong>Skill Creator</strong> helps turn a workflow that works into a reusable skill. For example, a “document a Spring Boot module” skill could use the same README structure every time. That makes documentation more consistent and saves me from repeating the format in each prompt.</p><p>A <strong>document skill</strong> can turn notes into a polished Word or PDF document when the documentation needs to be shared outside the repository.</p><p>The general rule: if you find yourself typing the same long prompt twice, consider turning it into a skill.</p><h3>What I’ve learned</h3><p>AI doesn’t replace understanding a codebase. It can help you reach that understanding faster and ask better questions along the way.</p><p>A few lessons I’d share:</p><ul><li>Treat Claude’s first answer as a draft to verify, not a fact to trust.</li><li>Being questioned can teach you more than asking questions. The interview step is where gaps in your understanding become visible.</li><li>Context is a budget. Spend it on the files that matter, and clear it when the task changes.</li><li>Turn repeated workflows into skills so the process becomes more consistent over time.</li></ul><p>If you’re onboarding to a large codebase or preparing for technical interviews, try the reverse engineer → grill me → document loop on one module this week.</p><p>I’d love to hear what you learn and what you’d add to the process.</p><p><em>I’m a Java full stack developer working with Spring Boot, microservices, and React, and I’m currently exploring new opportunities. Feel free to connect with me on LinkedIn.</em></p><p><a href="https://www.linkedin.com/in/sidharth-ram-work/">https://www.linkedin.com/in/sidharth-ram-work/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cb984b60d8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to GraphQl with SpringBoot]]></title>
            <link>https://medium.com/@sidharth.ram2001/introduction-to-graphql-with-springboot-adf76ce2de09?source=rss-cf6835731c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/adf76ce2de09</guid>
            <category><![CDATA[network]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Sidharth Ram]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 11:37:19 GMT</pubDate>
            <atom:updated>2026-02-10T11:37:19.974Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is GraphQL?</strong></p><p>GraphQL is a modern API query language and runtime that allows clients to request exactly the data they need — no more, no less. Instead of multiple endpoints returning fixed responses, GraphQL exposes a single endpoint where clients can define the structure of the response they want.</p><h3>GraphQl Vs REST</h3><h3>1. Data Fetching</h3><ul><li><strong>GraphQL:</strong> Client requests exactly the fields it needs.</li><li><strong>REST:</strong> Server returns a fixed response structure.</li></ul><h3>2. Over-fetching &amp; Under-fetching</h3><ul><li><strong>GraphQL:</strong> Avoids both over-fetching and under-fetching.</li><li><strong>REST:</strong> Often returns unnecessary data or requires multiple API calls.</li></ul><h3>3. Endpoints</h3><ul><li><strong>GraphQL:</strong> Uses a <strong>single endpoint</strong> for all operations.</li><li><strong>REST:</strong> Uses <strong>multiple endpoints</strong> for different resources.</li></ul><h3>4. API Versioning</h3><ul><li><strong>GraphQL:</strong> No versioning needed; fields can be added or deprecated.</li><li><strong>REST:</strong> Requires versioning (v1, v2, etc.) when responses change.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHGFJcUNWxUg1bnrR15JbA.png" /></figure><h3>5. Strong Typing &amp; Schema</h3><ul><li><strong>GraphQL:</strong> Has a strongly typed schema that defines data and operations.</li><li><strong>REST:</strong> No strict type system; depends on documentation.</li></ul><h3>6. Tooling &amp; API Exploration</h3><ul><li><strong>GraphQL:</strong> Built-in introspection enables tools like GraphiQL for auto-documentation.</li><li><strong>REST:</strong> Uses external tools like Swagger/OpenAPI.</li></ul><h3>7. Network Efficiency</h3><ul><li><strong>GraphQL:</strong> Fewer network requests and smaller payloads.</li><li><strong>REST:</strong> May require multiple calls to fetch related data.</li></ul><h3>8. Learning Curve</h3><ul><li><strong>GraphQL:</strong> Slightly steeper learning curve.</li><li><strong>REST:</strong> Easier to learn and widely adopted.</li></ul><h3>9. Caching</h3><ul><li><strong>GraphQL:</strong> More complex caching at HTTP level.</li><li><strong>REST:</strong> Simple and effective caching using HTTP methods.</li></ul><h3>10. Use Cases</h3><ul><li><strong>GraphQL:</strong> Best for complex, data-driven frontend applications.</li><li><strong>REST:</strong> Best for simple, resource-based APIs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_H08E5K4G7Z5hPMEZxCWrA.png" /></figure><blockquote><strong>Setting Up GraphQL with Spring Boot</strong></blockquote><p><strong>1. Dependencies</strong></p><p>First, add the GraphQL dependencies to your `build.gradle`:</p><pre>dependencies {<br>implementation &#39;org.springframework.boot:spring-boot-starter-graphql&#39;<br>implementation &#39;org.springframework.boot:spring-boot-starter-webmvc&#39;<br>testImplementation &#39;org.springframework.boot:spring-boot-starter-graphql-test&#39;<br>}</pre><p>The spring-boot-starter-graphql provides everything needed to build GraphQL APIs with Spring Boot.</p><p>src/<br>├── main/<br>│ ├── java/com/example/graphqlserver/<br>│ │ ├── GraphqlServerApplication.java<br>│ │ ├── BookController.java<br>│ │ ├── Book.java<br>│ │ ├── Author.java<br>│ │ └── Review.java<br>│ └── resources/<br>│ ├── application.properties<br>│ └── graphql/<br>│ └── schema.graphqls</p><h3>Defining Your GraphQL Schema</h3><p>The schema is the heart of your GraphQL API. It defines what data can be queried and how it’s structured.</p><pre>type Query {<br> bookById(id: ID): Book<br> books:[Book]<br>}<br>type Book {<br> id: ID!<br> name: String<br> pageCount: Int<br> author: Author<br> review: Review<br>}<br>type Author {<br> id: ID!<br> firstName: String<br> lastName: String<br> age: String<br>}<br>type Review {<br> id: ID!<br> book: Book<br> comment: String<br>}</pre><p><strong>Key Concepts:</strong></p><ul><li>! means the field is non-nullable</li><li>Query type defines all available queries</li><li>Types can reference other types (relationships)</li></ul><h3>Creating Data Models with Java Records</h3><p>Java 17+ records provide a concise way to create immutable data models:</p><pre>package com.example.graphqlserver;<br><br>import java.util.Arrays;<br>import java.util.List;<br><br>public record Book(String id, String name, int pageCount, <br>                   String authorId, String reviewId) {<br><br>    private static List&lt;Book&gt; books = Arrays.asList(<br>        new Book(&quot;book-1&quot;, &quot;Effective Java&quot;, 416, &quot;author-1&quot;, &quot;review-1&quot;),<br>        new Book(&quot;book-2&quot;, &quot;Hitchhiker&#39;s Guide to the Galaxy&quot;, 208, &quot;author-2&quot;, &quot;review-2&quot;),<br>        new Book(&quot;book-3&quot;, &quot;Down Under&quot;, 436, &quot;author-3&quot;, &quot;review-3&quot;)<br>    );<br><br>    public static Book getById(String id) {<br>        return books.stream()<br>            .filter(book -&gt; book.id().equals(id))<br>            .findFirst()<br>            .orElse(null);<br>    }<br><br>    public static List&lt;Book&gt; getAllBooks() {<br>        return books;<br>    }<br>}</pre><pre>package com.example.graphqlserver;<br><br>import java.util.Arrays;<br>import java.util.List;<br><br>public record Author(String id, String firstName, <br>                     String lastName, String age) {<br><br>    private static List&lt;Author&gt; authors = Arrays.asList(<br>        new Author(&quot;author-1&quot;, &quot;Joshua&quot;, &quot;Bloch&quot;, &quot;50&quot;),<br>        new Author(&quot;author-2&quot;, &quot;Douglas&quot;, &quot;Adams&quot;, &quot;49&quot;),<br>        new Author(&quot;author-3&quot;, &quot;Bill&quot;, &quot;Bryson&quot;, &quot;68&quot;)<br>    );<br><br>    public static Author getById(String id) {<br>        return authors.stream()<br>            .filter(author -&gt; author.id().equals(id))<br>            .findFirst()<br>            .orElse(null);<br>    }<br>}</pre><pre>package com.example.graphqlserver;<br><br>import java.util.Arrays;<br>import java.util.List;<br><br>public record Review(String id, String bookId, String comment) {<br><br>    private static List&lt;Review&gt; reviews = Arrays.asList(<br>        new Review(&quot;review-1&quot;, &quot;book-1&quot;, &quot;An excellent book on Java best practices.&quot;),<br>        new Review(&quot;review-2&quot;, &quot;book-2&quot;, &quot;A hilarious and imaginative sci-fi adventure.&quot;),<br>        new Review(&quot;review-3&quot;, &quot;book-3&quot;, &quot;A fascinating travelogue with witty commentary.&quot;)<br>    );<br><br>    public static Review getById(String id) {<br>        return reviews.stream()<br>            .filter(review -&gt; review.id().equals(id))<br>            .findFirst()<br>            .orElse(null);<br>    }<br><br>    public static Review getByBookId(String bookId) {<br>        return reviews.stream()<br>            .filter(review -&gt; review.bookId().equals(bookId))<br>            .findFirst()<br>            .orElse(null);<br>    }<br>}</pre><h3>Implementing Resolvers</h3><p>Resolvers are the functions that fetch the data for each field in your schema. Spring for GraphQL provides two main annotations:</p><h3>@QueryMapping — Root Query Resolvers</h3><p>Use @QueryMapping for top-level queries defined in your Query type:</p><pre>@QueryMapping<br>public Book bookById(@Argument String id) {<br> return Book.getById(id);<br>}<br>@QueryMapping<br>public List&lt;Book&gt; books() {<br> return Book.getAllBooks();<br>}</pre><h3>@SchemaMapping — Field Resolvers</h3><p>Use @SchemaMapping to resolve nested fields and relationships:</p><pre>@SchemaMapping<br>public Author author(Book book) {<br>    return Author.getById(book.authorId());<br>}<br><br>@SchemaMapping<br>public Review review(Book book) {<br>    return Review.getByBookId(book.id());<br>}<br><br>@SchemaMapping<br>public Book book(Review review) {<br>    return Book.getById(review.bookId());<br>}</pre><h3>2. Project Structure</h3><h3>Defining Your GraphQL Schema</h3><p>The schema is the heart of your GraphQL API. It defines what data can be queried and how it’s structured.</p><p>Create schema.graphqls:</p><p><strong>Key Concepts:</strong></p><ul><li>! means the field is non-nullable</li><li>Query type defines all available queries</li><li>Types can reference other types (relationships)</li></ul><h3>Implementing Resolvers</h3><p>Resolvers are the functions that fetch the data for each field in your schema. Spring for GraphQL provides two main annotations:</p><p>@QueryMapping — Root Query Resolvers</p><p>Use @QueryMapping for top-level queries defined in your Query type:</p><p>@SchemaMapping — Field Resolvers</p><p>Use @SchemaMapping to resolve nested fields and relationships:</p><p><strong>How it works:</strong></p><ul><li>Spring automatically maps the method name to the field name in the schema</li><li>The parent object (e.g., Book, Review) is passed as a parameter</li><li>Return the resolved value for that field</li></ul><pre>package com.example.graphqlserver;<br><br>import org.springframework.graphql.data.method.annotation.Argument;<br>import org.springframework.graphql.data.method.annotation.QueryMapping;<br>import org.springframework.graphql.data.method.annotation.SchemaMapping;<br>import org.springframework.stereotype.Controller;<br>import java.util.List;<br><br>@Controller<br>public class BookController {<br>    <br>    // Root query: Get book by ID<br>    @QueryMapping<br>    public Book bookById(@Argument String id) {<br>        return Book.getById(id);<br>    }<br><br>    // Root query: Get all books<br>    @QueryMapping<br>    public List&lt;Book&gt; books() {<br>        return Book.getAllBooks();<br>    }<br><br>    // Field resolver: Get author for a book<br>    @SchemaMapping<br>    public Author author(Book book) {<br>        return Author.getById(book.authorId());<br>    }<br><br>    // Field resolver: Get review for a book<br>    @SchemaMapping<br>    public Review review(Book book) {<br>        return Review.getByBookId(book.id());<br>    }<br><br>    // Field resolver: Get book for a review<br>    @SchemaMapping<br>    public Book book(Review review) {<br>        return Book.getById(review.bookId());<br>    }<br>}</pre><h3>Conclusion</h3><p>GraphQL with Spring Boot provides a powerful, flexible way to build APIs. Key takeaways:</p><ul><li><strong>Single Endpoint</strong>: All queries go through /graphql</li><li><strong>Client-Driven</strong>: Clients request exactly what they need</li><li><strong>Strongly Typed</strong>: Schema provides clear API contract</li><li><strong>Easy to Implement</strong>: Spring Boot’s annotations make resolvers simple</li><li><strong>Developer-Friendly</strong>: GraphiQL provides interactive API exploration</li></ul><p>The combination of GraphQL’s flexibility and Spring Boot’s simplicity makes it an excellent choice for modern API development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adf76ce2de09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Command Handler and Event Driven Architecture]]></title>
            <link>https://medium.com/@sidharth.ram2001/command-handler-and-event-driven-architecture-437befc8c3f6?source=rss-cf6835731c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/437befc8c3f6</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[command-handler]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <dc:creator><![CDATA[Sidharth Ram]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 09:56:26 GMT</pubDate>
            <atom:updated>2025-12-16T09:56:26.682Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern distributed systems need to be <strong>scalable</strong>, <strong>loosely coupled</strong>, and <strong>resilient</strong>. Two architectural patterns help achieve this:</p><ul><li><strong>Command Handlers</strong></li><li><strong>Event-Driven Architecture (EDA)</strong></li></ul><p>These ideas frequently work together, especially in systems using <strong>CQRS</strong> or <strong>microservices</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*5VvG29FDkUU3E8TaJqDVFw.jpeg" /></figure><h3>1. Introduction</h3><p>A <strong>Command Handler</strong> is a component responsible for <strong>processing a specific command</strong> — a request to change the system state.</p><p>Example commands:</p><ul><li>CreateOrderCommand</li><li>TransferMoneyCommand</li><li>UpdateProfileCommand</li></ul><p>An <strong>Event-Driven Architecture</strong> is a system where components communicate using <strong>events</strong> — facts about something that already happened.</p><p>Examples of events:</p><ul><li>OrderCreatedEvent</li><li>PaymentFailedEvent</li></ul><p>In short:</p><p>ConceptMeaning<strong>Command</strong>Intent to perform an action (request to change state)<strong>Event</strong>Something that already happened (historical fact)<strong>Command Handler</strong>Executes business logic for a command<strong>EDA</strong>Architecture where components react to events</p><p>Both patterns help build decoupled, scalable, maintainable systems.</p><h3>2. Use Case — Money Transfer System</h3><p>Let’s take a simple example: <strong>transferring money between two accounts</strong>.</p><h3>Flow:</h3><ol><li>User initiates a <strong>TransferMoneyCommand</strong>.</li><li>Command Handler validates balance and business rules.</li><li>If valid → Deduct amount → Publish <strong>MoneyDebitedEvent</strong>.</li><li>Another service listens and credits the receiver’s account.</li><li>Finally publishes <strong>MoneyCreditedEvent</strong>.</li></ol><p>This makes the system <strong>modular</strong> and allows <strong>independent scaling</strong> of debit/credit operations.</p><h3>3. Simple Java/Spring Boot Example</h3><h3>3.1 Define a Command</h3><pre>public class TransferMoneyCommand {<br>    private final String fromAccount;<br>    private final String toAccount;<br>    private final double amount;</pre><pre>    public TransferMoneyCommand(String fromAccount, String toAccount, double amount) {<br>        this.fromAccount = fromAccount;<br>        this.toAccount = toAccount;<br>        this.amount = amount;<br>    }</pre><pre>    // getters<br>}</pre><h3>3.2 Command Handler</h3><pre>@Service<br>public class TransferMoneyCommandHandler {</pre><pre>    @Autowired<br>    private AccountService accountService;</pre><pre>    @Autowired<br>    private ApplicationEventPublisher publisher;</pre><pre>    public void handle(TransferMoneyCommand command) {</pre><pre>        boolean debited = accountService.debit(<br>                command.getFromAccount(),<br>                command.getAmount()<br>        );</pre><pre>        if (!debited) {<br>            throw new RuntimeException(&quot;Insufficient balance&quot;);<br>        }</pre><pre>        publisher.publishEvent(new MoneyDebitedEvent(this, command));<br>    }<br>}</pre><h3>3.3 Define an Event</h3><pre>public class MoneyDebitedEvent extends ApplicationEvent {<br>    private final TransferMoneyCommand command;</pre><pre>    public MoneyDebitedEvent(Object source, TransferMoneyCommand command) {<br>        super(source);<br>        this.command = command;<br>    }</pre><pre>    public TransferMoneyCommand getCommand() {<br>        return command;<br>    }<br>}</pre><h3>3.4 Event Listener</h3><pre>@Component<br>public class MoneyDebitedEventListener {</pre><pre>    @Autowired<br>    private AccountService accountService;</pre><pre>    @Autowired<br>    private ApplicationEventPublisher publisher;</pre><pre>    @EventListener<br>    public void onMoneyDebited(MoneyDebitedEvent event) {<br>        accountService.credit(<br>                event.getCommand().getToAccount(),<br>                event.getCommand().getAmount()<br>        );</pre><pre>        publisher.publishEvent(new MoneyCreditedEvent(this, event.getCommand()));<br>    }<br>}</pre><h3>3.5 Final Event</h3><pre>public class MoneyCreditedEvent extends ApplicationEvent {<br>    public MoneyCreditedEvent(Object source, TransferMoneyCommand command) {<br>        super(source);<br>    }<br>}</pre><p>This demonstrates a <strong>clean, decoupled flow</strong> using commands and events.</p><h3>4. When to Use Command Handlers + Event Driven Architecture</h3><h3>✅ Good Use Cases</h3><ul><li>Banking (money transfers, ledger updates)</li><li>E-commerce (orders → payments → invoice → shipping)</li><li>Notification systems</li><li>Inventory and supply chain workflows</li><li>Microservice communication</li><li>CQRS systems needing clear separation of <strong>write (commands)</strong> and <strong>read models</strong></li></ul><h3>Benefits:</h3><ul><li>Loose coupling</li><li>High scalability</li><li>Clear separation of responsibilities</li><li>Easy to extend without modifying existing code</li><li>Great fit for distributed systems</li></ul><h3>5. When NOT to Use It</h3><p>Event-driven systems add <strong>complexity</strong>, so avoid them when the system is simple.</p><h3>❌ Do NOT use EDA + Command Handlers when:</h3><ul><li>You’re building a <strong>simple CRUD application</strong>.</li><li>You have <strong>tight deadlines</strong> and don’t need scalability yet.</li><li>Business workflows are <strong>small and synchronous</strong>.</li><li>You don’t need asynchronous communication.</li><li>Debugging complexity outweighs benefits.</li></ul><h3>Signs it’s overkill:</h3><ul><li>Only one service handles all operations</li><li>No real need for decoupling</li><li>You don’t need event replay/history</li></ul><h3>6. Conclusion</h3><p>Command Handlers provide a clean way to structure <strong>write operations</strong>, and Event-Driven Architecture enables <strong>scalable, decoupled</strong> workflows.</p><p>When combined, they provide:</p><ul><li>Clear business logic separation</li><li>Powerful asynchronous flows</li><li>High scalability and fault tolerance</li></ul><p>But they should be used <strong>only where necessary</strong> — complex systems, distributed workflows, and event-driven domains like banking or e-commerce.</p><p>If you’re building modern microservices with Spring Boot, these patterns will significantly improve your architecture clarity and long-term maintainability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=437befc8c3f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Middleware vs Message Brokers: Clearing the Confusion]]></title>
            <link>https://medium.com/@sidharth.ram2001/middleware-vs-message-brokers-clearing-the-confusion-6ab15fd8d78b?source=rss-cf6835731c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ab15fd8d78b</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[communication]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[message-broker]]></category>
            <dc:creator><![CDATA[Sidharth Ram]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 03:10:49 GMT</pubDate>
            <atom:updated>2025-09-30T03:10:49.240Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve been working with distributed systems, microservices, or enterprise software development, you’ve probably come across the terms <strong>middleware</strong> and <strong>message broker</strong>. Many developers (including myself, when I started) often get confused between the two. They sound similar, sometimes even overlap in functionality, but they’re not the same thing. Let’s break it down in simple terms.</p><h3>What is Middleware?</h3><p>Think of <strong>middleware</strong> as the “glue” that connects different applications, services, or systems.<br> It sits <strong>between the application layer and the operating system/network layer</strong>, handling tasks that applications don’t want to reinvent every time.</p><h3>Key Responsibilities of Middleware:</h3><ul><li><strong>Communication management</strong>: Ensures applications can talk to each other regardless of protocol differences.</li><li><strong>Data transformation</strong>: Converts data formats (e.g., XML → JSON).</li><li><strong>Authentication &amp; authorization</strong>: Provides security services like identity management.</li><li><strong>Transaction management</strong>: Coordinates distributed transactions.</li><li><strong>Abstraction</strong>: Hides complexity so developers can focus on business logic.</li></ul><p>👉 Examples:</p><ul><li><strong>Web servers</strong> (Apache, Nginx)</li><li><strong>Application servers</strong> (Tomcat, WebLogic, JBoss)</li><li><strong>Integration middleware</strong> (Enterprise Service Bus — ESB)</li></ul><p>In short, middleware is a <strong>broad category</strong> of software that makes sure systems can communicate and work together.</p><h3>What is a Message Broker?</h3><p>A <strong>message broker</strong> is a <strong>specialized type of middleware</strong> that focuses on one job: <strong>managing communication between applications via messaging.</strong></p><p>Instead of services directly calling each other, they send messages to the broker, and the broker routes, stores, and delivers them.</p><h3>Key Responsibilities of a Message Broker:</h3><ul><li><strong>Message routing</strong>: Directs messages to the right consumer (e.g., topic-based or queue-based routing).</li><li><strong>Decoupling</strong>: Producers and consumers don’t need to know about each other.</li><li><strong>Reliability</strong>: Guarantees delivery (at-least-once, exactly-once).</li><li><strong>Scalability</strong>: Buffers high loads, ensuring systems don’t crash under spikes.</li><li><strong>Protocol translation</strong>: Bridges different communication protocols.</li></ul><p>👉 Examples:</p><ul><li><strong>RabbitMQ</strong></li><li><strong>Apache Kafka</strong></li><li><strong>ActiveMQ</strong></li><li><strong>Amazon SQS</strong></li></ul><p>In short, a message broker is <strong>middleware focused purely on asynchronous communication and message handling</strong>.</p><h3>Middleware vs Message Broker: The Analogy</h3><p>Imagine you’re at an international conference:</p><ul><li><strong>Middleware</strong> is like the event organizer. They set up the venue, provide translation booths, coordinate schedules, and make sure everything works smoothly.</li><li><strong>Message Broker</strong> is like the translator sitting in the booth, ensuring that when someone speaks in Spanish, it reaches the English listener in a language they understand.</li></ul><p>Both are essential, but one handles the <strong>big picture of integration</strong>, while the other specializes in <strong>messaging</strong>.</p><h3>When to Use What?</h3><ul><li>Use <strong>Middleware</strong> when you need:</li><li>End-to-end integration between different systems.</li><li>Security, logging, monitoring, and orchestration.</li><li>Support for multiple communication styles (HTTP, SOAP, REST, RPC, Messaging).</li><li>Use <strong>Message Brokers</strong> when you need:</li><li>Asynchronous communication between services.</li><li>Decoupling producers and consumers.</li><li>Handling high throughput data pipelines (e.g., Kafka for logs, events).</li><li>Reliable delivery even if services go down temporarily.</li></ul><h3>Final Thoughts</h3><p>The confusion arises because <strong>message brokers themselves are a type of middleware</strong> — but not all middleware is a message broker.</p><ul><li><strong>Middleware</strong> = the bigger umbrella (general-purpose glue).</li><li><strong>Message Broker</strong> = a specialized tool under that umbrella (messaging-focused glue).</li></ul><p>So next time you’re designing a system, ask yourself: <em>Do I just need a way to pass messages reliably, or do I need broader integration capabilities?</em><br> That will guide whether you’re looking at <strong>middleware in general</strong> or a <strong>message broker specifically</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ab15fd8d78b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fix Spring Boot Performance Bottlenecks Step-by-Step Using Java Flight Recorder (JFR Guide)]]></title>
            <link>https://medium.com/@sidharth.ram2001/fix-spring-boot-performance-bottlenecks-step-by-step-using-java-flight-recorder-jfr-guide-bbac7e8f2a5d?source=rss-cf6835731c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbac7e8f2a5d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[flight-recorder]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Sidharth Ram]]></dc:creator>
            <pubDate>Sat, 31 May 2025 10:41:21 GMT</pubDate>
            <atom:updated>2025-05-31T10:41:21.601Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Java Flight Recorder (JFR)</strong> is a powerful, low-overhead profiling and diagnostics tool built into the JVM. It enables developers to <strong>analyze performance bottlenecks</strong>, <strong>trace memory and CPU usage</strong>, and <strong>optimize Spring Boot applications effectively</strong> — all without significant impact on runtime performance.</blockquote><blockquote>In this step-by-step guide, you’ll learn how to <strong>enable JFR</strong>, <strong>capture recordings</strong>, and <strong>analyze them to fine-tune your Spring Boot application’s performance</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*1D-OjjaeTBWNJtbg-XUjZA.png" /></figure><h3>Setting Up JFR in Spring Boot</h3><h4>1. Enable JFR</h4><p>To enable JFR in your Spring Boot application, add these JVM arguments:</p><pre>java -XX:+FlightRecorder -jar your-spring-boot-app.jar</pre><h4>2. Start Recording</h4><pre>jcmd &lt;pid&gt; JFR.start name=MyRecording settings=profile</pre><h4><strong>Java Mission Control (JMC):</strong></h4><p><strong>Java Mission Control (JMC)</strong> is a powerful analysis tool for working with Java Flight Recorder (JFR) recordings. It enables developers to connect to live JVM instances, start and stop recordings on demand, and visually explore the captured performance data. With its intuitive interface, JMC makes it easy to identify bottlenecks, memory leaks, and thread issues, helping optimize Java applications efficiently.</p><h3>Common Performance Bottlenecks and Solutions</h3><h4>1. Database Connection Issues</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*bFzy39k63yDhYpU7NNG9fw.png" /></figure><h4>2. Memory Leaks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*BfxIZVgRQXX_XiRdNK3D0w.png" /></figure><h4>3. Thread Contention</h4><pre>sequenceDiagram<br>    participant T1 as Thread 1<br>    participant R as Resource<br>    participant T2 as Thread 2<br>    <br>    T1-&gt;&gt;R: Lock Resource<br>    T2-&gt;&gt;R: Wait for Resource<br>    Note over T2: Thread Contention<br>    R--&gt;&gt;T1: Resource Released<br>    R-&gt;&gt;T2: Resource Available</pre><h3>Using JFR to Identify Issues</h3><h4>Step 1: Configure Event Recording</h4><pre>// Recording configuration<br>jfr.configure(&quot;myconfig&quot;)<br>   .with(&quot;jdk.ThreadStart#enabled&quot;, &quot;true&quot;)<br>   .with(&quot;jdk.ThreadAllocationStatistics#enabled&quot;, &quot;true&quot;)<br>   .with(&quot;jdk.ClassLoadingStatistics#period&quot;, &quot;1 s&quot;);</pre><h3>Common JFR Events to Monitor</h3><ol><li><strong>jdk.ThreadStart</strong></li></ol><ul><li>Thread lifecycle</li><li>Thread creation patterns</li></ul><p><strong>2. jdk.CPULoad</strong></p><ul><li>System and process CPU usage</li><li>CPU saturation points</li></ul><p><strong>3. jdk.GCPhasePause</strong></p><ul><li>Garbage collection pauses</li><li>Memory management impact</li></ul><h3>Advanced JFR Techniques</h3><h4>Custom Event Recording</h4><pre>@EventFactory<br>class CustomEvents {<br>    @Label(&quot;Database Query&quot;)<br>    @Description(&quot;Database query execution time&quot;)<br>    static class DBQueryEvent extends Event {<br>        @Label(&quot;Query&quot;)<br>        String query;<br>        <br>        @Label(&quot;Duration&quot;)<br>        long duration;<br>    }<br>}</pre><p>Conclusion</p><p>Java Flight Recorder is an invaluable tool for Spring Boot performance optimization. By following these practices and regularly analyzing JFR recordings, you can:</p><ul><li>Identify performance bottlenecks early</li><li>Make data-driven optimization decisions</li><li>Maintain optimal application performance</li><li>Reduce operational costs</li></ul><p>Remember that performance optimization is an iterative process, and JFR provides the insights needed to make informed decisions about where to focus your optimization efforts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbac7e8f2a5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Rule of 30: A Timeless Guide to Clean Code as Java Turns 30]]></title>
            <link>https://medium.com/@sidharth.ram2001/the-rule-of-30-a-timeless-guide-to-clean-code-as-java-turns-30-01880dd3636c?source=rss-cf6835731c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/01880dd3636c</guid>
            <dc:creator><![CDATA[Sidharth Ram]]></dc:creator>
            <pubDate>Fri, 23 May 2025 07:16:35 GMT</pubDate>
            <atom:updated>2025-05-23T07:16:35.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNhBV2SKbJpmDirt8yFsFw.png" /></figure><p>As Java celebrates its 30th anniversary in 2025, it’s fitting to reflect on one of the most practical yet often overlooked guidelines in software development: The Rule of 30. This numerical coincidence offers us a perfect opportunity to explore how this principle has helped shape clean code practices in Java and beyond.</p><blockquote><strong>The Magic Number: Why 30 Matters</strong></blockquote><p>Just as Java has stood the test of time for 30 years, the Rule of 30 has emerged as a reliable compass for code organization. Originally discussed in “Refactoring in Large Software Projects” by Martin Lippert and Stephen Roock, this guideline provides a hierarchical framework for managing code complexity.</p><blockquote>The Five Tiers of the Rule of 30</blockquote><p><strong>1. Method-Level Clarity (30 Lines)</strong></p><pre>java public class OrderProcessor { // Aim for methods around 30 lines public void processOrder(Order order) { validateOrder(order); calculateTotalPrice(order); applyDiscounts(order); saveToDatabase(order); notifyCustomer(order); } }</pre><p>Think of methods as paragraphs in your code story. If you’re writing more than 30 lines, you’re probably trying to tell multiple stories at once.</p><p><strong>2. Class-Level Organization (30 Methods)</strong></p><p>Your classes should be focused and cohesive. If you find yourself approaching 30 methods, it’s often a sign that your class is trying to do too much. Consider the Single Responsibility Principle (SRP).</p><p><strong>3. Package-Level Structure (30 Classes)</strong></p><p>j<em>ava com.example.ecommerce ├── order/ ├── payment/ ├── inventory/ ├── shipping/ └── customer/</em></p><p>Packages should tell a coherent story. More than 30 classes might indicate a need for subpackages or a different organizational structure.</p><p><strong>4. Subsystem Architecture (30 Packages)</strong></p><p>When your subsystem grows beyond 30 packages, it’s time to consider breaking it into smaller, more manageable subsystems.</p><p><strong>5. System-Level Design (30 Subsystems)</strong></p><p>At the highest level, keeping subsystems under 30 helps maintain a comprehensible system architecture.</p><blockquote>Beyond Numbers: The Spirit of the Rule</blockquote><p>The beauty of the Rule of 30 isn’t in strict adherence to the number, but in its spirit. As Java has evolved over 30 years, so too should our understanding of this guideline. Here’s what really matters:</p><p><strong>1. Maintainability First</strong></p><p>- Code should be easy to understand</p><p>- Each component should have a clear purpose</p><p>- Changes should be localized and predictable</p><p><strong>2. Flexibility in Application</strong></p><p>The rule shouldn’t be treated as a hard limit but as a warning sign. When you exceed these numbers, ask yourself:</p><p>- Is this complexity necessary?</p><p>- Could this be broken down more elegantly?</p><p>- Am I maintaining good separation of concerns?</p><p><strong>3. Context Matters</strong></p><p>Different domains and requirements might call for different thresholds. A complex algorithm might legitimately need more than 30 lines to express its logic clearly.</p><blockquote>Modern Java Context</blockquote><p>As Java celebrates 30 years, modern practices have evolved:</p><p>- Functional programming features introduced in Java 8 often lead to more concise methods</p><p>- Microservices architecture naturally encourages smaller, focused components</p><p>- Modern IDEs and tools make it easier to manage and refactor code</p><blockquote>Practical Tips for Application</blockquote><p><strong>1. Use IDE Features</strong></p><p>- Leverage code analysis tools</p><p>- Use refactoring assistants</p><p>- Monitor complexity metrics</p><p><strong>2. Regular Code Reviews</strong></p><p>- Make the Rule of 30 part of your review checklist</p><p>- Look for opportunities to simplify</p><p>- Consider it a conversation starter rather than a strict rule</p><p><strong>3. Continuous Refactoring</strong></p><p>- Don’t wait for code to become problematic</p><p>- Refactor incrementally</p><p>- Keep components small from the start</p><p><strong><em>Conclusion</em></strong></p><p>As Java turns 30, the Rule of 30 remains a valuable tool in our development toolkit. It’s not about rigid compliance but about maintaining code that’s easy to understand, modify, and maintain. Like Java itself, the key to longevity is finding the right balance between structure and flexibility.</p><p>Remember: The best code is not just about following numbers — it’s about creating maintainable, readable, and efficient solutions that stand the test of time.</p><p>#Java #CleanCode #SoftwareDevelopment #Programming #CodeQuality</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01880dd3636c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing and Using MVC Pagination with Spring Data Pageable]]></title>
            <link>https://medium.com/@sidharth.ram2001/implementing-and-using-mvc-pagination-with-spring-data-pageable-321c120d146d?source=rss-cf6835731c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/321c120d146d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[spring-mvc]]></category>
            <dc:creator><![CDATA[Sidharth Ram]]></dc:creator>
            <pubDate>Wed, 14 May 2025 02:02:23 GMT</pubDate>
            <atom:updated>2025-05-14T02:02:23.625Z</atom:updated>
            <content:encoded><![CDATA[<p>Pagination is an essential part of building modern APIs to handle large datasets efficiently. Spring MVC simplifies pagination and sorting by providing the `Pageable` interface and Spring Data’s built-in support for query parameter mapping. This document explains how to properly implement and use pagination in your APIs with Spring MVC and `<strong>Pageable</strong>`.</p><p>1. What is `Pageable`?<br>The `Pageable` interface in Spring Data defines pagination information for API queries. It integrates seamlessly with the Spring Data repository methods and provides the following features:<br>- Pagination by specifying the <strong>page number</strong> and <strong>page size</strong>.<br>- Sorting results by defining <strong>sort fields</strong> and sort <strong>directions</strong>.<br>- Flexibility to use default values or provide custom query parameters dynamically.</p><p>2. Query Parameters for Pagination<br>When using the <strong>Pageable</strong> interface in an endpoint, Spring Data automatically maps the following query parameters:</p><blockquote>1. <strong>page</strong><br> — Specifies the zero-based page number to retrieve.<br> — Default value: <strong>0</strong>.</blockquote><blockquote>2. <strong>size</strong><br> — Specifies the number of elements per page.<br> — Default value: Configurable at the application level or overridden via <a href="http://twitter.com/PageableDefault"><strong>@PageableDefault</strong></a>.</blockquote><blockquote>3. <strong>sort</strong><br> — Specifies sorting criteria for the results.<br> — Format: sort=fieldName, asc|desc.<br> — Example: `sort=createdDate,asc` or `sort=eventType,desc`.<br> — Multiple sort fields are supported, e.g., `sort=field1,asc&amp;sort=field2,desc`.</blockquote><p>3. How Spring Processes Pagination Queries<br>When a controller sets up a method parameter as `Pageable`, Spring automatically interprets the query parameters (`page`, `size`, and `sort`). For example:<br><strong>Request</strong>:</p><p><strong><em>GET /api/data?page=0&amp;size=10&amp;sort=field1,asc&amp;sort=field2,desc</em></strong></p><p><strong>Spring Interprets It As:</strong><br>- Fetch the <strong>first page of data</strong> (`page=0`) with <strong>10 results per page</strong> (`size=10`).<br>- Sort by `field1` in ascending order, then by in descending order. `field2`</p><p>4. Implementing Pagination in Spring MVC<br>Here’s how to define an endpoint that supports pagination using the `Pageable` interface:</p><p>Endpoint Definition</p><pre>@GetMapping(&quot;/data&quot;)<br>public Page&lt;DataDTO&gt; getPaginatedData(@PageableDefault(size = 10, sort = &quot;fieldName&quot;, direction = Sort.Direction.ASC) Pageable pageable) {<br> return dataService.getData(pageable); // Delegates pagination to the service layer<br>}</pre><p>Key Highlights:<br>- : Allows you to configure default values for `size` and `sort` if not explicitly provided in query parameters. `PageableDefault`<br>- `Page`: A container class returned by Spring Data that:<br> — Holds actual paginated data.<br> — Provides additional metadata like total elements, total pages, and page number.</p><p>5. Customizing Pagination Defaults<br>Default values for pagination can be customized globally using the application configuration.<br> Global Default Settings<br>You can set default values in `application.properties`:</p><pre>spring.data.web.pageable.default-page-size=20 # Default size of each page<br>spring.data.web.pageable.max-page-size=200 # Maximum allowed size per page<br>spring.data.web.pageable.page-parameter=page # Query parameter for page<br>spring.data.web.pageable.size-parameter=size # Query parameter for size<br>spring.data.web.sort.sort-parameter=sort # Query parameter for sorting</pre><p>This ensures consistent pagination behavior across your application unless explicitly overridden.</p><p>6. Sorting Data<br>Sorting is an essential feature of pagination. You can sort data using the `sort` query parameter. Sorting works directly on fields that exist in the underlying entity or database.<br>Example Request</p><p>To sort data by a specific field (e.g., `fieldName`) in ascending order:</p><p><strong><em>GET /api/data?page=1&amp;size=10&amp;sort=fieldName,asc</em></strong></p><p>To apply multiple sorting criteria:</p><p><strong><em>GET /api/data?page=0&amp;size=10&amp;sort=field1,asc&amp;sort=field2,desc</em></strong></p><p>Handling Sorting in DTOs<br>If sorting is applied to fields that are only defined in a <strong>DTO</strong> (Data Transfer Object), ensure those fields exist in the database query explicitly or map them through aliases. Otherwise, `Invalid property name` errors may occur.<br>7. Common Issues and Solutions<br>Problem 1: “Invalid property name” in `sort` parameter<br>Occurs when the `sort` parameter references a field that doesn’t exist in the entity or database query.</p><p><strong>Solution</strong>:<br>- Use property/column names that are defined in the entity or explicitly included in database queries.<br>- Alias fields in custom queries to ensure proper mapping between entity fields and DTO definitions.</p><p>8. Benefits of Using `Pageable`<br>1. <strong>Reduced Data Overhead:</strong><br> — Pagination ensures the API only delivers the required portion of the data set, improving performance.</p><p>2. <strong>Simplified Implementation:</strong><br> — Spring Data provides seamless integration with repository methods, reducing boilerplate code.</p><p>3. <strong>Dynamic Sorting:</strong><br> — Users can sort data dynamically by providing column names in query parameters.</p><p>4. <strong>Automatic Validation:</strong><br> — Spring automatically validates query parameters like `page` and `size` to prevent invalid pagination requests.</p><p>9. Best Practices for Pagination<br>1. <strong>Provide Default Values</strong>: Always define reasonable defaults for `page` and `size` to avoid unnecessary large data loads in case the client does not specify them.<br>2. <strong>Secure Sorting Logic:</strong> Validate the `sort` parameter to prevent SQL injection or unexpected failures. Use Spring Data’s system to control allowed fields.<br>3. <strong>Global Pagination Settings:</strong> Set sensible global limits for `size` and restrict excessively large values to prevent performance degradation.<br>4. <strong>DTO Use Cases:</strong> If using a DTO, ensure consistency between the database query and the expected DTO field names.<br>5. <strong>Error Handling:</strong> Provide user-friendly messages for common pagination errors like invalid `page`, `size`, or `sort` parameters.</p><p>10. Example API Request Summary</p><pre>| **Request Type** | **Query Parameters**                                | **Description**                                                                                       |<br>| ---------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |<br>| **Default**      | `/api/data`                                         | Fetches the default page (page 0) with a preset size (usually defined by the backend, e.g., 10 or 20) |<br>| **Custom Size**  | `/api/data?size=20`                                 | Fetches the first page (page 0) with 20 results                                                       |<br>| **Custom Page**  | `/api/data?page=1&amp;size=10`                          | Fetches the second page (index 1) with 10 results                                                     |<br>| **Sorting**      | `/api/data?page=0&amp;sort=fieldName,asc`               | Fetches the first page, sorted by `fieldName` in ascending order                                      |<br>| **Multi-Sort**   | `/api/data?page=0&amp;sort=field1,asc&amp;sort=field2,desc` | Fetches the first page, sorted first by `field1` ascending, then by `field2` descending               |</pre><p>11. Conclusion<br>Pagination and sorting are crucial for delivering manageable amounts of data to the client. Spring MVC provides an elegant and robust solution with its `Pageable` interface. By adhering to best practices such as using default values, securing query parameters, and validating sorting fields, you can build scalable APIs that meet user needs effectively.<br>Using the `Pageable` interface in combination with the repository or service layer is a straightforward and powerful way to ensure your API handles large datasets efficiently while offering user-friendly control through query parameters.</p><p><strong>Default</strong> /api/data Fetches the default page (page 0) with a preset size (usually defined by the backend, e.g., 10 or 20) <strong>Custom Size</strong> /api/data?size=20 Fetches the first page (page 0) with 20 results <strong>Custom Page</strong> /api/data?page=1&amp;size=10 Fetches the second page (index 1) with 10 results <strong>Sorting</strong> /api/data?page=0&amp;sort=fieldName,asc Fetches the first page, sorted by fieldName in ascending order <strong>Multi-Sort</strong> /api/data?page=0&amp;sort=field1,asc&amp;sort=field2,desc Fetches the first page, sorted first by field1 ascending, then by field2 descending<br>### 11. Conclusion<br>Pagination and sorting are crucial for delivering manageable amounts of data to the client. Spring MVC provides an elegant and robust solution with its `Pageable` interface. By adhering to best practices such as using default values, securing query parameters, and validating sorting fields, you can build scalable APIs that meet user needs effectively.<br>Using the `Pageable` interface in combination with the repository or service layer is a straightforward and powerful way to ensure your API handles large datasets efficiently while offering user-friendly control through query parameters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=321c120d146d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Local and Global Scopes in AngularJS]]></title>
            <link>https://medium.com/@sidharth.ram2001/understanding-local-and-global-scopes-in-angularjs-1aa205e2b4f2?source=rss-cf6835731c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aa205e2b4f2</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[scopes]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Sidharth Ram]]></dc:creator>
            <pubDate>Tue, 06 May 2025 18:07:13 GMT</pubDate>
            <atom:updated>2025-05-06T18:07:13.761Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with AngularJS, one of the fundamental concepts a developer must grasp is the scope of variables and how they interact within the application. Understanding the distinction between <strong>local scope</strong> and <strong>global scope</strong> is essential for writing efficient, maintainable, and bug-free code. This article explains these scopes with examples and visual diagrams to make the discussion intuitive and approachable.</p><p><strong>What is Scope in AngularJS?</strong></p><p>In AngularJS, <strong>scope</strong> refers to the context where variables and functions are defined and accessible. It acts as the glue between an Angular controller and the view. Scopes in AngularJS are objects that provide control over data-binding between the controller (JavaScript) and the HTML (view).</p><p>Broadly, scopes can be categorized into:</p><ol><li><strong>Global Scope</strong></li><li><strong>Local Scope</strong></li></ol><p>Let’s explore each in detail with examples.</p><p><strong>Local Scope</strong></p><p>Local scope refers to variables that are defined and accessible only within the boundaries of a specific function or context. These variables aren’t shared across components nor exposed to the global window object. A local scope ensures data encapsulation and makes the code modular.</p><p>Here’s an example:</p><pre>(function() {<br>  angular<br>    .module(&#39;sampleApp&#39;)<br>    .controller(&#39;LocalScopeController&#39;, function($scope) {<br>      // Local variable defined inside the controller<br>      const vm = this;<br>      vm.localMessage = &#39;This message is local to this controller&#39;;<br><br>      // Defining a function inside local scope<br>      vm.doSomething = function() {<br>        console.log(&#39;Doing something!&#39;);<br>      };<br><br>      // This variable and function are restricted to this controller<br>      console.log(vm.localMessage); // Accessible here<br>    });<br>})();</pre><p><strong>Key Characteristics of Local Scope:</strong></p><ol><li>Variables cannot be accessed outside the function or controller where they are defined.</li><li>Functions within the same controller can interact with these variables.</li><li>Prevents scope pollution and naming conflicts.</li></ol><p><strong>Global Scope</strong></p><p>Global scope in AngularJS refers to variables or functions that are defined on the $rootScope or the global window object. These variables are accessible across all controllers, directives, and services. While global scope provides convenience, it is often discouraged because it can lead to unexpected side effects and coupling.</p><p>Here’s an example of global scope usage:</p><pre>(function() {<br>  angular<br>    .module(&#39;sampleApp&#39;)<br>    .run(function($rootScope) {<br>      // Setting a global variable<br>      $rootScope.globalMessage = &#39;This message is accessible globally&#39;;<br><br>      // Defining a global function<br>      $rootScope.globalFunction = function() {<br>        console.log(&#39;Global function invoked!&#39;);<br>      };<br>    })<br>    .controller(&#39;GlobalScopeController&#39;, function($rootScope) {<br>      // Accessing global variable and function<br>      console.log($rootScope.globalMessage); // Output: This message is accessible globally<br>      $rootScope.globalFunction(); // Output: Global function invoked!<br>    });<br>})();</pre><p><strong>Key Characteristics of Global Scope:</strong></p><ol><li>Variables and functions are accessible everywhere in the application.</li><li>Can introduce hard-to-debug issues due to scope pollution.</li><li>Should be used cautiously for essential data that needs to be shared across components.</li></ol><p><strong>Case Study: Local vs. Global Scope</strong></p><p>To better understand, let’s look at the example provided in the code snippet. Here’s how the <strong>ContractContactEditorController</strong> handles local and global variables:</p><p><strong>Local Variables:</strong></p><ol><li><strong>vm</strong>:</li></ol><ul><li>Declared as const vm = this; to define controller variables in a local scope.</li><li>Ensures data such as vm.contract, vm.localContract, and functions like updateContacts are only accessible within the controller.</li></ul><p><strong>2. Encapsulation in activate()</strong>:</p><ul><li>The getContract() function fetches the contract data and copies it into vm.localContract. This copy is isolated within the local scope of the controller.</li></ul><p><strong>3. No $rootScope Pollution</strong>:</p><ul><li>Data modifications are performed within the controller, ensuring no reliance on global $rootScope or other shared data stores.</li></ul><p><strong>Global Event Handling Example:</strong></p><p>While the controller uses local scope for data, events like $scope.$emit(‘contractUpdated’, {…}) are used to notify the parent or other parts of the application about changes. This is a controlled way of broadcasting data across Angular modules, limiting the need for global variables.</p><p><strong>Diagram: Local vs. Global Scope</strong></p><p>Below is a visual representation of how local and global scopes function in AngularJS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPiR8yuGsuqa6uf7XgfyWQ.png" /></figure><p>In the above diagram:</p><ul><li><strong>Global scope</strong> (top rectangle) represents shared resources like $rootScope.</li><li><strong>Local scopes</strong> are isolated instances, tied to specific controllers (Controller A and Controller B).<strong> Best Practices for Managing Scopes in AngularJS:</strong></li><li>To ensure clean, maintainable code:</li><li><strong>Minimize Global Scope</strong>:</li><li>Use $rootScope sparingly and store global variables in services or factories instead.</li><li><strong>Leverage Local Scope</strong>:</li><li>Encapsulate logic within controllers, components, and directives to prevent scope pollution.</li><li><strong>Use ControllerAs Syntax</strong>:</li><li>Avoid ambiguity by using the ControllerAs syntax and vm variable to refer to the controller instance.</li><li><strong>Emit and Broadcast Thoughtfully</strong>:</li><li>Use $scope.$emit and $scope.$broadcast for inter-component communication rather than flooding $rootScope with shared state.</li></ul><h3>Conclusion</h3><p>Understanding the distinction and use cases of local and global scopes is crucial for writing scalable and reusable AngularJS applications. While local scope ensures encapsulation and clarity, global scope is useful for sharing critical application-level data. By following best practices and adhering to modular principles, developers can effectively manage both scopes to avoid common pitfalls and enhance the robustness of their applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aa205e2b4f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple Todo Application Using Vaadin and Spring Boot]]></title>
            <link>https://medium.com/@sidharth.ram2001/building-a-simple-todo-application-using-vaadin-and-spring-boot-ec51345ceb29?source=rss-cf6835731c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec51345ceb29</guid>
            <category><![CDATA[todo]]></category>
            <category><![CDATA[vaadin]]></category>
            <dc:creator><![CDATA[Sidharth Ram]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 13:48:13 GMT</pubDate>
            <atom:updated>2024-07-02T13:48:13.987Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this tutorial, we’ll walk through creating a simple Todo application using Vaadin and Spring Boot. This application will allow users to add tasks, mark them as complete, and persist their state across sessions using a database.</p><h3>Prerequisites</h3><ul><li>Basic understanding of Java and Spring Boot</li><li>Java Development Kit (JDK) 17 installed</li><li>Maven installed</li></ul><h3>Project Setup</h3><p>We’ll start by setting up a new Spring Boot project with Vaadin and JPA dependencies.</p><h3>Project Structure</h3><p>Our project will have the following structure:</p><p>src/<br>├── main/<br>│ ├── java/<br>│ │ └── com/<br>│ │ └── example/<br>│ │ └── demo/<br>│ │ ├── model/<br>│ │ │ └── Todo.java<br>│ │ ├── repository/<br>│ │ │ └── TodoRepo.java<br>│ │ └── Views/<br>│ │ └── TodoView.java<br>│ └── resources/<br>│ └── application.properties<br>├── test/<br>└── pom.xml</p><h3>pom.xml</h3><p>Here’s the pom.xml file to include the necessary dependencies:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br> xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br> &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br> &lt;parent&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br> &lt;version&gt;3.3.1&lt;/version&gt;<br> &lt;relativePath/&gt; &lt;! - lookup parent from repository →<br> &lt;/parent&gt;<br> &lt;groupId&gt;com.example&lt;/groupId&gt;<br> &lt;artifactId&gt;demo&lt;/artifactId&gt;<br> &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;<br> &lt;name&gt;demo&lt;/name&gt;<br> &lt;description&gt;Demo project for Spring Boot&lt;/description&gt;<br> &lt;properties&gt;<br> &lt;java.version&gt;17&lt;/java.version&gt;<br> &lt;vaadin.version&gt;24.4.3&lt;/vaadin.version&gt;<br> &lt;/properties&gt;<br> &lt;dependencies&gt;<br> &lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br> &lt;/dependency&gt;<br> &lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br> &lt;/dependency&gt;<br> &lt;dependency&gt;<br> &lt;groupId&gt;com.vaadin&lt;/groupId&gt;<br> &lt;artifactId&gt;vaadin-spring-boot-starter&lt;/artifactId&gt;<br> &lt;/dependency&gt;<br> &lt;dependency&gt;<br> &lt;groupId&gt;com.h2database&lt;/groupId&gt;<br> &lt;artifactId&gt;h2&lt;/artifactId&gt;<br> &lt;scope&gt;runtime&lt;/scope&gt;<br> &lt;/dependency&gt;<br> &lt;dependency&gt;<br> &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br> &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br> &lt;optional&gt;true&lt;/optional&gt;<br> &lt;/dependency&gt;<br> &lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br> &lt;scope&gt;test&lt;/scope&gt;<br> &lt;/dependency&gt;<br> &lt;/dependencies&gt;<br> &lt;dependencyManagement&gt;<br> &lt;dependencies&gt;<br> &lt;dependency&gt;<br> &lt;groupId&gt;com.vaadin&lt;/groupId&gt;<br> &lt;artifactId&gt;vaadin-bom&lt;/artifactId&gt;<br> &lt;version&gt;${vaadin.version}&lt;/version&gt;<br> &lt;type&gt;pom&lt;/type&gt;<br> &lt;scope&gt;import&lt;/scope&gt;<br> &lt;/dependency&gt;<br> &lt;/dependencies&gt;<br> &lt;/dependencyManagement&gt;<br> &lt;build&gt;<br> &lt;plugins&gt;<br> &lt;plugin&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br> &lt;/plugin&gt;<br> &lt;/plugins&gt;<br> &lt;/build&gt;<br>&lt;/project&gt;</pre><h3>Creating the Todo Entity</h3><p>First, let’s create the Todo entity.</p><h3>Todo.java</h3><pre>package com.example.demo.model;<br>import jakarta.persistence.Entity;<br>import jakarta.persistence.GeneratedValue;<br>import jakarta.persistence.GenerationType;<br>import jakarta.persistence.Id;<br>import lombok.Data;<br>import lombok.NoArgsConstructor;<br>@Data<br>@Entity<br>@NoArgsConstructor<br>public class Todo {<br>@Id<br> @GeneratedValue(strategy = GenerationType.IDENTITY)<br> private int id;<br>private String task;<br> private boolean done;<br>public Todo(String task){<br> this.task = task;<br> }<br>public boolean isDone(){<br> return done;<br> }<br>}</pre><h3>Creating the Repository</h3><p>Next, we’ll create a repository interface for our Todo entity.</p><h3>TodoRepo.java</h3><pre>package com.example.demo.repository;<br>import org.springframework.data.jpa.repository.JpaRepository;<br>import com.example.demo.model.Todo;<br>public interface TodoRepo extends JpaRepository&lt;Todo, Integer&gt; {<br>}j</pre><h3>Creating the View</h3><p>Now, let’s create the main view for our application using Vaadin.</p><h3>TodoView.java</h3><pre>package com.example.demo.Views;<br>import com.example.demo.model.Todo;<br>import com.example.demo.repository.TodoRepo;<br>import com.vaadin.flow.component.Component;<br>import com.vaadin.flow.component.button.Button;<br>import com.vaadin.flow.component.checkbox.Checkbox;<br>import com.vaadin.flow.component.html.H1;<br>import com.vaadin.flow.component.orderedlayout.HorizontalLayout;<br>import com.vaadin.flow.component.orderedlayout.VerticalLayout;<br>import com.vaadin.flow.component.textfield.TextField;<br>import com.vaadin.flow.router.Route;<br>import org.springframework.beans.factory.annotation.Autowired;<br>@Route(&quot;&quot;)<br>public class TodoView extends VerticalLayout {<br>private TodoRepo repo;<br>@Autowired<br> public TodoView(TodoRepo repo) {<br> this.repo = repo;<br> var task = new TextField();<br> var button = new Button(&quot;Add&quot;);<br> var todos = new VerticalLayout();<br> button.addClickListener(click -&gt; {<br> var todo = repo.save(new Todo(task.getValue()));<br> todos.add(createCheckbox(todo));<br> });<br> repo.findAll().forEach(todo -&gt; todos.add(createCheckbox(todo)));<br> add(<br> new H1(&quot;Todo&quot;),<br> new HorizontalLayout(task, button),<br> todos<br> );<br> }<br>private Component createCheckbox(Todo todo) {<br> return new Checkbox(todo.getTask(), todo.isDone(), e -&gt; {<br> todo.setDone(e.getValue());<br> repo.save(todo);<br> });<br> }<br>}</pre><h3>Explanation</h3><ol><li><strong>Initialization</strong>: The TodoView is instantiated with an instance of TodoRepo injected by Spring. We create UI components for entering tasks (TextField), adding tasks (Button), and displaying tasks (VerticalLayout).</li><li><strong>Loading Existing Tasks</strong>: We retrieve all tasks from the database and add them to the UI using createCheckbox method.</li><li><strong>Adding a New Task</strong>: When the &quot;Add&quot; button is clicked, a new Todo is created and saved to the database. A new checkbox is then added to the UI.</li><li><strong>Checkbox Creation</strong>: The createCheckbox method creates a checkbox for each task, binding it to the task&#39;s completion status. When the checkbox is checked or unchecked, the task&#39;s done status is updated in the database.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PPsTxS0JESGTuq86PII87g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec51345ceb29" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>