<?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:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:googleplay="http://www.google.com/schemas/play-podcasts/1.0"><channel><title><![CDATA[Novacodes : Reading Code Line by Line]]></title><description><![CDATA[Learning programming is not only writing code — it is learning to read code well.
In this series we examine carefully written code line by line and explore the thinking behind it.]]></description><link>https://novacodes.substack.com/s/reading-code-line-by-line</link><image><url>https://substackcdn.com/image/fetch/$s_!FEN-!,w_256,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b7fcf87-faab-49cc-9494-a1a3cc927414_1024x1024.png</url><title>Novacodes : Reading Code Line by Line</title><link>https://novacodes.substack.com/s/reading-code-line-by-line</link></image><generator>Substack</generator><lastBuildDate>Tue, 14 Apr 2026 21:21:56 GMT</lastBuildDate><atom:link href="https://novacodes.substack.com/feed" rel="self" type="application/rss+xml"/><copyright><![CDATA[Nova]]></copyright><language><![CDATA[en]]></language><webMaster><![CDATA[novacodes@substack.com]]></webMaster><itunes:owner><itunes:email><![CDATA[novacodes@substack.com]]></itunes:email><itunes:name><![CDATA[Nova]]></itunes:name></itunes:owner><itunes:author><![CDATA[Nova]]></itunes:author><googleplay:owner><![CDATA[novacodes@substack.com]]></googleplay:owner><googleplay:email><![CDATA[novacodes@substack.com]]></googleplay:email><googleplay:author><![CDATA[Nova]]></googleplay:author><itunes:block><![CDATA[Yes]]></itunes:block><item><title><![CDATA[Reading Code Line by Line — ReportBuilder]]></title><description><![CDATA[How Thoughtful Design Turns Raw Data Into Structured Information]]></description><link>https://novacodes.substack.com/p/reading-code-line-by-line-reportbuilder</link><guid isPermaLink="false">https://novacodes.substack.com/p/reading-code-line-by-line-reportbuilder</guid><dc:creator><![CDATA[Nova]]></dc:creator><pubDate>Thu, 02 Apr 2026 20:05:15 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!FEN-!,w_256,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3b7fcf87-faab-49cc-9494-a1a3cc927414_1024x1024.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This code defines a small reporting system that collects numeric records and turns them into a structured summary.</p><p>Each record contains a category and an amount. The class stores those records, normalizes the data format, and then calculates useful information such as totals per category and percentage distribution.</p><p>In the end, the <strong>build_report()</strong> method combines everything into a single structured report that includes the total number of records, the totals per category, and the percentage distribution of the values.</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">from typing import Dict, List
from collections import defaultdict


class ReportBuilder:
    """
    Build structured reports from raw numeric records.
    Each record contains a category and an amount.
    """

    def __init__(self) -&gt; None:
        self.records: List[Dict[str, float | str]] = []

    def add_record(self, category: str, amount: float) -&gt; None:
        """ Store a normalized record."""
        record = self._normalize_record(category, amount)
        self.records.append(record)

    def _normalize_record(self, category: str, amount: float) -&gt; Dict[str, float | str]:
        """Ensure consistent data format."""
        return {
            "category": category.strip().lower(),
            "amount": float(amount)
        }

    def totals_by_category(self) -&gt; Dict[str, float]:
        """Aggregate totals per category."""
        totals = defaultdict(float)

        for record in self.records:
            totals[record["category"]] += record["amount"]

        return dict(totals)

    def _sorted_totals(self, totals: Dict[str, float]) -&gt; List[Dict[str, float | str]]:
        """Return category totals sorted from highest to lowest."""
        rows = []

        for category, amount in totals.items():
            rows.append({
                "category": category,
                "total": round(amount, 2)
            })

        rows.sort(key=lambda row: row["total"], reverse=True)
        return rows

    def percentage_breakdown(self, totals: Dict[str, float]) -&gt; List[Dict[str, float | str]]:
        """Calculate percentage share per category."""
        overall_total = sum(totals.values())

        breakdown = []

        for category, amount in totals.items():
            percentage = (amount / overall_total) * 100 if overall_total else 0

            breakdown.append({
               "category": category,
                "percentage": round(percentage, 2)
            })

        breakdown.sort(key=lambda row: row["percentage"], reverse=True)

        return breakdown

    def build_report(self) -&gt; Dict:
        """Produce the final report structure."""
        totals = self.totals_by_category()

        return {
            "records": len(self.records),
            "totals": self._sorted_totals(totals),
            "distribution": self.percentage_breakdown(totals)
        }
records = [
    ("books", 120.50),
    ("books", 35.20),
    ("food", 42.10),
    ("food", 15.90),
    ("tools", 210.00),
]

report = ReportBuilder()

for category, amount in records:
    report.add_record(category, amount)

result = report.build_report()

print(result)</code></pre></div><div><hr></div><h1>What This Program Does</h1><p>This class collects simple records consisting of a category and an amount. It then transforms those records into useful summaries.</p><p>The class performs several steps:</p><ul><li><p>store records in memory</p></li><li><p>normalize incoming data</p></li><li><p>aggregate totals per category</p></li><li><p>calculate percentage distribution</p></li><li><p>build a structured report</p></li></ul><p>In other words, the program turns raw input into structured information. Before looking at each line of code, it helps to understand this overall idea.</p><div><hr></div><h1>Reading the Code Line by Line</h1><p>Now we examine how the program is structured. The goal is not only to understand what the code does, but also to see how the logic is organized.</p><div><hr></div><p><strong>Imports</strong></p><pre><code>from typing import Dict, List
from collections import defaultdict</code></pre><p>The code imports <strong>Dict </strong>and <strong>List </strong>from Python&#8217;s <strong>typing module, </strong>and <strong>defaultdict </strong>from the <strong>collections</strong> module.</p><p><strong>Dict </strong>and <strong>List  </strong>are type hints. They do not change how the Python interpreter executes the program, but they help static analysis tools. By reading this line, we already know the program will likely store data as lists of dictionaries. </p><p><strong>defaultdict </strong>is a specialized dictionary type. It automatically creates a default value when a missing key is first accessed.</p><p>For example:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">defaultdict(float)</code></pre></div><p>means a new key automatically starts with:</p><pre><code>0.0</code></pre><p>This makes it especially useful for counting, grouping, and aggregation tasks.</p><p>From these imports alone, we can already infer two things:</p><ul><li><p>the program stores structured data in lists and dictionaries</p></li><li><p>the program likely uses automatic default values during aggregation</p></li></ul><div><hr></div><p><strong>Defining the Class</strong></p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">class ReportBuilder:</code></pre></div><p>The class name clearly communicates its role. It does not simply hold data. It builds a report from records. Good naming is one of the first signs of well-designed code.</p><div><hr></div><p><strong>Class Documentation</strong></p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">"""
Build structured reports from raw numeric records.
Each record contains a category and an amount.
"""</code></pre></div><p>The docstring explains the responsibility of the class.</p><p>Two key ideas appear immediately:</p><ul><li><p>input consists of raw records</p></li><li><p>each record contains a category and an amount</p></li></ul><p>Example input might look like this:</p><pre><code>("food", 12.5)
("rent", 800)
("food", 7.25)</code></pre><p>These incoming values are later normalized and stored internally as dictionaries like:</p><pre><code>{"category": "food", "amount": 12.5}</code></pre><p>The rest of the program transforms these simple records into a structured report.</p><div><hr></div><p><strong>Object Initialization</strong></p><pre><code>def __init__(self) -&gt; None:
    self.records: List[Dict[str, float | str]] = []</code></pre><p>When a <strong>ReportBuilder </strong>object is created, the constructor initializes an empty list. This list will hold all records added to the system.</p><p>Each stored record will look like this:</p><pre><code>{"category": "food", "amount": 12.5}</code></pre><p>At this stage, the class prepares an empty container where future records will be stored.</p><div><hr></div><p><strong>Adding a Record</strong></p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">def add_record(self, category: str, amount: float) -&gt; None:</code></pre></div><p>This method is the public entry point for inserting data. The user provides a category and an amount. However, the program does not store these values immediately.</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">record = self._normalize_record(category, amount)
self.records.append(record)</code></pre></div><p>Before storing anything, the input is normalized. Centralizing this step keeps the rest of the program simple and ensures that all stored records follow the same format.</p><div><hr></div><p><strong>Data Normalization</strong></p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">def _normalize_record(self, category: str, amount: float) -&gt; Dict[str, float | str]:</code></pre></div><p>The leading underscore indicates that the method is intended for internal use.</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">return {
    "category": category.strip().lower(),
    "amount": float(amount)
}</code></pre></div><p>Two normalization steps occur here. First, the category is cleaned.</p><pre><code>" Food "
"FOOD"
"food"</code></pre><p>All become:</p><pre><code>"food"</code></pre><p>Second, the amount is converted to a numeric value using <strong>float(). </strong>Normalization ensures that logically identical inputs are treated as the same category. Without this step, values like &#8220;Food&#8221;, &#8220; food &#8220;, and &#8220;FOOD&#8221; would appear as separate categories during aggregation.</p><div><hr></div><p><strong>Calculating Totals</strong></p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">def totals_by_category(self) -&gt; Dict[str, float]:</code></pre></div><p>This method aggregates all stored records.</p><p>The program uses:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">totals = defaultdict(float)</code></pre></div><p>This means every new category automatically starts with the value <strong>0.0. </strong></p><p>Because of that, the loop can stay compact:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">totals[record["category"]] += record["amount"]</code></pre></div><p>There is no need to manually check whether the category already exists in the dictionary.</p><p>At the end, the method returns a normal dictionary:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">return dict(totals)</code></pre></div><p>So the outside world still receives a plain <strong>dict</strong>, while the method uses <strong>defaultdict </strong>internally to keep the logic concise.</p><div><hr></div><p><strong>Sorting Totals</strong></p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">def _sorted_totals(self, totals: Dict[str, float]) -&gt; List[Dict[str, float | str]]:</code></pre></div><p>Dictionaries are convenient for aggregation and lookup, but converting the data into a list of rows makes it easier to sort and present in a predictable order.</p><p>The totals are converted into rows like this:</p><pre><code>{"category": "food", "total": 35.5}</code></pre><p>The totals are rounded to two decimal places to make the report easier to read and avoid long floating-point representations. These rows are then sorted so that the largest category appears first.</p><div><hr></div><p><strong>Percentage Distribution</strong></p><p>This method calculates how much each category contributes to the overall total.</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">def percentage_breakdown(self, totals: Dict[str, float]) -&gt; List[Dict[str, float | str]]:</code></pre></div><p>The percentage is calculated using:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">percentage = (amount / overall_total) * 100 if overall_total else 0</code></pre></div><p>The conditional prevents a division-by-zero error if the overall total equals zero. Each percentage value is rounded to two decimal places to keep the report readable.</p><div><hr></div><p><strong>Building the Final Report</strong></p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">def build_report(self) -&gt; Dict:</code></pre></div><p>The final method assembles the report.</p><p>First the totals are calculated once:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:null}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">totals = self.totals_by_category()</code></pre></div><p>Those totals are then reused when building the rest of the report.</p><p>The output structure looks like this:</p><pre><code>{
    "records": 3,
    "totals": [...],
    "distribution": [...]
}</code></pre><p>The result is a structured summary of the data.</p><div><hr></div><h1>Interesting Design Decisions</h1><p>Several design choices make this code clear and maintainable.</p><p><strong>Normalization before storage</strong></p><p>Incoming data is cleaned before it enters the system. This prevents inconsistent values from spreading through the program.</p><p><strong>Small focused methods</strong></p><p>Each method performs one clear task.</p><pre><code>add_record &#8594; receive input
_normalize_record &#8594; clean data
totals_by_category &#8594; aggregate values
_sorted_totals &#8594; organize totals
percentage_breakdown &#8594; analyze distribution
build_report &#8594; assemble the final output</code></pre><p>Breaking logic into small methods makes the program easier to test and maintain.</p><p><strong>Reusing existing logic</strong></p><p>Both <strong>_sorted_totals() </strong>and <strong>percentage_breakdown() </strong>reuse the totals produced by totals_by_category()</p><p>Computing totals once and passing them to other methods avoids repeated work and follows the single-responsibility principle, where each method performs one specific task.</p><p><strong>A cleaner aggregation pattern</strong></p><p>Using <strong>defaultdict(float) </strong>removes manual key initialization and keeps the aggregation logic concise. Small design choices like this often make production Python code easier to read and maintain.</p><h1>Behind the Camera</h1><p>When I first read this code, I do not start by examining each line. Instead, I try to understand <strong>what story the code is trying to tell</strong>.</p><ol><li><p>What problem is it solving?</p></li><li><p>What kind of data flows through the program?</p></li><li><p>What is the final result supposed to look like?</p></li></ol><p>Once I understand that story, I break it into smaller pieces.</p><p>For this example, the story looks roughly like this:</p><pre><code><code>receive records  
clean the data  
store the records  
calculate totals  
calculate percentages  
build a final report</code></code></pre><p>After that, I go back to the code and ask a simple question for each part of the story:</p><p><strong>Which function is responsible for this step?</strong></p><p>When you read code this way, the program stops looking like a wall of syntax.<br>It becomes a sequence of decisions made by the person who wrote it.</p><p>And that is the real goal of this series:<br>not just to read code &#8212; but to understand the thinking behind it.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://novacodes.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Novacodes ! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item></channel></rss>