<?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 Omair Al Aktaa on Medium]]></title>
        <description><![CDATA[Stories by Omair Al Aktaa on Medium]]></description>
        <link>https://medium.com/@omair.alaktaa?source=rss-108584afa82c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JLKrd_yQ4AnRYtLRoeXGMg.png</url>
            <title>Stories by Omair Al Aktaa on Medium</title>
            <link>https://medium.com/@omair.alaktaa?source=rss-108584afa82c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:44:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omair.alaktaa/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[Understanding Service Mesh: Why Your Microservices Need a Traffic Police]]></title>
            <link>https://medium.com/@omair.alaktaa/understanding-service-mesh-why-your-microservices-need-a-traffic-police-a342563c74e8?source=rss-108584afa82c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a342563c74e8</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Omair Al Aktaa]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 18:20:38 GMT</pubDate>
            <atom:updated>2026-06-21T18:20:38.645Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Service Mesh</h3><h4>Why Your Microservices Need a Traffic Police</h4><h3>1. Introduction</h3><p>Imagine you are managing a growing city.</p><ul><li>Every <strong>building</strong> is a microservice.</li><li>Every <strong>road carries </strong>requests between services.</li><li>Every <strong>car </strong>represents a network request.</li><li>Every traffic light controls how traffic flows.</li><li>Every <strong>security checkpoint</strong> verifies identities.</li></ul><p>When the city only has a few buildings, everything works smoothly.</p><p>But as the city grows to hundreds of buildings, traffic becomes chaotic. Cars get lost, accidents happen, roads become congested, and it becomes difficult to monitor everything.</p><p>This is exactly what happens in a microservices architecture.</p><h3>2. What is a Service Mesh?</h3><p>A <strong>Service Mesh</strong> acts like the city’s intelligent traffic management system. It controls communication between services, secures every connection, monitors traffic, and enforces rules without requiring developers to change their application code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*en18oO3wTed1BLZjo562Qw.png" /></figure><h3>3. Why Do We Need Service Mesh?</h3><p>In a microservices architecture, every service communicates over the network. Without a Service Mesh, developers often need to implement networking features such as retries, load balancing, TLS encryption, authentication, authorization, logging, metrics, and tracing inside every application.</p><p>Now imagine maintaining these features across hundreds of microservices. A Service Mesh removes these responsibilities from the application and centralizes them in the infrastructure, allowing developers to focus on business logic instead.</p><h3>4. Think Like a City</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*lKV26MQ7YWgFnfyT5JhCZg.png" /></figure><p>Just as a city manages traffic without requiring every driver to coordinate with others, a Service Mesh manages communication between services so applications can focus solely on their business logic.</p><blockquote>The applications don’t need to worry about traffic anymore because the “city” manages it.</blockquote><h3>5. Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eqwBdV2aaG2j3-cHUoplsQ.png" /></figure><h4>5.1 Core Components</h4><p>A service mesh consists of:<br>- Data Plane: Handles actual traffic typically implemented using sidecar proxies.<br>- Control Plane: Configures and manages the proxies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*dyV4egl7fcR3f1UfN0YexA.png" /></figure><h4>5.2 Data Plane and Sidecar Proxies</h4><p>Each service instance usually has a sidecar proxy such as Envoy Proxy. Traffic flows through the proxies instead of directly between services. This allows centralized control over retries, security, and monitoring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*S4lcb45LFQnMPW7hL6ZBxw.png" /></figure><h4>5.3 Control Plane</h4><p>The control plane distributes configuration and policies to proxies. It manages routing rules, certificates, security policies, observability settings, and service discovery.</p><h3>6. Security Flow</h3><p>A Service Mesh secures communication by routing every request through Envoy sidecar proxies. These proxies authenticate services, establish encrypted mTLS connections, enforce authorization policies, and collect observability data such as metrics, logs, and traces. As a result, security and monitoring are applied consistently without modifying application code.</p><h3>7. Key Features</h3><h4>7.1 Traffic Management</h4><p>A Service Mesh provides intelligent traffic control, including load balancing, retries, timeouts, circuit breaking, and advanced deployment strategies such as Canary and Blue-Green deployments.</p><h4>7.2 Security</h4><p>Security is built into the mesh through mutual TLS (mTLS), authentication, authorization policies, SPIFFE identities, and Zero Trust networking.</p><h4>7.3 Observability</h4><p>Without modifying application code, the mesh automatically collects metrics, logs, and distributed traces, making it easier to monitor and troubleshoot services.</p><h4>7.4 Policy Enforcement</h4><p>Centralized policies allow administrators to enforce rate limits, role-based access control (RBAC), quotas, and other governance rules consistently across all services.</p><h3>8. Performance Trade-off</h3><p>Nothing is free… Adding Envoy introduces:</p><ul><li>extra network hops</li><li>encryption overhead</li><li>CPU usage</li><li>memory usage</li></ul><p>Usually:</p><blockquote><em>2-10 ms latency per request (depending on workload) and additional CPU/memory per proxy.</em></blockquote><p>Many organizations accept this cost because of the operational and security benefits.</p><h3>9. Modern Service Mesh</h3><p>One proxy protects many applications.</p><p>Benefits:</p><ul><li>Lower CPU</li><li>Lower Memory</li><li>Faster startup</li><li>Easier operations</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*ATnrcJm0dQOfehbfkueqoA.png" /></figure><h3>10. Conclusion</h3><p>A Service Mesh is like an intelligent city traffic system for your applications.</p><p>Applications remain focused on business logic, while the Service Mesh manages the roads, traffic lights, security checkpoints, and surveillance systems.</p><p>As your microservices ecosystem grows, this separation becomes one of the most valuable architectural decisions you can make.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a342563c74e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Clean Code Part 6]]></title>
            <link>https://medium.com/@omair.alaktaa/mastering-clean-code-part-6-3b7c3bcf39ff?source=rss-108584afa82c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b7c3bcf39ff</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Omair Al Aktaa]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 13:09:55 GMT</pubDate>
            <atom:updated>2026-03-31T13:09:55.883Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Clean Code Part 6: Design flexible systems by balancing objects and data structures</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d35jBpWLi0_05FywiryQTA.png" /></figure><h4>1. Introduction</h4><p>There is a reason that we keep our variables private. We don’t want anyone else to depend on them. We want to keep the freedom to change their type or implementation on a whim or an impulse. Why, then, do so many programmers automatically add getters and setters to their objects, exposing their private variables as if they were public?</p><h4>2. Data Abstraction</h4><p>When we talk about clean code, abstraction is at its core.<br>It’s not just about hiding variables, it’s about hiding implementation and revealing intention.</p><p>Imagine two ways to represent a point in space.<br>One exposes its x and y coordinates directly, anyone can poke around, manipulate, or even break them. The other hides how the point is stored (Cartesian or polar) and simply offers clear actions like <em>setCartesian()</em> or <em>setPolar()</em>. That’s the beauty of abstraction</p><blockquote>You don’t need to know how it works, only what it does.</blockquote><h4>3. Data/Object Anti-Symmetry</h4><p>These two examples show the difference between objects and data structures. Objects hide their data behind abstractions and expose functions that operate on that data. Data structure expose their data and have no meaningful functions.</p><p>The Procedural Approach:</p><pre>public class Circle<br>{<br>    public double Radius;<br>}<br><br>public class Rectangle<br>{<br>    public double Width;<br>    public double Height;<br>}<br><br>public static class Geometry<br>{<br>    public static double GetArea(object shape)<br>    {<br>        if (shape is Circle c)<br>            return Math.PI * c.Radius * c.Radius;<br><br>        if (shape is Rectangle r)<br>            return r.Width * r.Height;<br><br>        throw new ArgumentException(&quot;Unknown shape type&quot;);<br>    }<br>}</pre><p>This approach makes it easy to add new operations Like <em>GetPerimeter()</em>, but hard to add new types of shapes you’d have to modify the Geometry class every time.</p><p>The Object-Oriented Approach:</p><pre>public interface IShape<br>{<br>    double GetArea();<br>}<br><br>public class Circle : IShape<br>{<br>    private double _radius;<br><br>    public Circle(double radius) =&gt; _radius = radius;<br><br>    public double GetArea() =&gt; Math.PI * _radius * _radius;<br>}<br><br>public class Rectangle : IShape<br>{<br>    private double _width;<br>    private double _height;<br><br>    public Rectangle(double width, double height)<br>    {<br>        _width = width;<br>        _height = height;<br>    }<br><br>    public double GetArea() =&gt; _width * _height;<br>}</pre><p>This time, it’s easy to add new shapes just create a new class that implements <em>IShape</em>. But adding new operations like <em>GetPerimeter()</em> means modifying all shape classes.</p><p>Use data structures when you expect your operations to evolve frequently, and objects when you expect new kinds of entities to emerge over time.</p><h4>4. The Law of Demeter</h4><p>The Law of Demeter is a design principle that encourages loose coupling between objects.<br>In practice, that means a method should only interact with:<br> - Its own fields (instance variables)<br> - Its method parameters<br> - Objects it creates itself<br> - Its immediate collaborators</p><p>When this rule is broken we often get what calls train wrecks long chains of method calls such as <em>order.Customer.Address.City</em></p><p>The situation becomes even worse when we create hybrids:<br>classes that partly behave like objects and partly like data structures. These classes expose their internal data through getters and setters while also containing business logic, which gives us the disadvantages of both approaches without the benefits of either.</p><blockquote>Talk to Friends, Not Strangers</blockquote><p>❌ Does not follow the Law of Demeter</p><pre>public class Address<br>{<br>    public string City { get; set; }<br>}<br><br>public class Customer<br>{<br>    public Address Address { get; set; }<br>}<br><br>public class Order<br>{<br>    public Customer Customer { get; set; }<br>}<br><br>public class ReportGenerator<br>{<br>    public void PrintCustomerCity(Order order)<br>    {<br>        Console.WriteLine(order.Customer.Address.City);<br>    }<br>}</pre><p>✅ Follows the Law of Demeter</p><pre>public class Address<br>{<br>    private readonly string _city;<br><br>    public Address(string city)<br>    {<br>        _city = city;<br>    }<br><br>    public string GetCity()<br>    {<br>        return _city;<br>    }<br>}<br><br>public class Customer<br>{<br>    private readonly Address _address;<br><br>    public Customer(Address address)<br>    {<br>        _address = address;<br>    }<br><br>    public string GetCity()<br>    {<br>        return _address.GetCity();<br>    }<br>}<br><br>public class Order<br>{<br>    private readonly Customer _customer;<br><br>    public Order(Customer customer)<br>    {<br>        _customer = customer;<br>    }<br><br>    public string GetCustomerCity()<br>    {<br>        return _customer.GetCity();<br>    }<br>}<br><br>public class ReportGenerator<br>{<br>    public void PrintCustomerCity(Order order)<br>    {<br>        Console.WriteLine(order.GetCustomerCity());<br>    }<br>}</pre><h4>5. Data Transfer Objects</h4><p>Not everything in software needs to be an object full of behavior.<br>Sometimes, all we need is a simple structure to carry data from one place to another and that’s where Data Transfer Objects (DTOs) come in.</p><h4>6. Conclusion</h4><p>Objects expose behavior and hide data, making it easy to add new kinds of objects but hard to add new behaviors. Data structures expose data with little behavior, making it easy to add new behaviors but hard to add new data structures. In a system, objects are preferred when adding new data types, while data structures and procedures are preferred when adding new behaviors. Good developers choose the approach that best fits the need without bias.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b7c3bcf39ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Clean Code Part 5]]></title>
            <link>https://medium.com/@omair.alaktaa/mastering-clean-code-part-5-249f69f46478?source=rss-108584afa82c------2</link>
            <guid isPermaLink="false">https://medium.com/p/249f69f46478</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[formatting-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Omair Al Aktaa]]></dc:creator>
            <pubDate>Sat, 05 Jul 2025 14:53:12 GMT</pubDate>
            <atom:updated>2025-07-05T14:59:40.274Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Clean Code Part 5: How Clean Formatting Boosts Readability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*a2btuAGdW2EPT3qz5ZLOHQ.jpeg" /></figure><h4>1. Introduction</h4><p>When people look under the hood, we want them to be impressed with the neatness, consistency, and attention to detail that they perceive. We want them to be struck by the orderliness. We want their eyebrows to rise as they scroll through the modules. We want them to perceive that professionals have been at work.</p><p>You should take care that your code is nicely formatted. You should choose a set of simple rules that govern the format of your code, and then you should consistently apply those rules. If you are working on a team, then the team should agree to a single set of formatting rules and all members should comply.</p><h4>2. The Purpose of Formatting</h4><p>First of all, let’s be clear. Code formatting is important. It is too important to ignore and it is too important to treat religiously. Code formatting is about communication, and communication is the professional developer’s first order of business. Perhaps you thought that “getting it working” was the first order of business for a professional developer. The functionality that you create today has a good chance of changing in the next release, but the readability of your code will have a profound effect on all the changes that will ever be made. Your style and discipline survives, even though your code does not.</p><h4>3. Vertical Formatting</h4><p><strong>3.1 The Newspaper Metaphor</strong></p><p>Think of a well-written newspaper article. You read it vertically. At the top you expect a headline that will tell you what the story is about and allows you to decide whether it is something you want to read. The first paragraph gives you a synopsis of the whole story, hiding all the details while giving you the broad-brush concepts. As you continue down ward, the details increase. We would like a source file to be like a newspaper article. The name should be simple but explanatory. The name, by itself, should be sufficient to tell us whether we are in the right module or not. The topmost parts of the source file should provide the high-level.</p><p><strong>3.2 Vertical Openness Between Concepts</strong></p><p>Nearly all code is read left to right and top to bottom. Each line represents an expression or a clause, and each group of lines represents a complete thought. Those thoughts should be separated from each other with blank lines. This extremely simple rule has a profound effect on the visual layout of the code. Each blank line is a visual cue that identifies a new and separate concept.</p><p>❌Bad Example</p><pre>using System.Collections.Generic;<br>namespace BadApiExample{<br>    public class CustomerRepository : ICustomerRepositor{<br>        private readonly List&lt;Customer&gt; _customers = new();<br>        public void AddCustomer(Customer customer){<br>            _customers.Add(customer);<br>        }<br>        public IEnumerable&lt;Customer&gt; GetAllCustomers(){<br>            return _customers;<br>        }<br>    }<br>}</pre><p>✅ Better Example:</p><pre>using System.Collections.Generic;<br><br>namespace GoodApiExample<br>{<br>    public class CustomerRepository : ICustomerRepository<br>    {<br>        private readonly List&lt;Customer&gt; _customers = new();<br><br>        public void AddCustomer(Customer customer)<br>        {<br>            _customers.Add(customer);<br>        }<br><br>        public IEnumerable&lt;Customer&gt; GetAllCustomers()<br>        {<br>            return _customers;<br>        }<br>    }<br>}</pre><p>This effect is even more pronounced when you unfocus your eyes. In the first example the different groupings of lines pop out at you, whereas the second example looks like a muddle. The difference between these two listings is a bit of vertical openness.</p><blockquote>If openness separates concepts, then vertical density implies close association.</blockquote><p><strong>3.3 Vertical Distance</strong></p><p>When reading code, you shouldn’t have to jump around endlessly trying to piece things together. Related concepts should appear close to each other to keep your reader’s mental focus on understanding logic — not hunting for it.</p><p>Variables should be declared as near as possible to where they’re used. Local variables belong at the top of short functions or within control statements like loops. Instance variables, on the other hand, should be grouped at the top of the class so they’re easy to find.</p><p>Functions that depend on each other should also be kept vertically close, ideally with the caller above the callee to preserve a natural flow. Likewise, functions with a strong conceptual connection — such as variations of the same operation — should be grouped together so that their relationship is clear at a glance.</p><p>By respecting vertical distance, you reduce unnecessary scrolling and help future readers follow the structure of your modules without confusion.</p><p><strong>3.4 Vertical Ordering</strong></p><p>In general we want function call dependencies to point in the downward direction. That is, a function that is called should be below a function that does the calling. This creates a nice flow down the source code module from high level to low level. We expect the low-level details to come last.</p><h4>4. Horizontal Formatting</h4><p><strong>4.1 Horizontal Openness and Density</strong></p><p>We use horizontal white space to associate things that are strongly related and disassociate things that are more weakly related. Consider the following function:</p><pre>private double CalculateAverage(List&lt;int&gt; numbers)<br>{<br>    int total = 0;<br>    int count = numbers.Count;<br><br>    foreach (int number in numbers) {<br>        total += number;<br>    }<br><br>    double average = (double) total / count;<br>    RecordAverage(average);<br>    return average;<br>}</pre><p>I surrounded the assignment operators with white space to accentuate them. Assignment statements have two distinct and major elements: the left side and the right side. The spaces make that separation obvious.</p><p>On the other hand, I didn’t put spaces between the function names and the opening parenthesis. This is because the function and its arguments are closely related. Separating them makes them appear disjoined instead of conjoined. I separate arguments within the function call parenthesis to accentuate the comma and show that the arguments are separate.</p><p><strong>4.2 Indentation</strong></p><p>A source file is a hierarchy rather like an outline. There is information that pertains to the file as a whole, to the individual classes within the file, to the methods within the classes, to the blocks within the methods, and recursively to the blocks within the blocks. Each level of this hierarchy is a scope into which names can be declared and in which declarations and executable statements are interpreted.</p><p>Programmers rely heavily on this indentation scheme. They visually line up lines on the left to see what scope they appear in. This allows them to quickly hop over scopes. Without indentation, programs would be virtually unreadable by humans.</p><pre>private double CalculateAverage(List&lt;int&gt; numbers){int total = 0;<br>int count = numbers.Count; foreach (int number in numbers) { total += <br>number; } double average = (double) total / count; RecordAverage<br>(average) ;return average; }</pre><blockquote>Your eye can rapidly discern the structure of the indented file.</blockquote><p><strong>4.3 Dummy Scopes</strong></p><p>Sometimes the body of a while or for statement is a dummy, as shown below. I don’t like these kinds of structures and try to avoid them. When I can’t avoid them, I make sure that the dummy body is properlyindented and surrounded by braces. Unless you make that semicolon visible by indenting it on it’s own line, it’s just too hard to see.</p><pre>while (dis.Read(buf, 0, readBufferSize) != 0)<br>    ;</pre><h4><strong>5. Team Rules</strong></h4><p>The title of this section is a play on words. Every programmer has his own favorite formatting rules, but if he works in a team, then the team rules.<br>A team of developers should agree upon a single formatting style, and then every member of that team should use that style. We want the software to have aconsistent style. We don’t want it to appear to have been written by a bunch of disagreeing individuals.</p><h4>6. Uncle Bob’s Formatting Rules</h4><p>1- Fields / variables.<br>2- Constructors.<br>3- Public static methods.<br>4- Public instance methods.<br>5- Private static methods.<br>6- Private instance methods.</p><pre>using packages;<br><br>namespace YourNamespace<br>{<br>    public class YourClassName : IYourInterface<br>    {<br>        // Fields<br>        private int _someField;<br>        private string _anotherField;<br><br>        // Constructor<br>        public YourClassName()<br>        {<br>        }<br><br>        // Public Static Methods<br>        public static void PublicStaticMethod()<br>        {<br>        }<br><br>        // Private Static Methods<br>        private static void PrivateStaticHelper()<br>        {<br>        }<br><br>        // Public Methods<br>        public void PublicMethodOne()<br>        {<br>        }<br><br>        public void PublicMethodTwo()<br>        {<br>        }<br><br>        // Private Methods<br>        private void PrivateHelperOne()<br>        {<br>        }<br><br>        private void PrivateHelperTwo()<br>        {<br>        }<br>    }<br>}</pre><h4>7. Conclusion</h4><p>Clean code is not just about making a program work — it’s about making it work well for everyone who touches it, now and in the future. Good formatting is an investment in clarity, maintainability, and teamwork. By applying consistent vertical and horizontal formatting, keeping related ideas together, and following team conventions, you help your future self and your collaborators navigate, extend, and improve your code with confidence.<br>Professionalism starts where the details live: in the whitespace, the indentation, and the discipline that ties it all together.</p><blockquote>Messy code might compile, but clean code communicates.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=249f69f46478" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Clean Code Part 4]]></title>
            <link>https://medium.com/@omair.alaktaa/mastering-clean-code-part-4-be1c9e2edb6d?source=rss-108584afa82c------2</link>
            <guid isPermaLink="false">https://medium.com/p/be1c9e2edb6d</guid>
            <category><![CDATA[comment]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Omair Al Aktaa]]></dc:creator>
            <pubDate>Sat, 03 May 2025 18:40:34 GMT</pubDate>
            <atom:updated>2025-05-03T18:40:34.010Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Clean Code Part 4: Writing Code That Speaks for Itself</h3><figure><img alt="Chapter 4 — Comments Cover" src="https://cdn-images-1.medium.com/max/1024/1*3vRHRwYF6jioJP5HwPmrzg.png" /></figure><h4>1. Introduction:</h4><p>Nothing can be quite so helpful as a well-placed comment. Nothing can clutter up a module more than frivolous dogmatic comments. Nothing can be quite so damaging as an old crufty comment that propagates lies and misinformation.</p><p>If we had the talent to subtly wield programming languages to express our intent, we would not need comments very much perhaps not at all.<br>The proper use of comments is to compensate for our failure to express our self in code.</p><p>The older a comment is, and the farther away it is from the code it describes, the more likely it is to be just plain wrong. The reason is simple. Programmers can’t realistically maintain them. Code changes and evolves.</p><blockquote>Don’t comment bad code — rewrite it.</blockquote><h4>2. Comments Do Not Make Up for Bad Code</h4><p>One of the more common motivations for writing comments is bad code. We write a module and we know it is confusing and disorganized. We know it’s a mess. So we say to ourselves, “Ooh, I’d better comment that!” No! You’d better clean it! Clear and expressive code with few comments is far superior to cluttered and complex code with lots of comments. Rather than spend your time writing the comments that explain the mess you’ve made, spend it cleaning that mess.</p><h4>3. Explain Yourself in Code</h4><p>There are certainly times when code makes a poor vehicle for explanation. Unfortunately, many programmers have taken this to mean that code is seldom, if ever, a good means for explanation. It takes only a few seconds of thought to explain most of your intent in code. In many cases it’s simply a matter of creating a function that says the same thing as the comment<br>you want to write.</p><p>❌Bad Example:</p><pre>// Determine if the user has admin privileges<br>if ((user.Permissions &amp; UserPermissions.Admin) != 0 &amp;&amp; user.YearsOfExperience &gt; 5)<br>{<br>    GrantAdminAccess();<br>}</pre><p>✅ Better Example:</p><pre>if (user.HasAdminPrivileges())<br>{<br>    GrantAdminAccess();<br>}</pre><h4>4. Good Comments</h4><p>Some comments are necessary or beneficial. We’ll look at a few that I consider worthy of the bits they consume. Keep in mind, however, that the only truly good comment is the comment you found a way not to write.</p><h4>4.1 TODO Comments</h4><p>Sometimes, it’s reasonable to leave “To do” notes in the form of // TODO comments. For example, in the snippet below, the TODO explains why the function currently has a barebones implementation and what is expected to happen with it in the future:</p><pre>// TODO-MdM: These are not needed<br>// We expect this to go away when we implement the checkout model<br>protected VersionInfo makeVersion() throws Exception <br>{<br>    return null;<br>}</pre><p>TODOs are reminders about tasks the programmer believes should be completed but, for some reason, can’t address immediately. This could include a note to remove deprecated code later, a request for someone else to review a tricky section, a suggestion to come up with a better name, or a reminder to change something after a future event occurs.</p><h4>4.2 Amplification</h4><p>Sometimes, a comment is useful to amplify the importance of a detail that might otherwise look trivial but is actually critical.</p><pre>string input = match.Groups[3].Value.Trim();<br>// The Trim() call is crucial — it removes leading spaces<br>// that would make the parser misinterpret this as a nested item.<br>var listItem = new ListItemWidget(this, input, this.Level + 1);<br>return BuildList(text.Substring(match.Index + match.Length));</pre><p>Here, the Trim() call might seem like just routine cleanup, but the comment emphasizes why it’s essential: without it, the logic downstream could break by mistakenly treating the item as part of a nested list. This kind of amplifying comment helps future maintainers understand the hidden importance of a small-looking detail.</p><h4>5. Bad Comments</h4><p>Most comments fall into this category. Usually they are crutches or excuses for poor code or justifications for insufficient decisions, amounting to little more than the programmer talking to himself.</p><h4>5.1 Mumbling</h4><p>Plopping in a comment just because you feel you should or because the process requires it, is a hack. If you decide to write a comment, then spend the time necessary to make sure it is the best comment you can write.</p><p>❌For Example</p><pre>public void ProcessOrder(Order order)<br>{<br>    try<br>    {<br>        ValidateOrder(order);<br>        SaveOrderToDatabase(order);<br>        SendConfirmationEmail(order);<br>    }<br>    catch (Exception)<br>    {<br>        // Something went wrong<br>    }<br>}</pre><h4>5.2 Redundant Comments</h4><p>simple function with a header comment that is completely redundant. The comment probably takes longer to read than the code itself.</p><pre>// Utility method that returns when &#39;closed&#39; is true. Throws an exception if the timeout is reached.<br>public void WaitForClose(int timeoutMillis)<br>{<br>    lock (lockObj)<br>    {<br>        if (!closed)<br>        {<br>            bool signaled = Monitor.Wait(lockObj, timeoutMillis);<br>            if (!closed)<br>            {<br>                throw new Exception(&quot;MockResponseSender could not be closed&quot;);<br>            }<br>        }<br>    }<br>}</pre><p>What purpose does this comment serve? It’s certainly not more informative than the code. It is rather like a glad-handing used-car salesman assuring you that you don’t need to look under the hood.</p><h4>5.3 Misleading Comments</h4><p>Sometimes, with all the best intentions, a programmer makes a statement in his comments that isn’t precise enough to be accurate.</p><pre>// This method calculates the total price after applying a 10% discount<br>public decimal CalculateTotalPrice(decimal price)<br>{<br>    // Actually applies a 20% discount, not 10%<br>    decimal discountedPrice = price * 0.8m;<br>    return discountedPrice;<br>}</pre><h4>5.4 Noise Comments</h4><p>Sometimes you see comments that are nothing but noise. They restate the obvious and provide no new information.</p><pre>/** * Default constructor. */<br> protected AnnualDateRule() { }</pre><pre>/** The name. */<br> private String name;<br> /** The version. */<br> private String version;<br> /** The licenceName. */<br> private String licenceName;<br> /** The version. */<br> private String info;</pre><h4>5.5 Don’t Use a Comment When You Can Use a Function or a Variable</h4><p>Consider the following stretch of code:</p><pre>// Check if the user is in the list of active users<br>if (activeUsers.Contains(currentUser.Username))<br>{<br>    // do something<br>}</pre><p>This could be rephrased without the comment as</p><pre>List&lt;string&gt; activeUsernames = activeUsers;<br>string username = currentUser.Username;<br><br>if (IsUserActive(currentUser))<br>{<br>    // do something<br>}<br><br>private bool IsUserActive(User user)<br>{<br>    return activeUsers.Contains(user.Username);<br>}</pre><h4>5. 6 Position Markers</h4><p>Sometimes, programmers like to mark specific positions in a source file. For instance, in a program I recently examined, I came across this:</p><pre>// Actions //////////////////////////////////</pre><p>There are rare occasions when grouping certain functions under a banner like this makes sense. But generally, such banners are just clutter that should be removed — especially when they include a noisy trail of slashes at the end.</p><p>Think about it this way: a banner only stands out and grabs attention if banners are used sparingly. Therefore, reserve them for situations where the benefit is genuinely significant. If you overuse banners, they’ll simply blend into the background noise and end up being ignored.</p><h4>5.7 Closing Brace Comments</h4><p>Sometimes programmers will put special comments on closing braces, Although this might make sense for long functions with deeply nested structures, it serves only to clutter the kind of small and encapsulated functions that we prefer. So if you find yourself wanting to mark your closing braces, try to shorten your functions instead.</p><pre>using System;<br>using System.IO;<br><br>public class WordCounter<br>{<br>    public static void Main(string[] args)<br>    {<br>        int lineCount = 0;<br>        int charCount = 0;<br>        int wordCount = 0;<br><br>        string line;<br>        try<br>        {<br>            while ((line = Console.ReadLine()) != null)<br>            {<br>                lineCount++;<br>                charCount += line.Length;<br>                string[] words = line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);<br>                wordCount += words.Length;<br>            } // while<br><br>            Console.WriteLine(&quot;wordCount = &quot; + wordCount);<br>            Console.WriteLine(&quot;lineCount = &quot; + lineCount);<br>            Console.WriteLine(&quot;charCount = &quot; + charCount);<br>        } // try<br>        catch (IOException e)<br>        {<br>            Console.Error.WriteLine(&quot;Error: &quot; + e.Message);<br>        } // catch<br>    } // Main<br>} // WordCounter</pre><h4>5.8 Attributions and Bylines</h4><pre>// Added by Anas<br>/*<br>  AI Logic Here...<br>*/</pre><p>Source code control systems are very good at remembering who added what, when. There is no need to pollute the code with little bylines. You might think that such comments would be useful in order to help others know who to talk to about the code. Again, the source code control system is a better place for this kind of information.</p><h4>5.9 Commented-Out Code</h4><p>Few practices are as odious as commenting-out code. Don’t do this!</p><p>Others who see that commented-out code won’t have the courage to delete it. They’ll assume it’s there for a reason and believe it’s too important to remove. So, the commented-out code piles up like dust in the corners of an old, neglected room.</p><pre>FileWriter writer = new FileWriter();<br>writer.WriteToFile(filePath, dataBytes);<br>// FileStream fileStream = new FileStream(filePath, FileMode.Create);<br>// fileStream.Write(dataBytes, 0, dataBytes.Length);<br>// fileStream.Close();</pre><h4>5.10 Non local Information</h4><p>If you must write a comment, then make sure it describes the code it appears near. Do not offer system wide information in the context of a local comment.</p><h4>5.11 In-obvious Connection</h4><p>The connection between a comment and the code it describes should be obvious. If you are going to the trouble to write a comment, then at least you’d like the reader to be able to look at the comment and the code and understand what the comment is talking about.</p><h4>6. Conclusion</h4><p>As we’ve explored, the best code is often the kind that reduces or eliminates the need for comments</p><p>Remember: code that speaks for itself is the ultimate form of clean communication. Instead of leaning on comments to clarify confusing logic, invest the time to refactor, simplify, and improve your codebase. This not only benefits you but also every developer who will interact with your work in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be1c9e2edb6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Clean Code Part 3]]></title>
            <link>https://medium.com/@omair.alaktaa/mastering-clean-code-part-3-6ae6fa8d9aef?source=rss-108584afa82c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ae6fa8d9aef</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[function]]></category>
            <dc:creator><![CDATA[Omair Al Aktaa]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 13:46:50 GMT</pubDate>
            <atom:updated>2025-02-28T08:26:21.804Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Clean Code Part 3: Writing Functions That Are Readable, Maintainable, and Effective</h3><figure><img alt="Function Diagram" src="https://cdn-images-1.medium.com/max/880/1*dY-0X8i0BM0l3l_lNsEXag.png" /></figure><h4>1. Introduction:</h4><p>In the early days of programming we composed our systems of routines and subroutines. Then, in the era of FORTRAN and PL/1 we composed our systems of programs, subprograms, and functions. Nowadays only the function survives from those early days. Functions are the first line of organization in any program. Writing them well is the topic of this article.</p><p>So, what is it that makes a function easy to read and understand?<br>How can we make a function communicate its intent?</p><h4>2. Small</h4><p><strong>How short should a function be?</strong><br>Lines should not be 150 characters long. Functions should not be 100 lines long. Functions should hardly ever be 20 lines long.</p><blockquote>The first rule of functions is that they should be small. the second rule of functions is that they should be smaller than that.3. Blocks and Indenting</blockquote><p>Blocks within control structures should be one line long, preferably a function call with a descriptive name. Functions should be small, avoiding deep nesting, with an indent level of one or two or three maximum for readability.</p><p>❌Bad Example:</p><pre>void processOrder(Order order)<br>{<br>    if (order.isValid)<br>    {<br>        if (order.isPaid)<br>        {<br>            if (order.HasStock)<br>            {<br>                shipOrder(order);<br>            }<br>            else<br>            {<br>                NotifyOutOfStock(order);<br>            }<br>        }<br>        else<br>        {<br>            RequestPayment(order);<br>        }<br>    }<br>    else<br>    {<br>        RejectOrder(order);<br>    }<br>}</pre><p>✅ Better Example:</p><pre>void ProcessOrder(Order order)<br>{<br>    if (!order.IsValid)<br>    {<br>        RejectOrder(order);<br>        return;<br>    }<br><br>    if (!order.IsPaid)<br>    {<br>        RequestPayment(order);<br>        return;<br>    }<br><br>    if (!order.HasStock)<br>    {<br>        NotifyOutOfStock(order);<br>        return;<br>    }<br><br>    ShipOrder(order);<br>}</pre><h4>4. Do One Thing</h4><p>A function should do one thing and do it well. If a function contains multiple levels of abstraction, it is doing more than one thing. If a function can be meaningfully broken down into smaller functions without simply restating the code, it is not truly doing only one thing.</p><p>❌Bad Example:</p><pre>void ProcessPayment(Order order)<br>{<br>    Console.WriteLine(&quot;Processing payment...&quot;);<br>    if (!order.HasSufficientBalance())<br>    {<br>        Console.WriteLine(&quot;Insufficient balance.&quot;);<br>        NotifyUser(order.User);<br>        return;<br>    }<br><br>    Console.WriteLine(&quot;Charging user...&quot;);<br>    ChargeUser(order);<br>    UpdateDatabase(order);<br>    SendReceipt(order);<br>    Console.WriteLine(&quot;Payment successful.&quot;);<br>}</pre><p>✅ Better Example:</p><pre>void ProcessPayment(Order order)<br>{<br>    Console.WriteLine(&quot;Processing payment...&quot;);<br>    <br>    if (!HasSufficientBalance(order))<br>    {<br>        HandleInsufficientBalance(order);<br>        return;<br>    }<br><br>    CompletePayment(order);<br>}<br><br>bool HasSufficientBalance(Order order) =&gt; order.HasSufficientBalance();<br><br>void HandleInsufficientBalance(Order order)<br>{<br>    Console.WriteLine(&quot;Insufficient balance.&quot;);<br>    NotifyUser(order.User);<br>}<br><br>void CompletePayment(Order order)<br>{<br>    Console.WriteLine(&quot;Charging user...&quot;);<br>    ChargeUser(order);<br>    UpdateDatabase(order);<br>    SendReceipt(order);<br>    Console.WriteLine(&quot;Payment successful.&quot;);<br>}</pre><blockquote>Functions should do one thing. they should do it well. they should do it only.</blockquote><h4>5. One Level of Abstraction per Function</h4><p>To ensure a function does only one thing, all statements inside it should be at the same level of abstraction. Mixing high-level and low-level concepts in a function makes it hard to understand because readers cannot easily notice core logic from implementation details.</p><p>❌Bad Example:</p><pre>void ProcessOrder(Order order)<br>{<br>    if (!order.IsValid)<br>    {<br>        Console.WriteLine(&quot;Order is invalid&quot;);<br>        return;<br>    }<br><br>    Console.WriteLine(&quot;Processing order...&quot;);<br>    <br>    // High-level logic<br>    UpdateOrderStatus(order, &quot;Processing&quot;);<br><br>    // Low-level details (should be in a separate function or layer)<br>    using (var connection = new SqlConnection(&quot;connection_string&quot;))<br>    {<br>        connection.Open();<br>        var command = new SqlCommand(&quot;UPDATE Orders SET Status=&#39;Processing&#39; WHERE Id=@Id&quot;, connection);<br>        command.Parameters.AddWithValue(&quot;@Id&quot;, order.Id);<br>        command.ExecuteNonQuery();<br>    }<br><br>    Console.WriteLine(&quot;Order processed successfully.&quot;);<br>}</pre><p>✅ Better Example:</p><pre>void ProcessOrder(Order order)<br>{<br>    if (!order.IsValid)<br>    {<br>        LogInvalidOrder(order);<br>        return;<br>    }<br><br>    Console.WriteLine(&quot;Processing order...&quot;);<br>    UpdateOrderStatus(order, &quot;Processing&quot;);<br>    SaveOrderToDatabase(order);<br>    Console.WriteLine(&quot;Order processed successfully.&quot;);<br>}<br><br>void LogInvalidOrder(Order order)<br>{<br>    Console.WriteLine(&quot;Order is invalid&quot;);<br>}<br><br>void SaveOrderToDatabase(Order order)<br>{<br>    using (var connection = new SqlConnection(&quot;connection_string&quot;))<br>    {<br>        connection.Open();<br>        var updateOrderCommand = new SqlCommand(&quot;UPDATE Orders SET Status=&#39;Processing&#39; WHERE Id=@Id&quot;, connection);<br>        updateOrderCommand.Parameters.AddWithValue(&quot;@Id&quot;, order.Id);<br>        updateOrderCommand.ExecuteNonQuery();<br>    }<br>}</pre><h4>6. Reading Code from Top to Bottom</h4><p>The Stepdown Rule ensures that code reads like a top-down narrative, where each function is followed by functions at the next level of abstraction. This allows programmers to read the code step by step, descending through abstraction levels.</p><p>Each function should introduce the next, maintaining a consistent level of abstraction. Although difficult to master, following this rule is essential for writing short, single-purpose functions and improving code readability.</p><h4>7. Switch Statements</h4><p>It’s hard to make a small switch statement. switch statements are inherently large and violate the Single Responsibility Principle (SRP) and Open-Closed Principle (OCP) because they require changes whenever new cases are added. Additionally, they often appear in multiple places, leading to code duplication.</p><p>The best way to handle this issue is to encapsulate the switch statement in an Abstract Factory and use polymorphism to dispatch behavior through an interface. A switch statement should appear only once in the system, hidden behind an inheritance structure, so the rest of the code remains unaware of it.</p><p>❌Bad Example (Using a Switch Statement Directly):</p><pre>public class Employee<br>{<br>    public EmployeeType Type { get; set; }<br><br>    public double CalculatePay()<br>    {<br>        switch (Type)<br>        {<br>            case EmployeeType.FullTime:<br>                return 5000;<br>            case EmployeeType.PartTime:<br>                return 3000;<br>            case EmployeeType.Contractor:<br>                return 2000;<br>            default:<br>                throw new ArgumentException(&quot;Invalid employee type&quot;);<br>        }<br>    }<br>}<br><br>public enum EmployeeType<br>{<br>    FullTime,<br>    PartTime,<br>    Contractor<br>}</pre><p>✅ Better Example (Using Polymorphism and Abstract Factory):</p><pre>// Step 1: Create an abstract base class<br>public abstract class Employee<br>{<br>    public abstract double CalculatePay();<br>}<br><br>// Step 2: Create concrete classes for each employee type<br>public class FullTimeEmployee : Employee<br>{<br>    public override double CalculatePay() =&gt; 5000;<br>}<br><br>public class PartTimeEmployee : Employee<br>{<br>    public override double CalculatePay() =&gt; 3000;<br>}<br><br>public class ContractorEmployee : Employee<br>{<br>    public override double CalculatePay() =&gt; 2000;<br>}<br><br>// Step 3: Use a Factory to hide the switch statement<br>public class EmployeeFactory<br>{<br>    public static Employee CreateEmployee(EmployeeType type)<br>    {<br>        return type switch<br>        {<br>            EmployeeType.FullTime =&gt; new FullTimeEmployee(),<br>            EmployeeType.PartTime =&gt; new PartTimeEmployee(),<br>            EmployeeType.Contractor =&gt; new ContractorEmployee(),<br>            _ =&gt; throw new ArgumentException(&quot;Invalid employee type&quot;)<br>        };<br>    }<br>}<br><br>// Step 4: Usage<br>public enum EmployeeType<br>{<br>    FullTime,<br>    PartTime,<br>    Contractor<br>}<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        Employee employee = EmployeeFactory.CreateEmployee(EmployeeType.FullTime);<br>        Console.WriteLine($&quot;Salary: {employee.CalculatePay()}&quot;);<br>    }<br>} </pre><h4>8. Use Descriptive Names</h4><p>Choosing descriptive and meaningful names for functions is crucial for writing clean code. A well-named function should accurately describe what it does, making the code predictable and easy to understand.</p><p>Long, descriptive names are better than short, unclear names or excessive comments. Trying different names and reading the code with each can help improve clarity and even lead to better code structure.</p><p>Consistency in naming across functions enhances readability, allowing the sequence of functions to tell a story and making the code more intuitive.</p><h4>9. Function Arguments</h4><p>The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification and then shouldn’t be used anyway.</p><p>Too many arguments increase complexity; harder to read and understand, harder to test due to multiple possible combinations.</p><p>Output arguments are harder to understand than input arguments so should be avoided, we typically expect functions to receive input arguments and return values, not modify arguments.</p><p>Using instance variables instead of passing arguments can simplify function calls and improve readability.</p><h4>10. Have No Side Effects</h4><p>Side effects mislead by making hidden changes to variables, parameters, or system globals, causing temporal couplings and order dependencies. For example, a function named checkPassword should not also initialize a session, as it creates unintended consequences. If a function must have a temporal dependency, its name should reflect all its actions, though this contradicts the principle of doing one thing.</p><h4>11. Don’t Repeat Yourself</h4><p>Duplication in code can be difficult to spot when intermixed with other logic, but it leads to bloated code, increased maintenance effort, and a higher risk of errors. Many software development principles and practices, such as database normalization, object-oriented programming, structured programming, and component-oriented programming, aim to eliminate duplication. Since the invention of subroutines, reducing redundancy has been a core goal of software development.</p><h4>12. How Do You Write Functions Like This?</h4><p>Writing software is similar to writing an article — it starts as a rough draft and is refined over time. Initial code may be complex, with long functions, deep nesting, and duplication. However, through refactoring splitting functions, renaming variables, and eliminating redundancy — code becomes cleaner and more structured. Unit tests ensure that changes don’t break functionality. This iterative process leads to well-structured functions, but they don’t start that way.</p><h4>13. Conclusion</h4><p>Programming is fundamentally about designing a domain-specific language to describe a system, where functions act as verbs and classes as nouns. Master programmers view systems as stories rather than just code, using their language’s features to create a rich, expressive way to convey that story. Well-structured functions form a hierarchy that defines system actions while maintaining clarity and cohesion. Ultimately, writing good functions isn’t just about following rules — it’s about crafting a language that tells the system’s story effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ae6fa8d9aef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Writing Clear and Effective Commit Messages]]></title>
            <link>https://medium.com/@omair.alaktaa/a-guide-to-writing-clear-and-effective-commit-messages-a7a2cf37cc3f?source=rss-108584afa82c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7a2cf37cc3f</guid>
            <category><![CDATA[code-collaboration]]></category>
            <category><![CDATA[conventional-commits]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[version-control]]></category>
            <dc:creator><![CDATA[Omair Al Aktaa]]></dc:creator>
            <pubDate>Thu, 02 Jan 2025 15:29:04 GMT</pubDate>
            <atom:updated>2025-01-03T17:48:43.609Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Guide to Write Clear and Effective Commit Messages</h3><h4>Art of Commit Messages</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wB_DDVnxTXOHy3qWWN3WFw.jpeg" /></figure><h4>1. Introduction</h4><p>The conventional commits specification provides a standard format for writing commit messages. This convention helps make commit history more readable and efficient.</p><h4>2 Commit Structure</h4><p><strong>2.1 A commit message should have the following structure:</strong></p><pre>&lt;type&gt;[optional scope]: &lt;description&gt;<br>[optional body]<br>[optional footer]</pre><p>Let’s break down the components:</p><p><strong>2.2 Type<br></strong>The type is the category of the change, the common type includes:</p><ul><li>feat: A new feature added.</li><li>fix: A patches a bug.</li><li>docs: Documentation.</li><li>style: Formatting changes that do not affect code functionality.</li><li>refactor: Code changes that neither fix a bug nor add a feature.</li><li>test: Adding or modifying tests.</li><li>perf: A performance improvement.</li><li>merge: To check in merging branches.</li><li>del: Removing files or folders etc.</li><li>mv: Move directories or anything else.</li><li>chore: Miscellaneous tasks, like build process or dependency updates.</li></ul><p><strong>2.3 Scope<br></strong>The code area affected by the commit (e.g., auth, config). It gives more context to the change and helps teams understand which part of the codebase was impacted.</p><p>Example:</p><pre>fix(auth): handle invalid login attempts</pre><p>In this example, the scope is auth, indicating that the change affects the authentication part of the code.</p><p><strong>2.4 Description<br></strong>The description should succinctly explain what the commit does. It should be written in the imperative mood (e.g., add, remove, fix, create), be short (ideally under 50 characters), and provide enough information to understand the challenge at a glance.</p><p>Example:</p><pre>feat(parser): add support for array parsing</pre><p><strong>2.5 Body<br></strong>The body of the commit message provides additional context, which is especially useful when the change is complex. It explains <strong>what</strong> the change does and <strong>why</strong> it was necessary.</p><p>Example:</p><pre>fix(auth): handle invalid login attempts<br><br>The login form now properly handles invalid credentials, preventing session data from being incorrectly stored.</pre><p><strong>2.6 Footer<br></strong>The footer is used for referencing issues (e.g., Closes #888) or for indicating <strong>BREAKING CHANGES. </strong>If the commit introduces a change that is incompatible with previous versions, a breaking change notice should be included.</p><p>Example:</p><pre>fix(auth): handle invalid login attempts<br><br>The login form now properly handles invalid credentials preventing session data from being incorrectly stored.<br><br>BREAKING CHANGE: refactored authentication to use OAuth 2.0</pre><h4><strong>3. Tips for good commit</strong></h4><ul><li>Keep it concise</li><li>Use the imperative mood</li><li>Separate concerns: Each commit should address one issue.</li></ul><h4>4. Conclusion</h4><p>Being aware of the conventional commit enhances clarity and maintainability. It makes collaboration easier by standardizing how changes are communicated in commit messages and improving the human readability of commit history.</p><blockquote>“Although the scope component is optional, I recommend making it required.”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7a2cf37cc3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Clean Code Part 2]]></title>
            <link>https://medium.com/@omair.alaktaa/mastering-clean-code-part-2-711ce22a290c?source=rss-108584afa82c------2</link>
            <guid isPermaLink="false">https://medium.com/p/711ce22a290c</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[naming-conventions]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Omair Al Aktaa]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 18:02:15 GMT</pubDate>
            <atom:updated>2024-11-09T18:02:15.509Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Mastering Clean Code Part 2: A Guide to Meaningful Naming Conventions</strong></h3><figure><img alt="Family meeting to choose a name for the newborn" src="https://cdn-images-1.medium.com/max/1024/1*8YycuWNWsf2PmLCAzbaRXw.jpeg" /></figure><blockquote>The amount of time you take to name your variables should be the same as the one you take to name your children</blockquote><h4>Introduction</h4><p>Names are everywhere in software. We name our variables, our functions, our arguments, classes, and packages. We name our source files and the directories that contain them. We name our jar files and war files and ear files. We name and name and name. Because we do so much of it, we’d better do it well. <strong>What follows are some simple rules for creating good names.<br></strong>This article is the second part of <a href="https://medium.com/@omair.alaktaa/mastering-clean-code-part-1-e933fd3e906e">Mastering Clean Code Part 1</a>.</p><h4>1. Use Intention-Revealing Names</h4><p>It is easy to say that names should reveal intent. What we want to impress upon you is that we are serious about this. Choosing good names takes time but saves more than it takes. So take care with your names and change them when you find better ones. Everyone who reads your code (including you) will be happier if you do. The name of a variable, function, or class, should answer all the big questions. It should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent.</p><pre>int d; // elapsed time in days</pre><p>The name d reveals nothing. It does not evoke a sense of elapsed time, nor of days. We should choose a name that specifies what is being measured and the unit of that measurement:</p><pre>int elapsedTimeInDays;<br>int daysSinceCreation;<br>int daysSinceModification;<br>int fileAgeInDays;</pre><h4>2. Avoid Disinformation</h4><p>We should avoid words whose entrenched meanings vary from our intended meaning. For example, hp, mac, and nba would be poor variable names. Even if you are coding a hypotenuse and hp looks like a good abbreviation, it could be disinformative.</p><p>Do not refer to a grouping of accounts as an accountList unless it’s actually a List.<br>The word list means something specific to programmers. If the container holding the accounts is not actually a List, it may lead to false conclusions. So accountGroup or bunchOfAccounts or just plain accounts would be better.</p><p>Beware of using names which vary in small ways. How long does it take to spot the subtle difference between a XYZControllerForEfficientHandlingOfStrings in one module and, somewhere a little more distant, XYZControllerForEfficientStorageOfStrings? The words have frightfully similar shapes.</p><p>A truly awful example of disinformative names</p><pre>int a = l;<br>if (O == l)<br>  a = O1;<br>else<br>  l = 01;</pre><h4>3. Make Meaningful Distinctions</h4><p>Programmers create problems for themselves when they write code solely to satisfy a compiler or interpreter. For example, because you can’t use the same name to refer to two different things in the same scope, you might be tempted to change one name in an arbitrary way. Sometimes this is done by misspelling one, leading to the surprising situation where correcting spelling errors leads to an inability to compile. It is not sufficient to add number series or noise words, even though the compiler is satisfied. If names must be different, then they should also mean something different.</p><p>Number-series naming (a1, a2, .. aN) is the opposite of intentional naming.<br>Such names are not disinformative they are noninformative; they provide no clue</p><pre>public static void copyChars(char a1[], char a2[])<br>{<br>    for (int i = 0; i &lt; a1.length; i++)<br>    {<br>        a2[i] = a1[i];<br>    }<br>}</pre><p>Here, the variables a1 and a2 provide no indication of what they represent. This can lead to confusion for anyone reading the code, as the variables don’t reveal their purpose.</p><pre>public static void copyChars(char[] source, char[] destination)<br>{<br>    for (int i = 0; i &lt; source.Length; i++)<br>    {<br>        destination[i] = source[i];<br>    }<br>}</pre><p>This function reads much better when source and destination are used for the argument names.</p><p>Noise words are another meaningless distinction. Imagine that you have a <em>Product </em>class. If you have another called <em>ProductInfo </em>or <em>ProductData</em>, you have made the names different without making them mean anything different.</p><p>Noise words are redundant. The word <em>variable </em>should never appear in a variable name. The word <em>table </em>should never appear in a table name.<br>How is <em>NameString </em>better than <em>Name</em>?<br>Would a <em>Name </em>ever be a floating point number? If so, it breaks an earlier rule about disinformation. Imagine finding one class named <em>Customer</em> and another named <em>CustomerObject</em>.<br>What should you understand as the distinction?<br>Which one will represent the best path to a customer’s payment history?</p><pre>getActiveAccount();<br>getActiveAccounts();<br>getActiveAccountInfo();</pre><p>How are the programmers in this project supposed to know which of these functions to call? In the absence of specific conventions, the variable <em>moneyAmount</em> is indistinguishable from <em>money</em>, <em>customerInfo</em> is indistinguishable from <em>customer</em>, <em>accountData </em>is indistinguishable from <em>account</em>, and <em>theMessage </em>is indistinguishable from <em>message</em>.<br>Distinguish names in such a way that the reader knows what the differences offer.</p><h4>4. Use Pronounceable Names</h4><p>Humans are good at words. A significant part of our brains is dedicated to the concept of words. And words are, by definition, pronounceable. It would be a shame not to take advantage of that huge portion of our brains that has evolved to deal with spoken language. So make your names pronounceable. If you can’t pronounce it, you can’t discuss it without sounding like an idiot. Compare</p><pre>class DtaRcrd102 {<br>    private DateTime genymdhms;<br>    private DateTime modymdhms;<br>    private const string pszqint = &quot;102&quot;;<br>    /* ... */<br>}</pre><p>to</p><pre>class Customer {<br>  private DateTime generationTimestamp;<br>  private DateTime modificationTimestamp;;<br>  private const string recordId = &quot;102&quot;;<br>  /* ... */<br>};</pre><h4>5. Use Searchable Names</h4><p>Using single-letter names and numeric constants makes code harder to search and debug, as these values are often hard to isolate in a body of text due to their lack of specificity.</p><p>For example, a numeric constant like 7 can appear in multiple contexts, making it unclear which instances hold the intended meaning.<br>It is even worse when a constant is a long number and someone might have transposed digits, thereby creating a bug while simultaneously evading the programmer’s search.</p><p>Likewise, the name e is a poor choice for any variable for which a programmer might need to search.</p><p>It is the most common letter in the English language and likely to show up in every passage of text in every program.</p><p>The recommended approach is to use descriptive names especially for variables with larger scopes to make them easier to identify and manage. For instance, defining <em>WORK_DAYS_PER_WEEK</em> rather than hardcoding 5 allows developers to understand its purpose and change it in a single location without ambiguity. Compare</p><pre>for (int j=0; j&lt;34; j++) {<br>s += (t[j]*4)/5;<br>}</pre><p>To</p><pre>int realDaysPerIdealDay = 4;<br>const int WORK_DAYS_PER_WEEK = 5;<br>int sum = 0;<br>int NUMBER_OF_TASKS = 10;<br>int[] taskEstimate = new int[NUMBER_OF_TASKS];<br><br>for (int j = 0; j &lt; NUMBER_OF_TASKS; j++) {<br>    int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;<br>    int realTaskWeeks = realTaskDays / WORK_DAYS_PER_WEEK;<br>    sum += realTaskWeeks;<br>}</pre><p>Consider how much easier it will be to find <em>WORK_DAYS_PER_WEEK</em> than to find all the places where 5 was used and filter the list down to just the instances with the intended meaning.</p><h4>6. Class Names</h4><p>Classes and objects should have noun or noun phrase names like <em>Customer</em>, <em>WikiPage</em>, <em>Account</em>, and <em>AddressParser</em>. Avoid words like <em>Manager</em>, <em>Processor</em>, <em>Data</em>, or <em>Info </em>in the name of a class. A class name should not be a verb.</p><h4>7. Method Names</h4><p>Methods should have verb or verb phrase names like <em>postPayment</em>, <em>deletePage</em>, or <em>save</em>. Accessors, mutators, and predicates should be named for their value and prefixed with get, set, and is.</p><pre>string name = employee.getName();<br><br>customer.setName(&quot;Adam&quot;);<br><br>if (paycheck.isPosted())</pre><h4>8. Don’t Be Cute</h4><p>If names are too clever, they will be memorable only to people who share the author’s sense of humor, and only as long as these people remember the joke. Will they know what the function named<em> HolyHandGrenade</em> is supposed to do? Sure, it’s cute, but maybe in this case <em>DeleteItems</em> might be a better name. Choose clarity over entertainment value.</p><h4>9. Pick One Word per Concept</h4><p>Pick one word for one abstract concept and stick with it. For instance, it’s confusing to have <em>fetch</em>, <em>retrieve</em>, and <em>get </em>as equivalent methods of different classes. How do you remember which method name goes with which class? Sadly, you often have to remember which company, group, or individual wrote the library or class in order to remember which term was used. Otherwise, you spend an awful lot of time browsing through headers and previous code samples.</p><h4>10. Don’t Pun</h4><p>Avoid using the same word for two purposes. Using the same term for two different ideas is essentially a pun.</p><p>If you follow the “one word per concept” rule, you could end up with many classes that have, for example, an <em>add </em>method. As long as the parameter lists and return values of the various add methods are semantically equivalent, all is well.</p><p>However one might decide to use the word add for “consistency” when he or she is not in fact adding in the same sense.</p><h4>11. Use Solution Domain Names</h4><p>Remember that the people who read your code will be programmers. So go ahead and use computer science (CS) terms, algorithm names, pattern names, math terms, and so forth. It is not wise to draw every name from the problem domain because we don’t want our coworkers to have to run back and forth to the customer asking what every name means when they already know the concept by a different name. The name AccountVisitor means a great deal to a programmer who is familiar with the VISITOR pattern. What programmer would not know what a JobQueue was? There are lots of very technical things that programmers have to do. Choosing technical names for those things is usually the most appropriate course.</p><h4>Final Words</h4><p>The hardest thing about choosing good names is that it requires good descriptive skills This is a teaching issue rather than a technical or any thing else. As a result many people in this field don’t learn to do it very well.</p><p>People are also afraid of renaming things for fear that some other developers will object.</p><p>Follow some of these rules and see whether you don’t improve the readability of your code. If you are maintaining someone else’s code, use refactoring tools to help resolve these problems. It will pay off in the short term and continue to pay in the long run.</p><blockquote>Professionals use their powers for writing code that others can understand.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=711ce22a290c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Clean Code Part 1]]></title>
            <link>https://medium.com/@omair.alaktaa/mastering-clean-code-part-1-e933fd3e906e?source=rss-108584afa82c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e933fd3e906e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[clean-code-principle]]></category>
            <dc:creator><![CDATA[Omair Al Aktaa]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 17:14:42 GMT</pubDate>
            <atom:updated>2024-10-02T17:14:42.184Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Clean Code Part 1: The Key to Professional Software Development</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7-PZpOiZUjvwU47DOqwJQ.png" /></figure><blockquote>Writing clean code is what you must do in order to call yourself a professional.<br>There is no reasonable excuse for doing anything less than your best.</blockquote><h3>Introduction:</h3><p>Learning to write clean code is hard work. It requires more than just the knowledge of principles and patterns. You must sweat over it. You must practice it yourself, and watch yourself fail. You must watch others practice it and fail. You must see them stumble and retrace their steps. You must see them agonize over decisions and see the price they pay for making those decisions the wrong way.<br> <br>Let’s say you believe that messy code is a significant impediment. Let’s say that you accept that the only way to go fast is to keep your code clean. Then you must ask yourself: “How do I write clean code?” It’s no good trying to write clean code if you don’t know what it means for code to be clean! The bad news is that writing clean code is a lot like painting a picture. Most of us know when a picture is painted well or badly. But being able to recognize good art from bad does not mean that we know how to paint. So too being able to recognize clean code from dirty code does not mean that we know how to write clean code!</p><h3>What is clean code?</h3><p>Clean Code is more than just code that works. It embodies a philosophy of writing software in a way that enhances readability, maintainability, and quality. It’s about making your code understandable by other developers (or even yourself at a later time) and minimizing the potential for introducing bugs. In essence, clean code is code that is clear, concise, and purpose-driven.</p><p><strong>- Bjarne Stroustrup, inventor of C++</strong><br><em>“I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well”</em></p><p><strong>- Grady Booch, author of Object-Oriented Analysis</strong><br><em>“Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control”</em></p><h3>Why should I write a clean code?</h3><p>Writing clean code isn’t just about following good practices; it’s about improving the overall quality, maintainability, and scalability of your software. Clean code benefits developers, teams, and organizations in a variety of ways, and the reasons for writing clean code are deeply rooted in both practical outcomes and long-term software success.</p><h4><strong>Here are some key reasons why you should prioritize writing clean code:</strong></h4><h4>1. Makes Maintenance Easier</h4><p>Clean code is typically more modular and organized, making it easier to write tests for each component. This leads to better overall software quality, as you can ensure that each part of the system works as expected. Clean code encourages practices like unit testing, where small parts of the system are tested in isolation.</p><p><strong>Why it matters:</strong> Software evolves with new features, bug fixes, and improvements. If the code is not clean, these changes become time-consuming and error-prone.</p><h4>2. Reduces Bugs and Errors</h4><p>Writing clean code minimizes the likelihood of introducing bugs. When the code is well-structured, simple, and easy to follow, there are fewer places for mistakes to hide. Clean code also follows principles like Single Responsibility and DRY (Don’t Repeat Yourself), which help reduce errors caused by duplicated or overly complex logic.</p><p><strong>Why it matters:</strong> Bugs are costly in terms of time and resources. Clean code reduces the chances of bugs creeping in and simplifies the process of finding and fixing them when they do appear.</p><h4>3. Facilitates Team Collaboration</h4><p>If you’re working in a team environment, clean code is essential for collaboration. Other developers should be able to easily understand and work with the code you’ve written without requiring extensive explanations. Clean code fosters better communication between team members and reduces onboarding time for new developers.</p><p><strong>Why it matters:</strong> Teams that work with clean code can move faster and collaborate more efficiently. Clean code prevents bottlenecks that arise when developers struggle to understand what the code is doing.</p><h4>4. Makes Code More Testable</h4><p>Clean code is typically more modular and organized, making it easier to write tests for each individual component. This leads to better overall software quality, as you can ensure that each part of the system works as expected. Clean code encourages practices like unit testing, where small parts of the system are tested in isolation.</p><p><strong>Why it matters:</strong> Testable code leads to more reliable software. Automated tests can catch issues early and give you confidence that your changes won’t break existing functionality.</p><h4>5. Enhances Scalability</h4><p>As your software grows in complexity, it becomes harder to manage if the code isn’t clean. Clean code is often designed to be modular and extensible, which makes it easier to scale as new features and requirements are added.</p><p><strong>Why it matters:</strong> Software systems need to evolve, and clean code ensures that this growth is smooth and manageable. If the code is messy, scaling becomes a complex and error-prone process.</p><h4>6. Saves Time in the Long Run</h4><p>While writing clean code may take a bit more time initially (e.g., choosing better names for variables, writing clear functions, refactoring), it saves enormous amounts of time in the long run. Clean code makes it easier to maintain, debug, and extend the software, which ultimately leads to faster overall development cycles.</p><p><strong>Why it matters:</strong> Investing a little more time upfront to write clean code saves a lot of time later when maintaining and expanding the system.</p><h4>7. Improves Code Reviews</h4><p>Code reviews are much easier and faster when the code being reviewed is clean. Reviewers can focus on improving the quality of the solution rather than trying to figure out what the code is doing. Clean code also makes it easier to spot potential issues and suggest improvements.</p><p><strong>Why it matters:</strong> Clean code leads to quicker reviews and better overall quality.</p><h3>When did the clean code concept appear?</h3><p>There is no clear starting point for clean code but, The concept of Clean Code evolved, starting in the 1970s with structured programming and the emphasis on readable, maintainable code by pioneers like Edsger Dijkstra and Donald Knuth. In the 1980s, object-oriented programming (OOP) with languages like Smalltalk, C++, and Java introduced principles like encapsulation and modularity, contributing to cleaner code. The 1990s saw Agile development and practices like Test-Driven Development (TDD) and refactoring, championed by Martin Fowler. Clean Code was fully formalized in 2008 by Robert C. Martin where he laid out specific principles for writing maintainable and efficient code. While earlier programming practices influenced it, Martin’s work established the Clean Code as a key modern development principle.</p><h3>How do I write a clean code?</h3><p>The following parts of the article will explain deeply how to write clean code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e933fd3e906e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>