<?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[A Beginner’s Roadmap to Readable C# Code - Medium]]></title>
        <description><![CDATA[Writing code is an art, and like any art form, it can range from a chaotic, messy canvas to a masterpiece of clarity and structure. We start here with Tips for fundamental improving C# readability. - Medium]]></description>
        <link>https://medium.com/a-beginners-roadmap-to-readable-c-code?source=rss----69094f5363f7---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>A Beginner’s Roadmap to Readable C# Code - Medium</title>
            <link>https://medium.com/a-beginners-roadmap-to-readable-c-code?source=rss----69094f5363f7---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:38:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/a-beginners-roadmap-to-readable-c-code" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Master the Art of Decoupled Communication: Pub/Sub in Action]]></title>
            <link>https://medium.com/a-beginners-roadmap-to-readable-c-code/master-the-art-of-decoupled-communication-pub-sub-in-action-b2a0700beb58?source=rss----69094f5363f7---4</link>
            <guid isPermaLink="false">https://medium.com/p/b2a0700beb58</guid>
            <dc:creator><![CDATA[Riddhi Shah]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 22:09:56 GMT</pubDate>
            <atom:updated>2025-04-12T22:08:32.680Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Imagine you’re building a modern, distributed application where multiple components need to communicate efficiently without tightly coupling them together. You want each component to operate independently, scale easily, and evolve without impacting others. How can this be achieved elegantly? Enter the Publish/Subscribe (Pub/Sub) pattern — a powerful messaging paradigm that promotes seamless, asynchronous communication among system components. In this article, we’ll explore what Pub/Sub is, why it’s essential, and how you can implement it effectively using C#.</p><h3>Table of Content</h3><ol><li>Core Concepts and Components</li><li>How the Pub/Sub Pattern Works</li><li>Relevance in Microservices Architecture</li><li>Key Design Considerations <br> — Scalability <br> — Reliability</li><li>Subscriber Management and Message Routing</li><li>Quality of Service (QoS) Levels</li><li>Advantages of Pub/Sub</li><li>Potential Drawbacks</li><li>C# Implementation of Pub/Sub Using Events and Delegates</li><li>Conclusion</li><li>References</li></ol><h3><strong>Core Concepts and Components</strong></h3><ul><li><strong>Publisher:</strong> An entity that sends out messages. It doesn’t know which subscribers (if any) will receive the message. It simply publishes the message to a central point, often associated with a specific “topic” or “channel”.</li><li><strong>Subscriber:</strong> An entity that expresses interest in receiving messages of a particular type or topic. It subscribes to these topics via a central mechanism and receives messages published to those topics without knowing who the publisher is.</li><li><strong>Message Broker / Event Aggregator / Hub:</strong> A central intermediary that manages the routing of messages from publishers to interested subscribers. Publishers send messages here, and subscribers register their interest here. This component decouples publishers and subscribers.</li><li><strong>Topic / Channel / Event Type:</strong> Messages are typically categorized using topics or types. Publishers send messages to specific topics, and subscribers express interest in specific topics. Topics provide a way to decouple the production and consumption of messages, allowing multiple publishers to send messages to the same topic and multiple subscribers to receive messages from the same topic independently. This decoupling enables greater scalability and flexibility in the system.</li></ul><h3><strong>How Pub/Sub Works</strong></h3><ol><li>Subscribers register their interest in specific message types or topics with the central message broker or hub.</li><li>A publisher sends a message related to a specific topic to the broker/hub.</li><li>The broker/hub identifies all subscribers who have registered interest in that topic.</li><li>The broker/hub forwards the message to all interested subscribers.</li><li>Subscribers receive the message and process it accordingly.</li></ol><h3><strong>Relevance in Microservice Architecture</strong></h3><p>The pub/sub model is particularly relevant in the context of microservices architecture. It enables services to communicate asynchronously and react to events, leading to highly responsive and flexible systems. By decoupling services, Pub/Sub allows individual microservices to be developed, deployed, and scaled independently, reacting to events from other services without requiring direct synchronous communication.</p><h3><strong>Key Design Considerations for Pub/Sub Systems</strong></h3><p>Let us now learn about some of the design considerations in building a pub/sub system. When architecting a pub/sub system, two pivotal factors that warrant meticulous attention are scalability and reliability. These elements are the cornerstones of ensuring that the system not only accommodates high volumes of messages seamlessly but also maintains unwavering performance regardless of varying operational loads.</p><p><strong>Scalability</strong></p><p>Scalability is the system’s ability to gracefully handle increases in workload without compromising performance. In a pub/sub context, this translates to effectively managing an escalating number of messages and subscribers. Let us look at scalability aspects of pub/sub systems:</p><ul><li><strong>Horizontal versus Vertical Scaling:</strong> This critical decision determines the scaling strategy. Horizontal scaling (adding more machines) offers enhanced flexibility and robustness, aligning with fluctuating demands. Vertical scaling (bolstering existing machines) might be simpler short-term but often lacks the long-term scalability and resilience of horizontal scaling.</li><li><strong>Dynamic Load Balancing:</strong> In pub/sub systems, load balancing is typically handled by message brokers to distribute the load across subscribers within a subscriber group. The aim is to decouple the concerns of production and consumption load distribution from publishers and subscribers. By distributing the load across multiple brokers, the system can achieve increased scalability and stability, ensuring no single node becomes a bottleneck.</li><li><strong>Topic Partitioning:</strong> This technique involves dividing topics into smaller, more manageable partitions. Topics can be created dynamically and provide varying levels of granularity. This division facilitates load distribution across the system and enhances throughput by spreading the workload across multiple nodes.</li></ul><p><strong>Reliability</strong></p><p>Reliability in a pub/sub system is pivotal for ensuring consistent operation and trustworthiness, particularly in handling message delivery and system resilience. Here are the design decisions to consider:</p><ul><li><strong>Message Delivery Guarantees:</strong> Implementing varying levels of delivery guarantees is fundamental. Options such as <em>at-most-once</em>, <em>at-least-once</em>, or <em>exactly-once</em> delivery provide different assurances depending on the criticality of the message, defining how the system handles potential data loss or duplication.</li><li><strong>Fault Tolerance:</strong> Designing for fault tolerance involves strategies such as replicating data across different nodes and implementing message re-delivery mechanisms. This ensures the system remains operational even in the face of component failures.</li><li><strong>Message Ordering:</strong> For applications where the sequence of messages is crucial, ensuring correct message order is key. This involves designing the system to maintain the chronological integrity of messages, which can be challenging in distributed environments.</li></ul><p>In essence, these considerations of scalability and reliability form the backbone of a well-designed pub/sub system, creating a resilient, efficient, and future-proof messaging infrastructure.</p><h3><strong>Subscriber Management and Message Routing</strong></h3><p>Managing subscribers and efficiently routing messages to them are vital components of a pub/sub system. This involves:</p><ul><li><strong>Subscriber Registration and Management:</strong> Handling the process by which subscribers can register, deregister, and manage their topic subscriptions.</li><li><strong>Efficient Message Routing:</strong> Developing algorithms to ensure that messages are routed to the right subscribers in the most efficient way, minimizing latency and resource usage.</li></ul><h3><strong>Quality of Service (QoS) Levels</strong></h3><p>Different applications require different levels of Quality of Service (QoS). Some systems might need guaranteed delivery (at-least-once or exactly-once), prioritizing data integrity. Others might prioritize lower latency over absolute delivery guarantees (at-most-once), accepting potential message loss for faster communication. The choice depends on the specific needs of the application.</p><h3><strong>Advantages of Using Pub/Sub</strong></h3><ul><li><strong>Loose Coupling:</strong> Reduces dependencies between components.</li><li><strong>Scalability:</strong> Facilitates easier scaling by adding/removing publishers/subscribers independently.</li><li><strong>Flexibility &amp; Modularity:</strong> Allows components to evolve independently.</li><li><strong>Reliability:</strong> Brokers often provide mechanisms for reliable message delivery.</li><li><strong>Responsiveness &amp; Asynchronicity:</strong> Enables asynchronous communication, improving system responsiveness.</li></ul><h3><strong>Potential Drawbacks</strong></h3><ul><li><strong>Complexity:</strong> Introduces a message broker/hub as an additional component.</li><li><strong>Latency:</strong> Can introduce slight delays compared to direct calls.</li><li><strong>Single Point of Failure:</strong> The broker can be a bottleneck if not made highly available.</li><li><strong>Message Ordering:</strong> Guaranteeing strict message order can be complex in distributed systems.</li><li><strong>Debugging:</strong> Tracing message flow across decoupled components can be more challenging.</li></ul><h3><strong>C# Implementation of Pub/Sub Using Events and Delegates</strong></h3><p>To better understand how the Pub/Sub model works in practice, I created toy examples in C# using the native event and delegate system. These examples model real-world communication patterns — one-to-many, many-to-one, and many-to-many — while staying small and focused for clarity. The goal is to show how decoupled messaging can be implemented in a lightweight way, without needing external libraries or infrastructure.</p><p><strong>One-to-Many Communication</strong></p><p><strong>Real-World Analogy:</strong> A single news broadcaster shares updates, and multiple subscribers receive the message.</p><p>In this example, one publisher (Broadcaster) raises an event, and multiple subscribers (Listeners) are notified.</p><pre>public class Broadcaster<br>{<br>    public event Action&lt;string&gt; OnMessagePublished;<br><br>    public void Publish(string message)<br>    {<br>        OnMessagePublished?.Invoke(message);<br>    }<br>}<br><br>public class Listener<br>{<br>    public Listener(Broadcaster broadcaster)<br>    {<br>        broadcaster.OnMessagePublished += HandleMessage;<br>    }<br><br>    private void HandleMessage(string message)<br>    {<br>        Console.WriteLine($&quot;Listener received: {message}&quot;);<br>    }<br>}</pre><p>To simulate this, you can instantiate one Broadcaster and several Listener objects that subscribe to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ln66b4EgwaVQtG_3169Gug.png" /><figcaption>One-To-Many Communication</figcaption></figure><p><strong>Many-to-One Communication</strong></p><p><strong>Real-World Analogy:</strong> Multiple IoT sensors send their readings to a central server.</p><p>In this example, multiple Client instances each send messages to a shared Server that handles all incoming messages.</p><pre>public class Server<br>{<br>    public void HandleMessage(string message, string senderId)<br>    {<br>        Console.WriteLine($&quot;Server received from {senderId}: {message}&quot;);<br>    }<br>}<br><br>public class Client<br>{<br>    private readonly string _id;<br>    private readonly Action&lt;string, string&gt; _sendAction;<br><br>    public Client(string id, Action&lt;string, string&gt; sendAction)<br>    {<br>        _id = id;<br>        _sendAction = sendAction;<br>    }<br><br>    public void Send(string message)<br>    {<br>        _sendAction.Invoke(message, _id);<br>    }<br>}</pre><p>Each Client is initialized with a reference to the server’s message handler and invokes it when sending data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6tAdO6jYcfO7MOn_SI2Cg.png" /><figcaption>Many-To-One Communication</figcaption></figure><p><strong>Many-to-Many Communication (with Topic Filtering)</strong></p><p><strong>Real-World Analogy:</strong> In a chat application, users send messages tagged by topic. Listeners only receive messages for the topics they’ve subscribed to.</p><p>In this example, a shared EventHub manages topic-based subscriptions and routes messages to the right subscribers.</p><pre>public static class EventHub<br>{<br>    private static readonly Dictionary&lt;string, Action&lt;string&gt;&gt; SubscribersByTopic = new();<br><br>    public static void Subscribe(string topic, Action&lt;string&gt; handler)<br>    {<br>        if (SubscribersByTopic.ContainsKey(topic))<br>            SubscribersByTopic[topic] += handler;<br>        else<br>            SubscribersByTopic[topic] = handler;<br>    }<br><br>    public static void Publish(string topic, string message)<br>    {<br>        if (SubscribersByTopic.TryGetValue(topic, out var handlers))<br>            handlers.Invoke(message);<br>    }<br>}</pre><p>Each topic has its own set of subscribers, and only those subscribed to a given topic will receive messages published under it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CmRBvi3uZ3R_nZjOdNnzBg.png" /><figcaption>Many-To-Many Communication</figcaption></figure><h3>Conclusion</h3><p>Publish/Subscribe is more than just a messaging pattern — it’s a mindset shift toward decoupled, flexible systems that are easier to scale, test, and maintain. Whether you’re building a simple desktop app or a distributed microservices backend, understanding how Pub/Sub works at a fundamental level helps you make better architecture decisions.</p><p>In this article, we walked through the concepts, design considerations, and real-world C# implementations of one-to-many, many-to-one, and many-to-many communication using events and delegates. While these are simplified toy examples, they demonstrate how much power and clarity you can get from a decoupled messaging model — even without a full-blown message broker.</p><p>If you’re just starting out, building these patterns in a language like C# is a great way to learn before moving on to enterprise-grade tools like RabbitMQ, Azure Service Bus, or Kafka.</p><h3><strong>References</strong></h3><ol><li><a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/publisher-subscriber">Publisher-Subscriber pattern</a></li><li><a href="https://www.c-sharpcorner.com/UploadFile/pranayamr/publisher-or-subscriber-pattern-with-event-or-delegate-and-e/">Publisher/Subscriber Pattern With Event /Delegate and EventAggregator</a></li><li><a href="https://github.com/Ashahet1/C-Project/tree/master/PubSubEventDelegate">GitHub Repo</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2a0700beb58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/a-beginners-roadmap-to-readable-c-code/master-the-art-of-decoupled-communication-pub-sub-in-action-b2a0700beb58">Master the Art of Decoupled Communication: Pub/Sub in Action</a> was originally published in <a href="https://medium.com/a-beginners-roadmap-to-readable-c-code">A Beginner’s Roadmap to Readable C# Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Starting Strong: A Beginner’s Roadmap to Readable C# Code]]></title>
            <link>https://medium.com/a-beginners-roadmap-to-readable-c-code/starting-strong-a-beginners-roadmap-to-readable-c-code-a8b534b3b070?source=rss----69094f5363f7---4</link>
            <guid isPermaLink="false">https://medium.com/p/a8b534b3b070</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <dc:creator><![CDATA[Riddhi Shah]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 20:51:10 GMT</pubDate>
            <atom:updated>2023-10-19T02:00:28.501Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Chapter 1: The Art of Writing Readable Code</strong></p><p>In the realm of software development, writing code is an art, and like any art form, it can range from a chaotic, messy canvas to a masterpiece of clarity and structure. While there are countless programming languages to choose from, C# stands out as a versatile and powerful language for creating a wide range of applications, from desktop software to web applications and games.</p><p><strong>The Importance of Readable Code</strong></p><p>Most developers, including myself, initially prioritize making code functional, often neglecting considerations of readability and structure. Bad code impedes programmers and makes work more difficult. However, programmers often write bad, non-readable code themselves when rushed, tired, or prioritizing speed over quality. This leads to technical debt that slows future work.</p><p>It took me some time to fully appreciate the importance of code that not only functions correctly but is also easy to understand and maintain. With this newfound insight, I’m committed to laying a strong foundation for those who are just beginning their journey into C# development, equipping beginners with the essential knowledge and tips needed to write clean, structured, and readable code.</p><p><strong>Tips for Writing Readable C# Code</strong></p><p><strong>Tip #1: Meaningful Names and Naming Conventions</strong></p><p>Names are everywhere in software. We name our variables, our functions, our methods, our properties, our arguments, classes, and packages. We name our source files and the directories that contain them.</p><p>Use Intention-Revealing Names</p><p>I know it is easy to say that names should reveal intent, but in fact, choosing good names takes time but saves more time when someone else reads your code.</p><p>Some of the common traps people often use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHjKLbJuJbu9pFxZWnOXpQ.png" /></figure><p>The name ‘d’ or ‘result’ or ‘variable’ reveals nothing. It does not evoke a sense of elapsed time or data trigger. We should choose a name that specifies what is being measured and the unit of that measurement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPk_lejBck3nyAG4l502ew.png" /></figure><p>One such example, I ran into something similar myself where I defined a struct named FileData as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ub8WNwpwoKr_zyHyrMXVeA.png" /></figure><p>Also,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PULILeuW9IiAdj_kd54hig.png" /></figure><p>During a code review, I realized that ‘columnNames’ did not follow the Property Rule as well.</p><p><strong>So, be specific with the intent of the name and to keep in mind following naming conventions:</strong></p><p>Parameter Property rule follows the CamelCase naming convention, such as ‘dataTrigger.’</p><p>Instance field rule is different for data modifier:</p><p>Public: you need to have ‘Pmbus.’</p><p>Private: you need to have ‘_pmbus.’</p><p>Method Property rule follows the PascalCase naming convention, such as ‘DataTrigger.’</p><p><strong>Tip #2: Understand CultureInfo for Formatting and Parsing</strong></p><p>In .NET, `CultureInfo` plays a pivotal role when dealing with string representations of numbers, dates, and other culture-sensitive data. Let’s dive deeper into its significance:</p><p>CultureInfo.InvariantCulture: This option ensures consistent formatting and parsing in a culture-independent manner. It acts as a universal format that remains the same regardless of the user’s locale or culture settings. For example, using `CultureInfo.InvariantCulture`, a decimal number like 1234.56 will always be represented as “1234.56” when converted to a string, irrespective of the user’s locale or culture settings.</p><p>CultureInfo.CurrentCulture: This option adapts to the user’s system preferences and culture settings, providing a user-friendly experience. For instance, if the user’s system culture is set to “fr-FR” (French — France), using `CultureInfo.CurrentCulture` will format numbers and dates in the French style, making the application more user-centric.</p><p>The choice between these two options depends on your specific context and requirements. Use `CultureInfo.InvariantCulture` when you want consistent and culture-independent data representation, which is especially useful when dealing with file formats or data exchange. On the other hand, opt for `CultureInfo.CurrentCulture` when you want to provide a user-friendly experience that respects the user’s system preferences and culture settings.</p><p><strong>Tip #3: Leverage the Ternary Operator for Concise Conditionals</strong></p><p>The ternary operator is a powerful and concise way to handle simple conditional statements in your code. It simplifies decision-making and enhances code readability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_iBmSVKHG2zmDlfGvzSsA.png" /></figure><p>I hope you’ve found this helpful on your journey to becoming a proficient C# developer. By following these tips, you’ll not only create code that works but also code that is clear, maintainable, and a joy for other developers to read. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8b534b3b070" width="1" height="1" alt=""><hr><p><a href="https://medium.com/a-beginners-roadmap-to-readable-c-code/starting-strong-a-beginners-roadmap-to-readable-c-code-a8b534b3b070">Starting Strong: A Beginner’s Roadmap to Readable C# Code</a> was originally published in <a href="https://medium.com/a-beginners-roadmap-to-readable-c-code">A Beginner’s Roadmap to Readable C# Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>