<?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 Harveer Narwar on Medium]]></title>
        <description><![CDATA[Stories by Harveer Narwar on Medium]]></description>
        <link>https://medium.com/@narwar_veer?source=rss-50fe98660542------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s6NykbpX0WNlU5yB_sBn5Q.jpeg</url>
            <title>Stories by Harveer Narwar on Medium</title>
            <link>https://medium.com/@narwar_veer?source=rss-50fe98660542------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:07:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@narwar_veer/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[I Added Kafka to WalletPe: Solving the KYC-to-Wallet Consistency Problem]]></title>
            <link>https://medium.com/@narwar_veer/i-added-kafka-to-walletpe-solving-the-kyc-to-wallet-consistency-problem-f90cd9683083?source=rss-50fe98660542------2</link>
            <guid isPermaLink="false">https://medium.com/p/f90cd9683083</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <dc:creator><![CDATA[Harveer Narwar]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 13:25:07 GMT</pubDate>
            <atom:updated>2026-10-27T13:25:07.013Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I used Apache Kafka and the Transactional Outbox Pattern to decouple KYC approval from wallet creation.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4or5CElJRap5Q-G13YrW0A.png" /></figure><p>While building <strong>WalletPe</strong>, my wallet application built around microservices, I reached an important architectural decision: what should happen after an administrator approves a user’s KYC application?</p><p>At this stage, WalletPe supports user registration, identity verification, KYC submission, and administrative KYC approval. The next step is to create an INR wallet for the approved user.</p><p>The business requirement sounds simple:</p><p><strong>Once KYC is approved, create a wallet for that user.</strong></p><p>But implementing this across two independent microservices introduces problems that are easy to overlook when everything works as expected.</p><p>What happens if the wallet service is unavailable? What if KYC approval succeeds but the event notifying the wallet service is lost? What happens if the same event is delivered twice?</p><p>I used this problem to explore Apache Kafka, asynchronous communication, the Transactional Outbox Pattern, and idempotent event processing.</p><p>This article explains the design I implemented, the failure scenarios I considered, and what I would change before taking this architecture into production.</p><h3>1. Understanding the problem</h3><p><em>The workflow in WalletPe is straightforward:</em></p><ol><li>A user registers and completes the required verification.</li><li>The user submits a KYC application.</li><li>An administrator reviews and approves the application.</li><li>WalletPe creates one active INR wallet with a zero balance for that user.</li><li>My first architectural consideration was whether the KYC service should call the wallet service directly using REST.</li></ol><h3>Approach 1: Synchronous communication</h3><p>The flow would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYRRShgrJI5Udo6Iumf8Zw.png" /></figure><p>This approach is simple and can work well for some systems. However, the KYC approval workflow becomes dependent on the availability and response time of the wallet service.</p><p>Consider this failure scenario:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jeOyfGYTyd5fWRMQSy7JnA.png" /></figure><p>The KYC record may already be approved even though the overall request reports an error. Retrying the operation could introduce further complications if the original operation partially succeeded.</p><p>This is a consistency and recovery problem, not merely an HTTP error-handling problem.</p><p>I wanted KYC approval and wallet creation to remain independent operations, with a reliable mechanism for communicating between them.</p><p>That led me to Kafka.</p><h3>2. Introducing event-driven communication</h3><p>Instead of directly invoking the wallet service, the KYC service publishes a KYC_APPROVED event. The wallet service consumes the event and initiates wallet creation.</p><p>The revised workflow is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYfSnSeHopFhJfA7LSrBeg.png" /></figure><p>This changes the dependency between the services.</p><p>The KYC service no longer needs the wallet service to be available during the approval request. Once the KYC approval and outbox event have been committed to PostgreSQL, the publisher can deliver the event when Kafka becomes available.</p><p>The wallet service can process the event independently.</p><p>However, introducing Kafka does not automatically make the workflow reliable. The way the application writes to the database and publishes events matters just as much as the broker itself.</p><h3>3. The dual-write problem</h3><p>A naive implementation might look like this:</p><pre>approveKycInDatabase();<br><br>kafkaTemplate.send(&quot;kyc.events.approved&quot;, event);</pre><p>There are two independent operations:</p><ul><li>Update the KYC record in PostgreSQL.</li><li>Publish an event to Kafka.</li></ul><p>These operations do not share a single atomic transaction.</p><p>What if PostgreSQL commits the approval, but the application crashes before publishing the Kafka event?</p><p>The KYC record says APPROVED, but the wallet service never receives the event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AwgE3O_SnZdWXgRoW9V_-Q.png" /></figure><p>The reverse ordering is problematic too. If an event is published before the corresponding database transaction commits, a consumer might act on an approval that is subsequently rolled back.</p><p>This is commonly known as the <strong>dual-write problem</strong>.</p><p>The important question became: how could I ensure that an approved KYC application always has a durable record of the event that needs to be published?</p><h3>4. My solution: the Transactional Outbox Pattern</h3><p>The Transactional Outbox Pattern addresses this problem by storing the business-state change and the event record in the same database transaction.</p><p>Instead of writing directly to Kafka from the approval workflow, the KYC service writes an event to an outbox table.</p><p>Conceptually, the transaction looks like this:</p><pre>BEGIN;<br><br>UPDATE kyc_applications<br>SET status = &#39;APPROVED&#39;<br>WHERE id = :kyc_id;<br><br>INSERT INTO kyc_outbox_events (<br>    event_id,<br>    event_type,<br>    aggregate_id,<br>    payload,<br>    status<br>)<br>VALUES (<br>    :event_id,<br>    &#39;KYC_APPROVED&#39;,<br>    :user_id,<br>    :payload,<br>    &#39;PENDING&#39;<br>);<br><br>COMMIT;</pre><p>The example is simplified; the actual implementation must validate the application state, handle concurrent reviews, and ensure the update affects the intended record.</p><p>The critical property is that both writes belong to the same PostgreSQL transaction.</p><p>If the transaction rolls back, neither the approval nor its outbox event is committed. If it commits, both are durable.</p><h4>The revised publishing flow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3coVSG3CKpqOo5GQxPNnA.png" /></figure><p>In my implementation, a scheduled KycEventPublisher looks for pending events, publishes their JSON payloads to Kafka, and marks them as PUBLISHED after Kafka acknowledges the send.</p><p>If Kafka is temporarily unavailable, the event remains pending and can be retried.</p><p>This does not create a distributed transaction between PostgreSQL and Kafka. Instead, it ensures that the intent to publish an event is persisted alongside the business-state change.</p><p>That is a much more useful guarantee for this workflow.</p><h3>5. How I separated responsibilities between services</h3><p>I wanted each microservice to own its business rules rather than allowing one service to modify another service’s data directly.</p><p>The responsibilities in WalletPe are:</p><ul><li><strong>KYC Service</strong> → Manages KYC applications and status.</li><li><strong>ReviewKycUseCase</strong> → Approves KYC + saves outbox event.</li><li><strong>KycEventPublisher</strong> → Publishes pending events to Kafka.</li><li><strong>Kafka</strong> → Transports events between services.</li><li><strong>KycApprovedKafkaConsumer</strong> → Receives and validates events.</li><li><strong>CreateWalletUseCase</strong> → Enforces wallet-creation rules.</li><li><strong>Wallet Service</strong> → Owns wallet records and lifecycle.</li></ul><p>This separation is reflected in the application code. The KYC approval use case does not call the wallet service directly, and the wallet service owns the actual wallet-creation operation.</p><p>The resulting architecture has a clear ownership boundary:</p><p><strong>KYC owns approval. Wallet owns wallet creation. Kafka connects the two.</strong></p><p>This makes the system easier to reason about and allows the services to evolve independently.</p><h3>6. Designing the Kafka event contract</h3><p>An event should contain enough information for the receiving service to process it without exposing unnecessary personal or security-sensitive data.</p><p>For WalletPe, the KYC_APPROVED event follows this structure:</p><pre>{<br>  &quot;eventId&quot;: &quot;d7fcd674-5fe0-4cf4-9b52-a0a31d3f24b2&quot;,<br>  &quot;eventType&quot;: &quot;KYC_APPROVED&quot;,<br>  &quot;eventVersion&quot;: 1,<br>  &quot;kycId&quot;: &quot;d180f2b5-a96d-4db9-b24d-b2f4a548acd2&quot;,<br>  &quot;userId&quot;: &quot;f00cfa0a-4d8a-463f-a5c7-bf3997d64d6e&quot;,<br>  &quot;reviewerId&quot;: &quot;6a3d2f4a-2cc9-49c4-8c8e-e26b6cef40da&quot;,<br>  &quot;occurredAt&quot;: &quot;2026-10-27T05:30:00Z&quot;,<br>  &quot;correlationId&quot;: &quot;request-correlation-id&quot;<br>}</pre><p><em>The identifiers are illustrative.</em></p><p>A few design choices matter here:</p><ul><li><strong>eventId</strong> uniquely identifies the event and supports deduplication.</li><li><strong>eventType</strong> tells consumers what happened.</li><li><strong>eventVersion</strong> provides a starting point for managing schema evolution.</li><li><strong>userId</strong> identifies the user whose wallet needs to be created.</li><li><strong>correlationId</strong> helps trace related operations across services.</li></ul><p>I deliberately exclude Aadhaar values, KYC document contents, document paths, passwords, OTPs, JWTs, and service secrets.</p><p>The event should communicate the business fact that KYC was approved, not transport the user&#39;s entire identity record.</p><h3>7. Why I chose userId as the Kafka message key</h3><p>Kafka ordering is guaranteed within a partition, not across an entire topic.</p><p>In WalletPe, I use userId as the record key:</p><pre>Topic: kyc.events.approved<br>Key:   userId<br>Value: KYC_APPROVED event</pre><p>This means events with the same key are routed to the same partition under a stable partitioning configuration.</p><p>That becomes useful if the system later introduces additional events such as KYC_ON_HOLD or KYC_REVOKED. A consistent key allows events for one user to share a partition and preserves their partition order.</p><p>I started with three partitions for local development to explore partitioning and consumer-group behaviour.</p><p>With three partitions, a consumer group can have at most three active consumers assigned one partition each at a time. Adding more consumers to that same group does not increase parallelism beyond the number of partitions.</p><p>For a small MVP, one partition could also be sufficient. The appropriate number depends on throughput requirements, ordering needs, and expected growth.</p><h3>8. Handling duplicate events</h3><p>This was one of the most important failure scenarios I considered.</p><p>Suppose the publisher successfully sends an event to Kafka, but crashes before marking its outbox row as PUBLISHED.</p><p>When the publisher restarts, the same event may be sent again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTKGcIkSiAMCe1ZCqhimGA.png" /></figure><p>This is normal at-least-once delivery behaviour. The outbox pattern prevents the original database-to-event gap, but it does not guarantee that every event will be published only once.</p><p>I addressed this at the application and database levels.</p><p>The wallet service checks whether an event has already been processed and whether the user already has a wallet. The database also enforces uniqueness through constraints on:</p><ul><li>processed_events.event_id</li><li>wallets.user_id</li></ul><p>The first constraint protects against processing the same event more than once. The second protects the underlying business invariant: one user should not receive multiple wallets.</p><p>These checks are complementary, not interchangeable.</p><p>An event ID protects against replaying the same event. The unique wallet constraint protects against duplicate wallet creation even if two different events attempt to create a wallet for the same user.</p><p>For correctness under concurrent processing, the deduplication record and wallet creation must also be coordinated in a database transaction, with unique-constraint violations handled safely. Application-level existence checks alone are not sufficient because two concurrent requests can both observe that a record does not exist.</p><p>The broader lesson is that <strong>idempotency must be enforced at the side-effect boundary, not assumed from Kafka delivery semantics</strong>.</p><h3>9. Handling invalid messages and local infrastructure</h3><p>I also configured the local Kafka environment to make the messaging workflow more predictable.</p><p>My Docker Compose setup uses a single Kafka broker running in KRaft mode, without ZooKeeper. Topics are created by a dedicated initialization container before the KYC and wallet services start.</p><p>The topics are:</p><ul><li>kyc.events.approved</li><li>kyc.events.approved.DLT</li></ul><p>The dead-letter topic provides a place to inspect messages that cannot be processed after the configured retry attempts, such as malformed JSON or invalid event payloads.</p><p>A dead-letter topic is not a complete recovery strategy by itself. A real system still needs alerting, investigation, and a controlled way to replay or resolve the failed message.</p><p>I also disabled automatic topic creation so that a service could not accidentally create a topic with an incorrect partition count before initialization ran.</p><p>For service-level tests, I can disable the messaging adapters through configuration rather than requiring Kafka for every controller test. Broker-dependent behaviour belongs in integration tests that exercise the actual messaging infrastructure.</p><h3>10. Testing the workflow: what passes and what remains</h3><p>One lesson from this implementation is that passing unit tests do not prove that a distributed workflow works correctly.</p><p>My KYC and wallet contract tests pass, but I have not yet completed an end-to-end integration test using a real Kafka broker and PostgreSQL together.</p><p>The next test suite I plan to add uses Testcontainers to exercise the complete flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o360jnB53gPyHANuER7gJQ.png" /></figure><p>Beyond the happy path, I would test these failure scenarios:</p><ol><li>Kafka is unavailable when the KYC approval commits.</li><li>The publisher crashes after Kafka acknowledges an event but before marking it published.</li><li>The same event is delivered repeatedly.</li><li>Two consumers attempt wallet creation concurrently.</li><li>The consumer receives malformed or unsupported event data.</li><li>The wallet database fails during processing, followed by a retry.</li><li>The application restarts while unpublished outbox events remain.</li></ol><p>These tests would provide evidence that the implementation behaves correctly under failure, rather than merely demonstrating that messages can travel from one service to another.</p><h3>11. What I would change before production</h3><p>WalletPe currently uses a single local Kafka broker with replication factor one, local Docker volumes, and plaintext internal development traffic. I have not yet performed multi-broker failover tests or completed the end-to-end Testcontainers suite.</p><p>That is acceptable for a learning MVP, but it is not enough for a production financial system.</p><p>Before a production deployment, I would consider the following improvements:</p><ul><li><strong>Availability</strong> → Multi-broker KRaft, replication, durability.</li><li><strong>Security</strong> → TLS/SASL, ACLs, secret management.</li><li><strong>Outbox</strong> → Safe event claiming, retries, stale-event recovery.</li><li><strong>Consumers</strong> → Atomic deduplication, transaction safety, concurrency control.</li><li><strong>Observability</strong> → Consumer lag, pending-event count, oldest-event age, publish failures.</li><li><strong>Dead-letter handling</strong> → Alerts, inspection, controlled replay.</li><li><strong>Testing</strong> → Integration tests, failure injection, broker failover.</li><li><strong>Schema evolution</strong> → Compatibility rules and event versioning.</li></ul><p>I would also monitor how long events remain pending. An outbox publisher can be technically healthy while events accumulate faster than they are published.</p><p>The goal is not to introduce every production technology immediately. It is to identify the guarantees the application needs, implement them deliberately, and validate them before increasing complexity.</p><h3>12. What I learned</h3><p>Adding Kafka to WalletPe was not primarily about introducing a message broker. It was about understanding what happens when independent services fail at different points in a business workflow.</p><p>The main lessons were:</p><ul><li>Synchronous communication creates runtime dependencies between services.</li><li>Kafka enables asynchronous communication, but does not automatically solve consistency problems.</li><li>The Transactional Outbox Pattern makes the business-state change and the intent to publish an event atomic within PostgreSQL.</li><li>At-least-once delivery means duplicate processing must be expected.</li><li>Idempotency needs durable enforcement at the database boundary.</li><li>Unit tests and contract tests are not substitutes for end-to-end integration tests.</li><li>A local Kafka setup is useful for learning, but production readiness requires deliberate work on durability, security, monitoring, and recovery.</li></ul><p>For me, the most important design decision was preserving clear ownership: the KYC service owns approval, and the wallet service owns wallet creation. Kafka connects the two without making one service responsible for the other’s business logic.</p><p><strong>The next phase of WalletPe is the ledger and transfer workflow.</strong> I intend to apply the same discipline there, with an additional focus on atomic financial updates, concurrent transfers, idempotency, and reconciliation.</p><p>Because in a financial application, processing an event is only part of the problem. The system must also be able to explain what happened, recover safely when something fails, and preserve the correctness of the underlying financial records.</p><p><em>This article documents the current WalletPe MVP implementation and the additional production-hardening work identified during development. The end-to-end Kafka/PostgreSQL integration tests described above are planned work, not completed validation.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f90cd9683083" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Reflection: The Invisible Engine Powering Spring Boot]]></title>
            <link>https://medium.com/@narwar_veer/java-reflection-the-invisible-engine-powering-spring-boot-005498799c57?source=rss-50fe98660542------2</link>
            <guid isPermaLink="false">https://medium.com/p/005498799c57</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[reflections]]></category>
            <dc:creator><![CDATA[Harveer Narwar]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 09:01:14 GMT</pubDate>
            <atom:updated>2026-03-24T09:01:14.603Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Most developers use Spring Boot for years and never once ask — how does it actually work? The honest answer: Reflection.</blockquote><blockquote>Remove Reflection from the JVM, and Spring Boot stops working. No dependency injection. No component scanning. No annotation processing. No proxies. The “magic” disappears — because Reflection <em>is</em> the magic.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuKjNmmTk5m4oEnMWoM9vw.png" /></figure><h3>What is Reflection?</h3><blockquote>Java is normally a static language — at compile time, the JVM already knows exactly which classes, methods, and fields your code touches. Reflection breaks that contract. It lets a program <strong>inspect and manipulate its own structure at runtime</strong>, without needing compile-time knowledge of what it’s touching.</blockquote><p>Here’s the difference in practice:</p><pre>// Normal, static call — compiler knows everything ahead of time<br>UserService service = new UserService();<br>service.process();<br><br>// Reflection - the JVM figures it out dynamically, at runtime<br>Class&lt;?&gt; clazz = Class.forName(&quot;UserService&quot;);        // load class by name<br>Object obj = clazz.getDeclaredConstructor().newInstance(); //create instance<br>Method method = clazz.getMethod(&quot;process&quot;);              // find method<br>method.invoke(obj);                                       // execute it</pre><p>No imports, no compile-time type checking — just raw runtime introspection.</p><h3>Why Frameworks Can’t Live Without It</h3><blockquote>Here’s the fundamental problem every framework faces: <em>it can’t know your code in advance.</em> Spring ships before you write a single line. Yet it still needs to discover your classes, read your annotations, create your beans, wire your dependencies, and invoke your methods.</blockquote><p><strong>Reflection is the only mechanism that makes this possible.</strong> Without it, you’d hand-wire every dependency yourself — which is precisely what Java development looked like before Spring existed.</p><h3>How the JVM Exposes Class Metadata</h3><p>Every class loaded by the JVM gets a corresponding Class&lt;?&gt; object. Think of it as a blueprint snapshot — it carries everything about the class: its fields, methods, constructors, and annotations. Reflection is simply the API for reading that snapshot.</p><pre>Compiled .class file<br>         ↓<br>ClassLoader loads the class into the JVM<br>         ↓<br>java.lang.Class object is created (fields, methods, constructors, annotations)<br>         ↓<br>Reflection API accesses and operates on that metadata<br>         ↓<br>Framework performs runtime operations on your code</pre><pre>Class&lt;?&gt; clazz = Class.forName(&quot;com.app.service.UserService&quot;);<br>Method[]      methods      = clazz.getDeclaredMethods();<br>Field[]       fields       = clazz.getDeclaredFields();<br>Constructor&lt;?&gt;[] ctors    = clazz.getDeclaredConstructors();</pre><h3>Breaking Into Private Fields</h3><p>Normally, private means inaccessible. Reflection can override that with a single call to setAccessible(true):</p><pre>class User {<br>    private String name = &quot;Narwar&quot;;<br>}<br>User user  = new User();<br>Field field = user.getClass().getDeclaredField(&quot;name&quot;);<br>field.setAccessible(true);                  // bypass private access<br>String value = (String) field.get(user);   // read the value directly<br>System.out.println(value); // → Narwar</pre><blockquote>This is exactly how @Autowired field injection works internally — Spring locates the field, bypasses visibility, and sets the bean reference directly on the object.</blockquote><h3>Invoking Methods Dynamically</h3><p>Beyond reading state, Reflection can <em>invoke</em> methods — including ones Spring has no compile-time awareness of:</p><pre>Class&lt;?&gt; clazz = Class.forName(&quot;UserService&quot;);<br>Object obj     = clazz.getDeclaredConstructor().newInstance(); // instantiate<br>Method method  = clazz.getMethod(&quot;process&quot;);<br>method.invoke(obj); // → Processing...</pre><blockquote>This is the mechanism behind how Spring invokes @RequestMapping handlers, @Scheduled jobs, and @EventListener callbacks — none of which Spring knew about at compile time.</blockquote><h3>Creating Objects via Constructor Injection</h3><p>Spring’s IoC container doesn’t use new. It dynamically resolves constructors and instantiates beans through Reflection:</p><pre>// Your class — Spring has no prior knowledge of it<br>class UserService {<br>    private UserRepository repo;<br>    public UserService(UserRepository repo) { this.repo = repo; }<br>}<br>// What Spring does internally<br>Constructor&lt;?&gt; ctor = UserService.class.getConstructor(UserRepository.class);<br>UserService service = (UserService) ctor.newInstance(new UserRepository());</pre><h3>Reading Annotations — The Core of Component Scanning</h3><p>When Spring Boot starts and scans your packages, it doesn’t read source files. It reads compiled class metadata through Reflection, looking for annotations:</p><pre>Class&lt;?&gt; clazz = UserService.class;<br>if (clazz.isAnnotationPresent(Service.class)) {<br>    System.out.println(&quot;Spring bean detected - register in IoC container&quot;);<br>}</pre><blockquote>Spring does this for @Component, @Service, @Repository, @Controller, and every other stereotype annotation — all via the same Reflection-based annotation check.</blockquote><h3>Spring Boot’s Full Startup Flow</h3><p>Put it all together, and here’s what happens every time your application starts:</p><pre>Application starts<br>        ↓<br>Component scan - walks packages recursively<br>        ↓<br>Load classes - ClassLoader brings them into the JVM<br>        ↓<br>Read annotations - Reflection checks each class for Spring stereotypes<br>        ↓<br>Build bean definitions - metadata is stored for later instantiation<br>        ↓<br>Instantiate objects - constructors invoked via Reflection<br>        ↓<br>Inject dependencies - fields/setters populated via Reflection<br>        ↓<br>Application is ready</pre><p>Every arrow in that flow is Reflection. It’s not a detail — it’s the spine of the entire framework.</p><h3>How @Autowired Actually Works</h3><pre>// Simplified internals of Spring&#39;s AutowiredAnnotationBeanPostProcessor<br><br>Field field = clazz.getDeclaredField(&quot;repo&quot;);         // 1. find the field<br>if (field.isAnnotationPresent(Autowired.class)) {      // 2. check annotation<br>    field.setAccessible(true);                        // 3. unlock access<br>    field.set(beanInstance, repositoryBean);           // 4. inject the dependency<br>}</pre><p>Four lines. That’s the core of dependency injection.</p><h3>Trade-offs: Power vs. Cost</h3><h4>Advantages</h4><p><strong>Flexibility</strong> — frameworks work with classes they’ve never seen before.</p><p><strong>Enables IoC containers</strong> — the entire Spring ecosystem is built on this foundation.</p><p><strong>Runtime adaptability</strong> — behavior can be determined and changed at execution time.</p><h4>Disadvantages</h4><p><strong>Breaks encapsulation</strong> — private is no longer a hard boundary.</p><p><strong>Performance overhead</strong> — reflective calls are slower than direct invocations.</p><p><strong>Harder to debug</strong> — stack traces become deep and unfamiliar.</p><blockquote><strong>Modern Spring is moving away from pure Reflection.</strong> Spring Boot 3 introduced <strong>AOT (Ahead-of-Time) processing</strong> and <strong>GraalVM Native Image</strong> support, which pre-compute much of what Reflection previously did at startup — giving you faster boot times and smaller memory footprints without sacrificing the programming model you already know.</blockquote><h3>Key Takeaway</h3><p>Reflection powers every major Spring feature. Understanding it means you understand Spring — not as a black box, but as a deliberate, well-engineered system built on JVM fundamentals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=005498799c57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Principles Behind Spring]]></title>
            <link>https://medium.com/@narwar_veer/design-principles-behind-spring-6fca0c818a85?source=rss-50fe98660542------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fca0c818a85</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[enterprisejavaapplication]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Harveer Narwar]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 07:14:29 GMT</pubDate>
            <atom:updated>2026-03-13T07:14:29.854Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Most developers think Spring is just a collection of annotations like @Service, @Autowired, and @Transactional. But those annotations are just the surface. Underneath, Spring is built on decades of software engineering principles that make large systems maintainable and scalable.</blockquote><blockquote>If you understand these principles, Spring stops looking like magic and starts looking like architecture.</blockquote><p>The two most important ideas behind Spring’s architecture are:</p><ul><li><strong>SOLID Principles</strong></li><li><strong>Composition Over Inheritance</strong></li></ul><p>Let’s break them down properly.</p><h3>1. SOLID Principles</h3><blockquote>SOLID is a set of five principles introduced by <strong>Robert C. Martin (Uncle Bob)</strong> to make software systems maintainable and scalable. Large frameworks like Spring rely heavily on these principles to prevent codebases from collapsing under their own complexity.</blockquote><p><strong>The five principles are:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6JthzLyxrXncPY1Rmg7og.png" /></figure><p>Even Spring itself follows SOLID principles internally. For example, the container is designed using layered abstractions such as BeanFactory, ApplicationContext, and ConfigurableApplicationContext, each adding new capabilities while keeping responsibilities separated.</p><pre>ApplicationContext<br>       ↑<br>ConfigurableApplicationContext<br>       ↑<br>AbstractApplicationContext</pre><blockquote>Spring uses <strong>interface segregation + abstraction layers</strong> internally</blockquote><h3>S = Single Responsibility Principle (SRP)</h3><blockquote>A class should have <strong>only one reason to change</strong>.</blockquote><p>Bad design example:</p><pre>class UserService {<br>    public void saveUser(User user) {}<br>    public void sendEmail(User user) {}<br>    public void generateReport() {}<br>}</pre><p>This class now has <strong>three responsibilities</strong>:</p><ul><li>user persistence</li><li>email notifications</li><li>reporting</li></ul><p>If email logic changes, the <strong>UserService changes</strong>.<br>If reporting changes, <strong>UserService changes again</strong>.</p><p>This creates fragile systems.</p><h4>Correct design</h4><p>Split responsibilities.</p><pre>class UserService {<br>    private UserRepository repo;<br>}<br>class EmailService {<br>}<br>class ReportService {<br>}</pre><p>Now each component handles <strong>one responsibility</strong>.</p><h3>O = Open Closed Principle (OCP)</h3><p>Software should be:</p><pre>Open for Extension<br>Closed for Modification</pre><blockquote>You should <strong>add new behavior without modifying existing code</strong>.</blockquote><p>Bad design:</p><pre>class PaymentService {<br>      public void pay(String type) {<br><br>        if(type.equals(&quot;CARD&quot;)) {}<br>        else if(type.equals(&quot;UPI&quot;)) {}<br>        else if(type.equals(&quot;NETBANKING&quot;)) {}<br><br>    }<br>}</pre><p>Every time you add a payment type you must <strong>modify the class</strong>.</p><h4>Better design using polymorphism</h4><pre>interface PaymentMethod {<br>    void pay();<br>}</pre><p>Implementations:</p><pre>class CardPayment implements PaymentMethod {}<br>class UpiPayment implements PaymentMethod {}<br>class NetBankingPayment implements PaymentMethod {}</pre><p>Now the service becomes:</p><pre>class PaymentService {<br>private PaymentMethod method;<br>    public PaymentService(PaymentMethod method) {<br>        this.method = method;<br>    }<br>}</pre><p>Now adding a new payment method requires <strong>no modification to existing code</strong>.</p><p>Spring promotes this pattern through:</p><ul><li>interface-based design</li><li>dependency injection</li><li>bean configuration</li></ul><h3>L = Liskov Substitution Principle (LSP)</h3><blockquote><em>A subclass should be replaceable with its superclass without breaking behavior.</em></blockquote><p>Bad design example:</p><pre>class Bird {<br>    void fly() {}<br>}<br>class Penguin extends Bird {<br>    void fly() {<br>        throw new RuntimeException();<br>    }<br>}</pre><p>This violates LSP because a <strong>penguin cannot fly</strong>.</p><p>Correct design:</p><pre>interface Bird {}<br>interface FlyingBird extends Bird {<br>    void fly();<br>}</pre><p>Now behavior is properly modeled.</p><p>Spring avoids such violations by encouraging <strong>interface-driven design</strong>.</p><h3>I = Interface Segregation Principle (ISP)</h3><blockquote>Clients should not depend on methods they do not use.</blockquote><p>Bad interface:</p><pre>interface Worker {<br>    void work();<br>    void eat();<br>}</pre><p>What if a robot worker exists?</p><pre>class RobotWorker implements Worker {<br>    public void work() {}<br>    public void eat() {} // meaningless<br>}</pre><p>Better approach:</p><pre>interface Workable {<br>    void work();<br>}<br>interface Eatable {<br>    void eat();<br>}</pre><p>Now classes implement <strong>only what they need</strong>.</p><p>Spring uses this idea extensively through <strong>small focused interfaces</strong>.</p><p>Example:</p><pre>BeanFactory<br>ListableBeanFactory<br>ConfigurableBeanFactory</pre><p>Each interface adds <strong>specific capabilities</strong>.</p><h3>D = Dependency Inversion Principle (The Core of Spring)</h3><p>This is the <strong>most important principle behind Spring</strong>.</p><blockquote>High-level modules should not depend on low-level modules.<br>Both should depend on abstractions.</blockquote><p>Without dependency inversion:</p><pre>class OrderService {<br>private PaymentService paymentService = new PaymentService();<br>}</pre><p>Problems:</p><ul><li>tight coupling</li><li>difficult testing</li><li>hard to replace implementations</li></ul><p><strong>With Dependency Inversion</strong></p><pre>@Service<br>class PaymentService {<br>}<br><br>@Service<br>class OrderService {<br><br>    private final PaymentService paymentService;<br><br>    public OrderService(PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><p>During application startup, the Spring container scans for components, creates the PaymentService bean, and injects it into OrderService.</p><h4>Spring Dependency Flow</h4><pre>Application<br>     │<br>     ▼<br>Spring Container<br>     │<br>Creates Objects<br>     │<br>Injects Dependencies<br>     │<br>Builds Dependency Graph</pre><p>Instead of:</p><pre>Object → creates dependency</pre><p>We get:</p><pre>Container → injects dependency</pre><p>This is called <strong>Inversion of Control (IoC)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uKpqskQoZhMmq2IJAvWQyg.png" /></figure><h3>2. Composition Over Inheritance</h3><blockquote>Inheritance creates <strong>tight coupling</strong>.</blockquote><p>Example:</p><pre>class AdvancedPaymentService extends PaymentService</pre><p>Problems:</p><ul><li>rigid hierarchy</li><li>fragile base class problem</li><li>difficult evolution</li></ul><p>Modern design prefers <strong>composition</strong>.</p><p>Example:</p><pre>class OrderService {<br>private PaymentService paymentService;<br>}</pre><p>Instead of inheriting behavior, we <strong>compose objects together</strong>.</p><h4>Composition Flow</h4><pre>OrderService<br>     │<br>     ▼<br>PaymentService<br>     │<br>     ▼<br>TransactionManager</pre><p>Objects collaborate rather than inherit.</p><p>Spring encourages composition through:</p><ul><li>dependency injection</li><li>bean wiring</li><li>interface-based design</li></ul><h3>Hidden Insight Most Developers Miss</h3><p>Spring is not just a framework.</p><p>It is a <strong>large-scale implementation of these principles</strong>.</p><p>Under the hood Spring is basically:</p><pre>Spring Container =<br>    Dependency Graph Builder<br>    + Proxy Factory<br>    + Object Lifecycle Manager</pre><p>Everything else — AOP, transactions, security, and caching — is built on top of this foundation.</p><h3>Why These Principles Matter</h3><p>If you ignore these principles:</p><ul><li>your services become tightly coupled</li><li>testing becomes painful</li><li>architecture collapses over time</li></ul><p>If you follow them:</p><ul><li>components remain modular</li><li>systems evolve safely</li><li>frameworks like Spring work <strong>with your design instead of against it</strong></li></ul><blockquote>Let’s connect on LinkedIn: <a href="https://www.linkedin.com/in/harveer-narwar/"><strong>Harveer Narwar</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fca0c818a85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Foundations: The “Why” Behind the Magic]]></title>
            <link>https://medium.com/@narwar_veer/spring-foundations-the-why-behind-the-magic-715eabfeee43?source=rss-50fe98660542------2</link>
            <guid isPermaLink="false">https://medium.com/p/715eabfeee43</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[enterprisejavaapplication]]></category>
            <dc:creator><![CDATA[Harveer Narwar]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 06:07:49 GMT</pubDate>
            <atom:updated>2026-03-12T06:07:49.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5BAzH4Rth3crRZqVw-1yOQ.png" /></figure><blockquote>Most developers start their Spring Boot journey like they’re following a Maggi recipe. Throw in a @RestController, sprinkle some @Autowired over a service, and when the API finally returns a JSON, they think they’ve become a &quot;Senior Java Architect.&quot;</blockquote><p><strong>Spoiler alert:</strong> You haven’t. You’ve just learned how to follow a tutorial.</p><h3>1. The “Infrastructure Tax” (Or: Why your code is a mess)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8IUPSxdxSGhgWhQgB41Ig.png" /></figure><p>In a simple “Hello World,” <strong><em>100%</em></strong> of your code is business logic. In a real-world enterprise system — think of something like the <strong>UPI payment switch</strong> or <strong>IRCTC</strong> — that logic drops to about 20%. The other 80% is the <strong>Infrastructure Tax</strong>. This is the boring, repetitive, soul-crushing boilerplate like managing DB connections, security, and transactions.</p><p><strong>The “Manual” Nightmare:</strong> Before frameworks, if you wanted to save a user, you had to write a 20-line block of boilerplate just to execute one single line of business logic. It looked like this:</p><pre>public void saveUser(User user) {<br>    Connection conn = null;<br>    try {<br>        // Step 1: Manually begging the DB for a connection<br>        conn = dataSource.getConnection();<br>        conn.setAutoCommit(false); <br>        <br>        // The ONLY line that actually matters for your business<br>        userRepository.save(user, conn);<br>        <br>        conn.commit(); <br>    } catch (Exception e) {<br>        if (conn != null) conn.rollback(); // Manual damage control<br>        throw new RuntimeException(&quot;The whole system is crashing like IRCTC at 11 AM&quot;, e);<br>    } finally {<br>        if (conn != null) conn.close(); // Forget this and your server is dead by tea break<br>    }<br>}</pre><p>Imagine writing that try-catch-finally mess in 500 different service methods. That’s not engineering; that’s just being a high-tech daily wage laborer.</p><h3>2. The Era of Invasive Frameworks (EJB 2.x: The License Raj)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUt3vMgWH9Et5MnlDkzJSg.png" /></figure><blockquote>In the late 90s, Sun Microsystems tried to “help” with Enterprise JavaBeans (EJB). It was the software equivalent of the <strong>License Raj</strong> — over-regulated, heavy, and impossible to get anything done quickly. It promised “enterprise features,” but at the cost of your sanity.</blockquote><p>To write a simple service, you couldn’t just write a Java class. You had to “marry” the framework:</p><ol><li><strong>Inheritance:</strong> You had to extend SessionBean and implement life-cycle methods you never used.</li><li><strong>Boilerplate:</strong> You had to create “Home” and “Remote” interfaces just to call a method in the same damn project. It was like needing a stamped permit from the local municipality just to walk into your own kitchen.</li><li><strong>The Hostage Situation:</strong> You couldn’t run your code without a 1GB Application Server (WebLogic, JBoss).</li></ol><p><strong>The Result:</strong> You couldn’t even run a simple unit test on your laptop without the fans sounding like a jet engine. Your business logic was a hostage of the server. This created a generation of developers who spent more time fighting XML configurations and deployment descriptors than actually solving business problems.</p><h3>3. The Spring Counter-Revolution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ki9C8WD6Fsdl-_MxAx33mA.png" /></figure><blockquote>In 2002, Rod Johnson got fed up with the EJB nonsense and wrote a book that basically said: “Enterprise Java is over-engineered. Let’s just use plain objects.” He argued for <strong>POJOs (Plain Old Java Objects)</strong> — code that looks like Java, not like a framework dependency.</blockquote><p>Spring was built on two radical ideas that every “Spring Developer” claims to know but usually fails to explain:</p><h3>I. Inversion of Control (IoC)</h3><p><strong>The Old Way (Hard Coupling):</strong> Your class creates its own dependencies. It’s like a <em>Chaiwala</em> having to grow his own tea leaves and own a cow just to make one cup of tea. If the milk source changes, the whole tea stall shuts down.</p><pre>public class OrderService {<br>    /* Hard-wired. If you want to use &#39;MockPaymentService&#39; for testing,<br> you&#39;re stuck.*/<br>    private PaymentService paymentService = new PaymentService(); <br>}</pre><p><strong>The Spring Way (IoC):</strong> You just tell the “Container” what you need, and it hands it to you. Like ordering from <strong>Zomato</strong> — you don’t care how the food is made or which specific kitchen prepares it; you just want the interface (the food) delivered.</p><pre>@Service<br>public class OrderService {<br>    private final PaymentService paymentService;<br>// The Container &quot;wires&quot; this at runtime.<br>    public OrderService(PaymentService paymentService) {<br>        this.paymentService = paymentService; <br>    }<br>}</pre><p>This simple change makes your code <strong>testable</strong>. You can finally swap the real Payment Service for a “Fake” one during testing without changing a single line of production code.</p><h3>II. Aspect-Oriented Programming (AOP)</h3><p>This is the “Magic” that makes the Infrastructure Tax disappear. Most developers think @Transactional is a keyword. It’s not. It’s an instruction for Spring to create a <strong>Dynamic Proxy</strong>.</p><ul><li><strong>The Illusion:</strong> You call service.save().</li><li><strong>The Reality:</strong> You are calling a <strong>Proxy</strong> class that Spring generated in the background. The Proxy calls begin transaction, then calls your actual method, then calls commit.</li><li><strong>The Benefit:</strong> Your code stays clean. You focus on the business logic, and Spring handles the “plumbing” via these invisible wrappers.</li></ul><h3>4. Why This Knowledge is the “1% Filter”</h3><p>If you don’t understand that Spring is basically just a <strong>Proxy-Factory</strong> and a <strong>Dependency Graph</strong>, you’re going to hit a wall.</p><p><em>For example, </em>have you ever wondered why @Transactional doesn&#39;t work when one method calls another in the same class? It’s because you’re bypassing the Proxy. It&#39;s like trying to get a VIP discount at a club by entering through the back door instead of the main gate where the bouncer (the Proxy) is standing.</p><p>You’ll also face “<strong>Circular Dependency</strong>” errors where</p><pre>ServiceA → ServiceB<br>ServiceB → ServiceA</pre><p>Without understanding how the Container builds the graph, you’ll stare at the logs like you’re reading a complicated government form, completely lost.</p><h3>Summary: Stop Being a Framework User</h3><p>Spring exists to solve the <strong>infrastructure chaos</strong> of enterprise systems — transactions, security, persistence, configuration — while keeping your business logic in <strong>Plain Old Java Objects (POJOs)</strong>.</p><p>When you understand this, Spring stops looking like a collection of annotations and starts looking like what it actually is:<br>a <strong>container that manages dependencies and proxies infrastructure around your code</strong>.</p><p>That’s the difference between a <strong>framework user</strong> and a <strong>software engineer</strong>.</p><p>If you found this useful, stay tuned — this series will break down <strong>Spring and Spring Boot from fundamentals to advanced internals</strong> with practical examples, code, and diagrams.</p><p>Let’s connect on LinkedIn: <a href="https://www.linkedin.com/in/harveer-narwar/"><strong>Harveer Narwar</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=715eabfeee43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Channels in Go — A Deep, Beginner‑Friendly Guide]]></title>
            <link>https://medium.com/@narwar_veer/channels-in-go-a-deep-beginner-friendly-guide-0729d7e5ae3b?source=rss-50fe98660542------2</link>
            <guid isPermaLink="false">https://medium.com/p/0729d7e5ae3b</guid>
            <category><![CDATA[golang-channel]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang-development]]></category>
            <dc:creator><![CDATA[Harveer Narwar]]></dc:creator>
            <pubDate>Sun, 10 Aug 2025 05:55:39 GMT</pubDate>
            <atom:updated>2025-08-10T05:55:39.174Z</atom:updated>
            <content:encoded><![CDATA[<h3>Channels in Go — A Deep, Beginner‑Friendly Guide</h3><p><em>If goroutines are workers, channels are the conveyor belts that move packages (values) safely between them.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMtcDbSnAP8pFeAYOGFy2A.png" /></figure><h3>TL;DR</h3><ul><li><strong>Channel</strong> = typed pipe for safe communication between goroutines.</li><li><strong>Unbuffered</strong> blocks sender <em>and</em> receiver until they rendezvous.</li><li><strong>Buffered</strong> lets sender get ahead up to cap(ch) items.</li><li>Close channels <strong>from the sender</strong>; receivers can range until closed.</li><li>select waits on multiple channel ops (timeouts, fan‑in/out, cancellation).</li><li>Prefer <strong>context</strong> for request‑scoped cancellation; use channels for data flow and one‑shot signals.</li><li>Avoid goroutine leaks by always having a plan to <strong>stop</strong> producers (done/context) and <strong>drain</strong> channels.</li></ul><p>Goroutines give you <em>concurrency</em> cheaply; Go can also give you parallelism if multiple CPU cores are available. <strong>Channels</strong> make coordination between those goroutines simple and safe.</p><h3>What exactly is a channel?</h3><p>A <strong>channel</strong> is a typed conduit. You send with ch &lt;- value and receive with value := &lt;-ch.</p><pre>ch := make(chan int)         // unbuffered channel of ints<br>bch := make(chan string, 2)  // buffered channel of strings (capacity 2)</pre><p><strong>Analogy</strong></p><ul><li><strong>Unbuffered</strong>: a <em>walkie‑talkie</em>. Sender and receiver must both press the button at the same time — they rendezvous.</li><li><strong>Buffered</strong>: a <em>mailbox</em>. The sender can drop up to N letters and walk away; the receiver picks them up later.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7znhuTLRLNPIGcJhTkXeug.png" /></figure><pre>// Send (blocks until a receiver is ready on unbuffered channels)<br>ch &lt;- 42<br>// Receive (blocks until a value is available)<br>v := &lt;-ch<br>// Discard the received value<br>&lt;-ch</pre><ul><li>On <strong>unbuffered</strong> channels: send blocks until a receiver arrives, and vice versa.</li><li>On <strong>buffered</strong> channels: send blocks only when the buffer is full; receive blocks when empty.</li></ul><h3>Closing channels (and how to detect it)</h3><p>Only the <strong>sender</strong> should close a channel — closing signals: <em>“no more values will be sent.”</em></p><pre>close(ch)  // after this, any send to ch will panic!<br>// Detect closed channel when receiving<br>v, ok := &lt;-ch<br>if !ok {<br>    // ch is closed and drained; v is the zero value of the element type<br>}</pre><p><strong>Important rules</strong></p><ul><li><strong>Do close</strong> to tell receivers to stop ranging.</li><li><strong>Don’t close</strong> from the receiver side.</li><li><strong>Don’t send</strong> on a closed channel (panic).</li><li>Receiving from a closed channel <strong>succeeds</strong> until buffer drains; then returns zero value with ok=false.</li></ul><p><strong>Range over a channel</strong></p><pre>for v := range ch { // loop ends when ch is closed and drained<br>    fmt.Println(v)<br>}</pre><h3>Directional channels for safer APIs</h3><p>You can restrict parameters to <em>send‑only</em> or <em>recv‑only</em> to prevent misuse.</p><pre>func producer(out chan&lt;- int) {<br>    for i := 0; i &lt; 5; i++ { out &lt;- i }<br>    close(out)<br>}</pre><pre>func consumer(in &lt;-chan int) {<br>    for v := range in { fmt.Println(&quot;got&quot;, v) }<br>}</pre><p>This documents intent and lets the compiler catch mistakes.</p><h3>select: the concurrency switchboard</h3><p>select waits on multiple channel operations and chooses one that’s ready.</p><pre>select {<br>case m := &lt;-ch1:<br>    fmt.Println(&quot;from ch1:&quot;, m)<br>case ch2 &lt;- &quot;ping&quot;:<br>    fmt.Println(&quot;sent ping on ch2&quot;)<br>case &lt;-time.After(500 * time.Millisecond):<br>    fmt.Println(&quot;timeout&quot;)<br>}<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FXt9f3P9MqHSjXgYcqbhw.png" /></figure><p><strong>Why it’s awesome</strong></p><ul><li>Implement <strong>timeouts</strong> with time.After.</li><li><strong>Fan‑in</strong> from multiple sources.</li><li><strong>Cancellation</strong> and <strong>backpressure</strong> control.</li></ul><p><strong>Trick</strong>: a nil channel blocks forever. Use this to <em>disable</em> cases dynamically:</p><pre>var ch &lt;-chan int // nil<br>select {<br>case v := &lt;-ch: // never fires because ch is nil<br>    _ = v<br>default:<br>    fmt.Println(&quot;disabled read&quot;)<br>}</pre><h3>Core patterns you’ll use a lot</h3><h4>A. Pipeline (stage‑by‑stage processing)</h4><pre>[nums] → (square) → (double) → [sink]</pre><pre>func gen(nums ...int) &lt;-chan int {<br>    out := make(chan int)<br>    go func() {<br>        for _, n := range nums { out &lt;- n }<br>        close(out)<br>    }()<br>    return out<br>}<br>func square(in &lt;-chan int) &lt;-chan int {<br>    out := make(chan int)<br>    go func() {<br>        for n := range in { out &lt;- n * n }<br>        close(out)<br>    }()<br>    return out<br>}<br>func double(in &lt;-chan int) &lt;-chan int {<br>    out := make(chan int)<br>    go func() {<br>        for n := range in { out &lt;- 2 * n }<br>        close(out)<br>    }()<br>    return out<br>}<br>func main() {<br>    src := gen(2, 3, 4)<br>    sq := square(src)<br>    db := double(sq)<br>    for v := range db { fmt.Println(v) } // 8, 18, 32<br>}</pre><h4>B. Fan‑out / Fan‑in (parallelize work, merge results)</h4><pre>┌── worker1 ──┐<br>[jobs] ──▶─┼── worker2 ──┼──▶ [results]<br>           └── worker3 ──┘</pre><pre>func worker(id int, jobs &lt;-chan int, results chan&lt;- int) {<br>    for j := range jobs {<br>        // pretend work<br>        time.Sleep(50 * time.Millisecond)<br>        results &lt;- j * 2<br>    }<br>}<br>func main() {<br>    jobs := make(chan int)<br>    results := make(chan int)<br>    // start workers<br>    for w := 1; w &lt;= 3; w++ { go worker(w, jobs, results) }<br>    // send jobs<br>    go func() {<br>        for j := 1; j &lt;= 5; j++ { jobs &lt;- j }<br>        close(jobs) // important!<br>    }()<br>    // collect results<br>    for i := 0; i &lt; 5; i++ {<br>        fmt.Println(&lt;-results)<br>    }<br>}</pre><h4>C. Worker pool with graceful shutdown (context)</h4><pre>func startPool(ctx context.Context, n int, in &lt;-chan int) &lt;-chan int {<br>    out := make(chan int)<br>    var wg sync.WaitGroup<br>    wg.Add(n)<br>    worker := func() {<br>        defer wg.Done()<br>        for {<br>            select {<br>            case &lt;-ctx.Done():<br>                return // stop when cancelled<br>            case v, ok := &lt;-in:<br>                if !ok { return } // input closed<br>                out &lt;- v * v<br>            }<br>        }<br>    }<br>    for i := 0; i &lt; n; i++ { go worker() }<br><br>// close out only after all workers finish<br>    go func() { wg.Wait(); close(out) }()<br>    return out<br>}</pre><h4>D. Timeouts &amp; retries</h4><pre>func requestWithTimeout(do func() (string, error), d time.Duration) (string, error) {<br>    type resp struct{ s string; err error }<br>    ch := make(chan resp, 1)<br>    go func() {<br>        s, err := do()<br>        ch &lt;- resp{s, err}<br>    }()<br><br>select {<br>    case r := &lt;-ch:<br>        return r.s, r.err<br>    case &lt;-time.After(d):<br>        return &quot;&quot;, context.DeadlineExceeded<br>    }<br>}</pre><h4>E. Rate limiting with a ticker</h4><pre>limiter := time.NewTicker(100 * time.Millisecond)<br>defer limiter.Stop()<br>for _, job := range jobs {<br>    &lt;-limiter.C // tick allows one job per 100ms<br>    go handle(job)<br>}</pre><h4>F. Semaphores via buffered channels</h4><pre>// Allow at most N concurrent downloads<br>sem := make(chan struct{}, 5)<br>for _, url := range urls {<br>    sem &lt;- struct{}{}<br>    go func(u string) {<br>        defer func() { &lt;-sem }()<br>        download(u)<br>    }(url)<br>}<br>// optional: wait for drain<br>for i := 0; i &lt; cap(sem); i++ { sem &lt;- struct{}{} }</pre><h4>G. The “or‑done” pattern to avoid leaks</h4><p>If a consumer stops early, producers might keep sending and leak goroutines. Use an extra signal channel.</p><pre>func orDone(done &lt;-chan struct{}, c &lt;-chan int) &lt;-chan int {<br>    out := make(chan int)<br>    go func() {<br>        defer close(out)<br>        for {<br>            select {<br>            case &lt;-done:<br>                return<br>            case v, ok := &lt;-c:<br>                if !ok { return }<br>                select {<br>                case out &lt;- v:<br>                case &lt;-done:<br>                    return<br>                }<br>            }<br>        }<br>    }()<br>    return out<br>}</pre><h3>Subtleties &amp; gotchas (read this twice!)</h3><ol><li><strong>Nil channels block forever</strong>: great for disabling select cases.</li><li><strong>Closing a closed channel panics</strong>: design a single closer; often the producer.</li><li><strong>Sending on a closed channel panics</strong>: ensure you close <em>after</em> all sends are done.</li><li><strong>Multiple producers with close</strong>: if many producers exist, use a sync.WaitGroup and let a coordinator close the output <em>once.</em></li><li><strong>Buffered ≠ non‑blocking</strong>: writes still block once buffer is full; reads block when empty.</li><li><strong>Don’t rely on timing</strong>: racey sleeps mask bugs. Use channels/select to synchronize instead.</li><li><strong>Draining matters</strong>: before exiting, drain or signal producers to stop; otherwise goroutines can leak.</li><li><strong>Order of delivery</strong>: channels preserve FIFO order <strong>per sender</strong>; with multiple senders, overall interleaving is not per‑sender deterministic.</li></ol><h3>Channels vs. other sync tools</h3><ul><li><strong>Channels</strong>: move <em>data</em> and synchronize implicitly; great for pipelines, streams, and backpressure.</li><li><strong>sync.Mutex/</strong><strong>RWMutex</strong>: protect shared <em>memory</em>; great when multiple goroutines need read/write access to the same structure.</li><li><strong>sync.WaitGroup</strong>: wait for a set of goroutines to finish; doesn’t move data.</li><li><strong>context.Context</strong>: cancellation, deadlines, and scoped values across API boundaries; pairs well with channels.</li></ul><p><strong>Guideline</strong>: If you’re sharing memory, consider a mutex. If you’re sharing ownership/handing off work, consider a channel.</p><h3>End‑to‑end example: web crawler sketch (cancel‑safe)</h3><pre>// NOTE: demo sketch; handle errors/logging in real code.<br><br>func crawl(ctx context.Context, seeds []string, fetch func(string) ([]string, error)) {<br>    type job struct{ url string; depth int }<br>    const maxDepth = 2<br>jobs := make(chan job)<br>    results := make(chan []string)<br>    // workers<br>    var wg sync.WaitGroup<br>    worker := func() {<br>        defer wg.Done()<br>        for {<br>            select {<br>            case &lt;-ctx.Done():<br>                return<br>            case j, ok := &lt;-jobs:<br>                if !ok { return }<br>                if j.depth &gt;= maxDepth { continue }<br>                links, _ := fetch(j.url)<br>                select {<br>                case results &lt;- links:<br>                case &lt;-ctx.Done():<br>                    return<br>                }<br>            }<br>        }<br>    }<br>    for i := 0; i &lt; 5; i++ { wg.Add(1); go worker() }<br>    // seed<br>    go func() {<br>        defer close(jobs)<br>        for _, s := range seeds { jobs &lt;- job{s, 0} }<br>    }()<br>    // coordinator<br>    go func() { wg.Wait(); close(results) }()<br>    // consume with cancellation awareness<br>    seen := map[string]bool{}<br>    for {<br>        select {<br>        case &lt;-ctx.Done():<br>            return<br>        case links, ok := &lt;-results:<br>            if !ok { return }<br>            for _, u := range links {<br>                if !seen[u] {<br>                    seen[u] = true<br>                    // enqueue next depth<br>                    select {<br>                    case jobs &lt;- job{u, 1}: // simplified depth handling<br>                    case &lt;-ctx.Done():<br>                        return<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>Testing channel code (without flakes)</h3><ul><li>Prefer <strong>deterministic signals</strong> over time.Sleep.</li><li>Use <strong>buffered channels</strong> to avoid deadlocks in tests when the consumer is the test goroutine.</li><li>Use select with a <strong>short timeout</strong> to assert that something <em>doesn’t</em> happen.</li></ul><pre>select {<br>case got := &lt;-ch:<br>    if got != want { t.Fatalf(&quot;got %v want %v&quot;, got, want) }<br>case &lt;-time.After(100 * time.Millisecond):<br>    t.Fatal(&quot;timed out waiting for value&quot;)<br>}</pre><h3>Performance notes</h3><ul><li>Prefer small, <strong>bounded buffers</strong> to match producer/consumer speeds and provide backpressure.</li><li>Avoid excessive goroutines; they’re cheap, not free. Profile with go test -bench and pprof.</li><li>Large messages? Consider passing <strong>pointers</strong> or indices rather than big structs.</li></ul><h3>Cheatsheet</h3><ul><li>Make: make(chan T), make(chan T, N)</li><li>Send/recv: ch &lt;- v, v := &lt;-ch, &lt;-ch</li><li>Close: close(ch) (sender only); detect: v, ok := &lt;-ch</li><li>Range: for v := range ch {}</li><li>Directional: chan&lt;- T, &lt;-chan T</li><li>select: multiple cases, default for non‑blocking, time.After for timeouts</li><li>Disable case: use a <strong>nil</strong> channel</li></ul><h3>Try it yourself</h3><p>Copy any snippet into the <strong>Go Playground</strong> (<a href="https://go.dev/play">https://go.dev/play</a>), tweak values, and observe how blocking changes with buffer sizes and select.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0729d7e5ae3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goroutines in Golang]]></title>
            <link>https://medium.com/@narwar_veer/goroutines-in-golang-d253b54845d1?source=rss-50fe98660542------2</link>
            <guid isPermaLink="false">https://medium.com/p/d253b54845d1</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[go-concurrency]]></category>
            <dc:creator><![CDATA[Harveer Narwar]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 06:05:48 GMT</pubDate>
            <atom:updated>2025-08-08T06:05:48.176Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJ6pjn7fWFu1HdsV7KyrFg.png" /></figure><p>Goroutines are lightweight threads managed by the Go runtime. Think of them as mini-workers that can run functions independently without blocking each other.</p><h3>Concurrency vs Parallelism</h3><p>Let’s begin with two important concepts: <strong>concurrency</strong> and <strong>parallelism</strong>.</p><p>Imagine you’re cooking dinner. You start boiling water (Task 1), and while waiting, you chop vegetables (Task 2). These two tasks don’t necessarily happen <em>at the same time</em> but are managed in a way where you’re not just waiting idly — that’s <strong>concurrency</strong>.</p><p>Now imagine you and your friend are in the kitchen. You boil water, and your friend chops vegetables at the same time. That’s <strong>parallelism</strong> — tasks happening truly simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILXANt7BWYV9Ic7WJ3aQ0w.png" /></figure><p>Golang is designed with <strong>concurrency</strong> as a core strength, and its secret weapon? <strong>Goroutines</strong>.</p><h3>Real-world Analogy</h3><p>Imagine a restaurant kitchen. A single chef trying to cook every dish sequentially is like a program without Goroutines. Now, give the chef multiple assistants who each take on different dishes at the same time — those assistants are Goroutines.</p><p>Each assistant (Goroutine) doesn’t need a new kitchen (system thread) — they share the space efficiently.</p><h3>Basic Example</h3><pre>package main<br>import (<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br>)<br>func sayHello() {<br>    fmt.Println(&quot;Hello from Goroutine!&quot;)<br>}<br>func main() {<br>    go sayHello() // Starts a Goroutine<br>    fmt.Println(&quot;Hello from main function&quot;)<br>    time.Sleep(1 * time.Second) // Wait so the Goroutine can finish<br>}<br><br>/* <br>Output<br>Hello from main function<br>Hello from Goroutine!<br>/*</pre><h4>Explanation</h4><ul><li>go sayHello() starts a new Goroutine.</li><li>The main function does not wait for it unless we add time.Sleep. Without it, the program might exit before the Goroutine runs.</li></ul><p>This shows that Goroutines run <strong>concurrently</strong> with the main function.</p><h3>Goroutines vs Threads</h3><p>Feature Goroutines Threads (Traditional) Memory Overhead ~2KB ~1MB. Managed by Go runtime Operating System Creation Speed Fast (non-blocking) Slower (resource heavy) Count Support Thousands Limited (dozens/hundreds).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*il3oa-Pg_kVG4O2tN4T3AQ.png" /></figure><h3>Common Mistakes with Goroutines</h3><ol><li><strong>Not Waiting for Goroutines to Finish</strong></li></ol><pre>go fmt.Println(&quot;Hello&quot;)<br>// Program might exit before this runs</pre><p><strong>Solution</strong>: Use time.Sleep, sync.WaitGroup, or channels.</p><p><strong>2. Race Conditions</strong></p><pre>var count = 0<br>for i := 0; i &lt; 5; i++ {<br>    go func() {<br>        count++<br>    }()<br>}</pre><p><strong>Problem</strong>: Multiple Goroutines accessing the same variable without coordination.<br> <strong>Fix</strong>: Use mutexes or channels.</p><p><strong>3. Goroutine Leaks</strong></p><p>Leaving Goroutines running indefinitely or waiting for something that never comes can lead to memory issues.</p><h3>How Goroutines Work</h3><p>Here’s a simple conceptual diagram:</p><pre>         +------------------+<br>         |     Main App     |<br>         +------------------+<br>                 |<br>  +--------------+-------------+<br>  |              |             |<br>Goroutine 1   Goroutine 2  Goroutine 3<br>(Function A)  (Function B) (Function C)</pre><p>Each Goroutine runs concurrently, managed by Go’s scheduler, using shared memory efficiently.</p><h3>Best Practices for Using Go routines</h3><ul><li><strong>Use sync.WaitGroup</strong> to wait for multiple Goroutines:</li></ul><pre>var wg sync.WaitGroup<br><br>for i := 0; i &lt; 3; i++ {<br>    wg.Add(1)<br>    go func(i int) {<br>        defer wg.Done()<br>        fmt.Println(&quot;Goroutine&quot;, i)<br>    }(i)<br>}<br>wg.Wait()</pre><p><strong>Avoid race conditions</strong> using:</p><ul><li>sync.Mutex for locking shared resources</li><li><strong>Channels</strong> for communication between Goroutines</li><li><strong>Limit Goroutines</strong>: Too many can overwhelm the system. Use worker pools or semaphores.</li><li><strong>Graceful exits</strong>: Use contexts to cancel Goroutines when no longer needed.</li></ul><h3>Common Misconceptions</h3><ul><li><em>“Goroutines are parallel by default”</em> → Not always, depends on GOMAXPROCS.</li><li><em>“They run instantly”</em> → They are scheduled, so not guaranteed immediate execution.</li><li><em>“They never cause memory issues”</em> → Goroutine leaks are real.</li></ul><h3>Key Takeaways</h3><ul><li>Goroutines are lightweight, concurrent functions managed by Go.</li><li>They make concurrent programming easier and more efficient.</li><li>Always manage synchronization to avoid race conditions or leaks.</li></ul><h3>Want to Learn More?</h3><ul><li><a href="https://blog.golang.org/concurrency-is-not-parallelism">Go Blog: Concurrency is not parallelism</a></li><li><a href="https://gobyexample.com/goroutines">Go by Example — Goroutines</a></li><li><a href="https://go.dev/tour/concurrency/1">Go Tour — Concurrency</a> — Try your code online instantly.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d253b54845d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interfaces in Go]]></title>
            <link>https://medium.com/@narwar_veer/interfaces-in-go-bd29a3a2a9a3?source=rss-50fe98660542------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd29a3a2a9a3</guid>
            <category><![CDATA[golang-interface]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go-programming]]></category>
            <category><![CDATA[golang-development]]></category>
            <dc:creator><![CDATA[Harveer Narwar]]></dc:creator>
            <pubDate>Thu, 07 Aug 2025 11:40:09 GMT</pubDate>
            <atom:updated>2025-08-07T11:40:09.636Z</atom:updated>
            <content:encoded><![CDATA[<p>Interfaces in Go allow you to define behavior (methods) without specifying exactly how this behavior should be implemented. It enables flexibility, abstraction, and cleaner code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_w3uONvHgFOIkL7Pw272xA.png" /></figure><h3>What is an Interface?</h3><ul><li>An <strong>interface</strong> is a collection of method signatures.</li><li>A <strong>type</strong> implements an interface if it defines all methods specified by the interface.</li></ul><p><strong>Syntax:</strong></p><pre>type InterfaceName interface {<br>    Method1() ReturnType<br>    Method2(param Type) ReturnType<br>}</pre><h3>Simple Example:</h3><p>Consider a simple example of a Shape interface:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;math&quot;<br>)<br><br>// Interface definition<br>type Shape interface {<br>    Area() float64<br>}<br><br>// Struct Circle implements Shape<br>type Circle struct {<br>    Radius float64<br>}<br><br>func (c Circle) Area() float64 {<br>    return math.Pi * c.Radius * c.Radius<br>}<br><br>// Struct Rectangle implements Shape<br>type Rectangle struct {<br>    Width, Height float64<br>}<br><br>func (r Rectangle) Area() float64 {<br>    return r.Width * r.Height<br>}<br><br>func main() {<br>    shapes := []Shape{<br>        Circle{Radius: 5},<br>        Rectangle{Width: 4, Height: 6},<br>    }<br><br>    for _, shape := range shapes {<br>        fmt.Println(&quot;Area:&quot;, shape.Area())<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>Area: 78.53981633974483<br>Area: 24</pre><h3>Key Features of Interfaces:</h3><ul><li>Provide <strong>abstraction and polymorphism</strong>.</li><li>Enable <strong>loose coupling</strong> between components.</li><li>Allow easy <strong>mocking</strong> and testing.</li></ul><h3>Important Points to Remember:</h3><ul><li>Interfaces define <strong>what</strong> to do, not <strong>how</strong>.</li><li>An interface can hold any type implementing its methods.</li><li>Implementation is implicit — no need for a keyword like implements.</li></ul><h3>Example: Database Connection Interface</h3><p>A common real-world scenario: using interfaces for database connections:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// DB interface for abstraction<br>type DB interface {<br>    Connect() error<br>    Close() error<br>}<br><br>// MySQL implementation<br>type MySQL struct{}<br><br>func (m MySQL) Connect() error {<br>    fmt.Println(&quot;MySQL connected.&quot;)<br>    return nil<br>}<br><br>func (m MySQL) Close() error {<br>    fmt.Println(&quot;MySQL connection closed.&quot;)<br>    return nil<br>}<br><br>// PostgreSQL implementation<br>type PostgreSQL struct{}<br><br>func (p PostgreSQL) Connect() error {<br>    fmt.Println(&quot;PostgreSQL connected.&quot;)<br>    return nil<br>}<br><br>func (p PostgreSQL) Close() error {<br>    fmt.Println(&quot;PostgreSQL connection closed.&quot;)<br>    return nil<br>}<br><br>// Application logic (independent of specific database)<br>func initializeDatabase(db DB) {<br>    db.Connect()<br>    defer db.Close()<br>}<br><br>func main() {<br>    mysql := MySQL{}<br>    postgres := PostgreSQL{}<br><br>    initializeDatabase(mysql)<br>    initializeDatabase(postgres)<br>}</pre><p><strong>Output:</strong></p><pre>MySQL connected.<br>MySQL connection closed.<br>PostgreSQL connected.<br>PostgreSQL connection closed.</pre><h3>Flow Diagram:</h3><pre>      ┌───────────────────┐<br>      │    Interface      │<br>      │ (defines methods) │<br>      └─────────┬─────────┘<br>                │<br>    ┌───────────┴───────────┐<br>    │                       │<br>    ▼                       ▼<br>┌───────────┐          ┌───────────┐<br>│ Struct A  │          │ Struct B  │<br>│(implements│          │(implements│<br>│ interface)│          │ interface)│<br>└───────────┘          └───────────┘</pre><h3>Advantages of Using Interfaces:</h3><ul><li><strong>Code Reusability:</strong> Define common behavior once, use many times.</li><li><strong>Flexibility:</strong> Change implementation without modifying usage.</li><li><strong>Testability:</strong> Easier to test components independently.</li></ul><h3>Common Mistakes with Interfaces:</h3><ul><li>Defining too many small interfaces unnecessarily.</li><li>Creating overly broad or large interfaces that reduce readability.</li></ul><h3>FAQs</h3><p><strong>1. Can an interface hold different data types?</strong><br> Yes, an interface can store any type that implements its methods.</p><p><strong>2. Do we need to explicitly declare that a type implements an interface?</strong><br> No, Go automatically recognizes types that match interface methods.</p><p><strong>3. What is an empty interface?</strong><br> interface{} is an empty interface in Go, which any type can implement. It&#39;s useful when you need a function that accepts parameters of unknown types.</p><h3>Conclusion</h3><p>Interfaces in Go are powerful tools for writing clean, maintainable, and efficient code. Leveraging interfaces allows developers to design robust and flexible software components with ease.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd29a3a2a9a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structs in Golang]]></title>
            <link>https://medium.com/@narwar_veer/structs-in-golang-3b746b5641c1?source=rss-50fe98660542------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b746b5641c1</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang-struct]]></category>
            <category><![CDATA[struct]]></category>
            <dc:creator><![CDATA[Harveer Narwar]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 04:38:39 GMT</pubDate>
            <atom:updated>2025-08-06T04:38:39.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0spZRIcXGUtYrbrncVZVw.png" /></figure><p>Today we’ll explore an essential concept in Go called “<strong>structs”</strong>. Structs allow you to group different types of data into a single, organized unit, making your programs clearer and more efficient.</p><h3>What is a Struct?</h3><p>Think of a struct as a container for related data. For instance, a person can have a name, age, and email — all stored neatly in a struct.</p><h3>Defining a Struct</h3><p>Here’s how you define a simple struct in Go:</p><pre>type Person struct {<br>    Name  string<br>    Age   int<br>    Email string<br>}</pre><h3>Creating and Using Structs</h3><p><strong>Initialization Method 1:</strong></p><pre>var p Person<br>p.Name = &quot;Veer&quot;<br>p.Age = 30<br>p.Email = &quot;veer@example.com&quot;</pre><p><strong>Initialization Method 2 (Struct Literal):</strong></p><pre>p := Person{<br>    Name:  &quot;Veer&quot;,<br>    Age:   30,<br>    Email: &quot;veer@example.com&quot;,<br>}</pre><h3>Accessing Struct Fields</h3><p>You can access or modify struct fields easily using the dot operator:</p><pre>fmt.Println(p.Name) // Veer<br>p.Age = 22</pre><h3>Anonymous Structs</h3><p>Useful for temporary data structures:</p><pre>temp := struct {<br>    Name string<br>    ID   int<br>}{<br>    Name: &quot;Narwar&quot;,<br>    ID:   123,<br>}<br><br>fmt.Println(temp.Name, temp.ID) <br>// Output: Veer, 22</pre><h3>Nested Structs</h3><p>Structs can contain other structs to model more complex relationships:</p><pre>type Address struct {<br>    City    string<br>    Country string<br>}</pre><pre>type Person struct {<br>    Name    string<br>    Address Address<br>}</pre><pre>p := Person{<br>    Name: &quot;Veer&quot;,<br>    Address: Address{<br>        City:    &quot;New Delhi&quot;,<br>        Country: &quot;India&quot;,<br>    },<br>}</pre><pre>fmt.Println(p.Name, &quot;lives in&quot;, p.Address.City)</pre><pre>// output: Veer lives in New Delhi</pre><h3>Struct Methods</h3><p>Structs can have methods, which define behaviors associated with them:</p><pre>type Rectangle struct {<br>    Width, Height float64<br>}</pre><pre>func (r Rectangle) Area() float64 {<br>    return r.Width * r.Height<br>}</pre><pre>rect := Rectangle{Width: 5, Height: 4}<br>fmt.Println(&quot;Area:&quot;, rect.Area())</pre><h3>Pointers to Structs</h3><p>Struct pointers let you modify structs directly:</p><pre>type Car struct {<br>    Model string<br>}</pre><pre>func updateModel(c *Car, newModel string) {<br>    c.Model = newModel<br>}</pre><pre>myCar := Car{Model: &quot;BMW&quot;}<br>updateModel(&amp;myCar, &quot;Tesla&quot;)<br>fmt.Println(myCar.Model) // Tesla</pre><h3>Summary</h3><p>Structs are versatile, useful tools in Go that help you structure your data clearly. Keep practicing with them, and they’ll soon become second nature!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b746b5641c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slices in Golang]]></title>
            <link>https://medium.com/@narwar_veer/slices-in-golang-0afebbf41133?source=rss-50fe98660542------2</link>
            <guid isPermaLink="false">https://medium.com/p/0afebbf41133</guid>
            <category><![CDATA[go-slices]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Harveer Narwar]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 08:37:35 GMT</pubDate>
            <atom:updated>2025-08-05T08:37:35.754Z</atom:updated>
            <content:encoded><![CDATA[<p>Slices are one of the most powerful and widely-used features in Golang. They provide a dynamic, flexible way to handle collections of elements.</p><h3>What are Slices?</h3><p>Slices in Go are dynamically-sized, flexible views into the elements of an array. They are more common than arrays because they can change size easily and efficiently.</p><ul><li><strong>Arrays</strong> have fixed size.</li><li><strong>Slices</strong> are flexible and can grow or shrink as needed.</li></ul><h3>How to Create a Slice?</h3><p>Here’s how you can create a slice from an array:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    // Initialize an array with 5 elements<br>    arr := [5]int{1, 2, 3, 4, 5}<br><br>    slice := arr[1:4] // This means elements at index 1, 2, and 3 =&gt; [2, 3, 4]<br><br>    fmt.Println(slice) // Output: [2 3 4]<br>}</pre><h3>Most Common Slice Operations</h3><h4>1. Appending Elements</h4><p>You can add elements to a slice easily using append():</p><pre>slice := []int{1, 2, 3}        // Create a slice with 3 elements<br>slice = append(slice, 4)      // Add the value 4 to the end of the slice<br>fmt.Println(slice)            // Output: [1 2 3 4]</pre><h4>2. Copying Slices</h4><p>Use the built-in copy() function to copy elements from one slice to another:</p><pre>src := []int{1, 2, 3}               // Source slice<br><br>// Create a destination slice with the same length as src<br>// make() creates a slice of integers with length = len(src)<br>dest := make([]int, len(src))      <br><br>copy(dest, src)                    // Copy elements from src to dest<br>fmt.Println(dest)                  // Output: [1 2 3]</pre><h4>3. Deleting Elements</h4><p>To delete an element from a slice, you can use slicing along with append():</p><pre>slice := []int{1, 2, 3, 4, 5}           // Original slice<br><br>// Delete the element at index 2 (which is 3)<br>// Take elements before index 2 (slice[:2] = [1, 2])<br>// and append them with elements after index 2 (slice[3:] = [4, 5])<br>slice = append(slice[:2], slice[3:]...)<br><br>fmt.Println(slice) // Output: [1 2 4 5]</pre><pre>Array: [1 | 2 | 3 | 4 | 5]<br>            |___|<br>Slice:        [2 | 3]</pre><h4>4. Slicing a Slice</h4><p>You can create a new slice by slicing an existing slice:</p><pre>slice := []int{1, 2, 3, 4, 5}    // Original slice<br>newSlice := slice[1:3]          // Get elements from index 1 to 2 =&gt; [2, 3]<br>fmt.Println(newSlice)           // Output: [2 3]</pre><pre>Array: [1 | 2 | 3 | 4 | 5]<br>            |___|<br>Slice:        [2 | 3]</pre><h3>Important Points to Remember</h3><ul><li>Slices point to an underlying array.</li><li>Modifying the slice can affect the array.</li><li>Slices have length (len()) and capacity (cap()).</li></ul><pre>slice := []int{1, 2, 3}       // Create a slice<br>fmt.Println(len(slice))      // Output: 3 =&gt; number of elements<br>fmt.Println(cap(slice))      // Output: 3 =&gt; capacity (same as length here)</pre><h3>Quick Recap:</h3><ul><li>Slices provide dynamic arrays.</li><li>Use append() to add elements.</li><li>Use copy() to duplicate slices.</li><li>Use slicing to delete or extract sub-slices.</li><li>Understand length and capacity for optimal usage.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0afebbf41133" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>