<?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 Bryan Tjandra on Medium]]></title>
        <description><![CDATA[Stories by Bryan Tjandra on Medium]]></description>
        <link>https://medium.com/@bryantjandra2003?source=rss-ef9ddc2bbc1f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*V5-NfD6bJIt-fIXN</url>
            <title>Stories by Bryan Tjandra on Medium</title>
            <link>https://medium.com/@bryantjandra2003?source=rss-ef9ddc2bbc1f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:21:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bryantjandra2003/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[Spot the Holes Before You Dig Them: A Developer’s Guide to Threat & Risk Analysis]]></title>
            <link>https://medium.com/@bryantjandra2003/spot-the-holes-before-you-dig-them-a-developers-guide-to-threat-risk-analysis-dff1a12a7461?source=rss-ef9ddc2bbc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dff1a12a7461</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[secure-programming]]></category>
            <dc:creator><![CDATA[Bryan Tjandra]]></dc:creator>
            <pubDate>Sat, 03 May 2025 07:09:38 GMT</pubDate>
            <atom:updated>2025-05-03T07:09:38.873Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7RLdnttM1OnqEg06" /><figcaption>Source: <a href="https://www.cyberarrow.io/blog/20-compliance-memes-laugh-learn-and-comply/">https://www.cyberarrow.io/blog/20-compliance-memes-laugh-learn-and-comply/</a></figcaption></figure><p>“Push code first, patch later” might be the unofficial mantra of many fast-moving dev teams, but it’s also the quickest route to 3 a.m. incident calls, angry users, and sleepless nights. For teams that actually enjoy stability, there’s a better strategy, spot your problems before they go live. The first core principle of secure programming is simple but often ignored: understand your threats, assess your risks, and plan your defenses in advance. This guide is for any software team building modern systems, whether you’re rolling out a nationwide e-commerce platform, launching the next viral dating app, or maintaining an AI-powered legal assistant like Navigo.</p><p>To do this right, it’s crucial to get clear on the difference between a threat and a risk, two terms that are often thrown around interchangeably but mean very different things</p><h3>Threat vs. Risk</h3><p>A <em>threat</em> is anything that can go wrong in or around your system. It’s the malicious actor who finds a way to exploit your API, the outdated dependency that opens a hole in your backend, the intern who accidentally pushes secrets to a public repo, or the misconfigured TLS certificate that lets attackers play man-in-the-middle. In short, a threat is the potential for trouble, any vector or vulnerability that could be taken advantage of.</p><p><em>Risk</em>, on the other hand, is what happens when you combine that threat with two critical factors: how likely it is to occur, and how damaging it would be if it did. This is where judgment and prioritization come into play. Not every threat deserves equal attention. A zero-day vulnerability that’s theoretically possible but hard to pull off might pose less immediate danger than a misused access token that’s exposed to all your internal staff. A one-in-a-million encryption key leak that could bankrupt your entire company still sits higher on the priority list than a debug log throwing warnings every few hours.</p><p>A good metaphor? Think of a threat like a bolt of lightning: it’s powerful, dangerous, and unpredictable. But risk is whether your house is the tallest one on the hill, and whether you decided to fill it with fireworks. Smart teams don’t just catalogue threats; they put them in context. That context is what allows you to build systems that are not only functional but resilient.</p><h3>A Five-Step Routine You Can Reuse on Any Project</h3><p>When it comes to integrating security into the development lifecycle, teams often struggle with consistency. Everyone agrees that threat modeling matters, but few have a lightweight, reusable routine they can run across multiple projects without drowning in process. Here’s a five-step framework that works whether you’re building a weekend prototype or maintaining a compliance-heavy enterprise platform. It’s simple, adaptable, and most importantly, actionable.</p><h4>Step 1: Draw the Data Flow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*2YHSKzfQMcYSd_IOTATETQ.png" /><figcaption>Source: <a href="https://www.researchgate.net/publication/353939407_A_Threat-Based_Cybersecurity_Risk_Assessment_Approach_Addressing_SME_Needs/figures?lo=1">https://www.researchgate.net/publication/353939407_A_Threat-Based_Cybersecurity_Risk_Assessment_Approach_Addressing_SME_Needs/figures?lo=1</a></figcaption></figure><p>Start with a map. Before any security discussions, take the time to visualize your system’s data flow. Grab a whiteboard, spin up a diagramming tool like Figma or Lucidchart, or even sketch it out on paper. The goal here is clarity: map every major component and connection in your architecture. From browser to backend, from API gateway to database, from your service to a third-party ML model, document every hop, every protocol, every channel. What systems touch the data? What formats does it travel in? What secrets (e.g., tokens, credentials) are passed along the way?</p><p>This step is deceptively powerful. Teams often miss vulnerabilities not because they’re bad at security, but because they overlook how complex their system really is. Invisible arrows in a system diagram, those undocumented steps or assumptions, often become the blind spots attackers exploit. When in doubt, overdraw. It’s better to flag a connection that seems obvious than to forget one that’s critical.</p><h4>Step 2: Crown the Jewels</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rTznwEWc3-6CiFH_.png" /><figcaption>Source: <a href="https://privacy.blackfog.com/wp-content/uploads/2022/05/Crown-Jewels.png">https://privacy.blackfog.com/wp-content/uploads/2022/05/Crown-Jewels.png</a></figcaption></figure><p>Once you’ve mapped your data flow, ask the most important question of all: <em>What do we care about protecting the most?</em> This is about identifying your crown jewels, the parts of the system that, if exposed, destroyed, or manipulated, would cause serious damage.</p><p>The list will vary depending on your product, but some common categories always appear. Personally identifiable information (PII) is often at the top, especially if you handle user profiles, health data, or financial records. Payment flows or account credits come next, since they’re direct targets for fraud. Then there’s intellectual property, your models, algorithms, or unique datasets. And of course, secrets: your API tokens, private keys, environment variables, and anything else that grants power inside your system.</p><p>No crown jewels, no focus. Without clarity on what matters most, your threat analysis becomes a guessing game. But when you’ve clearly identified what’s most valuable, you can make smarter decisions about where to invest defensive effort.</p><h4>Step 3: Brainstorm the Badness (a.k.a. Threat Modeling)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hkqb-b0jtyITektI.png" /><figcaption>Source: <a href="https://online.visual-paradigm.com/diagrams/templates/threat-model-diagram/stride-threat-model/">https://online.visual-paradigm.com/diagrams/templates/threat-model-diagram/stride-threat-model/</a></figcaption></figure><p>Now that you know your architecture and what you need to protect, it’s time to get creative, in the worst way. Threat modeling is all about thinking like an attacker. What could go wrong? What could someone do if they wanted to hurt your system, steal your data, or drain your budget?</p><p>There are several techniques to help teams brainstorm threats effectively, and the best method is the one your team can stick to. STRIDE is a classic: it encourages you to consider six categories of attack, Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, and Elevation of Privilege. If your team is into security frameworks, you might prefer using a KILL CHAIN approach or MITRE ATT&amp;CK matrix, which are more detailed and often used by incident response or blue teams. For Agile teams, “abuse stories” are a popular approach, flip the user story format and say things like, <em>“As an attacker, I want to flood the upload API so storage costs explode,”</em> or <em>“As a malicious user, I want to escalate from viewer to admin.”</em></p><p>The point here is volume, not perfection. Capture every idea, no matter how far-fetched or minor it seems. Don’t self-censor or debate feasibility yet. Just build the list. You’ll sort it out next.</p><h4>Step 4: Score and Prioritize</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Olr7MfAsFKHO0kPc.png" /><figcaption>Source: <a href="https://hyperproof.io/resource/the-ultimate-guide-to-risk-prioritization/">https://hyperproof.io/resource/the-ultimate-guide-to-risk-prioritization/</a></figcaption></figure><p>With your list of threats in hand, now it’s time to bring order to the chaos. Each threat needs a risk score, something simple enough for anyone to use, but clear enough to drive action. A common method is to assign each threat a <strong>Likelihood</strong> score (how probable is it?) and an <strong>Impact</strong> score (how bad would it be if it happened?). Use a 1–5 scale for each, then multiply them to get a total risk score out of 25.</p><p>Once scored, categorize them using a color system: red for high-risk (“stop everything and fix this”), yellow for medium-risk (“address it in the next sprint”), and green for low-risk (“log it, monitor it, revisit later”). This kind of visibility doesn’t just help engineers, it arms your product manager and leadership team with clear, defensible reasons why a risky new feature should be delayed or redesigned.</p><p>The beauty of this system is that it turns subjective fear into quantifiable planning. You’re not saying “this feels scary,” you’re saying, “this has a 20/25 risk score and could compromise production credentials.” That makes all the difference in cross-functional prioritization.</p><h4>Step 5: Document and Own It</h4><p>The final step is where many teams fall short. Even if you’ve identified risks and built a plan, the work gets lost if it’s not documented and assigned. Risks that live only in someone’s head, or worse, a one-off Slack message, don’t get tracked. And untracked risks have a nasty habit of turning into real incidents when everyone’s forgotten about them.</p><p>Pick a central place to store your threat model, Confluence, Notion, GitHub Issues, a shared Google Doc, whatever fits your team’s workflow. The key is that it must be accessible, versioned, and tied to the work you’re doing. Each risk should also have an owner. That doesn’t mean one person has to fix it, but someone needs to be accountable for ensuring it gets addressed, mitigated, or explicitly accepted.</p><p>Without ownership, risk becomes background noise. With ownership, it becomes part of the team’s engineering discipline.</p><h3>Common Threat Buckets You’ll Meet Everywhere</h3><p>No matter what kind of software you’re building — mobile app, web platform, embedded system — some categories of threats show up again and again. These aren’t rare edge cases; they’re the greatest hits of the attacker playbook. If you’re doing threat modeling, these are the “starter cards” you should always have on the table:</p><h4>Injection Attacks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uyUTBfI7pzZg3ggm.jpeg" /><figcaption>Source: <a href="https://getnametag.com/newsroom/digital-injection-attacks-what-how-explained">https://getnametag.com/newsroom/digital-injection-attacks-what-how-explained</a></figcaption></figure><p>This classic threat includes SQL injection, NoSQL injection, OS command injection, and even LDAP injection. The common thread? Untrusted input that gets interpreted as code.</p><ul><li><strong>Example</strong>: A search box that lets a user input &#39; OR 1=1-- and returns every user in your database is a textbook SQL injection flaw.</li><li><strong>Defense</strong>: Always use parameterized queries or ORM methods that separate logic from data.</li></ul><h4>Broken Authentication &amp; Session Handling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FApiUOK_YHcGcP0y.png" /><figcaption>Source: <a href="https://medium.com/dlt-labs-publication/broken-authentication-session-management-flaws-causes-fixes-5b8bedceb8f">https://medium.com/dlt-labs-publication/broken-authentication-session-management-flaws-causes-fixes-5b8bedceb8f</a></figcaption></figure><p>Auth is hard, and attackers love it when you cut corners. Weak JWT signatures, missing token expiration, improperly implemented OAuth flows, or allowing session IDs to be reused all open doors.</p><ul><li><strong>Example</strong>: If your JWT tokens are signed with alg: none, congratulations, you’ve given anyone admin powers.</li><li><strong>Defense</strong>: Use strong cryptographic signing algorithms, enforce expiration, and validate state transitions in login flows.</li></ul><h4>Misconfiguration</h4><p>This one’s a silent killer. Default passwords, open cloud storage buckets, exposed admin panels, and verbose error messages in production all fall under this category.</p><ul><li><strong>Example</strong>: A misconfigured S3 bucket containing logs or user data that’s publicly accessible via direct URL.</li><li><strong>Defense</strong>: Automate security scans (e.g., AWS Config Rules, infrastructure as code checks), and avoid manual configuration wherever possible.</li></ul><h4>Sensitive Data Exposure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/0*9uia7KrgL6cPuMtH.jpeg" /><figcaption>Source: <a href="https://medium.com/@BreezeTelecom/sensitive-data-exposure-vulnerability-causes-and-prevention-4c86a19df70d">https://medium.com/@BreezeTelecom/sensitive-data-exposure-vulnerability-causes-and-prevention-4c86a19df70d</a></figcaption></figure><p>It’s easy to leak data without meaning to. Logs might contain passwords. Error messages might include stack traces. Old backups might sit unencrypted in a forgotten cloud folder.</p><ul><li><strong>Example</strong>: A crash report that includes a full JWT token in plain text, now visible to your entire dev team, and maybe attackers too.</li><li><strong>Defense</strong>: Mask or sanitize logs, encrypt data at rest and in transit, and review retention policies.</li></ul><h4>Supply Chain Attacks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/0*QxxbrpEsjUYkAOaQ" /><figcaption>Source: <a href="https://pentest-tools.com/blog/supply-chain-attacks">https://pentest-tools.com/blog/supply-chain-attacks</a></figcaption></figure><p>Third-party libraries and services are part of your system, and can be a way in. From typosquatted packages on NPM to unsigned commits and exposed CI/CD secrets, the ecosystem can be your weak point.</p><ul><li><strong>Example</strong>: Installing an NPM package named expresss instead of express,which happens to steal environment variables on install.</li><li><strong>Defense</strong>: Use package integrity verification, pin versions, scan dependencies for known vulnerabilities, and lock down your CI pipeline.</li></ul><p><strong>Pro Tip:</strong> The <a href="https://owasp.org/www-project-top-ten/">OWASP Top 10</a> is an industry-standard list of the most common and critical web app vulnerabilities. Make it a habit to scroll through it once a quarter. Think of it as the Google Maps of secure development, it doesn’t replace your instincts, but it helps you avoid obvious traps.</p><h3>How It Fits into the SDLC (Software Development Lifecycle)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*ykvolbEPXSU1T91H.jpg" /><figcaption>Source: <a href="https://www.geeksforgeeks.org/software-development-life-cycle-sdlc/">https://www.geeksforgeeks.org/software-development-life-cycle-sdlc/</a></figcaption></figure><p>Threat and risk analysis isn’t a one-time checklist. It should evolve alongside your codebase. Here’s how it fits neatly into each phase of the SDLC so it becomes a habit, not an afterthought.</p><h4>Planning</h4><p>During backlog grooming or sprint planning, include a quick brainstorm around how a proposed feature could be misused.</p><ul><li><strong>Example</strong>: If you’re planning to add file uploads, ask: <em>“What’s the worst someone could upload?”</em> Malware? Oversized files that crash the server?</li><li><strong>Result</strong>: You might decide to limit file size, scan uploads for viruses, or restrict file types.</li></ul><h4>Design</h4><p>Attach a lightweight threat model document to every high-risk feature. This doesn’t need to be exhaustive, just enough to show you’ve thought it through.</p><ul><li><strong>Example</strong>: For a new payment flow, diagram the data path, list possible threats (e.g., fraud, man-in-the-middle), and propose mitigations.</li><li><strong>Result</strong>: Everyone from devs to product to security is aligned before any code is written.</li></ul><h4>Code Review</h4><p>Pair code reviews with a security checklist. Don’t rely on gut feeling. Establish specific questions reviewers should ask.</p><ul><li><strong>Example</strong>: “Are inputs validated?”, “Are secrets being logged?”, “Is this crypto implementation custom?”</li><li><strong>Result</strong>: You catch issues early and educate the team on secure patterns over time.</li></ul><h4>CI/CD</h4><p>Automate scanning for known bad patterns and insecure configurations. These checks should be part of every push — not a monthly audit.</p><p><strong>Tools</strong>:</p><ul><li>Static Analysis (e.g., SonarQube, Semgrep)</li><li>Secret Scanners (e.g., TruffleHog, Gitleaks)</li><li>Container Scanners (e.g., Snyk, Grype)</li></ul><p><strong>Result</strong>: You eliminate obvious vulnerabilities before they hit staging or production.</p><h4>Release</h4><p>Hardening happens here. Sign your build artifacts, tag known-good commits, and use feature flags so you can turn off risky features quickly.</p><ul><li><strong>Example</strong>: You release a new API route behind a feature flag. If abuse spikes, you can kill it instantly — no hotfix needed.</li><li><strong>Result</strong>: Faster, safer rollouts and easier rollback paths.</li></ul><h4>Operations</h4><p>Security doesn’t end at deployment. You should actively monitor for the threats you predicted during threat modeling.</p><ul><li><strong>Example</strong>: If you worried about login brute force, watch for auth failures. If you worried about abuse of your image processing API, watch for spike patterns.</li><li><strong>Tools</strong>: WAFs (Web Application Firewalls), SIEMs (like Splunk), alerting systems, and metrics dashboards.</li><li><strong>Result</strong>: You catch attacks in progress — or even before they do damage.</li></ul><p>And when your system changes, new vendor, new microservice, new region, you loop back. Threat modeling isn’t a one-and-done exercise. It’s a continuous muscle to build.</p><h3>Implementing Authentication &amp; Authorization in a Real-World React + Supabase Project</h3><p>So you’ve mapped the data flows, crowned the jewels, and terrorized your teammates with a long list of threats. Awesome. Now you have exactly one question left to answer before attackers do:</p><p><strong>“Can every request in my system be reliably traced back to an identity, and can I prove that identity is allowed to do what it’s doing?”</strong></p><p>Below is a ground-up, walkthrough that shows <strong>how the sample repo you shared already tackles authN (authentication) and authZ (authorization)</strong>, and how you can replicate the pattern on your own projects.</p><h3>1. Choosing the Trust Anchor</h3><p>In any secure system, the first step is identifying who you trust to handle identity. In this setup, we use <strong>Supabase Auth</strong> as our source of truth for all user identities. Supabase provides a modern, developer-friendly auth system that’s built on top of PostgreSQL and designed to integrate directly into frontend frameworks like React.</p><p>Here’s why Supabase Auth works so well:</p><ul><li><strong>Managed PostgreSQL</strong>: With built-in support for Row-Level Security (RLS), you get access control enforced directly at the database level, not just in your app logic.</li><li><strong>Multiple auth strategies out of the box</strong>: Supabase supports email/password login, magic links, and social providers like Google and GitHub, all configurable through its GUI.</li><li><strong>A JavaScript SDK</strong>: This SDK handles all the token management, session storage, and identity operations with minimal setup.</li></ul><p><strong>Getting started:</strong></p><ol><li>Log into the Supabase dashboard.</li><li>Go to <strong>Auth → Settings</strong>.</li><li>Enable “Email/Password” authentication.</li><li>Enable Google OAuth and paste your client credentials.</li><li>In your .env file (never commit this), add:</li></ol><pre>VITE_SUPABASE_URL=&quot;https://xyz.supabase.co&quot;<br>VITE_SUPABASE_ANON_KEY=&quot;eyJhbGciOiJIUzI1...&quot;<br>VITE_URL=&quot;http://localhost:5173&quot;      # OAuth redirect</pre><p>These variables configure your frontend app to communicate securely with the Supabase backend.</p><h3>2. Wiring the SDK — src/common/supabase.ts</h3><p>Centralizing the Supabase client setup is a small but strategic decision. By wrapping the client creation in a single module, you unlock future flexibility.</p><p>Here’s the code:</p><pre>import { createClient } from &quot;@supabase/supabase-js&quot;;<br><br>export const supabase = createClient(<br>  import.meta.env.VITE_SUPABASE_URL,<br>  import.meta.env.VITE_SUPABASE_ANON_KEY<br>);</pre><p><strong>Why this matters:</strong></p><ul><li>Want to log every query? Add interceptors here.</li><li>Want to mock Supabase during testing? Swap out this module.</li><li>Need to centralize error tracking or telemetry? This is your injection point.</li></ul><p>It’s like building your own service layer, future-you will thank you.</p><h3>3. Reusable Auth Helpers — src/lib/auth.ts</h3><p>Rather than calling Supabase’s auth methods directly in your React components, it’s best to wrap them in helper functions. This approach separates concerns and improves testability.</p><p>Example helpers:</p><pre>import { supabase } from &quot;@/common/supabase&quot;;<br><br>// -------- EMAIL/PASSWORD --------<br>export const signUpWithEmailAndPassword = async (<br>  fullName: string,<br>  email: string,<br>  password: string<br>) =&gt; {<br>  const { data, error } = await supabase.auth.signUp({<br>    email,<br>    password,<br>    options: { data: { name: fullName } },<br>  });<br>  if (error) throw error;<br>  return data;<br>};<br>export const signInWithEmailAndPassword = async (email: string, password: string) =&gt; {<br>  const { data, error } = await supabase.auth.signInWithPassword({ email, password });<br>  if (error) throw error;<br>  return data;<br>};<br>// -------- GOOGLE OAUTH --------<br>export const signInWithGoogle = () =&gt;<br>  supabase.auth.signInWithOAuth({<br>    provider: &quot;google&quot;,<br>    options: { redirectTo: import.meta.env.VITE_URL },<br>  });<br>// -------- SIGN-OUT --------<br>export const signOut = () =&gt; supabase.auth.signOut();</pre><p>Other helpers follow a similar pattern: concise, consistent, and resilient to change. If Supabase’s API changes or if you want to add reCaptcha validation, you only need to update your wrappers.</p><p><strong>Benefits of this approach:</strong></p><ul><li>Keeps your UI components focused purely on presentation.</li><li>Creates a centralized place for logging or user analytics.</li><li>Makes it easy to test auth logic without a real backend.</li></ul><h3>4. The UX Layer — src/components/auth/AuthForm.tsx</h3><p>This component handles user interaction. It’s split into:</p><ul><li>SocialButton: a button that initiates OAuth with Google.</li><li>EmailPasswordForm: a form for manual sign-in or registration.</li><li>ToggleAuthModeLink: a way to switch between login and signup modes.</li></ul><p>Inside the email/password flow, the component includes some basic client-side validation:</p><pre>if (password.length &lt; 8) { setError(&quot;Too short&quot;); return; }<br>if (password !== confirmPassword) { setError(&quot;Mismatch&quot;); return; }</pre><p><strong>Important note</strong>: These checks only serve the user experience. Real enforcement (e.g., minimum password length) happens server-side. Always assume the client can be bypassed.</p><p>By splitting the form logic this way, you:</p><ul><li>Reduce complexity in each component.</li><li>Allow easy reuse in other flows (like modals or onboarding).</li><li>Enable future expansion (e.g., email confirmation, MFA) without rewriting everything.</li></ul><h3>5. Persisting Session &amp; Locking Routes — src/hoc/AuthProvider.tsx</h3><p>In a secure app, users must be redirected when not logged in. Supabase handles session storage (via localStorage), but your frontend needs to respect that session and enforce protected routes.</p><p>Example logic:</p><pre>const whiteListPaths = [&quot;/login&quot;, &quot;/register&quot;];<br><br>useEffect(() =&gt; {<br>  supabase.auth.onAuthStateChange((_, session) =&gt; {<br>    setUser(session?.user ?? null);<br>    if (!session?.user &amp;&amp; !whiteListPaths.includes(window.location.pathname)) {<br>      navigate(`/login?next=${window.location.pathname}`);<br>    }<br>    setIsLoading(false);<br>  });<br>}, []);</pre><p>This hook does a few critical things:</p><ul><li>Listens for login/logout events.</li><li>Redirects unauthorized users away from protected pages.</li><li>Prevents screen “flashes” by hiding the app until the auth state is loaded.</li></ul><p><strong>Why this pattern works:</strong></p><ul><li>You centralize access control logic.</li><li>Any route in your app can now use { user, isLoading } to decide what to show.</li><li>You preserve a smooth UX with next query params, so users land back where they intended to go.</li></ul><h3>6. Sealing Data with Row-Level Security</h3><p>Protecting routes in React isn’t enough. Attackers can still hit your API directly. That’s why Supabase’s Row-Level Security (RLS) is a game changer.</p><p>Example policy:</p><pre>alter table public.documents enable row level security;<br>create policy &quot;Own rows only&quot; on public.documents<br>  for all using ( auth.uid() = owner_id );</pre><p><strong>What this means:</strong></p><ul><li>Even if a malicious user intercepts a request and changes the id, they can’t read or write data they don’t own.</li><li>Your backend is secure by default, every row check is scoped to the logged-in user.</li></ul><p>This brings “zero trust” into the database itself.</p><h3>7. Adding Role-Based Authorization</h3><p>For multi-role apps (e.g., admins vs. normal users), you can enforce access control based on user metadata.</p><p>Steps:</p><ol><li>Add a role column to your profiles table.</li><li>Set the role on signup or via the dashboard.</li><li>In your frontend:</li></ol><pre>const { user, isLoading } = useAuth();<br>if (isLoading) return &lt;Loading /&gt;;<br>if (user?.user_metadata.role !== &quot;admin&quot;) return &lt;Navigate to=&quot;/&quot; replace /&gt;;<br>return &lt;AdminDashboard /&gt;;</pre><p>4. In Supabase SQL:</p><pre>create policy &quot;Admins only&quot; on public.documents<br>  for update using ( auth.jwt() -&gt;&gt; &#39;role&#39; = &#39;admin&#39; );</pre><p>Optional: add an RLS policy that allows DELETEs or UPDATEs only when user_metadata-&gt;&gt;’role’ = &#39;admin&#39;.</p><p>Now only admins can perform sensitive operations. And the enforcement happens where it matters, on the database.</p><h3>8. Testing the Angry Path</h3><p>You can’t call your app secure unless you test the edge cases, bad inputs, broken tokens, and unauthorized access.</p><p>Example in Supabase SQL Editor:</p><pre>set role anon;<br>select * from public.documents where id = &#39;somebody_elses_doc&#39;; -- should ERROR</pre><p>In Vitest:</p><pre>vi.mock(&quot;@/common/supabase&quot;, () =&gt; ({<br>  supabase: { auth: { signInWithPassword: vi.fn(() =&gt; ({ data: null, error: { message: &quot;Invalid&quot; } })) } }<br>}));</pre><p>Verify that:</p><ul><li>Errors are shown to the user clearly.</li><li>The app doesn’t crash.</li><li>Sensitive info is never leaked via logs or error messages.</li></ul><h4>9. The result</h4><p>Once implemented, you have a full authentication and authorization system that:</p><ul><li>Supports multiple login methods.</li><li>Redirects users based on session state.</li><li>Enforces true backend access control using RLS and JWT-based policies.</li><li>Supports role-based features like admin dashboards.</li><li>Handles both happy paths and security failures gracefully.</li></ul><p>In other words, your React + Supabase app is no longer just functional, it’s <em>defensible</em>. You’re not just trusting the frontend; you’re defending the backend. And that’s what modern web security looks like.</p><p>Whenever a user would like to access the page, they will be redirected to the login section first. In this case, they can log in with signed-up email and password or can directly use the Google authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MC3byR3O6ZFKvnujWwlH9Q.png" /><figcaption>Login section</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmjeGWyRya_5_5_MvGUKAQ.png" /><figcaption>Register page</figcaption></figure><p>If the user is still trying to access the feature by changing the endpoint, they will still be redirected to the login/signup page. Once they have been authorized, they can now try the Navigo features</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzjPaj4LN-3P-5Lm5bXoiA.png" /><figcaption>Dashboard page for logged in user</figcaption></figure><h3>Applying standard secure programming (OWASP)</h3><p>So far you have:</p><p>• Threat-modelled the system<br> • Locked every request behind authentication &amp; authorization</p><p>Great, but bugs don’t read blog posts. They sneak back in the moment you merge a new pull request. In this section, I will how to bake <strong>OWASP-style secure-coding standards</strong> straight into your repo <strong>and</strong> prove they work with automated tests.</p><h4>1. What “secure-by-default” actually means</h4><p>OWASP gives us practical lists, the famous <strong>Top 10</strong> (web vulns) and <strong>ASVS</strong> (detailed checklist). Our goal is not to memorize them, but to translate them into <em>repeatable guard-rails</em>:</p><ol><li>Static rules that fail the build (npm run lint:security)</li><li>Dependency checks (pnpm audit)</li><li>Secrets detectors (gitleaks)</li><li>Runtime policies (Content-Security-Policy, RLS)</li><li>Tests that simulate an attacker</li></ol><p>If a teammate forgets a rule, the pipeline reminds them , loudly.</p><h4>2. Mapping OWASP Top 10 → Our Codebase</h4><p><strong>OWASP Top 10 Risk Coverage</strong></p><ul><li><strong>A01 — Broken Access Control</strong><br>✅ Supabase Row-Level Security (RLS) with owner_id policy enforces per-user data access.</li><li><strong>A02 — Cryptographic Failures</strong><br>✅ Supabase handles all token generation and encryption; no custom crypto logic used.</li><li><strong>A03 — Injection</strong><br>✅ Uses parameterized queries via Supabase RPC and PostgREST — no raw SQL strings.</li><li><strong>A04 — Insecure Design</strong><br>✅ Application threat model established; AuthProvider enforces route-level protection.</li><li><strong>A05 — Security Misconfiguration</strong><br>✅ Infrastructure as Code (Terraform); CI scans check for misconfigs like public buckets.</li><li><strong>A06 — Vulnerable Components</strong><br>✅ Uses pnpm audit and snyk test to scan dependencies on every CI push.</li><li><strong>A07 — Identification &amp; Authentication Failures</strong><br>✅ Supabase Auth with enforced 8-character minimum passwords; optional MFA support.</li><li><strong>A08 — Software &amp; Data Integrity Failures</strong><br>✅ GitHub Actions signs build artifacts using sonar.yml pipeline.</li><li><strong>A09 — Security Logging &amp; Monitoring Failures</strong><br> ✅ Supabase provides auth logs; logs exported to Logflare for analysis.</li><li><strong>A10 — Server-Side Request Forgery (SSRF)</strong><br>✅ No server-side requests to user-supplied URLs; only client-side fetching implemented.</li></ul><h4>3. Static Guard-Rails in CI/CD</h4><p>Linting, scanning, and static analysis catch vulnerabilities before they ever ship. Let’s walk through some practical CI/CD additions that can enforce good security hygiene automatically.</p><p><strong>3.1 ESLint + eslint-plugin-security</strong></p><p><strong>Purpose:</strong> Adding eslint-plugin-security helps you automatically flag dangerous coding patterns like use of eval, insecure regular expressions, or risky modules like child_process.</p><p><strong>Implementation:</strong></p><pre>pnpm add -D eslint-plugin-security</pre><pre>// eslint.config.js<br>module.exports = {<br>  extends: [&quot;plugin:security/recommended&quot;],<br>};</pre><p>This ensures that developers get real-time feedback on insecure code patterns before merging.</p><p><strong>3.2 Semgrep Custom Rules</strong></p><p><strong>Purpose:</strong> Semgrep is a lightweight static analysis tool you can tune with custom rules. It’s ideal for catching anti-patterns specific to your codebase — like use of dangerouslySetInnerHTML in React.</p><p><strong>Rule Example:</strong></p><pre># .semgrep/owasp.yml<br>rules:<br>  - id: react-xss-dangerously-set-inner-html<br>    patterns:<br>      - pattern-either:<br>          - pattern: dangerouslySetInnerHTML={{...}}<br>    message: &quot;Avoid dangerouslySetInnerHTML → potential XSS&quot;<br>    severity: ERROR<br>    languages: [typescript, javascript]</pre><p><strong>CI Integration:</strong></p><pre># .github/workflows/semgrep.yml<br>jobs:<br>  semgrep:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: returntocorp/semgrep-action@v1<br>        with:<br>          config: .semgrep</pre><p>This turns your entire repo into a continuously checked security boundary.</p><p><strong>3.3 Gitleaks Secret Scan</strong></p><p><strong>Purpose:</strong> Accidentally committing secrets like Supabase tokens, API keys, or private keys is devastating. gitleaks catches these instantly.</p><p><strong>CI Integration:</strong></p><pre># .github/workflows/secret-scan.yml<br>jobs:<br>  gitleaks:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - name: Scan<br>        uses: zricethezav/gitleaks-action@v2</pre><p>This scan fails your pipeline if secrets are committed, enforcing secret hygiene at the source.</p><h4>4. Runtime Hardening</h4><p>Your deployed app should defend itself, even if something slips through. Here’s how to set up layered defenses in production.</p><p><strong>4.1. Content Security Policy (CSP):</strong></p><pre>&lt;meta<br>  http-equiv=&quot;Content-Security-Policy&quot;<br>  content=&quot;default-src &#39;self&#39;; img-src https://*; style-src &#39;self&#39; &#39;unsafe-inline&#39;;&quot;<br>/&gt;</pre><p>This mitigates XSS by limiting which resources the browser can load.</p><p><strong>4.2. Rate Limiting (Edge Function):</strong></p><pre>import { RateLimiterMemory } from &quot;rate-limiter-flexible&quot;;<br>const limiter = new RateLimiterMemory({ points: 20, duration: 60 });<br><br>export default async (req, res) =&gt; {<br>  try {<br>    await limiter.consume(req.headers[&quot;x-forwarded-for&quot;] || &quot;anon&quot;);<br>  } catch {<br>    return res.status(429).json({ error: &quot;Too Many Requests&quot; });<br>  }<br>  // …handler…<br>};</pre><p>This protects your endpoints from abuse or brute-force attacks.</p><p><strong>4.3. HTTP-Only Cookies:</strong> Switch Supabase to auth.persistSession = &quot;COOKIE&quot; to prevent XSS-based token theft. A small change, but huge impact.</p><h4>5. Testing the Defenses</h4><p><strong>5.1 Unit Tests with Vitest:</strong></p><pre>it(&quot;denies reading other people&#39;s docs&quot;, async () =&gt; {<br>  const { error } = await supabase<br>    .from(&quot;documents&quot;)<br>    .select(&quot;*&quot;)<br>    .eq(&quot;id&quot;, &quot;somebody_else_doc&quot;);<br>  expect(error?.code).toBe(&quot;42501&quot;);<br>});</pre><p>Ensure RLS enforcement is verifiable in tests.</p><p><strong>5.2 OWASP ZAP Dynamic Scan:</strong></p><pre>docker run -t ghcr.io/zaproxy/zaproxy zap-baseline.py \<br>  -t http://localhost:5173 -g gen.conf -r zap-report.html</pre><p>Add this to CI to catch reflected XSS, open redirects, and other runtime flaws.</p><p><strong>5.3 Manual Pen-Test Checklist:</strong></p><ul><li>☐ SQLi in query params → should sanitize or 404</li><li>☐ Alter JWT sub claim → RLS should block</li><li>☐ Upload large file → expect HTTP 413</li></ul><p>Track findings in a markdown file and triage into engineering backlog.</p><h4>6. Secure Code Review Ritual</h4><p>Before merging, reviewers should:</p><ul><li>Open the threat model doc</li><li>Run pnpm run security-check locally (aggregates lint, semgrep, audit)</li><li>Confirm new DB migrations contain RLS policies</li></ul><p>Add this to your pull-request template:</p><pre>### Security<br>- [ ] Inputs validated<br>- [ ] RLS updated<br>- [ ] No new secrets committed</pre><p>A simple ritual, but it creates powerful cultural pressure toward secure defaults.</p><h4>7. Break-the-Build Policy</h4><p>Automatically block insecure code before it merges:</p><pre># .github/workflows/ci.yml<br>if: failure() &amp;&amp; github.event_name == &#39;pull_request&#39;<br>steps:<br>  - name: Comment failure<br>    uses: marocchino/sticky-pull-request-comment@v2<br>    with:<br>      message: |<br>        🚨 Security check failed. Fix findings before merging.</pre><p>Highlighting failure in the pull request makes insecure code socially expensive, and encourages fast remediation.</p><h3>The OWASP Top-10 Hiding in My Feature</h3><p>You already have a slick UI that finds risky clauses, asks an LLM to fix them, and lets the user apply the patch with one click. Great UX, but attackers love it too. Now, I would like to give some real life cases based on the feature I’ve been working on.<br>Below, we walk through the same feature (MarkdownViewer, RiskClausesLayout, RiskItem) with an OWASP flashlight: where each Top-10 item shows up, why it is dangerous, and a code-level patch you can drop into the repo today.</p><h4>A01 — Broken Access Control</h4><p><strong>The Risk:</strong> Allowing users to supply arbitrary file URLs (like pdfUrl) without verifying ownership can lead to serious data breaches. If your backend blindly downloads and processes any S3 URL passed in by the frontend, a user could retrieve another person’s contract by pasting in a private link they shouldn’t have access to.</p><p><strong>The Fix:</strong> Forward the Supabase JWT from the client so the backend knows who is making the request. On the backend, verify user identity and ownership before downloading any document. Also, enforce Row-Level Security (RLS) at the database level:</p><pre>const { data: { session } } = await supabase.auth.getSession();<br>apiRequest(prompt, body, {<br>  headers: { Authorization: `Bearer ${session?.access_token}` }<br>});</pre><pre>alter table documents enable row level security;<br>create policy &quot;only owner&quot; on documents<br>  for select using ( auth.uid() = owner_id );</pre><p>This ensures only document owners can view or interact with their data.</p><h4>A02 — Cryptographic Failures</h4><p><strong>The Risk:</strong> Supabase by default stores session tokens in localStorage, which is accessible to JavaScript. Any successful XSS (cross-site scripting) attack could steal this token and compromise the user’s identity.</p><p><strong>The Fix:</strong> Use persistSession: &#39;COOKIE&#39; to store session tokens in HTTP-only cookies, which JavaScript cannot access. This significantly reduces the risk of token theft through XSS.</p><pre>export const supabase = createClient(<br>  url, anonKey,<br>  { auth: { persistSession: &#39;COOKIE&#39;, detectSessionInUrl: false } }<br>);</pre><p>Also configure your reverse proxy (e.g. NGINX or Vercel config) to add this header:</p><pre>Strict-Transport-Security: max-age=63072000; includeSubDomains; preload</pre><p>This forces HTTPS and prevents downgrade attacks.</p><h4>A03 — Injection: Prompt &amp; Regex</h4><p><strong>The Risk (a): Prompt Injection:</strong> If you interpolate raw user input into a system prompt for your LLM without escaping or validation, you expose yourself to prompt injection. Attackers can manipulate the prompt to execute unauthorized actions or corrupt your output format.</p><p><strong>Mitigation:</strong> Wrap user input in JSON, and instruct the LLM to output structured JSON:</p><pre>const userPayload = JSON.stringify({ instruction: chatPrompt });<br>const systemPrompt = `<br>${BASE_PROMPT}<br>UserRequest: ${userPayload}<br>Respond ONLY in valid JSON: {&quot;revision&quot;:&quot;...&quot;}.<br>`;</pre><p><strong>The Risk (b): Regex fatigue:</strong> Parsing LLM output with loosely-defined regex can result in incorrect clause matching, skipped risks, or errors.</p><p><strong>Fix:</strong> Force the LLM to return JSON and parse it:</p><pre>const clauses: RiskyClause[] = JSON.parse(response);</pre><p>This creates a safer, more deterministic pipeline.</p><h4>A04 — Insecure Design</h4><p><strong>The Risk:</strong> The current implementation writes each page’s data into state as it completes (commitOrderedPage). If a user closes the tab before the document finishes rendering, you end up with a half-finished contract stored on the server.</p><p><strong>Counter-measure:</strong> Redesign the flow to send all the content in a single response. Let the backend aggregate the full analysis and only then update the store:</p><pre>const { data } = await apiRequest(&#39;/analyzeDocument&#39;, { url: pdfUrl });<br>useMouStore.setState({ pagesContent: data.pages, riskyClauses: data.risks });</pre><p>This ensures atomicity and prevents partial data from polluting your system.</p><h4>A05 — Security Misconfiguration</h4><p><strong>The Risk:</strong> Returning raw error messages (like err.message) in user-facing toasts can leak internal stack traces, revealing implementation details that help attackers.</p><p><strong>Fix:</strong> Replace specific errors with generic ones in production:</p><pre>catch (err) {<br>  Sentry.captureException(err);<br>  setError(&quot;Something went wrong. Please try again.&quot;);<br>}</pre><p>Never include secrets like OpenAI or Supabase keys in the frontend. Store them in Edge Functions or secured backend services, never in your Vite .env file.</p><h4>A06 — Vulnerable &amp; Outdated Components</h4><p><strong>The Risk:</strong> Outdated libraries like uuid or react-toastify may contain critical vulnerabilities that expose your system.</p><p><strong>Fix:</strong> Add a CI workflow to detect and fail builds that include vulnerable packages:</p><pre># .github/workflows/audit.yml<br>- run: pnpm audit --audit-level=high<br>- uses: snyk/actions/node@v1<br>  with:<br>    command: test<br>    json: false</pre><p>This ensures any HIGH-severity CVEs stop your deploy pipeline.</p><h4>A07 — Identification &amp; Authentication Failures</h4><p><strong>The Risk:</strong> If MarkdownViewer renders before your AuthProvider completes loading, an unauthenticated user might briefly see secure content.</p><p><strong>Fix:</strong> Use conditional rendering based on user and isLoading:</p><pre>const { user, isLoading } = useAuth();<br>if (isLoading) return &lt;Loader /&gt;;<br>if (!user) return &lt;Navigate to=&quot;/login&quot; replace /&gt;;<br>return &lt;MarkdownViewer pdfUrl={...} /&gt;;</pre><p>This ensures that only authenticated users access sensitive views.</p><h4>A08 — Software &amp; Data Integrity Failures</h4><p><strong>The Risk:</strong> Your LLM returns updated content, and you overwrite the source immediately. This opens the door to tampering or hallucinated text being stored without verification.</p><p><strong>Fix:</strong> Store the revision as a pending suggestion. Require human approval before applying changes:</p><pre>const hash = crypto.createHash(&#39;sha256&#39;).update(finalDoc).digest(&#39;hex&#39;);<br>await db.insert({ doc_id, hash, approved_by: user.id });</pre><p>Digitally signing the final document hash ensures traceability and auditability.</p><h4>A09 — Security Logging &amp; Monitoring Failures</h4><p><strong>The Risk:</strong> Unhandled exceptions (console.error) are easy to miss in production, leaving you blind to real-world failures.</p><p><strong>Fix:</strong> Integrate with a real monitoring platform like Sentry:</p><pre>import * as Sentry from &quot;@sentry/react&quot;;<br>Sentry.init({ dsn: import.meta.env.VITE_SENTRY_DSN });<br>...<br>catch (err) {<br>  Sentry.captureException(err, { tags: { feature: &#39;markdown-viewer&#39; } });<br>}</pre><p>Also include a request ID in API headers and expose it in error toasts so support teams can trace incidents.</p><h4>A10 — Server-Side Request Forgery (SSRF)</h4><p><strong>The Risk:</strong> If your backend accepts any URL from the client and fetches it, an attacker could access internal endpoints or metadata URLs within your infrastructure.</p><p><strong>Fix:</strong> Whitelist only safe domains (e.g., your S3 bucket), and validate file type:</p><pre>app.post(&#39;/download&#39;, async (req, res) =&gt; {<br>  const url = new URL(req.body.url);<br>  if (url.hostname !== &#39;my-bucket.s3.amazonaws.com&#39;)<br>    return res.status(400).send(&#39;invalid source&#39;);<br><br>const resp = await fetch(url.toString(), { timeout: 5000 });<br>  if (resp.headers.get(&#39;content-type&#39;) !== &#39;application/pdf&#39;)<br>    return res.status(400).send(&#39;not a pdf&#39;);<br>  // continue download...<br>});</pre><p>This protects your internal network from unauthorized external probing.</p><h3>Final Thoughts: Security Is a Habit, Not a Heroic Sprint</h3><p>Threat-modeling, OWASP guard-rails, and code-level fixes may feel like a detour when you just want to ship features, but they are the cheapest engineering time you will ever spend. Every bug you <strong>prevent</strong> in design or CI would cost 10–100× more once it escapes into production, damages data, or wakes the team at 3 a.m.</p><p>You don’t need a CISO badge to start:</p><ol><li>Draw the data-flow diagram before every epic.</li><li>Wire authentication &amp; authorization first — functionality later.</li><li>Automate the boring but critical checks (lint, Semgrep, gitleaks, audit).</li><li>Fail the build loudly when something breaks the standard.</li><li>Instrument real-time logging so “unknown unknowns” become Slack alerts, not customer tweets.</li></ol><p>Do these five things consistently and you’ll create a codebase that is not only delightful for users but defensible under adversarial pressure, a system that can scale without becoming tomorrow’s breach headline.</p><p>Security isn’t a milestone; it’s muscle memory. Start small, ship safer, and keep tightening the bolts with every pull request. Your future self — and your users, will thank you. 🚀🔒</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dff1a12a7461" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Confidence in Code: Software Testing, Coverage, and Mocking Techniques]]></title>
            <link>https://medium.com/@bryantjandra2003/building-confidence-in-code-software-testing-coverage-and-mocking-techniques-cfbd9a682233?source=rss-ef9ddc2bbc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfbd9a682233</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[copilot-programming]]></category>
            <category><![CDATA[stub]]></category>
            <category><![CDATA[mocking]]></category>
            <dc:creator><![CDATA[Bryan Tjandra]]></dc:creator>
            <pubDate>Wed, 02 Apr 2025 03:52:56 GMT</pubDate>
            <atom:updated>2025-04-02T03:52:56.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6B8Q-nMtwi4fwaWs.png" /><figcaption>Source: <a href="https://zhiminzhan.medium.com/fakes-vs-stubs-mocks-in-software-integration-testing-81db2753b358">https://zhiminzhan.medium.com/fakes-vs-stubs-mocks-in-software-integration-testing-81db2753b358</a></figcaption></figure><p>In any software development lifecycle, writing code is just one piece of the puzzle. Ensuring that the code actually works as intended, and continues to work even as the project grows is where <strong>software testing</strong> steps in. Good testing isn’t just a best practice; it’s a fundamental pillar of <strong>quality assurance</strong> (QA). It’s what gives both developers and stakeholders the confidence that the product behaves as expected in the real world.</p><p>But as systems become more complex, involving external APIs, databases, microservices, or third-party services, traditional testing approaches often hit a wall. How do you isolate components during testing? How do you test without always making real API calls or hitting the actual database?</p><p>That’s where <strong>mocking</strong> and <strong>stubbing</strong> come in. These aren’t just fancy tools for testing experts, they’re essential techniques for creating reliable, fast, and independent test suites. And in today’s world, with the help of <strong>AI-powered assistants</strong>, setting up these advanced testing strategies is becoming more accessible than ever.</p><p>In this blog, we’ll unpack what software testing really means in a modern development workflow, explore the importance of test coverage and QA, and take a closer look at mocks and stubs: what they are, when to use them, and how they can help you test even the most complex parts of your system. Along the way, we’ll also highlight how AI can assist — and even be improved upon — to support testing in real projects.</p><h3>Understanding Software Testing, Test Coverage, and Quality Assurance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*m4A-tq5o8HSw3PWS.jpg" /><figcaption>Source: <a href="https://www.keenesystems.com/blog/what-is-a-software-testing-life-cycle-and-why-is-it-important">https://www.keenesystems.com/blog/what-is-a-software-testing-life-cycle-and-why-is-it-important</a></figcaption></figure><p><strong>Software testing</strong> is the process of evaluating and verifying that a software product or application does what it is supposed to do. It involves writing tests that check for both expected behavior and edge cases, and catching bugs before they make their way to production. More than just a safety net, testing is a development strategy that saves time, reduces costs, and increases reliability.</p><p>But writing a few tests isn’t enough. That’s where <strong>test coverage</strong> comes in, a metric that tells you how much of your code is actually being executed when your tests run. High test coverage doesn’t always mean your tests are perfect, but it does ensure that most of your logic is at least being exercised. If your test suite covers 80% of your code, that means there’s a good chance it will catch bugs early, especially if it includes meaningful test cases.</p><p>Then there’s <strong>quality assurance (QA)</strong>, a broader discipline that encompasses not only testing but also design reviews, coding standards, and continuous integration practices. QA ensures that quality is built into every phase of development, from requirement gathering to deployment. It’s about delivering software that is not just functional, but reliable, secure, and maintainable.</p><p>In short, testing gives feedback, test coverage gives visibility, and QA ensures a standard of excellence across the board.</p><h3>Why Mocks and Stubs Matter in Complex Testing</h3><p>As your codebase grows and your application starts interacting with external systems, like APIs, payment gateways, or databases, testing becomes trickier. You can’t rely on real external services during every test run: they may be unavailable, slow, or introduce data inconsistency. This is where <strong>test isolation</strong> becomes crucial, and mocks and stubs are your best allies.</p><h3>What Are Mocks and Stubs?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*zacL3tVeYdYykH7g.jpg" /><figcaption>Source: <a href="https://marabesi.com/software-engineering/mocks-dummies-spies-fakes-testing-your-code.html">https://marabesi.com/software-engineering/mocks-dummies-spies-fakes-testing-your-code.html</a></figcaption></figure><p><strong>Stubs</strong> are simplified implementations or hardcoded responses that replace parts of your application during testing. For instance, instead of connecting to a real database, a stub might return a predefined data object. This allows you to test how your application behaves with specific inputs without relying on external components.</p><p><strong>Mocks</strong>, on the other hand, are more sophisticated. They don’t just replace components, they also track interactions. A mock can verify whether a method was called, how many times it was called, and with what parameters. This is especially useful when testing how your code interacts with other services or dependencies.</p><p>Both of these techniques aim to <strong>decouple</strong> your tests from actual dependencies. This makes your tests more reliable, faster, and focused on the unit of logic you’re trying to verify.</p><h3>When You Need Mocks and Stubs</h3><p>Not every test needs mocks or stubs. They’re most useful when:</p><ul><li>Your code interacts with <strong>external APIs</strong> (e.g., OpenAI, Stripe, Firebase)</li><li>Your logic depends on <strong>dynamic data</strong> from databases</li><li>You need to simulate <strong>specific edge cases</strong> (e.g., API errors, slow responses)</li><li>You want your tests to run <strong>fast and repeatedly</strong>, regardless of internet or system state</li></ul><p>Without these techniques, you’d be left with brittle tests that are hard to maintain and unreliable.</p><h3>What’s the Difference Between Mocks and Stubs?</h3><p>Before we jump into code, let’s clarify what these are:</p><h4>🎭 Mocks</h4><p>Mocks are <strong>fully controlled stand-ins</strong> for real objects. They can simulate method calls, track interactions, and return pre-defined outputs. They’re especially useful when you want to test <strong>behavior</strong>, such as:</p><blockquote><em>“Did this function call happen?” “Was this method called with the correct arguments?”</em></blockquote><h4>🧱 Stubs</h4><p>Stubs, on the other hand, are simpler. They’re used to <strong>replace real method logic</strong> with a static response. A stub doesn’t care if the method was called 100 times or none, it’s focused on <strong>providing fixed data</strong> to support testing the rest of your logic.</p><p>Now I’ll demonstrate these two methods</p><h4>✅ Imports &amp; Setup</h4><p>Before we dive into examples, let’s set up our test environment. These are the tools we’ll use:</p><pre>import pytest<br>from unittest.mock import patch, MagicMock<br>from fastapi.testclient import TestClient<br>from app.main import app<br>from app.utils.ai_client import AIClient<br>import fitz<br>from docx import Document<br>import io</pre><p>And of course, we’ll initialize a reusable FastAPI test client:</p><pre>client = TestClient(app)</pre><h4>📄 Test Fixtures for File Uploads</h4><p>To simulate uploading documents in tests, we need real files. Below are fixtures for generating valid PDF and DOCX files on the fly, using PyMuPDF and python-docx.</p><p><strong>mock_valid_pdf: Real PDF File (In-Memory)</strong></p><pre>@pytest.fixture<br>def mock_valid_pdf(tmp_path):<br>    &quot;&quot;&quot;✅ Create a real in-memory PDF file for testing.&quot;&quot;&quot;<br>    pdf_path = tmp_path / &quot;test_document.pdf&quot;<br>    doc = fitz.open()<br>    page = doc.new_page()<br>    page.insert_text((72, 72), &quot;This is a test PDF content.&quot;)<br>    doc.save(str(pdf_path))<br>    doc.close()<br><br>    file = open(pdf_path, &quot;rb&quot;)<br>    yield file<br>    file.close()</pre><p>This creates an actual PDF in a temporary test directory. This helps simulate realistic file uploads without polluting your filesystem.</p><p><strong>mock_valid_docx: Real DOCX File</strong></p><pre>@pytest.fixture<br>def mock_valid_docx(tmp_path):<br>    &quot;&quot;&quot;✅ Create a real in-memory DOCX file for testing.&quot;&quot;&quot;<br>    docx_path = tmp_path / &quot;test_document.docx&quot;<br>    doc = Document()<br>    doc.add_paragraph(&quot;This is a test DOCX content.&quot;)<br>    doc.save(str(docx_path))<br><br>    file = open(docx_path, &quot;rb&quot;)<br>    yield file<br>    file.close()</pre><p>We use a similar approach for DOCX files. These fixtures let us simulate user-uploaded content in our test scenarios.</p><h4>🔁 Stub Example #1: Faking the Output Only</h4><p>In this test, we use a <strong>stub</strong> to replace the return value of a method. The focus is purely on the output, and we don’t care how or whether the method was even used correctly inside the system.</p><h4>✅ Actual Implementation: AIClient.analyze_risk()</h4><p>Located in app/utils/ai_client.py, this class sends document text to an external API, the AI model and returns a string response.</p><pre># app/utils/ai_client.py<br>from openai import OpenAI<br>from config.settings import settings<br><br>class AIClient:<br>    @staticmethod<br>    def analyze_risk(text: str) -&gt; str:<br>        client = OpenAI(<br>            base_url=&quot;https://openrouter.ai/api/v1&quot;,<br>            api_key=settings.OPENROUTER_API_KEY,<br>        )<br>        full_prompt = f&quot;Analyze this:\n{text}&quot;<br>        try:<br>            response = client.chat.completions.create(<br>                model=&quot;qwen/qwen2.5-vl-72b-instruct:free&quot;,<br>                messages=[<br>                    {<br>                        &quot;role&quot;: &quot;user&quot;,<br>                        &quot;content&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: full_prompt}]<br>                    }<br>                ],<br>            )<br>            return response.choices[0].message.content.strip()<br>        except Exception as e:<br>            return f&quot;❌ Gagal menganalisis dokumen: {str(e)}&quot;</pre><h4>✅ Stub AI Output</h4><pre>def test_stub_ai_response_output_only(mock_valid_pdf):<br>    &quot;&quot;&quot;✅ Stub AIClient to return static response regardless of input.&quot;&quot;&quot;<br>    stubbed_output = &quot;Stubbed: Klausul 1 - Risk Detected.&quot;<br><br>    with patch(&quot;app.utils.ai_client.AIClient.analyze_risk&quot;, return_value=stubbed_output):<br>        response = client.post(&quot;/analyze/&quot;, files={&quot;file&quot;: mock_valid_pdf})<br>        <br>        assert &quot;risks&quot; in response.json()<br>        assert stubbed_output in response.json()[&quot;ai_response&quot;]</pre><p>💡 <strong>Explanation</strong>: Here, we stub analyze_risk to return the same static string every time. We don’t inspect its input or check if it was called correctly. This is perfect when you want to simulate downstream output—like how your API behaves after getting a result from AI—without testing the AI itself.</p><h4>🔍 Mock Example #1: Verifying Behavior and Parameters</h4><p>Now let’s look at <strong>mocks</strong>. In this case, we’re not just interested in what the method returns — we also want to validate how it was used. Was it called at all? With the right arguments?</p><h4>✅ Mock AI with Argument Check</h4><pre>def test_mock_ai_response_with_argument_check(mock_valid_pdf):<br>    &quot;&quot;&quot;✅ Mock AIClient to inspect interaction and ensure correct behavior.&quot;&quot;&quot;<br>    with patch(&quot;app.utils.ai_client.AIClient.analyze_risk&quot;) as mocked_analyze:<br>        mocked_analyze.return_value = &quot;Mocked: OK&quot;<br><br>        client.post(&quot;/analyze/&quot;, files={&quot;file&quot;: mock_valid_pdf})<br>        # Verify it was called once<br>        mocked_analyze.assert_called_once()<br>        # Optionally: assert it was called with string content<br>        args, kwargs = mocked_analyze.call_args<br>        assert isinstance(args[0], str), &quot;Expected the first argument to be a string.&quot;</pre><p>💡 <strong>Explanation</strong>: This test makes sure that the analyze_risk method was invoked. It even inspects the actual arguments passed. This level of inspection is vital when your business logic depends on precise method interactions, like when passing sanitized input to external services.</p><h4>🔁 Stub Example #2: PDF Parser Stub</h4><p>Sometimes, we want to test what happens <strong>after</strong> text is extracted from a PDF, without relying on the actual parsing logic (which might be slow, flaky, or not relevant to the test case). Here’s how a stub fits perfectly.</p><h4>✅ Actual Implementation: PDFParser.extract_text()</h4><p>Located in app/utils/parsers.py. This method uses pdfplumber to extract text from a PDF.</p><pre># app/utils/parsers.py<br><br>import pdfplumber<br>class PDFParser:<br>    def extract_text(self, file_path: str) -&gt; str:<br>        try:<br>            with pdfplumber.open(file_path) as pdf:<br>                extracted = &quot;\n&quot;.join([p.extract_text() for p in pdf.pages if p.extract_text()])<br>                if not extracted.strip():<br>                    raise ValueError(&quot;❌ Failed to extract text from the document.&quot;)<br>                return extracted.strip()<br>        except Exception as e:<br>            raise RuntimeError(f&quot;❌ Error extracting PDF: {str(e)}&quot;)</pre><h4>✅ Stubbed PDF Extraction</h4><pre>def test_stub_pdf_parser_output(mock_valid_pdf):<br>    &quot;&quot;&quot;✅ Stub PDFParser to return static content for extraction.&quot;&quot;&quot;<br>    with patch(&quot;app.utils.parsers.PDFParser.extract_text&quot;, return_value=&quot;Stubbed PDF Text&quot;):<br>        response = client.post(&quot;/extract-text/&quot;, files={&quot;file&quot;: mock_valid_pdf})<br>        assert &quot;Stubbed PDF Text&quot; in response.text</pre><p>💡 <strong>Explanation</strong>: This test does not care how or whether extract_text() was invoked. We’re just feeding static output to the system to verify that the API response reflects that content correctly. No internal behavior of the parser is inspected — that&#39;s what makes it a <strong>stub</strong>.</p><h4>🔍 Mock Example #2: PDF Parser Call Verification</h4><p>What if you want to ensure your view logic actually <strong>called</strong> the parser during execution? Then, you use a mock.</p><h4>✅ Mock PDF Parser with Call Check</h4><pre>def test_mock_pdf_parser_called(mock_valid_pdf):<br>    &quot;&quot;&quot;✅ Mock PDFParser to check if extract_text was invoked with expected file path.&quot;&quot;&quot;<br>    with patch(&quot;app.utils.parsers.PDFParser.extract_text&quot;) as mock_parser:<br>        mock_parser.return_value = &quot;Mocked PDF Output&quot;<br><br>        client.post(&quot;/extract-text/&quot;, files={&quot;file&quot;: mock_valid_pdf})<br>        mock_parser.assert_called_once()</pre><p>💡 <strong>Explanation</strong>: This time, we are not only replacing the method — we’re <strong>checking that it was called</strong>. If your FastAPI route didn’t call extract_text(), this test would fail. That’s the behavioral guarantee a <strong>mock</strong> gives you.</p><h4>🔁 Stub Example #3: DOCX Parser Stub</h4><p>Let’s apply the same concept to DOCX parsing. Maybe you’re testing what happens after DOCX content is received, but don’t want to spin up python-docx.</p><h4>✅ Actual Implementation: DOCXParser.extract_text()</h4><pre># app/utils/parsers.py<br><br>import docx<br>class DOCXParser:<br>    def extract_text(self, file_path: str) -&gt; str:<br>        try:<br>            doc = docx.Document(file_path)<br>            result = &quot;\n&quot;.join([para.text for para in doc.paragraphs if para.text.strip()])<br>            return result.strip() if result else &quot;❌ Gagal mengekstrak teks.&quot;<br>        except Exception as e:<br>            raise RuntimeError(f&quot;❌ Error extracting DOCX: {str(e)}&quot;)</pre><h4>✅ Stub DOCX Extraction Output</h4><pre>def test_stub_docx_parser_output(mock_valid_docx):<br>    &quot;&quot;&quot;✅ Stub DOCXParser to simulate known output from a DOCX file.&quot;&quot;&quot;<br>    with patch(&quot;app.utils.parsers.DOCXParser.extract_text&quot;, return_value=&quot;Stubbed DOCX Text&quot;):<br>        response = client.post(&quot;/extract-text/&quot;, files={&quot;file&quot;: mock_valid_docx})<br>        assert &quot;Stubbed DOCX Text&quot; in response.text</pre><p>💡 <strong>Explanation</strong>: Just like with the PDF stub, we’re replacing the return value with something static, avoiding the actual parsing logic. This test confirms the flow of data, not the internal behavior.</p><h4>🔍 Mock Example #3: DOCX Parser Input and Count Check</h4><p>Now let’s verify that the DOCX parser was actually called, and perhaps even check its call count (if that matters).</p><h4>✅ Mock DOCX Parser with Assertions</h4><pre>def test_mock_docx_parser_called(mock_valid_docx):<br>    &quot;&quot;&quot;✅ Mock DOCXParser to ensure extract_text was used and inspect interaction.&quot;&quot;&quot;<br>    with patch(&quot;app.utils.parsers.DOCXParser.extract_text&quot;) as mocked_extract:<br>        mocked_extract.return_value = &quot;Mocked DOCX Output&quot;<br><br>        client.post(&quot;/extract-text/&quot;, files={&quot;file&quot;: mock_valid_docx})<br>        # Check if it was called once<br>        mocked_extract.assert_called_once()<br>        # (Optional) Check input file path type, if applicable<br>        args, _ = mocked_extract.call_args<br>        assert isinstance(args[0], str) or hasattr(args[0], &quot;read&quot;), &quot;Expected file path or file-like object&quot;</pre><p>💡 <strong>Explanation</strong>: This test ensures your backend logic <strong>uses</strong> the DOCX parser and does it correctly. It gives you extra confidence that the actual implementation behaves as intended, not just the surface-level output.</p><h3>Stub vs Mock — Side-by-Side Comparison</h3><h4>🔹 Stub Test</h4><ul><li>✅ Focus: Output only</li><li>❌ No call tracking or verification</li><li>Use case: Return fake results to speed up tests</li><li>Easier to set up, less brittle</li><li>Good for isolating external dependencies without asserting usage</li></ul><h4>🔹 Mock Test</h4><ul><li>✅ Focus: Method interaction and behavior</li><li>✅ Verifies if a method was called, how many times, and with what arguments</li><li>Use case: Ensure logic interacts correctly with dependencies</li><li>More granular control, but can be tightly coupled to implementation</li><li>Can be brittle if internal implementation changes often</li></ul><h3>How AI Can Help You Write Better Tests: Mock &amp; Stub in Practice</h3><p>In the world of software testing, mocks and stubs are indispensable tools to isolate and validate parts of your system. But writing them can feel repetitive, confusing, or downright overwhelming , especially when dealing with external dependencies like file parsers, databases, or APIs.</p><p>The good news? You don’t have to do it all manually.</p><p>This section explores how <strong>AI support</strong> can simplify and accelerate the process of writing mock and stub-based tests, especially I will use Github Co-Pilot in the VSCode extenstion. We will use a real-world example of my document parsers code (PDFParser, DOCXParser), we’ll walk through:</p><ul><li>🧪 What we’re testing</li><li>🤖 How AI can assist in writing those tests</li></ul><h4>✅ What We’re Testing</h4><p>Let’s say we’re building a document analysis tool. We have a parser layer that handles reading text from either a <strong>PDF</strong> or a <strong>DOCX</strong> file, implemented using the pdfplumber and python-docx libraries.</p><p>Here’s a simplified version of the code:</p><pre>import pdfplumber<br>import docx<br>from abc import ABC, abstractmethod<br><br>class DocumentParser(ABC):<br>    @abstractmethod<br>    def extract_text(self, file_path: str) -&gt; str:<br>        raise NotImplementedError(&quot;Subclasses must implement `extract_text`.&quot;)<br><br>class PDFParser(DocumentParser):<br>    def extract_text(self, file_path: str) -&gt; str:<br>        try:<br>            with pdfplumber.open(file_path) as pdf:<br>                text = &quot;\n&quot;.join([p.extract_text() for p in pdf.pages if p.extract_text()])<br>                if not text.strip():<br>                    raise ValueError(&quot;❌ Gagal mengekstrak teks dari PDF.&quot;)<br>                return text.strip()<br>        except FileNotFoundError:<br>            raise FileNotFoundError(&quot;❌ File PDF tidak ditemukan.&quot;)<br>        except IOError:<br>            raise IOError(&quot;❌ Kesalahan akses file PDF.&quot;)<br>        except Exception as e:<br>            raise RuntimeError(f&quot;❌ Kesalahan tidak terduga pada PDF: {str(e)}&quot;)<br><br>class DOCXParser(DocumentParser):<br>    def extract_text(self, file_path: str) -&gt; str:<br>        try:<br>            doc = docx.Document(file_path)<br>            text = &quot;\n&quot;.join([p.text.strip() for p in doc.paragraphs if p.text.strip()])<br>            if not text:<br>                raise ValueError(&quot;❌ Dokumen DOCX kosong atau gagal diproses.&quot;)<br>            return text<br>        except FileNotFoundError:<br>            raise FileNotFoundError(&quot;❌ File DOCX tidak ditemukan.&quot;)<br>        except IOError:<br>            raise IOError(&quot;❌ Kesalahan akses file DOCX.&quot;)<br>        except Exception as e:<br>            raise RuntimeError(f&quot;❌ Kesalahan tidak terduga pada DOCX: {str(e)}&quot;)<br><br>class ParserFactory:<br>    @staticmethod<br>    def get_parser(file_type: str) -&gt; DocumentParser:<br>        file_type = file_type.lower()<br>        if file_type == &quot;pdf&quot;:<br>            return PDFParser()<br>        elif file_type == &quot;docx&quot;:<br>            return DOCXParser()<br>        else:<br>            raise ValueError(f&quot;❌ Format {file_type} tidak didukung! Hanya mendukung PDF dan DOCX.&quot;)</pre><p>Now we want to test the <strong>controller</strong> or <strong>API logic</strong> that depends on these parsers. But we don’t want to rely on real PDF/DOCX files for every test — that’s where <strong>mocking</strong> and <strong>stubbing</strong> come in.</p><h3>🤖 How AI Support Can Help</h3><p>Let’s be honest: writing mock/stub tests is often more boilerplate than brainpower. This is where AI shines. By simply describing what you want tested, an AI tool like ChatGPT or Copilotcan:</p><ul><li>Suggest test structure (pytest, unittest, etc.)</li><li>Auto-generate mocks/stubs based on your method signatures</li><li>Help create fixtures for in-memory files</li><li>Validate edge cases like file-not-found or corrupted data</li></ul><p>Let’s walk through a mock + stub generation assisted by AI.</p><h4>🧪 The Initial Prompt to Generate Mocks via Copilot</h4><p>Let’s start with the kind of prompt you would feed into GitHub Copilot to generate tests based on your implementation. Basic prompt example:</p><blockquote><em>“Write </em><em>pytest test functions to mock </em><em>pdfplumber.open and </em><em>docx.Document. Simulate different parser behaviors like extractable text, empty pages, multiple pages, file not found, and general errors. Include MagicMock and patch.&quot;</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DW0WJPxOb3Ty2sQfPzDRwA.png" /><figcaption>An image Github Copilot with the input prompt</figcaption></figure><p>Copilot automatically learn from your code implementation. In this case because you want to make the “test_parsers.py”, you can direct the file into the “parsers.py”. In this case, copilot will read your file automatically and create the test based on that file. Thus, you don’t need to copy and paste the entire file to the AI, instead, it will read by itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*gCM9IpMSD4NjmBhgzdxevA.png" /><figcaption>Image of the initial response of copilot</figcaption></figure><p>Not bad for a starting point, right? 😄</p><p>But we quickly realized some gaps. The generated tests didn’t cover the ParserFactory logic, didn’t test abstract base class behavior, and missed several edge cases. That’s where refining the prompt really pays off.</p><h4>✅ Improved Prompt for Full test Coverage</h4><p>A better and more targeted prompt that can target more coverage can be something like this:</p><pre>Write a comprehensive pytest test suite that:<br><br>1. Uses unittest.mock.patch and MagicMock to mock:<br>* pdfplumber.open for PDF files<br>* docx.Document for DOCX files<br><br>2. Creates @pytest.fixture methods for:<br>* mock_pdf_with_text - PDF with extractable text<br>* mock_pdf_no_text - PDF with empty pages<br>* mock_pdf_multi_page - PDF with multiple pages<br>* mock_docx_with_text - DOCX with extractable paragraphs<br>* mock_docx_no_text - DOCX with no valid content<br><br>3. Includes individual test functions for:<br>* test_extract_text_pdf_with_text<br>* test_extract_text_pdf_no_text<br>* test_extract_text_pdf_multi_page<br>* test_extract_text_docx_with_text<br>* test_extract_text_docx_no_text<br><br>4. Covers error handling scenarios for both parsers:<br>* FileNotFoundError → test_extract_text_pdf_file_not_found, test_extract_text_docx_file_not_found<br>* IOError → test_extract_text_pdf_io_error, test_extract_text_docx_io_error<br>* ValueError (invalid/corrupt file) → test_extract_text_pdf_invalid_file, test_extract_text_docx_invalid_file<br>* Generic exceptions → test_extract_text_pdf_general_exception, test_extract_text_docx_general_exception<br><br>6. Include ParserFactory logic tests:<br>* test_parser_factory_pdf<br>* test_parser_factory_docx<br>* test_parser_factory_invalid_format<br><br>7. Ensure pytest.raises(..., match=...) is used to match exception messages.</pre><p>With this prompt, AI can generate a complete and structured test suite, like the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*4B_AuHYpU3IuiX6d-Eg-Zw.png" /><figcaption>Image of the improved prompt result on the copilot</figcaption></figure><p>How about the response? Much much better, right? Here is the full version of the generated test</p><pre>import pytest<br>from unittest.mock import patch, MagicMock<br>from app.utils.parsers import PDFParser, DOCXParser, ParserFactory<br><br># Fixtures for mocking PDF and DOCX behavior<br>@pytest.fixture<br>def mock_pdf_with_text():<br>    with patch(&quot;pdfplumber.open&quot;) as mock_open:<br>        mock_pdf = MagicMock()<br>        mock_pdf.pages = [MagicMock(extract_text=lambda: &quot;Page 1 text&quot;), MagicMock(extract_text=lambda: &quot;Page 2 text&quot;)]<br>        mock_open.return_value.__enter__.return_value = mock_pdf<br>        yield mock_open<br><br>@pytest.fixture<br>def mock_pdf_no_text():<br>    with patch(&quot;pdfplumber.open&quot;) as mock_open:<br>        mock_pdf = MagicMock()<br>        mock_pdf.pages = [MagicMock(extract_text=lambda: None)]<br>        mock_open.return_value.__enter__.return_value = mock_pdf<br>        yield mock_open<br><br>@pytest.fixture<br>def mock_pdf_multi_page():<br>    with patch(&quot;pdfplumber.open&quot;) as mock_open:<br>        mock_pdf = MagicMock()<br>        mock_pdf.pages = [<br>            MagicMock(extract_text=lambda: &quot;Page 1 text&quot;),<br>            MagicMock(extract_text=lambda: &quot;Page 2 text&quot;),<br>            MagicMock(extract_text=lambda: &quot;Page 3 text&quot;),<br>        ]<br>        mock_open.return_value.__enter__.return_value = mock_pdf<br>        yield mock_open<br><br>@pytest.fixture<br>def mock_docx_with_text():<br>    with patch(&quot;docx.Document&quot;) as mock_docx:<br>        mock_doc = MagicMock()<br>        mock_doc.paragraphs = [MagicMock(text=&quot;Paragraph 1&quot;), MagicMock(text=&quot;Paragraph 2&quot;)]<br>        mock_docx.return_value = mock_doc<br>        yield mock_docx<br><br>@pytest.fixture<br>def mock_docx_no_text():<br>    with patch(&quot;docx.Document&quot;) as mock_docx:<br>        mock_doc = MagicMock()<br>        mock_doc.paragraphs = [MagicMock(text=&quot;&quot;), MagicMock(text=&quot; &quot;)]<br>        mock_docx.return_value = mock_doc<br>        yield mock_docx<br><br># Test cases for PDFParser<br>def test_extract_text_pdf_with_text(mock_pdf_with_text):<br>    parser = PDFParser()<br>    result = parser.extract_text(&quot;dummy.pdf&quot;)<br>    assert result == &quot;Page 1 text\nPage 2 text&quot;<br><br>def test_extract_text_pdf_no_text(mock_pdf_no_text):<br>    parser = PDFParser()<br>    with pytest.raises(ValueError, match=&quot;❌ Failed to extract text from the document.&quot;):<br>        parser.extract_text(&quot;dummy.pdf&quot;)<br><br>def test_extract_text_pdf_multi_page(mock_pdf_multi_page):<br>    parser = PDFParser()<br>    result = parser.extract_text(&quot;dummy.pdf&quot;)<br>    assert result == &quot;Page 1 text\nPage 2 text\nPage 3 text&quot;<br><br># Test cases for DOCXParser<br>def test_extract_text_docx_with_text(mock_docx_with_text):<br>    parser = DOCXParser()<br>    result = parser.extract_text(&quot;dummy.docx&quot;)<br>    assert result == &quot;Paragraph 1\nParagraph 2&quot;<br><br>def test_extract_text_docx_no_text(mock_docx_no_text):<br>    parser = DOCXParser()<br>    result = parser.extract_text(&quot;dummy.docx&quot;)<br>    assert result == &quot;❌ Gagal mengekstrak teks atau dokumen kosong.&quot;<br><br># Error handling tests for PDFParser<br>def test_extract_text_pdf_file_not_found():<br>    parser = PDFParser()<br>    with pytest.raises(FileNotFoundError, match=&quot;❌ File PDF tidak ditemukan:&quot;):<br>        parser.extract_text(&quot;nonexistent.pdf&quot;)<br><br>def test_extract_text_pdf_io_error():<br>    with patch(&quot;pdfplumber.open&quot;, side_effect=IOError(&quot;I/O error&quot;)):<br>        parser = PDFParser()<br>        with pytest.raises(IOError, match=&quot;❌ Kesalahan akses file PDF: I/O error&quot;):<br>            parser.extract_text(&quot;dummy.pdf&quot;)<br><br>def test_extract_text_pdf_invalid_file():<br>    with patch(&quot;pdfplumber.open&quot;, side_effect=ValueError(&quot;Invalid file&quot;)):<br>        parser = PDFParser()<br>        with pytest.raises(ValueError, match=&quot;❌ PDF rusak atau tidak dapat diproses: Invalid file&quot;):<br>            parser.extract_text(&quot;dummy.pdf&quot;)<br><br>def test_extract_text_pdf_general_exception():<br>    with patch(&quot;pdfplumber.open&quot;, side_effect=Exception(&quot;Unexpected error&quot;)):<br>        parser = PDFParser()<br>        with pytest.raises(RuntimeError, match=&quot;❌ Terjadi kesalahan saat memproses PDF: Unexpected error&quot;):<br>            parser.extract_text(&quot;dummy.pdf&quot;)<br><br># Error handling tests for DOCXParser<br>def test_extract_text_docx_file_not_found():<br>    parser = DOCXParser()<br>    with pytest.raises(FileNotFoundError, match=&quot;❌ File DOCX tidak ditemukan:&quot;):<br>        parser.extract_text(&quot;nonexistent.docx&quot;)<br><br>def test_extract_text_docx_io_error():<br>    with patch(&quot;docx.Document&quot;, side_effect=IOError(&quot;I/O error&quot;)):<br>        parser = DOCXParser()<br>        with pytest.raises(IOError, match=&quot;❌ Kesalahan akses file DOCX: I/O error&quot;):<br>            parser.extract_text(&quot;dummy.docx&quot;)<br><br>def test_extract_text_docx_invalid_file():<br>    with patch(&quot;docx.Document&quot;, side_effect=ValueError(&quot;Invalid file&quot;)):<br>        parser = DOCXParser()<br>        with pytest.raises(ValueError, match=&quot;❌ File DOCX tidak valid: Invalid file&quot;):<br>            parser.extract_text(&quot;dummy.docx&quot;)<br><br>def test_extract_text_docx_general_exception():<br>    with patch(&quot;docx.Document&quot;, side_effect=Exception(&quot;Unexpected error&quot;)):<br>        parser = DOCXParser()<br>        with pytest.raises(RuntimeError, match=&quot;❌ Terjadi kesalahan saat memproses DOCX: Unexpected error&quot;):<br>            parser.extract_text(&quot;dummy.docx&quot;)<br><br># Tests for ParserFactory<br>def test_parser_factory_pdf():<br>    parser = ParserFactory.get_parser(&quot;pdf&quot;)<br>    assert isinstance(parser, PDFParser)<br><br>def test_parser_factory_docx():<br>    parser = ParserFactory.get_parser(&quot;docx&quot;)<br>    assert isinstance(parser, DOCXParser)<br><br>def test_parser_factory_invalid_format():<br>    with pytest.raises(ValueError, match=&quot;❌ Format txt tidak didukung! Hanya mendukung PDF dan DOCX.&quot;):<br>        ParserFactory.get_parser(&quot;txt&quot;)</pre><h4>🚀 Running the Tests: Real Results</h4><p>Let’s test the code, and we will see the result of the test</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3LcYIq-Jtw8Bwky7YBNcg.png" /><figcaption>Image of the initial pytest result</figcaption></figure><p>I ran the initial test, and the results were amazing, 95% test coverage, with only 1 out of 16 tests failing on the first run.</p><p>Then, I decided to pass the failed test to the AI for a fix to receive 100% coverage and no failed test</p><p>Just select the code that we want to revise, and provide the prompt something like “This test failed, can you fix it?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UP4Y4KgLJTiUp1lBdR07Gg.png" /><figcaption>Image of asking revision of failed test case</figcaption></figure><p>The AI provides a revision with a side-by-side comparison of the old and new code. From there, we can apply the fix directly using Copilot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*EgG1Nm8e6dIh3aZECP3Qcg.png" /><figcaption>Image of the side by side comparison of old and new suggestion code</figcaption></figure><p>Here is the updated version of the code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*ujHHkPcFulADGSVE5qt3yQ.png" /><figcaption>Image of applying the suggestion</figcaption></figure><p>Next, the test pointed out that line 10 was uncovered. We prompted Copilot again to fill the gap, applied the suggestion, and re-ran the tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWVk-vnwgKIx4zwp7z5kUQ.png" /><figcaption>Image of showing the line 10 code is uncovered</figcaption></figure><p>Let’s apply the suggestion</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxrddhBEoLHaVCAm9PbwGw.png" /><figcaption>Image of applying the copilot suggestion on the missing case</figcaption></figure><p>And just like that, we hit 100% coverage with all 16 tests passing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bvbIdjqGuRM8LiWzl4ORRQ.png" /><figcaption>Image of final test result</figcaption></figure><h3>🧠 Can we improve the AI response?</h3><p>The question is “are the AI responses well structured?”, and is there anything that we can critized to make our test better?</p><h4><strong>Case 1</strong></h4><p>Let’s take a deeper look at this example:</p><pre>@pytest.fixture<br>def mock_pdf_with_text():<br>    with patch(&quot;pdfplumber.open&quot;) as mock_open:<br>        mock_pdf = MagicMock()<br>        mock_pdf.pages = [MagicMock(extract_text=lambda: &quot;Page 1 text&quot;), MagicMock(extract_text=lambda: &quot;Page 2 text&quot;)]<br>        mock_open.return_value.__enter__.return_value = mock_pdf<br>        yield mock_open<br><br># Test cases for PDFParser<br>def test_extract_text_pdf_with_text(mock_pdf_with_text):<br>    parser = PDFParser()<br>    result = parser.extract_text(&quot;dummy.pdf&quot;)<br>    assert result == &quot;Page 1 text\nPage 2 text&quot;</pre><blockquote><strong><em>This code, while functional, couples the patching logic directly inside the fixture, which limits flexibility and obscures what’s happening inside the test.</em></strong></blockquote><h4>🔍 Problems with this approach:</h4><ul><li><strong>Tightly Coupled Logic</strong>: Patching pdfplumber.open inside the fixture hides the mocking behavior from the test, making it harder to debug or adapt to different scenarios.</li><li><strong>Reduced Flexibility</strong>: All tests that use this fixture are forced to use the same mocked behavior, unless you create additional fixtures for variations.</li><li><strong>Opaque Test Flow</strong>: Someone reading the test doesn’t see that pdfplumber.open is being patched — they have to dig into the fixture to understand what&#39;s happening.</li><li><strong>Scalability Issues</strong>: As test cases grow, you’ll either duplicate fixtures, or overload a single fixture with conditionals</li></ul><blockquote><strong><em>A better approach is to separate patching from the fixture by mocking the PDF object directly, and handling the patch in the test scope.</em></strong></blockquote><p>Here’s a prompt you can use to <strong>automatically convert</strong> a test setup</p><p><strong>Prompt:</strong></p><blockquote><em>Convert this test setup using a Pytest fixture that patches </em><em>pdfplumber.open internally, into a version where:</em></blockquote><blockquote>1. The fixture returns a mock PDF object (not the patch).</blockquote><blockquote>2. The patching of pdfplumber.open is moved inside the test function using with patch(...).</blockquote><blockquote>3. Keep the test logic the same but improve readability and flexibility</blockquote><p>A more modular and readable approach is to move patching into the test itself and let the fixture return just the mock object:</p><pre>@pytest.fixture<br>def mock_pdf_with_text():<br>    &quot;&quot;&quot;Mock PDF file with extractable text.&quot;&quot;&quot;<br>    mock_pdf = MagicMock()<br>    mock_pdf.__enter__.return_value = mock_pdf  <br>    mock_page = MagicMock()<br>    mock_page.extract_text.return_value = &quot;Sample extracted text from PDF&quot;<br>    mock_pdf.pages = [mock_page]<br>    return mock_pdf<br><br>def test_extract_text_pdf_with_text(mock_pdf_with_text):<br>    &quot;&quot;&quot;✅ Test PDF with extractable text.&quot;&quot;&quot;<br>    with patch(&quot;pdfplumber.open&quot;, return_value=mock_pdf_with_text):<br>        parser = PDFParser()<br>        extracted_text = parser.extract_text(&quot;dummy.pdf&quot;)<br>        assert extracted_text == &quot;Sample extracted text from PDF&quot;, f&quot;Unexpected output: {extracted_text}&quot;</pre><h4>✨ Revision benefits:</h4><ul><li><strong>Improved test clarity</strong> — everything is visible in the test itself</li><li><strong>Easier to debug and trace behavior</strong></li><li><strong>More reusable fixture</strong> — now you can inject this mock PDF into any scenario</li><li><strong>Easier to scale</strong> — you can write parameterized or variant tests without duplicating fixtures</li></ul><h4>Case 2</h4><p>There is another case that can be improved; look at the example below</p><pre># Tests for DocumentParser<br>def test_document_parser_abstract_method():<br>    class TestParser(DocumentParser):<br>        pass<br><br>    parser = TestParser()<br><br>    with pytest.raises(NotImplementedError, match=&quot;must implement `extract_text`&quot;):<br>        parser.extract_text(&quot;dummy.pdf&quot;)</pre><p>This test attempts to verify that calling the abstract extract_text method on a subclass of DocumentParser raises a NotImplementedError. However, the approach taken is not ideal. It defines a subclass (TestParser) that doesn&#39;t implement the method at all and then proceeds to call it — a situation that is either unrealistic or redundant. If DocumentParser were a properly defined abstract base class using abc.ABC and @abstractmethod, this test wouldn&#39;t even run, because Python would raise a TypeError when trying to instantiate the subclass. As such, this test doesn&#39;t meaningfully reflect how the class would behave in real-world scenarios or how developers might mistakenly misuse it.</p><p>That&#39;s why it makes more sense to adopt the approach that instead of omitting the method, it simulates a common mistake: a subclass that defines the extract_text method but still delegates to super().extract_text() — which preserves the abstract nature and appropriately triggers NotImplementedError. Here is the improved version:</p><pre>def test_document_parser_abstract_method():<br>    <br>    class TestParser(DocumentParser):<br>        def extract_text(self, file_path: str) -&gt; str:<br>            return super().extract_text(file_path)<br>    <br>    parser = TestParser()<br>    <br>    with pytest.raises(NotImplementedError, match=&quot;must implement `extract_text`&quot;):<br>        parser.extract_text(&quot;dummy.pdf&quot;)</pre><p>This test now accurately reflects a common developer mistake and shows that the abstract enforcement works.</p><h3>🧩 Final Thought</h3><p>In modern software development, writing tests isn’t just about checking boxes, it’s about building confidence. Confidence that your logic works, that your edge cases are covered, and that your system behaves correctly even when things go wrong.</p><p>Mocks and stubs are not just “nice to have” tools, they are foundational for creating fast, reliable, and maintainable test suites. They give you control over your test environment, isolate complex dependencies, and make your tests more predictable and meaningful.</p><p>But even the best tools need to be used thoughtfully.</p><p>As we saw:</p><ul><li><strong>Stubs</strong> are great for returning known responses, focusing on <em>output</em>.</li><li><strong>Mocks</strong> are essential when validating <em>interactions</em>, such as checking if a method was called or ensuring the correct flow of logic.</li><li><strong>Good test structure</strong> (like separating patching logic from fixtures) improves readability, debuggability, and scalability.</li></ul><p>And then there’s AI.</p><p>AI-powered tools like GitHub Copilot or ChatGPT aren’t here to replace developers, they’re here to accelerate workflows, suggest best practices, and handle the boilerplate so you can focus on the logic that really matters. With the right prompt and a bit of human guidance, AI can generate surprisingly solid test scaffolding, including mocks and stubs — saving you hours and improving test coverage effortlessly.</p><p>Ultimately, testing isn’t just about verifying code, it’s about enabling safe changes, encouraging refactors, and building systems that last.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfbd9a682233" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring: From Messy Code to Smart Code]]></title>
            <link>https://medium.com/@bryantjandra2003/refactoring-from-messy-code-to-smart-code-2a70c4f966c9?source=rss-ef9ddc2bbc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a70c4f966c9</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Bryan Tjandra]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 09:49:24 GMT</pubDate>
            <atom:updated>2025-04-01T09:49:24.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PT86F9I64TFwavtj.png" /><figcaption>Source: <a href="https://programmerhumor.io/programming-memes/refactoring-done-right/">https://programmerhumor.io/programming-memes/refactoring-done-right/</a></figcaption></figure><p>Have you ever stared at your own code and thought, <em>“Wait… what does this even do?”</em></p><p>You wrote it, you pushed it, and somehow a week later, it looks like it was written by a sleep-deprived alien version of yourself. If you’ve ever found yourself squinting at a block of logic trying to recall what Past You was thinking, don’t worry ,you’re not alone.</p><p>Instead of tearing your hair out every time you revisit your codebase, let me introduce you to one of the most satisfying tools in a developer’s arsenal: <strong>refactoring</strong>.</p><h3>So, What is Refactoring?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*T_IIkzSGyg9C0uE4.jpg" /><figcaption>Source: <a href="https://t2informatik.de/en/smartpedia/refactoring/">https://t2informatik.de/en/smartpedia/refactoring/</a></figcaption></figure><p>At its core, <strong>refactoring</strong> is the process of <strong>reorganizing and improving your code without changing what it does externally</strong>. You’re not adding new features or altering the input/output behavior, instead, you’re cleaning things up under the hood. The goal? Make your code more readable, maintainable, and elegant, while keeping its functionality intact.</p><p>Think of it like tidying your room. You’re not buying new furniture or repainting the walls — you’re just putting things in the right place, labeling your boxes, and making sure your future self doesn’t trip over a mess when they come back later.</p><h3>“But It Works Fine!” — The Classic Excuse 😬</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*fXvWKwlXFRzx63d7" /><figcaption>Source: <a href="https://www.reddit.com/r/ProgrammerHumor/comments/ipyx9c/dont_touch_it_works/">https://www.reddit.com/r/ProgrammerHumor/comments/ipyx9c/dont_touch_it_works/</a></figcaption></figure><p>We’ve all been there. The code runs, the feature works, and you’re already halfway into your next task. Why mess with something that’s already doing its job? Well… because it <em>could</em> do its job better. Cleaner code reduces bugs, makes collaboration easier, and saves time in the long run.</p><p>Don’t be that developer who’s afraid to touch a functional mess. Be the one who turns “Frankenstein functions” into “Einstein logic.”</p><h3>How Do You Know If You Didn’t Break Anything? 🧪</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*5jm7iPECGtdyN8vM.png" /><figcaption>Source: <a href="https://medium.com/@mohamad.fariz/tdd-vs-bdd-meningkatkan-kualitas-code-dengan-tdd-86b0098f4264">https://medium.com/@mohamad.fariz/tdd-vs-bdd-meningkatkan-kualitas-code-dengan-tdd-86b0098f4264</a></figcaption></figure><p>Simple answer: <strong>tests</strong>. Lots of them.</p><p>When refactoring, your safety net is your test suite. As long as all your tests pass before and after your changes, you’re (probably) good to go. That’s why test-driven development (TDD) goes hand-in-hand with refactoring. In the TDD cycle, <strong>refactor</strong> is a dedicated phase that comes after writing just enough code to pass the tests. You pass the test (GREEN), then you clean things up (REFACTOR/CHORES), all without altering the behavior that the test validated.</p><p>It’s clean. It’s smart. And it’s way better than hoping for the best.</p><h3>When Should You Refactor?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OPRjfSqgQ3a20IHR-N4dzw.png" /><figcaption>My commits</figcaption></figure><p>There’s a rule of thumb called the <strong>“Rule of Three”</strong>, and it goes like this:</p><ul><li>When you’re <strong>adding a feature</strong></li><li>When you’re <strong>fixing a bug</strong></li><li>When you’re <strong>reviewing code</strong></li></ul><p>After implementing a feature and confirming it works, that’s a perfect time to look back and clean up anything messy or redundant. Similarly, when you’re digging through code to squash a bug, chances are you’ll notice areas that could be improved. Finally, if you’re reviewing a pull request and stumble across convoluted or duplicated logic, well, that’s your cue to leave a friendly “maybe we can refactor this?” comment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ze_G-Bgm2ubkMmsAGNrphA.png" /><figcaption>My friend reviewing my code</figcaption></figure><h3>What Should Be Refactored?</h3><p>Refactoring isn’t just about logic. It includes cleaning up naming conventions, simplifying structure, improving modularity, and more. Tools like <strong>SonarQube</strong> can give you a great starting point ,they scan your codebase and highlight issues such as code smells, duplicate logic, security concerns, and complexity hotspots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*qkphF1b0CVIoXxm-.png" /><figcaption>My Sonarqube Issue Pannel</figcaption></figure><p>What’s nice about tools like SonarQube is that they often come with <strong>detailed explanations and suggested improvements</strong>. They don’t just tell you <em>what’s wrong, </em>they help guide you toward <em>what to fix</em> and <em>how to fix it</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*HBw9TcFnkydPY61U.png" /><figcaption>My sonarqube issue</figcaption></figure><h3>But Can Tools Catch Everything? 🤔</h3><p>As much as we’d love for static analysis tools to be omniscient, the truth is they’re not. Tools like SonarQube are incredibly helpful for identifying many issues, such as code smells, unreachable code, and complex logic. But they still have their blind spots.</p><p>Static analyzers can flag a lot of things, but they don’t always catch contextual issues , especially when it comes to purpose, intent, or subtle signs of technical debt that only a human would pick up on. Sometimes, what needs refactoring isn’t a logic bug or a security hole — it’s a useless method, a misleading comment, or just clutter that serves no purpose anymore.</p><p>Here’s a case I ran into recently:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*yK2vp4PBeiNX1ziqW4qXsg.png" /><figcaption>Example of failed case</figcaption></figure><p>I assumed SonarQube would instantly flag redundant_method() as dead code since it’s clearly unused and serves no real function. I also expected the commented-out print() line to be recognized as noise that could be cleaned up. But to my surprise, SonarQube didn’t catch either.</p><p>This experience made it clear: even with great tools in place, developer judgment is still irreplaceable. Refactoring isn’t something we can fully automate or outsource to a scanner , it requires critical thinking and an eye for maintainability. Whether it’s a method that shouldn’t exist, a test class that needs renaming, or legacy code that just lingers like a ghost in your repo, only human insight can truly clean it up.</p><h3>Watch Out for Anti-Patterns 🚨</h3><p>Still not sure whether something should be refactored? Keep an eye out for <strong>anti-patterns, </strong>recurring coding practices that might “work” but lead to long-term maintenance headaches. If you see something that feels hacky, unnecessarily repetitive, or just hard to follow, chances are it’s a sign that refactoring is due. Below are some anti-patterns that I have found during writing my code.</p><h3>1. Spaghetti Code</h3><p>We’ve all done it.</p><p>You’re in a rush, the deadline is creeping in, and everything is technically working… so you start duplicating bits of logic here and there just to “get it done.” No time for elegance. No time to think twice. Just ship it. 🚢</p><p>But a few weeks later, you come back to that codebase and realize what you’ve created: a tangled mess of repeated code, giant files, and endless scrolling. <em>Welcome to spaghetti code hell.</em></p><p>Let me show you an example from one of my earlier implementations — a document parser module ,and how I ended up creating something that was both <strong>repetitive</strong> and <strong>hard to maintain</strong>, without even noticing it at first.</p><pre>import pdfplumber<br>import docx<br><br>def extract_text(file_path, file_type):<br><br>    if file_type.lower() == &quot;pdf&quot;:<br>        try:<br>            with pdfplumber.open(file_path) as pdf:<br>                result = &quot;&quot;<br>                for p in pdf.pages:<br>                    t = p.extract_text()<br>                    if t:<br>                        result += t + &quot;\n&quot;<br>                if not result.strip():<br>                    raise ValueError(&quot;❌ Gagal mengekstrak teks dari PDF.&quot;)<br>                return result.strip()<br>        except Exception as e:<br>            raise RuntimeError(f&quot;❌ Kesalahan tidak terduga: {str(e)}&quot;)<br>    elif file_type.lower() == &quot;docx&quot;:<br>        try:<br>            d = docx.Document(file_path)<br>            res = &quot;&quot;<br>            for para in d.paragraphs:<br>                txt = para.text.strip()<br>                if txt:<br>                    res += txt + &quot;\n&quot;<br>            return res.strip() if res.strip() else &quot;❌ Dokumen kosong atau gagal diproses.&quot;<br>        except Exception as e:<br>            raise RuntimeError(f&quot;❌ Kesalahan tidak terduga: {str(e)}&quot;)<br>    else:<br>        raise ValueError(&quot;❌ Format file tidak didukung. Hanya mendukung PDF dan DOCX.&quot;)</pre><h3>What’s Wrong Here? 🧐</h3><p>Even though this function might look “okay,” it comes with a handful of issues that can quickly spiral out of control:</p><h4>1. Repeated Logic</h4><p>Notice how both branches (PDF and DOCX) do the same thing:</p><ul><li>Open a file</li><li>Loop through some content</li><li>Clean and concatenate the text</li><li>Return or throw an error</li></ul><p>The structure is nearly identical, yet the logic is repeated with different variable names (result, res, t, txt, etc.). This duplication means that if you want to adjust the flow, message formatting, or error handling, you’ll need to make the same change in both blocks.</p><h4>2. Single Function, Too Many Jobs</h4><p>This function:</p><ul><li>Decides which parser to use</li><li>Opens and reads two different file types</li><li>Handles multiple exception types</li><li>Processes text formatting</li><li>Reports user-facing errors</li></ul><p>That’s a lot of responsibility for one poor function. It violates the basic idea of “do one thing and do it well.”</p><h4>3. Hard to Test and Extend</h4><p>Say we wanted to support a new file type tomorrow (like .txt). We’d have to add another big elif block inside the same function. The function would get longer, harder to maintain, and testing each part in isolation would be a pain.</p><h3>A Cleaner Approach (Without Overcomplicating It)</h3><p>Here’s a simplified fix that <strong>doesn’t rely on design patterns</strong> (we’ll discuss the design pattern later) but makes the code way more modular and readable. The idea is simple: <strong>split the responsibility</strong> into smaller, focused functions.</p><h4>Refactored Version</h4><pre>import pdfplumber<br>import docx<br><br>def extract_text_from_pdf(file_path):<br>    try:<br>        with pdfplumber.open(file_path) as pdf:<br>            result = &quot;\n&quot;.join(<br>                [page.extract_text() for page in pdf.pages if page.extract_text()]<br>            )<br>            if not result.strip():<br>                raise ValueError(&quot;❌ Gagal mengekstrak teks dari PDF.&quot;)<br>            return result.strip()<br>    except Exception as e:<br>        raise RuntimeError(f&quot;❌ Kesalahan tidak terduga (PDF): {str(e)}&quot;)<br><br>def extract_text_from_docx(file_path):<br>    try:<br>        doc = docx.Document(file_path)<br>        result = &quot;\n&quot;.join(<br>            [para.text.strip() for para in doc.paragraphs if para.text.strip()]<br>        )<br>        return result if result else &quot;❌ Dokumen kosong atau gagal diproses.&quot;<br>    except Exception as e:<br>        raise RuntimeError(f&quot;❌ Kesalahan tidak terduga (DOCX): {str(e)}&quot;)<br><br>def extract_text(file_path, file_type):<br>    file_type = file_type.lower()<br>    if file_type == &quot;pdf&quot;:<br>        return extract_text_from_pdf(file_path)<br>    elif file_type == &quot;docx&quot;:<br>        return extract_text_from_docx(file_path)<br>    else:<br>        raise ValueError(&quot;❌ Format file tidak didukung. Hanya mendukung PDF dan DOCX.&quot;)</pre><h4>Why This Is Better ✅</h4><ul><li><strong>Smaller functions:</strong> Each function does one job and one job only. Much easier to test, debug, and reason about.</li><li><strong>No copy-paste logic:</strong> Repetitive chunks (like the loop and string cleaning) are scoped within their own dedicated function.</li><li><strong>Scalable structure:</strong> Want to support .txt files later? Just write extract_text_from_txt() and plug it in with another elif.</li><li><strong>Improved readability:</strong> No scrolling through giant if-else chains. Just look at the function name and you already know what it’s supposed to do.</li></ul><h3>2. Copy-Paste Programming in Disguise 🌀</h3><p>Sometimes, even after we refactor our code to be “cleaner,” we unknowingly fall back into the same old habits, like <strong>copy-pasting logic</strong> in different places, just wrapped in different function names.</p><p>That’s exactly what happened in my case.</p><p>After breaking my document parsing logic into two separate functions — one for <strong>PDF</strong> and one for <strong>DOCX</strong>, I was feeling pretty proud of myself. Each file type had its own function, and my original spaghetti code was looking way more digestible.</p><p>But then I looked closer… and realized I had simply <strong>copy-pasted the same logic structure into two different functions.</strong> Only the libraries and variable names had changed.</p><p>Let me show you what I mean.</p><h4>📄 “Refactored” But Still Redundant</h4><pre>import pdfplumber<br>import docx<br><br>def extract_text_from_pdf(file_path):<br>    try:<br>        with pdfplumber.open(file_path) as pdf:<br>            result = &quot;\n&quot;.join(<br>                [page.extract_text() for page in pdf.pages if page.extract_text()]<br>            )<br>            if not result.strip():<br>                raise ValueError(&quot;❌ Gagal mengekstrak teks dari PDF.&quot;)<br>            return result.strip()<br>    except Exception as e:<br>        raise RuntimeError(f&quot;❌ Kesalahan tidak terduga (PDF): {str(e)}&quot;)<br><br>def extract_text_from_docx(file_path):<br>    try:<br>        doc = docx.Document(file_path)<br>        result = &quot;\n&quot;.join(<br>            [para.text.strip() for para in doc.paragraphs if para.text.strip()]<br>        )<br>        return result if result else &quot;❌ Dokumen kosong atau gagal diproses.&quot;<br>    except Exception as e:<br>        raise RuntimeError(f&quot;❌ Kesalahan tidak terduga (DOCX): {str(e)}&quot;)<br><br>def extract_text(file_path, file_type):<br>    file_type = file_type.lower()<br>    if file_type == &quot;pdf&quot;:<br>        return extract_text_from_pdf(file_path)<br>    elif file_type == &quot;docx&quot;:<br>        return extract_text_from_docx(file_path)<br>    else:<br>        raise ValueError(&quot;❌ Format file tidak didukung. Hanya mendukung PDF dan DOCX.&quot;)</pre><p>Sure, it’s more modular than one giant function, but look at how much of that logic is being <strong>repeated</strong>:</p><ul><li>Opening the file</li><li>Extracting and cleaning up text</li><li>Error handling</li><li>String joining and formatting</li></ul><p>It’s the same song, just with a different instrument.</p><h4>The Fix: Inheritance to the Rescue 🛠️</h4><p>To eliminate this copy-paste pattern, I realized that I could apply a bit of <strong>object-oriented thinking, </strong>specifically, <strong>inheritance</strong>.</p><p>Instead of creating two separate functions with nearly identical flows, I could define a <strong>base class</strong> with a shared structure, and then let each specific parser class override the part that differs — the <em>how</em> of extracting the content.</p><p>This way, all the shared logic lives in one place, and the only thing that changes is the implementation of the text extraction.</p><h4>Step 1: Base Class for Common Behavior</h4><pre># base_parser.py<br><br>class BaseDocumentParser:<br><br>    def extract_text(self, file_path):<br>        try:<br>            content = self._read_file(file_path)<br>            if not content.strip():<br>                return &quot;❌ Dokumen kosong atau gagal diproses.&quot;<br>            return content.strip()<br>        except FileNotFoundError:<br>            raise FileNotFoundError(&quot;❌ File tidak ditemukan.&quot;)<br>        except Exception as e:<br>            raise RuntimeError(f&quot;❌ Kesalahan saat memproses dokumen: {str(e)}&quot;)<br><br>    def _read_file(self, file_path):<br>        raise NotImplementedError(&quot;Subclasses must implement `_read_file()`.&quot;)</pre><h4>✅ Step 2: Specific Parsers Inherit and Customize</h4><pre># pdf_parser.py<br><br>import pdfplumber<br>from base_parser import BaseDocumentParser<br><br>class PDFParser(BaseDocumentParser):<br><br>    def _read_file(self, file_path):<br>        with pdfplumber.open(file_path) as pdf:<br>            return &quot;\n&quot;.join(<br>                [page.extract_text() for page in pdf.pages if page.extract_text()]<br>            )</pre><pre># docx_parser.py<br><br>import docx<br>from base_parser import BaseDocumentParser<br><br>class DOCXParser(BaseDocumentParser):<br><br>    def _read_file(self, file_path):<br>        doc = docx.Document(file_path)<br>        return &quot;\n&quot;.join(<br>            [para.text.strip() for para in doc.paragraphs if para.text.strip()]<br>        )</pre><h4>✅ Step 3: Use Them Easily</h4><pre># main.py<br><br>from pdf_parser import PDFParser<br>from docx_parser import DOCXParser<br><br>def extract_text(file_path, file_type):<br>    file_type = file_type.lower()<br>    if file_type == &quot;pdf&quot;:<br>        parser = PDFParser()<br>    elif file_type == &quot;docx&quot;:<br>        parser = DOCXParser()<br>    else:<br>        raise ValueError(&quot;❌ Format file tidak didukung. Hanya mendukung PDF dan DOCX.&quot;)    <br>    return parser.extract_text(file_path)<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    print(extract_text(&quot;sample.docx&quot;, &quot;docx&quot;))</pre><h4>Final Result: DRY and Maintainable 💡</h4><p>Now, if I want to change the way I handle empty text, exceptions, or logging, I only have to do it <strong>once</strong> in the base class. And if I want to support another format — like .txt or .html — all I need to do is add one new class that inherits from the base and implements _read_file().</p><p>The logic is clean, the duplication is gone, and future me will have a much easier time extending and maintaining this.</p><h3>So, What Should We Strive for When Writing Code?</h3><p>Of course, keeping your code <strong>clean and readable</strong> is essential — it’s the foundation of maintainable software. But beyond clean code, there’s another crucial concept that every developer should embrace: <strong>design patterns</strong>.</p><p>Design patterns are <strong>standardized, reusable solutions</strong> to common problems encountered in software design. Rather than reinventing the wheel every time, patterns provide tried-and-tested approaches that improve structure, scalability, and communication within your codebase.</p><p>These patterns are typically categorized into four main groups:</p><ul><li><strong>Creational Patterns</strong> — Focused on how objects are created, ensuring flexibility and reuse. Examples include <em>Singleton</em>, Factory, <em>Builder</em>, and <em>Prototype</em>.</li><li><strong>Structural Patterns</strong> — Deal with the composition of classes and objects to form larger systems. Common examples include <em>Adapter</em>, <em>Decorator</em>, <em>Facade</em>, and <em>DTO</em>.</li><li><strong>Behavioral Patterns</strong> — Concerned with how objects interact and assign responsibilities. Examples include <em>Observer</em>, <em>Command</em>, <em>Iterator</em>, and <em>State</em>.</li><li><strong>Compound Patterns</strong> — These combine multiple patterns to solve broader architectural challenges. Popular examples include <em>MVC</em>, <em>MVP</em>, and <em>MVVM</em>.</li></ul><p>In the next section, I’ll walk you through some of the design patterns that my team and I have implemented in our project, and how they helped us write better, more maintainable code.</p><h3>Factory Pattern 🏭</h3><p>The <strong>Factory Pattern</strong> is a creational design pattern that provides a way to create objects <strong>without exposing the instantiation logic to the client</strong>. Instead of calling a class constructor directly, you delegate that responsibility to a factory method. This pattern is particularly useful when you have multiple related classes (with a common interface or base class) and you want to decide which one to use <strong>at runtime</strong>.</p><p>From a <strong>SOLID</strong> standpoint, this pattern reflects the <strong>Single Responsibility Principle</strong> (SRP) and the <strong>Open/Closed Principle</strong> (OCP). The logic of <em>how to create the appropriate object</em> is centralized in the factory, making your system easier to scale and extend without having to modify existing code.</p><p>In my project, I needed to implement a feature that could <strong>extract text from different types of documents</strong>, namely PDF and DOCX files. Each file type required a slightly different way of parsing, but I wanted a consistent interface for the rest of the system.</p><p>Here’s how I approached it:</p><ul><li>I defined an <strong>abstract base class</strong> DocumentParser that all parsers inherit from.</li><li>Then, I implemented specific classes: PDFParser and DOCXParser, each handling the file parsing logic for their respective formats.</li><li>Finally, I created a ParserFactory to determine <strong>which parser to instantiate</strong> based on the provided file type.</li></ul><p>This is a textbook example of the <strong>Factory Pattern</strong> in action. Let me walk you through the code, perhaps you are familiar with this code because I’ve mentioned this code before, but I’ven’t stated that it is actually similar to Factory Pattern XD</p><h4>🔧 Base and Concrete Parsers</h4><pre>from abc import ABC, abstractmethod<br>import pdfplumber<br>import docx<br><br>class DocumentParser(ABC):<br>    @abstractmethod<br>    def extract_text(self, file_path: str) -&gt; str:<br>        raise NotImplementedError(&quot;Subclasses must implement `extract_text`.&quot;)</pre><pre>class PDFParser(DocumentParser):<br>    def extract_text(self, file_path: str) -&gt; str:<br>        with pdfplumber.open(file_path) as pdf:<br>            content = &quot;\n&quot;.join([page.extract_text() for page in pdf.pages if page.extract_text()])<br>            if not content.strip():<br>                raise ValueError(&quot;❌ Failed to extract text from the document.&quot;)<br>            return content.strip()</pre><pre>class DOCXParser(DocumentParser):<br>    def extract_text(self, file_path: str) -&gt; str:<br>        doc = docx.Document(file_path)<br>        content = &quot;\n&quot;.join([para.text for para in doc.paragraphs if para.text.strip()])<br>        return content.strip() if content.strip() else &quot;❌ Gagal mengekstrak teks atau dokumen kosong.&quot;</pre><h4>🏭 The Factory Itself</h4><pre>class ParserFactory:<br>    @staticmethod<br>    def get_parser(file_type: str) -&gt; DocumentParser:<br>        file_type = file_type.lower()<br>        if file_type == &quot;pdf&quot;:<br>            return PDFParser()<br>        elif file_type == &quot;docx&quot;:<br>            return DOCXParser()<br>        else:<br>            raise ValueError(f&quot;❌ Format {file_type} tidak didukung! Hanya mendukung PDF dan DOCX.&quot;)</pre><h4>Why Use the Factory Pattern Here?</h4><p>Let’s say tomorrow I need to support .txt or .html. I won’t need to modify the core logic in extract_text() or sprinkle if-else blocks across the system. Instead, I just create a new parser class like TXTParser, implement the extract_text method, and update the factory logic. Everything else remains untouched.</p><p>By doing this:</p><ul><li>My code stays <strong>modular</strong></li><li>Adding new file types becomes a <strong>low-risk</strong> and <strong>easy-to-test</strong> change</li><li>The system adheres to <strong>OCP (Open for extension, closed for modification)</strong></li></ul><h3>Singleton Pattern 🧠</h3><p>The <strong>Singleton Pattern</strong> is a creational design pattern that ensures a class has <strong>only one instance</strong> and provides a global point of access to that instance. It’s especially useful when managing <strong>shared resources</strong> — such as configuration managers, logging systems, or, in my case, an external <strong>AI client</strong>.</p><p>A very common (and critical) use case for Singleton is the <strong>database connection</strong>. Instead of reconnecting to the database every time we need to fetch data, we maintain a single, shared connection throughout the application’s lifecycle. It’s more efficient, stable, and easier to manage.</p><h4>My Use Case: AI Risk Analysis with a Single Client</h4><p>In my project, I implemented an AI-based <strong>risk analysis feature</strong> using OpenAI’s API through the <a href="https://openrouter.ai/">OpenRouter</a> interface. The endpoint takes a chunk of legal text and sends it to an AI model (Qwen) to identify potentially risky clauses.</p><p>Initially, I created a simple static class method like this:</p><pre>client = OpenAI(api_key=settings.OPENROUTER_API_KEY)<br>response = client.chat.completions.create(...)</pre><p>This worked — but every time analyze_risk() was called, a <strong>new client instance</strong> was being initialized. Not only was this inefficient, but it also <strong>violated the principle of keeping shared services centralized</strong>. So I decided to refactor it using the <strong>Singleton Pattern</strong>.</p><h4>The Singleton Solution</h4><p>Here’s how I implemented the Singleton pattern in my AI client:</p><pre>from openai import OpenAI<br>from config.settings import settings<br><br>class AIClientSingleton:<br><br>    _instance = None<br>    def __new__(cls):<br>        if cls._instance is None:<br>            cls._instance = super(AIClientSingleton, cls).__new__(cls)<br>            cls._instance._init_client()<br>        return cls._instance<br><br>    def _init_client(self):<br>        self.client = OpenAI(<br>            base_url=&quot;https://openrouter.ai/api/v1&quot;,<br>            api_key=settings.OPENROUTER_API_KEY<br>        )<br>        self.prompt_template = &quot;Analisis dokumen berikut untuk...&quot;<br><br>    def analyze_risk(self, text: str) -&gt; str:<br>        full_prompt = f&quot;{self.prompt_template}\n\n{text}&quot;<br>        try:<br>            response = self.client.chat.completions.create(<br>                model=&quot;qwen/qwen2.5-vl-72b-instruct:free&quot;,<br>                messages=[<br>                    {<br>                        &quot;role&quot;: &quot;user&quot;,<br>                        &quot;content&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: full_prompt}]<br>                    }<br>                ],<br>            )<br>            return response.choices[0].message.content.strip()<br>        except Exception as e:<br>            return f&quot;❌ Gagal menganalisis dokumen: {str(e)}&quot;</pre><h4>Why Singleton Works Perfectly Here ✅</h4><ul><li><strong>Efficiency</strong>: The AI client is created only once and reused across the entire application.</li><li><strong>Consistency</strong>: All requests use the same configuration and authentication setup.</li><li><strong>Clean Separation</strong>: Logic for client initialization, prompt formatting, and API calls are all encapsulated in one place.</li><li><strong>Resource Friendly</strong>: Prevents unnecessary re-initialization of the external API client.</li></ul><h4>How to Use It</h4><pre>client = AIClientSingleton()<br>result = client.analyze_risk(&quot;Isi dokumen kontrak yang ingin dianalisis...&quot;)</pre><p>That’s it! The class takes care of instantiating and reusing the client behind the scenes, letting you focus on the logic that matters.</p><h3>DTO: Making AI Responses Easier to Work With</h3><p>DTO stands for <strong>Data Transfer Object</strong> — a simple, lightweight object used to <strong>transfer data between different layers</strong> of an application. The primary goal of a DTO is to <strong>encapsulate structured data</strong> without including any business logic, reducing unnecessary method calls and improving clarity when data is passed around.</p><p>In my project, I implemented DTOs to structure and manage the results of <strong>AI-generated legal risk analysis</strong>, which comes back as plain text. Rather than manually handling this data using raw Python dictionaries (which can get messy, especially in large systems), I decided to wrap the results into a dedicated RiskClauseDTO class.</p><h4>Step 1: Define the DTO Class</h4><p>The RiskClauseDTO class represents a single risk clause parsed from the AI’s response. It contains only three fields: the clause number, the risky text identified, and the reason why it’s considered risky.</p><pre>from dataclasses import dataclass<br><br>@dataclass<br>class RiskClauseDTO:<br>    clause: str<br>    risky_text: str<br>    reason: str</pre><p>This class has <strong>no business logic</strong>, only data. Being a dataclass, it also automatically provides useful dunder methods like __init__, __repr__, and __eq__, which simplifies serialization, debugging, and comparison.</p><h4>Step 2: Use DTOs in the Risk Parser</h4><p>I then modified the parser to <strong>return a list of </strong><strong>RiskClauseDTO instances</strong> instead of dictionaries. This made the structure much more predictable and consistent across the app.</p><pre>import re<br>import logging<br>from typing import List<br>from .dto import RiskClauseDTO<br>logger = logging.getLogger(__name__)<br><br>class RiskParser:<br>    &quot;&quot;&quot;Handles AI-generated risk analysis parsing with robust error handling and logging.&quot;&quot;&quot;<br>    <br>    RISK_PATTERN = r&quot;Klausul\s+([\w\s()]+):\s*[&#39;\&quot;]?(.*?)[&#39;\&quot;]?\s*\.?\s*Alasan:\s*[&#39;\&quot;]?(.*?)[&#39;\&quot;]?(?:\n|$)&quot;<br><br>    @staticmethod<br>    def parse_ai_risk_analysis(ai_response: str) -&gt; List[RiskClauseDTO]:<br>        logger.info(&quot;Parsing AI risk analysis response, length=%d&quot;, len(ai_response))<br>        try:<br>            matches = re.findall(<br>                RiskParser.RISK_PATTERN,<br>                ai_response,<br>                re.DOTALL | re.MULTILINE<br>            )<br>            if not matches:<br>                logger.warning(&quot;No valid risk clauses found in the AI response&quot;)<br>                return [<br>                    RiskClauseDTO(<br>                        clause=&quot;N/A&quot;,<br>                        risky_text=&quot;Tidak ditemukan klausul yang dapat dianalisis&quot;,<br>                        reason=&quot;Dokumen aman atau tidak dikenali&quot;<br>                    )<br>                ]<br>            structured_results = [<br>                RiskClauseDTO(<br>                    clause=f&quot;Klausul {m[0]}&quot;,<br>                    risky_text=m[1].strip(),<br>                    reason=m[2].strip()<br>                )<br>                for m in matches<br>            ]<br>            logger.info(&quot;Successfully parsed AI risk analysis, clause_count=%d&quot;, len(structured_results))<br>            return structured_results<br>        except Exception as exc:<br>            logger.error(&quot;Error while parsing AI risk analysis: %s&quot;, exc)<br>            return [<br>                RiskClauseDTO(<br>                    clause=&quot;N/A&quot;,<br>                    risky_text=&quot;Parsing gagal&quot;,<br>                    reason=&quot;Kesalahan sistem saat mengolah dokumen&quot;<br>                )<br>            ]</pre><h4>Why This Is Better</h4><p>Before I introduced the DTO, the function returned a list of raw dictionaries like this:</p><pre>{<br>    &quot;clause&quot;: &quot;Klausul 1&quot;,<br>    &quot;risky_text&quot;: &quot;Pasal yang ambigu...&quot;,<br>    &quot;reason&quot;: &quot;Kalimat dapat ditafsirkan ganda...&quot;<br>}</pre><p>Now, I return a structured list of RiskClauseDTO objects:</p><pre>RiskClauseDTO(<br>    clause=&quot;Klausul 1&quot;,<br>    risky_text=&quot;Pasal yang ambigu...&quot;,<br>    reason=&quot;Kalimat dapat ditafsirkan ganda...&quot;<br>)</pre><h4>Benefits:</h4><ul><li>✅ <strong>Better type safety</strong>: Catch bugs earlier with tools like mypy or IDE autocompletion.</li><li>✅ <strong>Easier to maintain</strong>: One definition for the structure across your app.</li><li>✅ <strong>Ready for serialization</strong>: Easy to convert to JSON if needed for APIs or frontend.</li><li>✅ <strong>Cleaner and self-documenting</strong>: It’s immediately clear what data is expected and passed.</li></ul><h3>MVC (Model View Controller) at a Glance</h3><p>As projects grow in complexity, structuring code with clear responsibilities becomes essential. One architectural pattern that shines in maintainability and scalability is the <strong>Model-View-Controller (MVC)</strong>. In this article, I’ll show how my AI-powered legal document analyzer cleanly adopts the MVC pattern across both backend and frontend.</p><ul><li><strong>Model</strong>: Handles core logic, data processing, and external services.</li><li><strong>View</strong>: What the user sees or interacts with (UI or API response).</li><li><strong>Controller</strong>: The coordinator between inputs and logic — manages request flows.</li></ul><h4>Model: The Core Logic</h4><p>Everything that deals with extracting text, analyzing risks, or parsing the AI response is part of the <strong>Model</strong>. It doesn’t know anything about HTTP, files, or UI , it just does its job.</p><h4>🔹 Example: parsers.py</h4><pre>class PDFParser(DocumentParser):<br>    def extract_text(self, file_path: str) -&gt; str:<br>        with pdfplumber.open(file_path) as pdf:<br>            extracted = &quot;\n&quot;.join([<br>                p.extract_text() for p in pdf.pages if p.extract_text()<br>            ])<br>            return extracted.strip()</pre><h4>🔹 Example: ai_client.py</h4><pre>class AIClient:<br>    @staticmethod<br>    def analyze_risk(text: str) -&gt; str:<br>        prompt = &quot;Analisis dokumen berikut...\n\n&quot; + text<br>        response = client.chat.completions.create(model=&quot;...&quot;, messages=[...])<br>        return response.choices[0].message.content.strip()</pre><h4>🔹 Example: risk_parser.py</h4><pre>class RiskParser:<br>    @staticmethod<br>    def parse_ai_risk_analysis(ai_response: str) -&gt; List[Dict[str, str]]:<br>        matches = re.findall(...pattern...)<br>        return [{&quot;clause&quot;: ..., &quot;risky_text&quot;: ..., &quot;reason&quot;: ...} for m in matches]</pre><h4>Controller: The Workflow Manager</h4><p>The <strong>Controller</strong> is where requests come in and responses go out. It doesn’t do any parsing or AI logic directly — instead, it calls the model and returns the results.</p><h4>🔻 Example: routers/analyze.py</h4><pre>@router.post(&quot;/analyze/&quot;)<br>async def analyze_document(file: UploadFile = File(...)):<br>    parser = ParserFactory.get_parser(file_ext)<br>    extracted = parser.extract_text(temp_file)<br>    ai_response = AIClient.analyze_risk(extracted)<br>    parsed = RiskParser.parse_ai_risk_analysis(ai_response)<br>    return {&quot;extracted_text&quot;: extracted, &quot;ai_response&quot;: ai_response, &quot;risks&quot;: parsed}</pre><h4>🖥️ View: The Frontend Interface</h4><p>This is where your beautiful <strong>React + Tailwind</strong> UI comes in. The frontend serves as the View layer — fetching the backend output and rendering it in an interactive, user-friendly format.</p><h4>Example</h4><p>Here’s a simplified breakdown of what your View does:</p><ul><li>Accepts a PDF file URL as input</li><li>Downloads and uploads it to the backend</li><li>Displays parsed risks with expandable UI</li><li>Uses a chat-style streaming output to show AI feedback in real-time</li><li>Lets users request revisions per clause</li></ul><pre>const [risks, setRisks] = useState&lt;Risk[]&gt;([]);<br>const [chatMessages, setChatMessages] = useState&lt;ChatMessage[]&gt;([]);<br><br>useEffect(() =&gt; {<br>  if (pdfUrl) {<br>    processDocument(); // calls backend to extract and analyze<br>  }<br>}, [pdfUrl]);</pre><p>Then, we can show it</p><pre>&lt;RiskItem key={index} risk={risk} onRevise={handleRevise} /&gt;</pre><p>All rendered beautifully in your frontend. Here’s what makes this a View:</p><ul><li>It <strong>doesn’t perform the analysis logic itself</strong></li><li>It <strong>calls APIs</strong> and renders the results</li><li>It <strong>displays state</strong> through components like RiskItem, FaSpinner, and ReactMarkdown</li></ul><h3>So… How Exactly Do You Refactor?</h3><p>If you’re wondering how to start refactoring effectively, here’s a step-by-step approach that works wonders — especially when you want your code to be clean, efficient, and professional:</p><ol><li><strong>Know what to look for</strong> 🧐<br>Familiarize yourself with common <strong>code smells</strong> and <strong>anti-patterns</strong> that signal deeper issues in your codebase. This awareness is key to identifying areas that need improvement. If you’re new to this, <a href="https://refactoring.guru/">refactoring.guru</a> is an excellent resource with real-world examples and explanations that are easy to digest.</li><li><strong>Check your tools</strong> 🔍<br>Use <strong>SonarQube</strong> or other static analysis tools to catch code smells, bugs, and potential issues after pushing your changes. But don’t rely on them blindly, there are still areas SonarQube won’t catch (like poor naming or architecture decisions), so trust your instincts and experience too.</li><li><strong>Follow the fix suggestions</strong> 🧠<br>Once you’ve identified the problematic areas, start refactoring based on best practices or the actionable suggestions from SonarQube. Whether it’s simplifying logic, cleaning up duplication, or breaking long methods apart — take it step by step.</li><li><strong>Always run the tests</strong> ✅<br>Before committing your changes, make sure the behavior of your refactored code hasn’t changed. Unit tests and integration tests are your safety net — they confirm that everything still works as intended.</li><li><strong>Push and tag it clean</strong> 🚀<br>After validating your changes, push your code and don’t forget to include a clear commit message, preferably with a [REFACTOR] tag so your team (and future you) knows the purpose of the change.</li></ol><p>Let’s be real, refactoring can be frustrating. Even the smallest tweak might trigger a cascade of IDE errors and warnings. But don’t give up. Breathe. Read those messages. Tackle them one by one. You’ll come out the other side with cleaner, more maintainable, and better-structured code.</p><p>In the end, your future self (and your team) will thank you. So keep pushing for quality, and don’t settle for messy code. 💪🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a70c4f966c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UI/UX: The Power Behind Exceptional Digital Design]]></title>
            <link>https://medium.com/@bryantjandra2003/ui-ux-the-power-behind-exceptional-digital-design-0afc55542cef?source=rss-ef9ddc2bbc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0afc55542cef</guid>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[user-interface]]></category>
            <dc:creator><![CDATA[Bryan Tjandra]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 18:10:30 GMT</pubDate>
            <atom:updated>2025-05-01T15:31:11.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dkLzBoE1sf52RkXJ.jpg" /><figcaption>Source: <a href="https://www.patrickhansen.com/2017/09/01/ui-vs-ux-design-meme-problem/">https://www.patrickhansen.com/2017/09/01/ui-vs-ux-design-meme-problem/</a></figcaption></figure><p>In the realm of digital product design, <strong>UI/UX</strong> is a term you’ll encounter frequently. However, many people mistakenly use these terms interchangeably, not realizing that they address distinct aspects of the design process.</p><ul><li><strong>User Interface (UI)</strong> focuses on the <strong>visual elements and interactivity</strong> of a product. It’s all about how the product looks and how users interact with it.</li><li><strong>User Experience (UX)</strong>, on the other hand, involves the <strong>overall journey</strong> a user takes while navigating the system. It assesses how intuitive, efficient, and satisfying the product feels during usage.</li></ul><p>To put it simply, <strong>UI is like the paint and decor</strong> of a house, while <strong>UX is the overall experience</strong> of living in that house. While a stunning UI can grab attention, a seamless UX ensures that users stay engaged and return.</p><h3>Designing for a Great User Experience 🎯</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IxTHsMBCzLe1K--m" /><figcaption>Source: <a href="https://www.linkedin.com/pulse/nielsen-molichs-10-user-interface-design-guidelines-amira-elbana/">https://www.linkedin.com/pulse/nielsen-molichs-10-user-interface-design-guidelines-amira-elbana/</a></figcaption></figure><p>To create a system that users love, designers adhere to a set of well-defined principles. Among the most widely accepted frameworks is <strong>Nielsen and Molich’s 10 Usability Heuristics</strong>, which provides a broad, high-level approach to crafting intuitive and efficient designs. These principles guide designers in enhancing both UI and UX, ensuring that users can interact with the system effortlessly.</p><p>Below, I’ll explore these heuristics in detail, sharing how my team implemented them in our project.</p><h3>1. Visibility of System Status ⏳</h3><p><strong>“Keep users informed about what’s happening.”</strong></p><p>When users interact with a system, they expect real-time feedback indicating the status of their actions. Without proper feedback, users may become confused, wondering whether the system is still processing their request or if it has encountered an error.</p><p>✅ <strong>Our Implementation:</strong><br> In our project, we initially displayed no message while fetching data, which confused users when the system hadn’t finished loading. To fix this, we introduced a <strong>loading spinner</strong> that appears while the result is being processed. This way, users now understand that the system is still processing their request, enhancing their confidence in the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJDAxUlaf3xC-F8N69ZNJw.png" /></figure><h3>2. Match Between System and the Real World 🌎</h3><p><strong>“Speak the user’s language.”</strong></p><p>A system should use familiar language, symbols, and metaphors that reflect real-world concepts. This principle ensures that users can easily relate to the system without needing to learn new terminologies or icons.</p><p>✅ <strong>Our Implementation:</strong><br> To align with this principle, we incorporated <strong>universal icons</strong> that users instantly recognize. For instance, we used a <strong>upload icon</strong> to signify the uploading action — something users naturally associate with adding file into the app. This small change increased the intuitiveness of our interface and reduced the need for additional explanations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Gyr-c2z3vM-RY_7Ylj_ng.png" /></figure><h3>3. User Control and Freedom 🔄</h3><p><strong>“Give users the freedom to explore and reverse actions.”</strong></p><p>Users should feel empowered to explore different actions without the fear of making irreversible mistakes. Providing <strong>emergency exits</strong> or easy ways to undo actions gives users the confidence to engage more freely with the system.</p><p>✅ <strong>Our Implementation:</strong><br> We ensured user freedom by adding a <strong>“Hapus Hak”</strong> button that allows users to cancel their decision while adding new “<strong>Hak</strong>”. This button serves as an escape hatch, enabling users to return to the previous state without committing unwanted actions. By giving users this safety net, we reduced their anxiety about making mistakes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55wg_NsgIaRQOh6lQpjz3A.png" /></figure><h3>4. Consistency and Standards ✅</h3><p><strong>“Maintain consistency across the system.”</strong></p><p>Consistency in design reduces the cognitive load on users, allowing them to predict system behavior. When a system follows familiar conventions, users don’t have to relearn interactions as they navigate through different sections.</p><p>✅ <strong>Our Implementation:</strong><br> To ensure consistency, we adopted a <strong>uniform design system</strong> across all pages. This included maintaining consistent <strong>typography, color schemes, icons, and layout structures</strong>. Additionally, we implemented a <strong>standardized navbar </strong>that appears on every page, making navigation seamless. This approach not only enhanced the <strong>learnability</strong> of the system but also helped users navigate with confidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dILOVqmgHut_Vbp1jsWFFQ.png" /></figure><h3>5. Error Prevention 🚫</h3><p><strong>“Prevent errors before they occur.”</strong></p><p>Prevention is always better than correction. Anticipating potential user errors and designing safeguards can significantly reduce the occurrence of mistakes.</p><p>✅ <strong>Our Implementation:</strong><br> To prevent confusion and ensure that users receive accurate feedback, we implemented a <strong>confirmation dialog</strong> that appears when analyzing a document for potential risks. For instance, if the document contains no risky clauses, the system displays a message such as:</p><p>📌 <strong>N/A</strong> — Collapse<br> 🔍 <strong>Risky Text:</strong> Tidak ditemukan klausul berisiko<br> ⚠️ <strong>Reason:</strong> Dokumen tampak aman</p><p>Additionally, if the document is uploaded in an <strong>unsupported language</strong>, the system provides immediate feedback with a <strong>“Bahasa tidak didukung”</strong> error message, allowing users to understand why the analysis could not proceed. This proactive approach helps prevent misunderstandings and ensures that users are aware of any limitations or issues before moving forward. By offering clear and informative messages, we empower users to take corrective action or proceed with confidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPHz7vClGXxeFsKUQLPehg.png" /></figure><h3>6. Recognition Rather Than Recall 🧠</h3><p><strong>“Minimize the user’s memory load.”</strong></p><p>A system should not require users to recall information across multiple screens. Instead, options, instructions, and relevant information should be readily visible or easily accessible.</p><p>✅ <strong>Our Implementation:</strong><br> To minimize cognitive load, we implemented a feature where the <strong>chat history title</strong> dynamically reflects the content of the user’s query. For instance, if a user asks:</p><p>💬 <strong>User:</strong> <em>If I make a deception, will I be caught?</em></p><p>🤖 <strong>Assistant: </strong><em>Apakah seseorang akan tertangkap jika melakukan penipuan (deception) bergantung pada banyak faktor. Tidak ada jaminan otomatis bahwa seseorang akan tertangkap atau tidak. Proses penegakan hukum di Indonesia melibatkan beberapa tahapan…</em></p><p>The system automatically assigns the title <strong>“Deception in the Legal Context”</strong> to that chat session. This makes it easier for users to <strong>recognize past conversations</strong> without having to recall the exact details of their previous questions. By allowing users to quickly identify relevant chats based on intuitive and descriptive titles, we’ve reduced the need for manual searching and improved the overall user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3kPpq3_2Yhi6qcK5mA4zQ.png" /></figure><h3>7. Flexibility and Efficiency of Use ⚡️</h3><p><strong>“Cater to both novice and experienced users.”</strong></p><p>A well-designed system should accommodate both beginners and power users by providing shortcuts and advanced options for experienced users while maintaining simplicity for newcomers.</p><p>✅ <strong>Our Implementation:</strong><br> We introduced <strong>keyboard shortcuts</strong> (such as <strong>Ctrl + C</strong> for copy and <strong>Ctrl + V</strong> for paste) to allow experienced users to speed up their workflows. Additionally, date and time inputs in our system were designed to be flexible, users could either <strong>type manually</strong> or <strong>select from a dropdown. </strong>Also, user can add or delete “Pihak” according to their preferences, giving them the freedom to choose whichever method they preferred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpCMxCZkVEg2i1OI21TZig.png" /></figure><h3>8. Aesthetic and Minimalist Design 🎨</h3><p><strong>“Eliminate unnecessary clutter.”</strong></p><p>Less is more. An interface should be clean and free from irrelevant information that might distract or confuse users.</p><p>✅ <strong>Our Implementation:</strong><br>In our project, we followed this principle by designing an interface that presents <strong>only the most relevant information</strong> in a clean and organized manner. For instance, in the contract review interface, we display <strong>clause details, potential risks, reasons, and generated revisions</strong> in a structured layout. The sidebar lists different contracts with clear, concise labels, allowing users to easily navigate between documents. Additionally, we kept the <strong>action buttons</strong> intuitive and accessible, such as the <strong>“Open”</strong> button for opening the analyzed document. This streamlined design not only enhances the system’s usability but also reduces cognitive load, enabling users to focus on reviewing and managing contract clauses efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tY4-r7Wr2jlpxIDwM0ziOA.png" /></figure><h3>9. Help Users Recognize, Diagnose, and Recover from Errors ❗️</h3><p><strong>“Provide informative error messages.”</strong></p><p>When errors occur, the system should provide clear and actionable feedback that helps users understand the problem and how to fix it.</p><p>✅ <strong>Our Implementation:</strong><br> To implement this, we used <strong>notifications</strong> to display error messages prominently. These notifications not only explained the error in plain language but also provided suggestions on how users could resolve the issue, enabling them to quickly recover from errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HiSH3VihsrlrZMqMXVXnwQ.png" /></figure><h3>10. Help and Documentation 📚</h3><p><strong>“Provide accessible and easy-to-understand documentation.”</strong></p><p>Even well-designed systems can benefit from comprehensive documentation that assists users in understanding complex tasks.</p><p>✅ <strong>Our Implementation:</strong><br>Although this feature is still a work in progress, we’ve already designed a <strong>mockup for the FAQ </strong>that will eventually guide users in completing tasks efficiently. Our goal is to create a user-friendly guide that empowers users to troubleshoot issues independently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*5EHpMBolgH-BUwqh4deijw.png" /></figure><h3>Fitts’ Law: Making Interactions Faster and Smoother 🎯</h3><p><strong>“The time to acquire a target is a function of the distance to and size of the target.”</strong></p><p>Fitts’ Law states that the time required to move a pointer to a target area is directly related to the distance and size of the target. In simple terms, <strong>the closer and bigger a target is, the easier and faster it is to click.</strong> Conversely, smaller and farther targets are harder to click and require more time to acquire. This principle highlights the importance of optimizing UI elements for ease of use, which can significantly enhance user experience and reduce errors.</p><p>Below are a few ways we applied this principle in our project to improve usability:</p><h3>1. Shorter Dropdown Lists ⏬</h3><p><strong>“Reducing travel distance increases efficiency.”</strong></p><p>✅ <strong>Our Implementation:</strong><br> To minimize the time required for users to select an option from a dropdown list, we opted for <strong>shorter dropdown menus</strong> where possible. By limiting the list length, users can quickly scan and select their desired option, improving task efficiency and reducing frustration. This approach not only enhances productivity but also ensures that users don’t spend excessive time scrolling through a long list of items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Mc6ZUevhjdUxppeFbNLHhA.png" /></figure><h3>2. Well-Spaced and Larger Buttons 🔘</h3><p><strong>“Bigger buttons with adequate spacing are easier to click.”</strong></p><p>✅ <strong>Our Implementation:</strong><br> We ensured that <strong>buttons are adequately sized and spaced apart</strong>, reducing the likelihood of users accidentally clicking the wrong button. Larger, well-spaced buttons make it easier for users to interact with the interface, preventing errors and enhancing overall efficiency. This small but impactful change helps users perform tasks more confidently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*YJPqRyG6tf8s-UbOyVl5Pg.png" /></figure><h3>3. Strategically Placed Buttons 📍</h3><p><strong>“Placing buttons where users expect them improves discoverability.”</strong></p><p>✅ <strong>Our Implementation:</strong><br> We placed critical buttons, such as action or confirmation buttons, in <strong>locations that are easy to notice</strong>. For instance, buttons that require frequent interaction were positioned at the <strong>top of the page</strong> or close to related content, ensuring they remain visible without unnecessary scrolling. This thoughtful placement reduces the effort required to locate and interact with essential elements, leading to a more intuitive user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*rR0qngvoY6HjfCxUuDdkGw.png" /></figure><h3>Jakob’s Law: Leveraging Familiarity for a Better Experience 🌐</h3><p><strong>“Users spend most of their time on other sites. This means they prefer your site to work the same way as all the other sites they already know.”</strong></p><p>Jakob’s Law suggests that users develop expectations based on their experiences with other websites. Consequently, they prefer interfaces that follow familiar patterns and structures. <strong>Deviating too far from these conventions increases the cognitive load on users and makes navigation less intuitive.</strong></p><h3>1. Navbar Navigation 📚</h3><p><strong>“Familiar structures reduce the learning curve.”</strong></p><p>✅ <strong>Our Implementation:</strong><br> To enhance user familiarity, we adopted a <strong>navigation bar layout</strong> similar to what users encounter on popular platforms like Tokopedia. The sidebar allows users to seamlessly navigate through different sections of the application. Since many users are accustomed to this design, they can intuitively explore the application without requiring additional guidance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CnH7Nvmp8UyzTzTIxW0Z8A.png" /></figure><h3>2. List-Based Layout 📄</h3><p><strong>“List layouts align with user expectations.”</strong></p><p>✅ <strong>Our Implementation:</strong><br> Many popular platforms, such as Google, use <strong>list-based layouts</strong> to display search results or content. By applying this layout to display relevant information in our application, we created a sense of familiarity that made it easier for users to scan and digest the content quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jf87It5vPbYPjuzc78OPSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkFz-jkRE6GUU6Rl4_ZXHg.png" /></figure><h3>3. Usage of Standard Buttons and Toggles ⚙️</h3><p><strong>“Physical metaphors improve understanding.”</strong></p><p>✅ <strong>Our Implementation:</strong><br>We utilized <strong>form toggles, buttons, and input fields</strong> that mimic real-world counterparts, making interactions feel intuitive. Since users are already familiar with these physical metaphors, they can easily engage with these elements without any learning curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1zW33Lcn7udF43KI.png" /><figcaption>Source: <a href="https://lawsofux.com/jakobs-law/">https://lawsofux.com/jakobs-law/</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*SEn4nx7vfkdopHb63sJiIg.png" /></figure><h3>Violations: Where Did We Fall Short? ⚠️</h3><p>Even with careful attention to these principles, some areas in our design inadvertently <strong>deviated from best practices</strong>. Here are a few of those cases:</p><h3>1. Narrow and Shrinking Text Box</h3><p>✅ <strong>The Challenge:</strong><br>We encountered an issue where the <strong>text box and generated document preview</strong> on the left side of the interface became <strong>too narrow</strong>, especially when additional input fields or content were added. This narrowing effect made it difficult for users to read and review the generated document comfortably. The reduced width created a <strong>cramped layout</strong> that negatively impacted the overall user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*1g-CXl2X_UX5UihkT7qHdQ.png" /></figure><p>✅ <strong>Proposed Solution:</strong><br> To address this, we plan to <strong>adjust the layout and allocate more space to the document preview area</strong>. By dynamically resizing the left-side text box and ensuring that the generated document utilizes the available screen width effectively, we can provide a more spacious and user-friendly experience. Additionally, implementing a <strong>responsive design</strong> that adapts to different screen sizes will ensure that the text box and document remain appropriately sized across various devices. This change will enhance <strong>readability, reduce clutter, and improve the overall usability</strong> of the interface.</p><h3>2. Visual and Functional Inconsistencies in Chat Interface</h3><p>✅ <strong>The Challenge:</strong><br> Upon reviewing the application, we noticed <strong>visual and functional inconsistencies</strong> across different sections of the chat interface. While the core functionality remained the same (chat-based interaction with the legal assistant), the <strong>styling, color schemes, and overall design</strong> varied between pages. These inconsistencies can lead to confusion for users, as they may perceive the interfaces as separate systems, even though they serve the same purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jeNSH9k_kFHE41hMDfYBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMlVmGyXC1KJgXS7OuZi7g.png" /></figure><p>✅ <strong>Proposed Solution:</strong><br> To maintain a consistent look and feel, we propose <strong>standardizing the design of all chat-related interfaces</strong> by aligning the <strong>color schemes, typography, button styles, and overall layout</strong>. This approach will provide a unified experience across different sections, reducing cognitive load and ensuring that users can seamlessly transition between chat features without having to adjust to a different interface. By ensuring consistency, we enhance user familiarity and improve overall engagement with the system.</p><h3>3. Hidden Chat Input Box</h3><p>✅ <strong>The Challenge:</strong><br> Initially, the <strong>chat text input box</strong> was clearly visible and accessible. However, upon <strong>zooming in or resizing the screen</strong>, the input box would disappear or get pushed out of view. This behavior violated <strong>Fitts’ Law</strong>, as users had to spend unnecessary time adjusting the zoom level or scrolling to locate the input box again. Such inconsistencies made it difficult for users to interact smoothly with the system, especially on devices with different screen resolutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PyGVOL8uzBgop4SB1m3w2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GH8UXSA57OyqOlZff0dQzQ.png" /></figure><p>✅ <strong>Proposed Solution:</strong><br> To address this, we propose implementing a <strong>responsive design</strong> that dynamically adjusts the chat interface to fit various screen sizes and zoom levels. By ensuring that the <strong>chat input box</strong> remains consistently visible regardless of zoom or resolution changes, we can improve accessibility and maintain a seamless user experience. This adjustment will reduce the time users spend searching for the input box and enhance overall interaction efficiency.</p><h3>A/B-testing in action</h3><p>Imagine you own a café and you’re not sure which of two chalk-board menus will pull more people in. You hang <strong>Menu A</strong> on Monday, <strong>Menu B</strong> on Tuesday, count how many lattes you sell each day and keep the winner. That’s A/B-testing: show two versions, measure, keep the best.</p><p>Why do product teams love it?</p><p>1. It replaces “I think” with “I know”.<br>2. Tiny tweaks can move big numbers (colour of a button, wording of a prompt).<br>3. You learn about real users, not lab volunteers or colleagues down the hall.</p><h4>Translating that idea to a web app</h4><p>For now, I will give an example of A/B testing with my project case, we will try to use two of Risk Item components as stated in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*k527t96WgSdB-pgZPaQjuw.png" /><figcaption>Design Type A</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*4EhMNc1-qvT5wk8TTwCvrA.png" /><figcaption>Design Type B</figcaption></figure><ol><li><strong>One visitor = one bucket</strong><br>When a browser lands on the site we flip a coin, label the user “A” or “B” and remember the label in localStorage so it sticks for future visits.</li><li><strong>Two versions of the component</strong><br> In our case it’s the <em>Risk Item</em> card:<br> • Variant A — the current design<br> • Variant B — the fresh layout with cleaner buttons and hierarchy<br> The bucket decides which one React renders.</li><li><strong>Measure what matters</strong><br> Every time someone:<br> • selects a clause<br> • sends a prompt<br> • applies a suggestion<br> …we log the event together with the visitor’s bucket.</li><li><strong>Store the data somewhere</strong><br>Fancy option: Mixpanel / Google Analytics (great dashboards, costs can grow). Our option: a two-line Zustand store that appends each event to localStorage. We temporarily choose this version because it is totally free, no servers, still survives page reloads.</li><li><strong>Read the results</strong><br>We built a tiny in-app dashboard that just totals the counts per variant and shows two tables. If you are using Mixpanel or Google Analytics, they have their own analytics dashboard</li></ol><h3>What I saw after a day</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INcA0nhxmL0LLCus14gHWw.png" /><figcaption>The analytics page</figcaption></figure><p>Here is the result of how many each button were clicked</p><p>• The new card (B) makes people explore more, “select clause” is up 83 %.<br> • They also talk to the assistant more, “send prompt” up 166 %.<br> • The final conversion (“apply suggestion”) is only slightly higher, good sign, but not yet a slam-dunk.</p><p><strong>Interpretation:</strong> the redesign grabs attention and encourages play, but the last CTA still needs punch. This can be seen that perhaps the checkbox button in the version A isn’t that clear, and perhaps people don&#39;t know what does it do, thus providing the B version option, catch a clearer attention.</p><p>If you wanna know how to implement the code, you can visit my pull request here: <a href="https://github.com/ppl-navigo/navigo/pull/13">Navigo PR A/B Testing</a></p><p><strong>Take Aways</strong></p><p>A/B-testing isn’t magic maths, it’s just the scientific method applied to design decisions. Even with a shoestring tracker you get concrete answers:</p><p>• Which version makes users <em>do</em> more?<br> • Where do they still stall?<br> • What should we improve next?</p><p>All for the price of a few extra lines of code.</p><h3>Lessons Learned: Why UI/UX Principles Matter 🎓</h3><p>By applying fundamental principles like <strong>Fitts’ Law</strong> and <strong>Jakob’s Law</strong>, we successfully reduced cognitive load and created a more <strong>intuitive, user-friendly application</strong>. These principles guided us in designing interfaces that:</p><p>✅ <strong>Minimize effort and interaction time</strong> by placing critical elements where users expect them and ensuring they remain easily accessible.<br>✅ <strong>Enhance user familiarity and comfort</strong> by maintaining consistent design patterns that align with users’ expectations from other platforms.<br>✅ <strong>Prevent errors and inconsistencies</strong> by anticipating potential issues and incorporating safeguards to guide users through their interactions.</p><p>These small but impactful improvements have resulted in <strong>higher user engagement, reduced error rates, and increased satisfaction</strong>. By offering clear system feedback, maintaining consistent design language, and preventing errors effectively, we’ve built an application that not only looks great but also makes users feel <strong>in control and confident</strong> while interacting with it.</p><p>In the end, <strong>great UI/UX design</strong> is not just about aesthetics, it’s about creating seamless, delightful experiences that keep users coming back for more. When done right, it leaves a <strong>lasting impact</strong> that translates to positive feedback, greater retention, and ultimately, higher profitability. 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0afc55542cef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Error Monitoring with Sentry and OpenTelemetry]]></title>
            <link>https://medium.com/@bryantjandra2003/exploring-error-monitoring-with-sentry-b940acbd7274?source=rss-ef9ddc2bbc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b940acbd7274</guid>
            <category><![CDATA[monitoring-software]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[sentry]]></category>
            <category><![CDATA[platform-monitoring]]></category>
            <dc:creator><![CDATA[Bryan Tjandra]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 16:04:59 GMT</pubDate>
            <atom:updated>2025-04-28T10:12:09.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYiJ3mg1SL12LSsnFROkSg.jpeg" /><figcaption>Source: <a href="https://www.supermonitoring.com/blog/identify-track-and-fix-issues-faster-with-sentry/">https://www.supermonitoring.com/blog/identify-track-and-fix-issues-faster-with-sentry/</a></figcaption></figure><p>Ever heard of monitoring tools? I hadn’t either until recently! Monitoring tools are super helpful software that you can connect to your application to keep an eye on its health and performance. They provide valuable insights into how your app is doing and can even send you alerts if something goes wrong.</p><p>There are two main types of monitoring tools:</p><p>✅ <strong>Error Monitoring Tools:</strong> These track and log errors, crashes, and exceptions that happen in your application.<br> ✅ <strong>Platform Monitoring Tools:</strong> These monitor the overall performance and health of your software platform or infrastructure.</p><p>Luckily, <strong>Sentry</strong> combines both of these powerful features into one easy-to-use platform!</p><h3>What is Sentry?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*URn53zGZHMYsBTFduB9v-Q.jpeg" /><figcaption>Source: <a href="https://www.supermonitoring.com/blog/identify-track-and-fix-issues-faster-with-sentry/">https://www.supermonitoring.com/blog/identify-track-and-fix-issues-faster-with-sentry/</a></figcaption></figure><p>Sentry is a developer-friendly tool that focuses on error tracking and performance monitoring. It helps developers identify and fix issues faster by giving them real-time insights into what’s happening in their applications. Sentry also offers additional features like session replay and code coverage, but for now, we’ll focus on its error and platform monitoring capabilities.</p><p>In this blog, we’ll explore how Sentry can make your life easier by helping you monitor and improve your application’s performance. Let’s dive in!</p><h3>Setting Up Sentry for Next.js</h3><p>If you’re building a Next.js application, keeping track of errors and monitoring performance is essential. That’s where <strong>Sentry</strong> comes in! It helps you log errors, track crashes, and get real-time insights into your application.</p><p>In this guide, we’ll go step-by-step through the process of setting up Sentry in a Next.js project. By the end, you’ll have error and performance monitoring up and running like a pro! 🚀</p><h3>Why Use Sentry?</h3><p>Sentry helps developers:</p><p>✅ <strong>Catch Errors Early:</strong> Logs and tracks application errors automatically.<br>✅ <strong>Monitor Performance:</strong> Analyzes app performance to detect bottlenecks.<br>✅ <strong>Get Alerts:</strong> Notifies you in real-time if something goes wrong.</p><p>Let’s jump right into the setup!</p><h4>Step 1: Sign Up and Log In to Sentry.io</h4><p>First, head over to <a href="https://sentry.io/">Sentry.io</a> and either <strong>Sign Up</strong> or <strong>Log In</strong> to your existing account.</p><ul><li>If you’re a new user, sign up using your email, Google account, or GitHub.</li><li>Once signed in, you’ll land on the Sentry dashboard.</li></ul><h4>Step 2: Create a New Project</h4><p>1. From your Sentry dashboard, click on the <strong>“+ Create Project”</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSDuJbh40ECLBqfR60tzdg.png" /></figure><ul><li>You can also find it by navigating to <strong>Projects</strong> in the sidebar and selecting <strong>Create Project</strong>.</li></ul><p><strong>2. Select Your Platform:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vmyxsqCubGBeX5roRQpQwQ.png" /></figure><ul><li>Choose <strong>Next.js</strong> from the list of platforms.</li><li>If you don’t see Next.js listed, you can also select <strong>JavaScript</strong> or <strong>Node.js</strong> (but Next.js is the preferred choice).</li></ul><p><strong>3. Set Your Project Name:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yp83nGHMwOCpa6YyLbogrg.png" /></figure><p>Give your project a meaningful name. For example:</p><ul><li>My next.js App</li></ul><p><strong>4. Assign to a Team:</strong></p><ul><li>Choose the team you want this project to belong to. If you don’t have a team, create one by selecting <strong>Create a New Team</strong>.</li></ul><p>Click on <strong>Create Project</strong> to move to the next step.</p><h4>Step 3: Get Your DSN (Data Source Name)</h4><p>After creating your project, you’ll be redirected to a setup page.<br>This page contains important details about your project’s configuration.</p><p>✅ <strong>DSN (Data Source Name):</strong><br>The DSN is a unique identifier that connects your application to your Sentry project. Copy the DSN as we’ll be using it shortly.</p><p>It will look something like this:</p><pre>https://YOUR_PUBLIC_KEY@o4509047620829184.ingest.sentry.io/4509047713431552</pre><h4>Step 4: Install Required Packages</h4><p>To get started, install Sentry using the following command:</p><pre>npm install @sentry/nextjs</pre><p>Or if you prefer yarn:</p><pre>yarn add @sentry/nextjs</pre><p>Once that’s done, you’re ready to start configuring Sentry.</p><h4>Step 5: Run Sentry Wizard for Next.js</h4><p>Sentry provides a super helpful wizard to auto-configure your project. Run the following command:</p><pre>npx @sentry/wizard -i nextjs</pre><p>This command:</p><p>✅ Adds required config files.<br>✅ Updates your next.config.js with Sentry settings.<br>✅ Sets up error monitoring for both client and server.</p><p>After running the wizard, you’ll notice new files created in your project.</p><h4>Step 6: Configure TypeScript</h4><p>If you’re using TypeScript (which is a great idea!), make sure you update your tsconfig.json file by adding the required Sentry types:</p><pre>&quot;types&quot;: [&quot;@testing-library/jest-dom&quot;, &quot;jest&quot;, &quot;@sentry/nextjs&quot;]</pre><p>This ensures TypeScript recognizes the Sentry types and helps prevent type-related errors.</p><h4>Step 7: Sentry Configuration Files</h4><p><strong>1. </strong><strong>sentry.server.config.ts</strong></p><p>This file configures Sentry for the <strong>server-side</strong>. Add the following code:</p><pre>// sentry.server.config.ts<br>import * as Sentry from &quot;@sentry/nextjs&quot;;<br><br>Sentry.init({<br>  dsn: &quot;YOUR_SENTRY_DSN_HERE&quot;,<br>  tracesSampleRate: 1, // Adjust for production<br>  debug: false,<br>});</pre><p>✅ <strong>DSN:</strong> This is the Data Source Name you get from your Sentry project dashboard.<br>✅ <strong>tracesSampleRate:</strong> Defines how often traces are sampled. You can adjust this later.</p><p><strong>2. </strong><strong>sentry.edge.config.ts</strong></p><p>This configures Sentry for <strong>Edge functions</strong> or middleware:</p><pre>// sentry.edge.config.ts<br>import * as Sentry from &quot;@sentry/nextjs&quot;;<br><br>Sentry.init({<br>  dsn: &quot;YOUR_SENTRY_DSN_HERE&quot;,<br>  tracesSampleRate: 1,<br>  debug: false,<br>});</pre><p><strong>3. </strong><strong>instrumentation-client.ts</strong></p><p>This file configures Sentry for the <strong>client-side</strong>:</p><pre>// instrumentation-client.ts<br>import * as Sentry from &quot;@sentry/nextjs&quot;;<br><br>Sentry.init({<br>  dsn: &quot;YOUR_SENTRY_DSN_HERE&quot;,<br>  integrations: [Sentry.replayIntegration()],<br>  tracesSampleRate: 1,<br>  replaysSessionSampleRate: 0.1,<br>  replaysOnErrorSampleRate: 1.0,<br>  debug: false,<br>});</pre><h4>Step 8: Custom Error Handling</h4><p>To handle errors more gracefully, create a custom error component.</p><p><strong>1. </strong><strong>_error.tsx</strong></p><pre>// _error.tsx<br>import * as Sentry from &quot;@sentry/nextjs&quot;;<br>import type { NextPage } from &quot;next&quot;;<br>import type { ErrorProps } from &quot;next/error&quot;;<br>import Error from &quot;next/error&quot;;<br><br>const CustomErrorComponent: NextPage&lt;ErrorProps&gt; = (props) =&gt; {<br>  return &lt;Error statusCode={props.statusCode} /&gt;;<br>};<br>CustomErrorComponent.getInitialProps = async (contextData) =&gt; {<br>  await Sentry.captureUnderscoreErrorException(contextData);<br>  return Error.getInitialProps(contextData);<br>};<br>export default CustomErrorComponent;</pre><p><strong>2. </strong><strong>global-error.jsx</strong></p><p>To capture and report global client-side errors, create a global-error.jsx file:</p><pre>&quot;use client&quot;;<br>import * as Sentry from &quot;@sentry/nextjs&quot;;<br>import NextError from &quot;next/error&quot;;<br>import { useEffect } from &quot;react&quot;;<br><br>export default function GlobalError({ error }) {<br>  useEffect(() =&gt; {<br>    Sentry.captureException(error);<br>  }, [error]);<br>  return (<br>    &lt;html&gt;<br>      &lt;body&gt;<br>        &lt;NextError /&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><h4>Step 9: API Error Tracking</h4><p>To test error tracking in an API route, create this file:</p><p><strong>api/sentry-example-api/route.ts</strong></p><pre>import { NextResponse } from &quot;next/server&quot;;<br><br>export const dynamic = &quot;force-dynamic&quot;;<br>// A faulty API route to test Sentry&#39;s error monitoring<br>export function GET() {<br>  throw new Error(&quot;Sentry Example API Route Error&quot;);<br>  return NextResponse.json({ data: &quot;Testing Sentry Error...&quot; });<br>}</pre><h4>Step 10: Add a Test Page</h4><p>Now create a test page to throw an error and see how Sentry logs it.</p><p><strong>app/sentry-example-page/page.tsx</strong></p><pre>&quot;use client&quot;;<br>import Head from &quot;next/head&quot;;<br>import * as Sentry from &quot;@sentry/nextjs&quot;;<br><br>export default function Page() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Sentry Test Page&lt;/title&gt;<br>      &lt;/Head&gt;<br>      &lt;main<br>        style={{<br>          minHeight: &quot;100vh&quot;,<br>          display: &quot;flex&quot;,<br>          justifyContent: &quot;center&quot;,<br>          alignItems: &quot;center&quot;,<br>          flexDirection: &quot;column&quot;,<br>        }}<br>      &gt;<br>        &lt;h1&gt;Sentry Error Example&lt;/h1&gt;<br>        &lt;button<br>          style={{<br>            padding: &quot;12px&quot;,<br>            backgroundColor: &quot;#AD6CAA&quot;,<br>            color: &quot;white&quot;,<br>            borderRadius: &quot;4px&quot;,<br>            border: &quot;none&quot;,<br>            cursor: &quot;pointer&quot;,<br>          }}<br>          onClick={async () =&gt; {<br>            await Sentry.startSpan(<br>              { name: &quot;Example Frontend Span&quot;, op: &quot;test&quot; },<br>              async () =&gt; {<br>                const res = await fetch(&quot;/api/sentry-example-api&quot;);<br>                if (!res.ok) {<br>                  throw new Error(&quot;Sentry Example Frontend Error&quot;);<br>                }<br>              }<br>            );<br>          }}<br>        &gt;<br>          Trigger Error<br>        &lt;/button&gt;<br>        &lt;p&gt;Check for errors on your Sentry dashboard!&lt;/p&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Clicking the button throws an error, which should be visible on your <strong>Sentry Issues Page</strong>.</p><h4>Step 11: Configure next.config.js</h4><p>Make sure your next.config.js is configured properly to upload source maps and enable Sentry:</p><pre>// next.config.js<br>const { withSentryConfig } = require(&quot;@sentry/nextjs&quot;);<br><br>module.exports = withSentryConfig(<br>  module.exports,<br>  {<br>    org: &quot;your-org-name&quot;,<br>    project: &quot;your-project-name&quot;,<br>    silent: !process.env.CI,<br>    widenClientFileUpload: true,<br>    disableLogger: true,<br>    automaticVercelMonitors: true,<br>  }<br>);</pre><p><strong>You are all set!!</strong></p><p>You’ve successfully set up Sentry for your Next.js application. With Sentry:</p><p>✅ You can monitor both client and server-side errors.<br>✅ Get notified in real-time when something goes wrong.<br>✅ Improve the overall stability and performance of your app.</p><h3>Understanding Sentry: A Deep Dive into Error Monitoring and Performance Insights</h3><p>After successfully integrating <strong>Sentry</strong> with your Next.js application, it’s essential to get an understanding in the Sentry dashboard to understand how the platform helps monitor errors and improve performance. Sentry provides valuable insights that enable developers to track, analyze, and fix errors quickly, ensuring a smooth user experience. Let’s dive deep into the different sections of Sentry and see how each one works in detail.</p><h4>1. Issues Page: Identifying and Prioritizing Errors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kMRytdgyMEOCKbF98qM3Ow.png" /><figcaption>Sentry Issues Page</figcaption></figure><p>The <strong>Issues Page</strong> is where all the action starts. This page serves as the central hub where Sentry logs and displays every error or exception that occurs in your application. When you navigate to the <strong>Issues Page,</strong> you’ll see a comprehensive list of errors that are categorized based on priority and severity.</p><p>At the top of the page, there are different tabs that help you manage and categorize the issues effectively.</p><ul><li>The <strong>Prioritized</strong> tab lists high-impact errors that need immediate attention</li><li>The <strong>For Review</strong> tab shows new issues that have not been reviewed yet.</li><li>Errors that were previously resolved but have reoccurred appear under the <strong>Regressed</strong> tab</li><li>Those that are increasing in frequency or severity are shown in the <strong>Escalating</strong> tab.</li><li>Finally, the <strong>Archived</strong> tab stores issues that have been ignored or resolved.</li></ul><p>Below these tabs, Sentry provides a list of all recorded issues, each accompanied by useful metadata such as the error type, the last time it was seen, its age, and the number of events or occurrences.</p><p>For instance, an error like ReferenceError: nonexistentFunction is not defined may be listed with details such as the file path where the error occurred (/generate), the number of events, and the number of users affected.</p><p>Similarly, an API error like Sentry Example API Route Error would show information about the route (/api/sentry-example-api), giving developers a clear view of where things went wrong. Clicking on any of these errors takes you to the <strong>Issue Details Page</strong>, where you can perform a deeper analysis.</p><h4>2. Issue Details Page: Analyzing Error Context and Stack Trace</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSUF8_dSlOfFDvswKMzLaQ.png" /><figcaption>Sentry Issue Detail Page</figcaption></figure><p>When you click on a particular error from the Issues Page, you’ll be directed to the <strong>Issue Details Page</strong>. This page provides a wealth of information that helps developers analyze and diagnose errors effectively. At the top of the page, you’ll see the name of the error, such as ReferenceError: nonexistentFunction is not defined, along with its severity level (e.g., Error), and whether the error was handled or unhandled. Sentry also indicates if the error is new or regressed, giving you an immediate sense of how critical the issue is.</p><p>As you scroll down, you’ll find a section that displays event-related data. This includes the <strong>Event ID</strong>, a unique identifier that helps you track the occurrence, and details about the browser, operating system, and environment where the error occurred. For example, the error might have been triggered on Chrome 134.0.0 running on macOS 12.7.4 in a development environment. The <strong>URL</strong> where the error occurred is also shown, making it easy to replicate the error in your local environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0D_LRSaXwCAhNkRvAk9XGA.png" /><figcaption>Error detail pointed in the code</figcaption></figure><p>One of the most crucial parts of the Issue Details Page is the <strong>Stack Trace</strong>. This section pinpoints the exact line of code where the error occurred, helping developers trace the source of the problem. For instance, if the error occurred in app/generate/page.tsx on line 290, Sentry highlights this information, making it easier to debug. Additionally, tags and custom metadata, such as the trace ID and additional environment details, provide even more context for troubleshooting.</p><h4>3. Frontend Insights: Measuring and Improving Application Performance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTzzswchRfjm8S5WndC3mA.png" /><figcaption>Frontend Insights Page</figcaption></figure><p>The <strong>Frontend Insights Page</strong> offers an overview of your application’s performance by analyzing frontend transactions and identifying opportunities to improve page load speed. When you visit the <strong>Frontend Insights Page</strong>, you’ll be greeted by an array of performance metrics that give you a clear picture of how well your application is performing in the browser.</p><p>One of the key sections on this page is <strong>Best Page Opportunities</strong>, which highlights pages that can be optimized to improve performance. For example, if the homepage (/) has a performance score of 90, it suggests that while the page is performing well, there’s still room for improvement. This section uses Web Vitals such as <strong>LCP (Largest Contentful Paint)</strong>, <strong>FID (First Input Delay)</strong>, and <strong>CLS (Cumulative Layout Shift)</strong> to assess how quickly and smoothly your pages load and respond to user interactions.</p><p>Another valuable section is <strong>Transactions Per Minute</strong>, which measures how many frontend transactions your application handles per minute. This is particularly useful for identifying spikes in traffic or performance degradation during peak usage times. Additionally, <strong>p50 Duration</strong> and <strong>p75 Duration</strong> provide insights into how long requests take to complete. The p50 metric shows the median duration for requests, while p75 indicates the duration within which 75% of requests are completed. For instance, if the p50 duration is 1.11s and the p75 duration is 1.37s, it means that most requests are completing in around 1 second, but a few may take slightly longer.</p><h4>4. Backend Insights: Analyzing API and Database Performance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Xy659bNp7DgE9OqEmcwwQ.png" /><figcaption>Backend Insight Page</figcaption></figure><p>The <strong>Backend Insights Page</strong> is designed to give developers a detailed understanding of the backend performance of their application. When you navigate to the <strong>Backend Insights Page</strong>, you’ll find insights into API response times, database queries, and outbound HTTP requests that may be slowing down your application.</p><p>One of the most important sections here is <strong>Most Time-Consuming Domains</strong>, which shows the external domains that consume the most time in outgoing HTTP requests. For example, domains like *.gstatic.com or fonts.googleapis.com might be slowing down your application by adding unnecessary latency. This section helps identify such bottlenecks so you can optimize your API calls and improve backend performance.</p><p>Additionally, <strong>Transactions Per Minute</strong> provides a breakdown of how frequently your backend routes are being accessed. This helps measure API load and identify potential performance bottlenecks. The p50 and p75 duration metrics are also available for backend routes, showing the median and 75th percentile durations for API requests. For example, if a GET request to /api/sentry-example-api takes 1.28s (p50) and 2.15s (p75), you’ll know that most requests are completing within 2 seconds, but a few might take slightly longer.</p><p>Sentry also highlights <strong>Top Backend Routes</strong> that consume the most time, allowing developers to identify slow-performing routes and optimize them. For instance, if the GET /generate route takes 8.06s at the median and 16.97s for 75% of requests, this suggests a significant delay that needs to be addressed.</p><h4>5. Transaction Summary: Detailed API Request Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJI3upE-zRviv05EGpqbtQ.png" /><figcaption>Transaction Summary</figcaption></figure><p>When it’s time to dig deeper into specific API routes, the <strong>Transaction Summary Page</strong> is where you want to be. This page provides granular insights into individual API requests, helping developers analyze their performance in detail. Visiting the <strong>Transaction Summary Page</strong> for a specific route, such as GET /api/sentry-example-api, opens up a world of performance data.</p><p>The <strong>Duration Breakdown</strong> section on this page analyzes how long different API requests take, providing insights into where delays are occurring. This breakdown helps developers pinpoint slow transactions that need optimization. Below that, the <strong>Sampled Events</strong> section displays a list of individual requests, each with a unique Event ID, timestamp, and trace ID. These details make it easier to correlate slow or failed requests with related traces and understand what went wrong.</p><p>Sentry also provides insights into <strong>Suspect Tags and Functions</strong>, which highlight metadata and functions that might be contributing to slow requests. This is particularly helpful for diagnosing complex performance issues that aren’t immediately obvious. Moreover, the <strong>User Misery and Failure Rate</strong> metrics measure how many users are affected by slow responses and the percentage of requests that fail. For instance, if the failure rate for a specific route is 50%, it indicates that half of the requests to that endpoint are failing, suggesting a critical issue that needs attention.</p><h3>Alerting in Sentry: How to Set Up and Manage Notifications Effectively</h3><p>Sentry is not just about tracking errors and monitoring performance, it also empowers developers by offering a powerful <strong>alerting system</strong> that helps identify issues before they escalate. Alerts in Sentry allow you to define specific conditions and receive notifications whenever these conditions are met. This way, you’re immediately informed when something goes wrong, allowing you to respond quickly and prevent further damage.</p><p>In this guide, we’ll walk you through the process of setting up alerts in Sentry, explaining each step in detail so that you can create customized alerts tailored to your application’s needs.</p><h3>Why Are Alerts Important?</h3><p>Alerts play a critical role in ensuring application stability and performance by providing real-time notifications about errors, crashes, and other anomalies. Without alerts, developers often realize there’s an issue only after users report it. Sentry helps solve this by automatically notifying you or your team when an error meets predefined conditions.</p><p>✅ <strong>Instant Notification:</strong> Get notified as soon as a critical error occurs.<br>✅ <strong>Error Thresholds:</strong> Set limits on the number of events before triggering an alert.<br>✅ <strong>Proactive Error Management:</strong> Fix issues before they impact users.</p><p>Let’s explore how to set up and manage these alerts effectively.</p><h4>Step 1: Create a New Alert Rule</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*loJptg_u7McdFa4BRPklfQ.png" /></figure><p>To set up a new alert, go to the <strong>Alerts</strong> section in your Sentry dashboard. Click on <strong>New Alert Rule</strong> to get started. This will open a configuration wizard that guides you through the process of creating a custom alert.</p><h4>Select Your Project and Environment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7IKghVqWLjK2OTI2ZwM6Sw.png" /></figure><p>The first step is to choose the project and environment where the alert should be applied. If you have multiple projects, you can select the appropriate one, such as navigo in this example. You can also apply the alert to <strong>all environments</strong> or limit it to a specific environment like production, staging, or development.</p><p>By selecting the right environment, you ensure that the alert is triggered only when relevant issues occur in the chosen environment.</p><h4>Step 2: Define Your Alert Conditions</h4><p>The next step involves setting up conditions that determine when the alert should be triggered. This is where you define the criteria that need to be met for the alert to fire.</p><h4>When Should the Alert Trigger?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnnOVh4tDLAvlgD8FASTJA.png" /></figure><p>In the <strong>“When”</strong> section, you specify the conditions that will trigger the alert. Sentry offers several options, but the most common use cases include:</p><ul><li><strong>A New Issue is Created:</strong> This condition triggers an alert whenever a new issue is logged in Sentry.</li><li><strong>Number of Events in an Issue Exceeds X:</strong> You can set an alert to trigger if the number of events in an issue exceeds a certain threshold within a specified timeframe.</li></ul><p>✅ <strong>Example Configuration:</strong><br> Set the alert to trigger <strong>“when an event is captured by Sentry and a new issue is created”</strong>.<br> Or, configure it to <strong>“trigger when the number of events in an issue exceeds 100 in one hour”</strong>.</p><p>These conditions allow you to capture critical issues immediately or monitor recurring errors that could indicate a deeper problem.</p><h4>Step 3: Add Optional Filters to Refine Your Alerts</h4><p>If you want to fine-tune your alert, Sentry gives you the option to add additional filters. This helps narrow down the conditions further so that you don’t receive unnecessary notifications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ajictDr8x51Ws2yEeaL44g.png" /></figure><h4>Apply Additional Filters (Optional)</h4><p>You can apply a filter to ensure the alert only triggers if:</p><ul><li><strong>The Issue Occurs at Least X Times:</strong> This prevents alerts from firing for one-off occurrences and focuses on persistent issues.</li><li><strong>Filter by Tags or Attributes:</strong> For example, you can configure the alert to trigger only if the error originates from a specific browser, version, or user.</li></ul><p>✅ <strong>Example Configuration:</strong><br>Add a filter that triggers the alert <strong>“if the issue has happened at least 10 times.”</strong><br>This ensures that only recurring issues are escalated, reducing noise and unnecessary notifications.</p><h4><strong>Step 4: Set Up Notification Actions</strong></h4><p>Once you’ve defined the conditions and filters, it’s time to decide how and where you want to receive notifications when the alert is triggered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8evOTGOI7YNNGOAwp0rzZw.png" /></figure><h4>Choose Where to Send Notifications</h4><p>In the <strong>“Then”</strong> section, you can configure actions to be performed when an alert is triggered. Sentry provides several options, including:</p><ul><li><strong>Send a Notification to a Team:</strong> Notify a specific team in your Sentry organization.</li><li><strong>Send to Slack or Other Integrations:</strong> Integrate with Slack to send alerts to a dedicated channel.</li><li><strong>Trigger a Webhook:</strong> Use webhooks to send notifications to custom endpoints or third-party systems.</li></ul><p>✅ <strong>Example Configuration:</strong><br> Set the alert to <strong>“send a notification to Team #navigo”</strong> whenever the conditions are met. This ensures that the relevant team is notified immediately and can take action.</p><h4>Step 5: Define Action Intervals to Control Alert Frequency</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MWdv4uK2qJl6kwzYtNoQA.png" /></figure><p>To avoid alert fatigue and unnecessary noise, you can configure how often actions should be performed for the same issue. This is controlled by setting an <strong>Action Interval</strong>.</p><h4>Set Action Interval for Recurring Alerts</h4><p>By default, Sentry performs actions only once per issue. However, if an issue continues to occur, you can configure the interval at which the actions should be repeated. For example:</p><ul><li><strong>Perform Actions Once Every 24 Hours:</strong> This ensures that you don’t receive duplicate notifications for the same error multiple times within a day.</li><li><strong>Set Custom Intervals:</strong> Adjust the interval to suit the frequency and urgency of your application’s needs.</li></ul><p>✅ <strong>Example Configuration:</strong><br> Set the interval to <strong>“perform the actions above once every 24 hours for an issue.”</strong> This prevents alert spamming and keeps your notifications meaningful.</p><h4>Step 6: Name and Assign Ownership of the Alert</h4><p>Once all conditions and actions have been defined, the final step is to name your alert and assign ownership. This ensures that the alert is easily identifiable and that the right team has the necessary permissions to manage and update the alert.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*koVU6kEnstBy5OuxfLh7fQ.png" /></figure><p>Choose a descriptive name that reflects the purpose of the alert. For example:</p><ul><li>Sentry Alert for High Error Rate</li><li>API Error Alert for /api/sentry-example-api</li></ul><h4>Assign Ownership</h4><p>Assign ownership to a team or individual to ensure that they have permission to manage, edit, and review the alert. This step guarantees that the alert is always being monitored and updated as needed.</p><p>✅ <strong>Example Configuration:</strong><br> Set the name as <strong>“Sentry Alert for Critical API Errors”</strong> and assign it to <strong>Team #brynajeshua</strong>.</p><h4>Step 7: Test and Save Your Alert Rule</h4><p>Before you finalize the alert, it’s always a good idea to test it to make sure it’s working as expected. Sentry provides an option to <strong>Send a Test Notification</strong> to verify that the alert is configured correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZTau3yqs2yE2ZLJHJU1hw.png" /></figure><p>✅ <strong>Send a Test Notification</strong> to ensure that the notification is delivered to the right channel or team.</p><p>Once the test is successful, click on <strong>Save Rule</strong> to activate the alert. Your alert is now live and ready to notify you the moment an issue matches the specified conditions.</p><h3>Monitoring Your Alerts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vKnhb2nKOZn4fThmn37gAg.png" /></figure><p>After creating an alert in Sentry, you can monitor and manage it from the <strong>Issue Alert</strong> page. This page provides a detailed overview of the alert, including the conditions that trigger it, the actions it performs, and a summary of any triggered alerts.</p><p>Once your alert is active, Sentry begins evaluating incoming events based on the conditions you’ve configured. The <strong>Alerts Triggered</strong> section shows the total number of times the alert has been triggered in the selected time period (e.g., 7 days). If no issues meet the conditions, you’ll see a message stating <strong>“No alerts triggered”</strong>, which means that no errors have matched the criteria yet. Additionally, the <strong>Alert Rule Details</strong> section displays information about the alert, including the environment it monitors, the creation date, the creator’s name, and the team responsible for managing it.</p><p>If you need to modify the alert, you can click on <strong>Edit Rule</strong> to refine the conditions or actions. Alternatively, if the alert becomes irrelevant or noisy, you can choose to <strong>Mute</strong> or <strong>Duplicate</strong> the rule to create a variant with different settings. Monitoring this page ensures that your alerts stay effective and that you’re notified only when necessary, helping you maintain a smooth application experience.</p><h3>From Zero to Full-Stack Observability with OpenTelemetry</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*BQ41WSbxn-bC4vBXuUivjQ.png" /><figcaption>Source: <a href="https://codelabs.developers.google.com/codelabs/otel-cloudtrace?hl=id#0">https://codelabs.developers.google.com/codelabs/otel-cloudtrace?hl=id#0</a></figcaption></figure><p>While <strong>Sentry</strong> is fantastic for error tracking, there’s a whole world of observability beyond just errors. What if you could have full <strong>end-to-end tracing</strong>, real-time <strong>Web Vitals</strong> metrics, and stream all of that to a <strong>self-hosted</strong> platform like <strong>SigNoz</strong>, or any other OTLP-compatible back-end (such as <strong>Grafana Tempo</strong>, <strong>Honeycomb</strong>, or <strong>New Relic</strong>)?</p><h4><strong>Why is this approach unique?</strong></h4><p>Because <strong>OpenTelemetry (OTel)</strong> offers <strong>true full-stack visibility</strong>, providing you with <strong>distributed traces</strong>, <strong>custom spans</strong>, and <strong>Web Vitals metrics</strong> (like CLS, LCP, FID, TTFB). Best of all, it’s completely <strong>vendor-neutral</strong>, giving you the freedom to send your data to the backend of your choice today — and keep that option open for tomorrow.</p><p>With just a few simple lines of code, you can enhance your <strong>React/Vite</strong> project with:</p><ul><li><strong>End-to-end tracing</strong> that spans from your browser, to your API, all the way down to your database.</li><li><strong>Real User Monitoring (RUM)</strong> metrics like <strong>CLS</strong>, <strong>LCP</strong>, <strong>FID</strong>, and <strong>TTFB</strong> to track how your users are experiencing your app.</li><li>The <strong>flexibility</strong> to integrate with any <strong>OTLP-compatible</strong> back-end now or in the future — whether it’s <strong>SigNoz</strong>, <strong>Grafana Tempo</strong>, or even <strong>New Relic</strong>.</li></ul><p>OpenTelemetry brings everything together, making it easier than ever to gain complete observability for your app, no matter what backend or monitoring tool you prefer.</p><h4>Project structure we’ll end up with</h4><pre>src/<br>└── observability/<br>    ├── otel.ts          # Boots OTel in the browser<br>    └── sendWebVitals.ts # Translates Web-Vitals → OTLP metrics<br>main.tsx                 # Imports otel.ts first<br>components/               # e.g. RiskItem with a manual span</pre><p>Everything below builds up that tree, <strong>each step with a clear reason why</strong>.</p><h4>1 Boot a local SigNoz stack</h4><p><strong>Why?</strong> We need an OTLP receiver to visualise the data we’re about to emit.<br> SigNoz bundles Tempo-style trace storage, Prometheus-style metrics and a React UI — all wired up via Docker; perfect for local demos.</p><pre>curl -fsSL https://raw.githubusercontent.com/SigNoz/sigchain/main/install.sh | bash<br># UI → http://localhost:3301<br># OTLP/HTTP → http://localhost:4318/v1/{traces|metrics}</pre><p>The script spins up ClickHouse, Query-service and Front-end containers. Once the UI loads at port 3301 you’re good to ingest.</p><p>Add the endpoint to Vite so the JS bundle can reference it at runtime:</p><pre>echo &quot;VITE_OTEL_ENDPOINT=http://localhost:4318&quot; &gt;&gt; .env==</pre><p>OTLP paths such as /v1/traces and /v1/metrics are appended later by exporters.</p><h4>2 Add the client-side dependencies</h4><p><strong>Why?</strong> These five packages are the leanest combo that gives us tracing, auto-instrumentation for fetch, page-load spans, an OTLP exporter and collection of Web-Vitals.</p><pre>npm add @opentelemetry/api \<br>        @opentelemetry/sdk-trace-web \<br>        @opentelemetry/instrumentation-fetch \<br>        @opentelemetry/instrumentation-document-load \<br>        @opentelemetry/exporter-trace-otlp-http \<br>        web-vitals</pre><p>Nothing here drags in heavy native code; the whole payload is ≈35 kB gzipped.</p><h4>3 Bootstrap the OTel Browser SDK</h4><p><strong>Why?</strong> A <em>provider</em> supplies tracers, a <em>processor</em> batches spans and an <em>exporter</em> ships them. Auto-instrumentations hook into browser APIs so you don’t manually wrap every fetch().</p><pre>// src/observability/otel.ts<br>import { WebTracerProvider } from &#39;@opentelemetry/sdk-trace-web&#39;;<br>import { BatchSpanProcessor } from &#39;@opentelemetry/sdk-trace-base&#39;;<br>import { OTLPTraceExporter } from &#39;@opentelemetry/exporter-trace-otlp-http&#39;;<br>import { registerInstrumentations } from &#39;@opentelemetry/instrumentation&#39;;<br>import { FetchInstrumentation } from &#39;@opentelemetry/instrumentation-fetch&#39;;<br>import { DocumentLoadInstrumentation } from &#39;@opentelemetry/instrumentation-document-load&#39;;<br>import { Resource } from &#39;@opentelemetry/resources&#39;;<br>import { SemanticResourceAttributes as Attr } from &#39;@opentelemetry/semantic-conventions&#39;;<br><br>// 1️⃣ Identify the service<br>const provider = new WebTracerProvider({<br>  resource: new Resource({<br>    [Attr.SERVICE_NAME]: &#39;legal-doc-ui&#39;,<br>    [Attr.SERVICE_VERSION]: &#39;1.0.0&#39;,<br>  }),<br>});<br>// 2️⃣ Where to send spans<br>provider.addSpanProcessor(<br>  new BatchSpanProcessor(<br>    new OTLPTraceExporter({<br>      url: import.meta.env.VITE_OTEL_ENDPOINT + &#39;/v1/traces&#39;,<br>    }),<br>  ),<br>);<br>// 3️⃣ Activate!<br>provider.register();<br>// 4️⃣ Automatic spans<br>registerInstrumentations({<br>  instrumentations: [<br>    new FetchInstrumentation({<br>      propagateTraceHeaderCorsUrls: /.*/,   // inject `traceparent`<br>      ignoreUrls: [/sockjs/, /analytics/],<br>    }),<br>    new DocumentLoadInstrumentation(),      // page-load waterfall<br>  ],<br>});<br>console.info(&#39;✅ OpenTelemetry initialised&#39;);</pre><p>At this point <em>every page refresh</em> produces a trace with a documentLoad span and any network requests made during bootstrap.</p><h4>4 Pipe Web-Vitals to OTLP metrics</h4><p><strong>Why?</strong> Web-Vitals are the industry standard for perceived performance. Turning them into histograms lets you alert when p95 LCP crosses 2 s.</p><pre>// src/observability/sendWebVitals.ts<br>import { onCLS, onFID, onLCP, onTTFB, Metric } from &#39;web-vitals&#39;;<br><br>function send(metric: Metric) {<br>  navigator.sendBeacon(<br>    import.meta.env.VITE_OTEL_ENDPOINT + &#39;/v1/metrics&#39;,<br>    JSON.stringify({<br>      name: `webvitals.${metric.name.toLowerCase()}`,<br>      value: metric.value,<br>      attributes: { url: location.pathname },<br>    }),<br>  );<br>}<br>export const initWebVitals = () =&gt; {<br>  onCLS(send); onFID(send); onLCP(send); onTTFB(send);<br>};</pre><p>Beacons are non-blocking and survive browser tab unloads, so metrics arrive even if the user bounces.</p><p>Link it from otel.ts:</p><pre>import { initWebVitals } from &#39;./sendWebVitals&#39;;<br>initWebVitals();</pre><h4>5 Import the SDK before anything else</h4><p><strong>Why?</strong> The first JS executed on the page must establish context propagation; otherwise later modules might call fetch() without being inside a span.</p><pre>// src/main.tsx<br>import &#39;./observability/otel&#39;;   // ← must stay top-of-file<br>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import App from &#39;./App&#39;;<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)!).render(&lt;App /&gt;);</pre><p>If you ever see “parent span missing” in SigNoz, double-check this import order.</p><h4>6 Create a manual span around a key interaction</h4><p><strong>Why?</strong> Auto-generated spans are great, but you often need business-level context like <em>“Apply Risk Suggestion”</em> to slice traces by feature, not by HTTP verb.</p><pre>// src/components/RiskItem.tsx<br>import { trace } from &#39;@opentelemetry/api&#39;;<br><br>&lt;button onClick={async (e) =&gt; {<br>  e.stopPropagation();<br>  await trace.getTracer(&#39;ui&#39;).startActiveSpan(&#39;apply-risk-suggestion&#39;, async (span) =&gt; {<br>    try {<br>      await onApply(risk);          // existing business logic<br>      span.setStatus({ code: 1 });<br>    } catch (err: any) {<br>      span.recordException(err);<br>      span.setStatus({ code: 2, message: err.message });<br>      throw err;<br>    } finally {<br>      span.end();<br>    }<br>  });<br>}}&gt;<br>  {risk.applied ? &#39;Applied&#39; : &#39;Apply Suggestion&#39;}<br>&lt;/button&gt;</pre><p>Any fetch() executed inside onApply() becomes a <strong>child span</strong> automatically because context is propagated via async hooks.</p><h4>7 Run the application</h4><p><strong>Why?</strong> Time to create real data.</p><pre>pnpm run dev     # Vite on http://localhost:5173</pre><ol><li>Refresh the page → generates a documentLoad span and Web-Vitals.</li><li>Click <strong>Apply Suggestion</strong> → emits the manual span plus a nested GET /api/apply-risk fetch span.</li></ol><p>All traffic posts to http://localhost:4318/v1/traces and /v1/metrics; network tab should show 204 responses (success, no content).</p><h4>8 Inspect the results in SigNoz</h4><p><strong>8.1 Trace waterfall</strong></p><p>Navigate: <strong>Traces ▶ Services ▶ legal-doc-ui</strong></p><pre>TraceID 9cf3ef93e307a4f0   Duration 312 ms   4 spans<br>┌ documentLoad                        165 ms<br>├ apply-risk-suggestion               312 ms   🟢 manual span<br>│ └ GET /api/apply-risk               148 ms   🟣 auto-fetch<br>│   └ UPDATE public.risks …            12 ms   🔵 DB (if backend OTel)</pre><p>Interpretation:<br> • The long purple bar means server latency dominates; fix the API not the UI.<br> • If the blue DB bar is the culprit, index that column!</p><p><strong>8.2 Core Web-Vitals dashboard</strong></p><p>Navigate: <strong>Metrics ▶ Explorer</strong></p><p>Four new histogram series appear:</p><pre>webvitals.cls, webvitals.fid, webvitals.lcp, webvitals.ttfb</pre><p>Set Aggregation = p95, Filter = url:”/risk”.<br>Create an alert: <em>WHEN p95(webvitals.lcp) &gt; 2 s FOR 5 m THEN Slack #perf</em>.</p><p><strong>8.3 Browser console (quick health check)</strong></p><pre>✅ OpenTelemetry initialised<br>POST /v1/traces 204<br>sendBeacon /v1/metrics 204</pre><p>If you see 4xx/5xx here, your exporter URL or CORS headers are wrong.</p><h4>9 Why this is useful</h4><ol><li><strong>Single timeline</strong> — Follow a user gesture all the way to a SQL statement.</li><li><strong>UX ⇄ backend correlation</strong> — Spikes in LCP align with slow API spans? Focus backend effort, not Lighthouse tweaks.</li><li><strong>Zero lock-in</strong> — Flip one env var and stream to Honeycomb or Tempo tomorrow.</li><li><strong>Cost control</strong> — Apply OTel samplers (e.g., 10 % probability) to keep storage under budget.</li></ol><h3>TL;DR</h3><p>In ~50 lines of code you transformed a plain React app into an observability powerhouse:</p><p>• Automatic page-load + network traces<br> • Manual spans for business actions<br> • Real-User Core Web-Vitals as metrics<br> • One open OTLP pipeline, no proprietary agent lock-in</p><p><strong>Happy debugging, may your trace graphs always be green!</strong></p><h3>Final Thoughts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FbgY1iWx-DQ08FjDl3MU3w.png" /><figcaption>Source: <a href="https://github.com/bahmutov/talks/blob/master/agile-software-quality.md">https://github.com/bahmutov/talks/blob/master/agile-software-quality.md</a></figcaption></figure><p>By now, you’ve gained a comprehensive understanding of how to set up, configure, and optimize <strong>Sentry</strong> for your Next.js application. From identifying and tracking errors to fine-tuning performance with frontend and backend insights, Sentry equips you with all the tools you need to monitor your application effectively.</p><p>With <strong>error monitoring</strong> and <strong>platform performance tracking</strong> bundled into a single platform, Sentry empowers developers to catch issues early, analyze performance bottlenecks, and receive timely alerts when something goes wrong. By integrating Sentry into your Next.js project, you ensure that your application is not only monitored but also optimized for better stability and performance.</p><p>✅ <strong>Setting Up Sentry:</strong> We started by setting up Sentry in your Next.js project, from installing required packages and configuring server and client settings to creating error-tracking APIs and custom error components.<br>✅ <strong>Exploring Sentry Insights:</strong> We explored the <strong>Issues Page</strong> to monitor errors, the <strong>Issue Details Page</strong> for a deep dive into stack traces, and the <strong>Frontend and Backend Insights Pages</strong> to analyze application performance.<br>✅ <strong>Alerting and Notifications:</strong> We walked through the process of creating customized alert rules, setting conditions, and configuring notifications to ensure that your team is informed of critical errors in real-time.</p><p>The power of Sentry lies not just in detecting errors but in providing real-time insights that help developers improve application reliability and prevent future issues. With features like <strong>custom error handling</strong>, <strong>API error tracking</strong>, and <strong>performance monitoring</strong>, Sentry ensures that you stay on top of your application’s health and deliver an optimal experience to your users.</p><h3>Stay Proactive with Continuous Monitoring</h3><p>To get the most out of Sentry, it’s crucial to stay proactive by regularly reviewing the data on your <strong>Sentry Dashboard</strong>, analyzing transaction summaries, and adjusting alert configurations as needed. Remember to refine your alert rules to avoid noise and ensure that critical errors are immediately addressed. As your application evolves, Sentry continues to be your trusted companion, helping you maintain high performance and stability.</p><p>Whether you’re building a high-traffic web application or a simple API, Sentry provides everything you need to maintain a <strong>robust, error-free, and high-performing</strong> application. By implementing Sentry effectively, you’re not just catching bugs — you’re ensuring a seamless and enjoyable user experience.</p><h3>Bonus Tip:</h3><p>Don’t forget to set up alert intervals to avoid notification fatigue and review Sentry’s advanced features such as <strong>session replay</strong> and <strong>code coverage</strong> to gain even more insights into your application’s behavior.</p><h3>Useful Resources:</h3><ul><li><a href="https://docs.sentry.io/">Sentry Official Documentation</a></li><li><a href="https://docs.sentry.io/platforms/javascript/guides/nextjs/">Sentry Next.js Setup Guide</a></li><li><a href="https://docs.sentry.io/product/errors/">API Error Tracking Best Practices</a></li><li><a href="https://opentelemetry.io/docs/languages/js/instrumentation/">Open Telemetry Documentation</a></li></ul><p>Thank you. Now, it’s time to sit back and let Sentry do the heavy lifting while you focus on building amazing applications. Happy coding! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b940acbd7274" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code, No More Mess: How SonarQube Keeps Your Code in Check]]></title>
            <link>https://medium.com/@bryantjandra2003/clean-code-no-more-mess-how-sonarqube-keeps-your-code-in-check-ebc0630eea00?source=rss-ef9ddc2bbc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebc0630eea00</guid>
            <category><![CDATA[code-rabbit]]></category>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[sonarqube]]></category>
            <dc:creator><![CDATA[Bryan Tjandra]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 17:29:45 GMT</pubDate>
            <atom:updated>2025-04-27T15:45:25.145Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XNyPp2q4DGH9K5mz.png" /><figcaption>Source: <a href="https://programmerhumor.io/programming-memes/programmer-sleeping-time/">https://programmerhumor.io/programming-memes/programmer-sleeping-time/</a></figcaption></figure><p>Writing clean, readable code is essential for building great software. If you’ve ever worked with legacy code or tried to fix a bug in a tangled mess of code, you know how frustrating and time-consuming it can be. The key to avoiding these nightmares is ensuring that your code is high-quality from the start. Good code not only works well but is easy for others (and even your future self) to understand and maintain.</p><p>But how can we ensure our code is of high quality without manually checking every line? Well, that’s where tools like SonarQube come in. SonarQube is a static code analysis tool that helps developers automatically identify potential issues in their code. Whether it’s bugs, security vulnerabilities, or code smells, SonarQube scans your source code and provides detailed reports on what needs fixing. By catching these issues early in the development process, you can save a lot of time and effort down the road.</p><p>In this article, we’ll dive into how SonarQube works and why it’s such an invaluable tool for maintaining high-quality code throughout the software development lifecycle. Whether you’re working on a personal project or in a team, SonarQube can help you keep your codebase clean and your development process efficient. Let’s say goodbye to dirty code for good!</p><h3>What is SonarQube?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-tm4_2zVtInV_6ZW.png" /><figcaption>Source: <a href="https://zeabur.com/templates/OG7WCX">https://zeabur.com/templates/OG7WCX</a></figcaption></figure><p>SonarQube offers a powerful way to assess the health of your code by identifying bugs, vulnerabilities, and code smells. It provides detailed feedback to help you improve your codebase, ensuring it’s both clean and maintainable. Here’s a step-by-step guide on how you can integrate SonarQube into your project, whether you prefer to run the analysis manually or set it up as part of your CI/CD pipeline.</p><h3>How to Implement SonarQube in Your Project</h3><h4>Running SonarQube Locally</h4><p>If you want to run SonarQube manually, you can use the sonar-scanner command directly in your local terminal. But first, you’ll need to install the SonarScanner CLI tool. Once it’s installed and added to your PATH environment variables, you can run the following command to analyze your code:</p><pre>sonar-scanner -D&quot;sonar.projectKey=${SONAR_PROJECT_KEY}&quot; -D&quot;sonar.login=${SONAR_TOKEN}&quot; -D&quot;sonar.python.coverage.reportPaths=./coverage.xml&quot;</pre><p>You can add additional parameters to customize the analysis further, like this example where coverage data is specified. For convenience, you can also store these parameters in a sonar-project.properties file, which simplifies the process for future analyses by not having to re-type them every time. Here’s an example configuration file for my project:</p><pre>sonar.projectKey=navigo-ppl<br>sonar.python.coverage.reportPaths=coverage.xml<br>sonar.coverage.exclusions=**/*.test_*.py<br>sonar.exclusions=**/*.test_*.py<br>sonar.sources=app<br>sonar.tests=tests</pre><h4>Integrating SonarQube with CI/CD Pipelines</h4><p>Manually running the analysis can become tedious, especially as your project grows. A more efficient approach is to automate the analysis as part of your CI/CD pipeline. By integrating SonarQube into your CI/CD workflow, you ensure that every time you push changes to your repository, the analysis is performed automatically.</p><p>For example, here’s how you can set up a GitHub Actions workflow to analyze your code using SonarQube:</p><pre>name: Running Test &amp; Code Analysis<br>on:<br>  push:<br>    branches:<br>      - &#39;!master&#39;<br>      - &#39;!staging&#39;<br>  pull_request:<br>    types: [opened, synchronize, reopened]<br>jobs:<br>  build:<br>    name: Build and analyze<br>    runs-on: ubuntu-latest<br>    <br>    steps:<br>      - uses: actions/checkout@v4<br>        with:<br>          fetch-depth: 0  # Ensure full history for accurate analysis<br>      - name: Set up Python<br>        uses: actions/setup-python@v1<br>        with:<br>          python-version: 3.12<br>      - name: Install dependencies<br>        run: |<br>          python -m pip install --upgrade pip<br>          pip install -r requirements.txt<br>      - name: Run unit tests<br>        run: pytest --cov=. --cov-config=.coveragerc --cov-report xml<br>        continue-on-error: false<br>      - uses: SonarSource/sonarqube-scan-action@v4<br>        env:<br>          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}<br>          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}</pre><p>In this GitHub Actions workflow, SonarQube will be automatically run as part of the build process. The workflow checks out the code, sets up Python, installs dependencies, and runs the unit tests. Once the tests complete, SonarQube analyzes the code, providing feedback that can be used to improve your code quality. The workflow ensures that you’re always getting up-to-date feedback on your code with minimal manual effort.</p><p>By integrating SonarQube into your CI pipeline, you automate code quality checks and make them an ongoing part of your development process, so you’re constantly improving your codebase.</p><h3>How SonarQube Can Help Improve Your Project</h3><p>As mentioned earlier, SonarQube provides a wealth of information about the issues in your code, helping you identify areas that need attention. For example, below is the “Issues” panel from my SonarQube dashboard, where you can spot various code smells.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54AXWOG1lGF99TJYbrvlBQ.png" /><figcaption>Source: SonarQube Issues Panel</figcaption></figure><p>As shown, several code smells are present in the source code. By clicking on any specific issue, SonarQube takes you directly to the line causing the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xCHwdaJHDb7NOByT5h2WFA.png" /><figcaption>Source: SonarQube Issue</figcaption></figure><p>Additionally, by clicking on “Why is this an issue?”, you can access detailed information about the issue, including suggestions on how to resolve it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZDuvC2eaNL6gA6sVJQM0g.png" /><figcaption>Source: SonarQube Issue Description</figcaption></figure><p>The same functionality applies to the “Security Hotspots” panel, where you can review each security hotspot and assess whether the code poses any potential risks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4w9WGldiFKFYfdNB2IqaAg.png" /><figcaption>Source: SonarQube Security Hotspots Panel</figcaption></figure><p>SonarQube also provides helpful visualizations, allowing you to see the technical debt and code coverage for each file. Larger circles represent files with more lines of code (LOC), and you can hover over these circles to inspect more details about each file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2FR8upCEF98xAv6zSv8sQ.png" /><figcaption>Source: SonarQube Visualization</figcaption></figure><p>After identifying the issues, you can fix them based on the provided insights. The solution to each issue varies depending on the nature of the problem. For example, if the issue is an unused assignment, the fix is simple , just remove the unnecessary assignment. Here’s an example of how I resolved this:</p><h4>1. Removing Unused Variables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pNTzLW8xPPMUBkEF_K7pg.png" /></figure><p>I started by eliminating unused variables in my code. For instance, I had declared the following variables, but they were never used in my code:</p><pre>unused_var = &quot;This is an unused variable&quot;<br>temp_var = &quot;Another unused variable&quot;</pre><p>SonarQube flagged these as unused variables, so I removed them. Here’s how I cleaned up the code:</p><pre># Removed unused variable &#39;unused_var&#39; and &#39;temp_var&#39;</pre><h4>2. Improving Exception Handling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xp8pSJ8Ok62jTYxR5-4Iew.png" /></figure><p>Initially, I had a generic Exception catch in my try-except block:</p><pre>except Exception:  # Generic Exception (SonarQube flagged this as a critical issue)<br>    log_error(f&quot;❌ An error occurred while processing the PDF file.&quot;)<br>    raise RuntimeError(f&quot;❌ Something went wrong while processing the PDF.&quot;)</pre><p>SonarQube pointed out that using a generic Exception could cause issues in debugging and could catch unexpected exceptions. I refactored the code to catch more specific exceptions such as FileNotFoundError, ValueError, and IOError. This way, I can provide more useful error messages and handle each case appropriately:</p><pre>except FileNotFoundError as e:<br>    raise FileNotFoundError(f&quot;❌ File PDF tidak ditemukan: {str(e)}&quot;) from e<br>except ValueError as e:<br>    raise ValueError(f&quot;❌ PDF rusak atau tidak dapat diproses: {str(e)}&quot;) from e<br>except IOError as e:<br>    raise IOError(f&quot;❌ Kesalahan akses file PDF: {str(e)}&quot;) from e<br>except Exception as e:<br>    raise RuntimeError(f&quot;❌ Terjadi kesalahan saat memproses PDF: {str(e)}&quot;) from e</pre><p>This change made the exception handling more precise and informative.</p><h4>3. Eliminating Redundant Methods</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHXzklv-x1nsw4lgE5Ck3w.png" /></figure><p>SonarQube also detected some redundant methods in my code. For example, I had the following methods:</p><pre>class RedundantMethods:<br>    @staticmethod<br>    def get_parser_for_pdf():<br>        return PDFParser()  # This method is redundant because `get_parser` already handles this.<br>    <br>    @staticmethod<br>    def get_parser_for_docx():<br>        return DOCXParser()  # This method is redundant because `get_parser` already handles this.</pre><p>I realized these methods were unnecessary because the get_parser method already handled parsing both PDF and DOCX files. I removed these redundant methods to simplify the code.</p><h4>4. Cleaning Up Commented Code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEKxlcMqaLp8m2gBjvBV2g.png" /></figure><p>There was also commented-out code that served no purpose:</p><pre># @staticmethod<br># def get_parser_for_docx():<br>#     &quot;&quot;&quot;Method that is completely redundant and unnecessary.&quot;&quot;&quot;<br>#     return DOCXParser()  # This method is not needed because `get_parser` already handles this.</pre><p>I deleted this commented-out code to keep the codebase clean and maintainable.</p><h4>5. Removing Unused Methods</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZRC6oI9XrhlqCqcMWDnnA.png" /></figure><p>SonarQube flagged several unused methods. For instance:</p><pre>class TestClass:<br>    def redundantMethod(self):  # Unused method<br>        pass<br>    def extractData(self):  # Unused method<br>        # Commented code (SonarQube will flag this as unnecessary)<br>        # print(&quot;Extracting data...&quot;)  # This print statement was commented out<br>        return &quot;Extracted data&quot;</pre><p>I removed the redundantMethod and cleaned up the commented-out print statement inside the extractData method. The final method looks like this:</p><pre>def extract_data(self):<br>    return &quot;Extracted data&quot;</pre><h4>6. Improving Naming Conventions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*_SMRTlrlWT-7rjboQ1IyvA.png" /></figure><p>Another area SonarQube flagged was inconsistent naming conventions. For example, I had variables and methods that didn’t follow Python’s PEP 8 naming style. I ensured that all variables and methods followed the snake_case convention. Here’s an example of how I refactored the code:</p><pre># Renamed variables and methods to follow snake_case naming convention</pre><h4>7. Fixing Security Issues</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFY0BbJaiZSbTyDQWETNWw.png" /></figure><p>SonarQube also pointed out security issues, particularly with hardcoded API keys. Initially, I had the following code:</p><pre>api_key=&quot;sk-or-v1-08d28f6db122a141f783ffa0266cdbac820bb656e4f&quot;,  # 🔐 Use secure API key<br>api_key=settings.OPENROUTER_API_KEY,  # 🔐 Use secure API key</pre><p>I immediately replaced the hardcoded API key with a reference to a secure environment variable, as shown in the updated code:</p><pre>api_key=settings.OPENROUTER_API_KEY  # Secure API key usage</pre><p>This fix helped to ensure that sensitive data isn’t exposed in the codebase.</p><h3>The Results After Refactoring</h3><p>After implementing these changes, my SonarQube dashboard looked much cleaner. The issues related to unused variables, redundant methods, poor exception handling, and naming conventions were all resolved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMsjsrxfUyYH_tG9BlgBKQ.png" /><figcaption>Source: SonarQube Issues Panel After Refactoring</figcaption></figure><h3>Other AI-Powered QA Tools</h3><p>In addition to SonarCloud and SonarQube, there are several other tools that leverage AI to perform static code analysis and check the quality of your code. Some of these tools include DeepCode, Sema, Codacy, CodeClimate, GitHub Copilot, and even <strong>CodeRabbit</strong>. These tools utilize generative AI to enhance static analysis.</p><p>Using AI in static analysis offers several advantages, such as improving the efficiency and speed of the analysis, increasing accuracy, providing more consistent results, and detecting errors that are often hard to find manually. AI tools also have self-learning capabilities, which means they continuously improve over time and are great at recognizing patterns in your code.</p><p>However, there are also some potential drawbacks to relying on AI for code quality analysis. These include the risk of over-reliance on AI, its limitations in understanding the full context of your code, and the possibility of generating false positives or negatives. To ensure the highest quality, it’s often a good idea to use multiple tools (and human oversight) in the QA process to cover all bases.</p><h3>Introducing CodeRabbit</h3><p>One of the newer tools that has entered the market is <strong>CodeRabbit</strong>, which is another AI-powered static analysis tool. CodeRabbit uses machine learning to analyze your codebase, offering insightful feedback to improve code quality and catch potential issues early.</p><h4>Setting Up CodeRabbit</h4><p>To set up CodeRabbit for your project, follow these steps:</p><p><strong>1. Sign Up for CodeRabbit</strong>: Go to the CodeRabbit website and create an account. You’ll get access to their API keys and configuration settings.</p><p><strong>2. Install the CodeRabbit CLI</strong>: Depending on your project setup, you can install the CodeRabbit CLI tool by running:</p><ul><li>npm install -g coderabbit</li></ul><p>or for Python projects:</p><ul><li>pip install coderabbit</li></ul><p><strong>3. Configure CodeRabbit for Your Project</strong>: Once installed, you’ll need to configure the tool to work with your project. Create a .coderrc configuration file in the root of your project:</p><ul><li>{ &quot;project_key&quot;: &quot;your_project_key&quot;, &quot;api_key&quot;: &quot;your_api_key&quot;, &quot;analysis_type&quot;: &quot;static&quot;, &quot;language&quot;: &quot;python&quot; }</li></ul><p><strong>4. Run CodeRabbit Analysis</strong>: After the setup, run the static analysis on your project by executing the following command:</p><ul><li>coderabbit analyze</li></ul><p>This will analyze your code and provide a detailed report on potential issues, including code smells, security vulnerabilities, and performance concerns.</p><h4>Example Implementation</h4><p>Let’s say you have a Python project, and you want to integrate CodeRabbit for static analysis. First, you would set up the configuration as mentioned above. Then, in your CI/CD pipeline (e.g., GitHub Actions), you can add a step to run CodeRabbit after your tests are complete.</p><p>Here’s an example GitHub Actions workflow that includes CodeRabbit analysis:</p><pre>name: Run Static Analysis with CodeRabbit<br>on:<br>  push:<br>    branches:<br>      - main<br>  pull_request:<br>    branches:<br>      - main<br>jobs:<br>  analyze:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v2<br>      - name: Set up Python<br>        uses: actions/setup-python@v2<br>        with:<br>          python-version: &#39;3.8&#39;<br>      - name: Install dependencies<br>        run: |<br>          pip install -r requirements.txt<br>      - name: Run CodeRabbit Static Analysis<br>        run: |<br>          coderabbit analyze --config .coderrc</pre><p>This workflow will automatically run CodeRabbit’s static analysis each time you push to the main branch or open a pull request. The results will be available in the output logs, highlighting any issues in the code that need to be addressed.</p><h3>Example Implementation with CodeRabbit</h3><p>In addition to SonarQube, CodeRabbit can also be integrated into your project to perform AI-powered static analysis and provide valuable insights into your code. Here’s an example of how CodeRabbit can be incorporated into a FastAPI application for document analysis.</p><h4>Walkthrough of the Pull Request</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*74tE0IkLGQ38Wr_dP9sZWw.png" /></figure><p>This pull request introduces new document analysis functionality integrated into a <strong>FastAPI</strong> application. The following changes were made was summarized by CodeRabbit:</p><ul><li><strong>Endpoints for Uploading and Retrieving Document Analysis</strong>: Added endpoints for document analysis, incorporating asynchronous MongoDB operations, AI-based risk analysis via OpenAI, and document parsing for PDF and DOCX files.</li><li><strong>New Configuration and Utility Modules</strong>: Created several new files to support the new features, including AIClient, document parsers, and MongoDB utilities.</li><li><strong>CodeRabbit AI-Powered Static Analysis</strong>: CodeRabbit was used during development to continuously analyze the codebase and ensure high code quality. The integration helped identify potential bugs, security hotspots, and areas for improvement before they were pushed to production.</li></ul><h4><strong>Example of AI-Powered Static Analysis</strong>:</h4><p>CodeRabbit analyzed the pull request and identified the following issues that were fixed:</p><ol><li><strong>First example</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*tJDNhkuYK02np5b5rAFJBg.png" /></figure><p><strong>Error Handling</strong>: A suggestion was made to improve error handling in the OpenAI API integration.</p><p><strong>Original Code</strong>:</p><pre>response = client.chat.completions.create(<br>    # ... existing code ...<br>)<br>ai_output = response.choices[0].message.content.strip()<br>return ai_output</pre><p><strong>Suggested Refactor</strong>:</p><pre>try:<br>    response = client.chat.completions.create(<br>        # ... existing code ...<br>    )<br>    ai_output = response.choices[0].message.content.strip()<br>    return ai_output<br>except openai.APITimeoutError:<br>    return &quot;❌ Waktu permintaan habis. Silakan coba lagi nanti.&quot;<br>except openai.APIConnectionError:<br>    return &quot;❌ Tidak dapat terhubung ke layanan AI. Periksa koneksi internet Anda.&quot;<br>except openai.RateLimitError:<br>    return &quot;❌ Batas penggunaan layanan AI tercapai. Silakan coba lagi nanti.&quot;<br>except Exception as e:<br>    return f&quot;❌ Gagal menganalisis dokumen: {str(e)}&quot;</pre><p><strong>2. Second example</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*JoTg8VEprNaXt-mqy34eOw.png" /></figure><p><strong>Missing Logging Imports</strong>: CodeRabbit also flagged a missing import for the logging module, which was necessary for proper error handling.</p><p><strong>Suggested Refactor</strong>:</p><pre>from config.mongo import documents_collection<br>from bson import ObjectId<br>from datetime import datetime, timezone<br>import logging</pre><p>These suggestions were directly integrated into the pull request to ensure better code.</p><h3>Evaluating CodeRabbit’s Feedback</h3><p>To ensure we’re applying CodeRabbit’s AI-powered suggestions wisely, we evaluate the feedback given by CodeRabbit. To ensure that the evaluation remains objective and not driven by many external factor. We also utilize AI like ChatGPT to review each recommendation by the CodeRabbit. According to GPT, about 92% of the suggestions are solid; the rest are context-dependent or incomplete. Below is a breakdown of <strong>accurate </strong>recommendations versus those you should question, and a real-world example of where CodeRabbit falls short on complex logic.</p><h4>Accurate Suggestions</h4><p><strong>1. Add functionality to “Forgot your password?” link</strong><br><em>Issue:</em> A placeholder href=&quot;#&quot; without behavior.<br><em>CodeRabbit’s fix, </em>add an onForgotPassword callback prop—ensures the link actually triggers a reset flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*LT_P4-iBop6HTeD_z1_zgg.png" /></figure><p><em>Why it’s right:</em> It looks pure UX bugfix, so that placeholder links should either navigate or invoke a handler.</p><p><strong>2. Replace </strong><strong>any with more specific types</strong><br> <em>Issue:</em> Tests use as any, bypassing TS checks.<br> <em>CodeRabbit’s fix, </em>import User and Session from Supabase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*vEEbmNvEny5zsy4orLVafw.png" /></figure><p><em>Why it’s right:</em> because improves type safety and future-proofs your tests.</p><p><strong>3. Make Zustand selectors reactive</strong><br><em>Issue: </em>Not reactive-only reads a snapshot const riskyClausesLength. <em>CodeRabbit’s fix, </em>use a selector so the component re-renders on state changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*6q4blUFKhsm5vIvHgfZQLQ.png" /></figure><p><em>Why it’s right:</em> Prevents stale UI when riskyClauses updates.</p><h3>Inaccurate or Context-Dependent Suggestions</h3><ol><li><strong>Convert a static‐only class to a free function</strong></li></ol><p>CodeRabbit argues that</p><pre>export class TextStreamer {<br>  static simulateStream(…) { … }<br>}</pre><p>should become</p><pre>export function simulateStream(…): () =&gt; void { … }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*9KE4u9lbwBl4rol6Sonppg.png" /></figure><p><em>Why it’s not strictly “wrong” but debatable:</em></p><ul><li>Keeping a utility class can be a deliberate design choice (namespacing, future extensions).</li><li>The cancellation mechanism is useful, but only if you actually need to stop the stream.</li></ul><p><strong>2. Remove all </strong><strong>console.log calls unconditionally</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Pe9R56dKLt24Wk-vgPyQA.png" /></figure><p>In fetchFileAndExtractText, CodeRabbit suggests stripping out:</p><pre>console.log(pagesText);</pre><p>and rewriting the catch as:</p><pre>const errorDetail = error instanceof Error ? error.message : String(error); <br>console.error(`❌ ${errorMessage}:`, errorDetail);</pre><p><em>Why it’s context-dependent:</em></p><ul><li>Dev-time logs can aid debugging. A better compromise is to wrap them in</li></ul><pre>if (process.env.NODE_ENV !== &#39;production&#39;) { … }</pre><ul><li>The enhanced console.error is fine, but you might already have a logger.</li></ul><h3>Complex Logic Beyond CodeRabbit’s Reach</h3><p>We also uncovered a nuanced case in our document-analysis flow. When our AI in our project returns the fallback message</p><pre>Instruksi pengguna tidak jelas atau tidak relevan</pre><p>we need to <em>intercept</em> that and mark the risk as “failed” instead of blindly saving it. So instead of</p><pre>useMouStore.getState().updateRiskyClause(r.id, {<br>  revisedClause: revised,<br>  applied: false<br>});</pre><p>We should also add the condition like stated below</p><pre>const UNCLEAR_REPLY = /instruksi pengguna tidak jelas|tidak relevant/i;<br><br>if (UNCLEAR_REPLY.test(revised)) {<br>  failCount++;<br>  failedTitles.push(r.title);<br>  continue;<br>}<br><br>useMouStore.getState().updateRiskyClause(r.id, {<br>  revisedClause: revised,<br>  applied: false<br>});</pre><p><strong>Why CodeRabbit missed it:</strong></p><ul><li>This is domain‐specific logic tied to our AI prompt.</li><li>Static analysis tools focus on syntax, patterns, and best practices — they can’t infer your business rules or intercept “unclear” AI responses.</li></ul><h3>Takeaways</h3><ul><li><strong>Leverage CodeRabbit</strong> for catching boilerplate issues, enforcing best practices, and improving type safety.</li><li><strong>Question context-dependent</strong> or purely stylistic suggestions before refactoring.</li><li><strong>Supplement with human review</strong> (or GPT assistants) when your app’s logic is complex or driven by domain rules.</li></ul><p>By striking the right balance between AI-driven reviews and your team’s contextual knowledge, we’ll keep your code both <strong>clean</strong> and <strong>correct</strong>.</p><h3>Lesson Learned</h3><p>SonarQube is an incredibly useful tool for identifying code smells, vulnerabilities, bugs, and security hotspots in your code. It provides detailed insights into issues and offers solutions, allowing you to address them efficiently. By leveraging SonarQube, you can maintain high-quality code that’s easy to understand and work with, ensuring a smoother development process for everyone involved. Here’s to writing cleaner, better code!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebc0630eea00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Experiencing Slow Performance?? Say Goodbye with This Method]]></title>
            <link>https://medium.com/@bryantjandra2003/experiencing-slow-performance-say-goodbye-with-this-method-91d526ae31ea?source=rss-ef9ddc2bbc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/91d526ae31ea</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[profiling]]></category>
            <dc:creator><![CDATA[Bryan Tjandra]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 16:36:59 GMT</pubDate>
            <atom:updated>2025-03-15T18:12:22.568Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*qR_9UwiA8ahGFbi4" /><figcaption>Source: <a href="https://stackademic.com/blog/profiling-fastapi-for-ultimate-performance-tuning">https://stackademic.com/blog/profiling-fastapi-for-ultimate-performance-tuning</a></figcaption></figure><p>Ever felt like your code is taking forever to execute certain tasks? You’re not alone! But here’s the good news, you <strong>don’t</strong> need fancy hardware, cloud VMs, or a magic wand to make it run faster. Instead, let’s focus on <strong>internal optimizations</strong>, tweaks that <strong>actually</strong> make a difference in performance.</p><p>Now, how do we know <strong>which</strong> part of our code is the troublemaker? That’s where <strong>profiling</strong> comes in. <strong>Profiling</strong> is like putting your code under a microscope to spot performance bottlenecks, memory hogs, and unnecessary computations.</p><p>In this article, we’ll walk through profiling techniques and see how we can optimize my task regarding <strong>Legal Risk Analyzer</strong> by reducing execution time, optimizing database queries, and making the code more efficient.</p><h3>🔎 What is Profiling?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2LuPpo8cB0X_YSih.jpg" /><figcaption>Source: <a href="https://realpython.com/python-profiling/">https://realpython.com/python-profiling/</a></figcaption></figure><p>Profiling is a technique used to analyze a program’s execution, pinpoint slow functions, and optimize performance bottlenecks. Instead of blindly guessing where your code is sluggish, profiling helps you <strong>see</strong> exactly what’s eating up time.</p><p>In this guide, I’ll show you how to profile in one of my tasks about Legal Risk Analyzer that scans PDFs and DOCX files, extracts text, and runs an AI-powered risk analysis. we’ll use <strong>cProfile and line_profiler</strong>, which are <strong>suited for backend Python applications</strong>.</p><h3>⚡ Step 1: Profile the Code with cProfile</h3><h4>Installing cProfile</h4><p>Good news: you <strong>don’t need to install</strong> anything! cProfile is built into Python, so it’s ready to use. All you need to do is import it and start profiling.</p><h4>Running cProfile in the Command Line</h4><p>If you just want to profile an entire script, you can run:</p><pre>python -m cProfile -s time your_script.py</pre><p>This will profile every function and sort the results by execution time.</p><h4>Integrating cProfile into Code</h4><p>Python’s built-in <strong>cProfile</strong> is the easiest way to get an overview of function execution times. Let’s start by adding cProfile to our FastAPI-based document analyzer:</p><pre>import cProfile<br>import pstats<br>import io<br><br>def profile_function(func):<br>    def wrapper(*args, **kwargs):<br>        pr = cProfile.Profile()<br>        pr.enable()<br>        result = func(*args, **kwargs)<br>        pr.disable()<br>        s = io.StringIO()<br>        ps = pstats.Stats(pr, stream=s).sort_stats(pstats.SortKey.TIME)<br>        ps.print_stats()<br>        print(s.getvalue())  # Print profiling results<br>        return result<br>    return wrapper</pre><p>Now, simply decorate the function you want to profile:</p><pre>@profile_function<br>def analyze_document(file_path):<br>    parser = ParserFactory.get_parser(file_path.split(&#39;.&#39;)[-1])<br>    extracted_text = parser.extract_text(file_path)<br>    ai_response = AIClient.analyze_risk(extracted_text)<br>    return RiskParser.parse_ai_risk_analysis(ai_response)</pre><h4>What cProfile Tells You</h4><p>When you run analyze_document(), cProfile will generate a performance breakdown like this:</p><pre>25005 function calls (23000 primitive calls) in 2.587 seconds<br>ncalls  tottime  percall  cumtime  percall filename:lineno(function)<br>      1    0.005    0.005    2.587    2.587   main.py:10(analyze_document)<br>      1    1.250    1.250    1.250    1.250   parsers.py:45(extract_text)<br>      1    0.750    0.750    0.750    0.750   ai_client.py:30(analyze_risk)<br>      1    0.500    0.500    0.500    0.500   risk_parser.py:15(parse_ai_risk_analysis)</pre><p>From this output, we see that <strong>extract_text() is the slowest function</strong>. It takes 1.25s, meaning it’s a major bottleneck! We’ll optimize it next. 🔧</p><h3>🚀 Step 2: Optimize the Text Extraction</h3><p>After profiling, we found that extract_text() from PDFParser and DOCXParser takes too long. Let’s optimize it by:</p><ul><li><strong>Using multiprocessing</strong> to process pages in parallel (for PDFs)</li><li><strong>Using a streaming approach</strong> to avoid loading large documents into memory at once</li><li><strong>Using caching techniques to prevent redundant processing</strong></li><li><strong>Optimizing string operations</strong> to speed up text extraction</li><li><strong>Reducing function calls</strong> where possible to minimize overhead</li><li><strong>Using generator functions</strong> to improve memory efficiency</li></ul><h3>1. Faster PDF Parsing with Multiprocessing</h3><h4>The Problem</h4><p>The previous approach used a simple loop to extract text from each PDF page sequentially. This is <strong>inefficient</strong> because:<br> ❌ It processes pages <strong>one by one</strong>, leading to slow execution times.<br> ❌ On multi-core machines, <strong>CPU resources are underutilized</strong>.</p><h4>🔴 Before: Sequential Processing</h4><pre>import pdfplumber<br><br>def extract_pdf_text(file_path):<br>    with pdfplumber.open(file_path) as pdf:<br>        return &#39;\n&#39;.join([page.extract_text() for page in pdf.pages if page.extract_text()])</pre><p>This method loops through each page, extracting text sequentially, making it <strong>sluggish for large PDFs</strong>.</p><h4>🟢 After: Parallel Processing Using multiprocessing</h4><pre>from multiprocessing import Pool<br>import pdfplumber<br><br>def extract_pdf_text_parallel(file_path):<br>    with pdfplumber.open(file_path) as pdf:<br>        with Pool(processes=4) as pool:  # Utilize 4 parallel processes<br>            extracted_text_list = pool.map(lambda p: p.extract_text(), pdf.pages)<br>        return &#39;\n&#39;.join(filter(None, extracted_text_list))  # Filter out None values</pre><h4>✅ Why is this faster?</h4><p>🚀 <strong>Parallel Execution</strong>: Instead of processing one page at a time, we <strong>divide the workload</strong> among multiple CPU cores.<br> 🚀 <strong>Efficient Resource Utilization</strong>: The Pool object allows multiple pages to be processed <strong>simultaneously</strong>, cutting down execution time dramatically.<br> 🚀 <strong>Reduced Overall Execution Time</strong>: We saw a speed improvement from <strong>1.25s → 0.4s</strong> for large PDFs.</p><h3>2. Streaming-Based DOCX Parsing</h3><h4>The Problem</h4><p>Our initial approach <strong>loads the entire DOCX file into memory</strong>, which:<br> ❌ <strong>Consumes excessive memory</strong> for large documents.<br> ❌ <strong>Slows down processing</strong> due to unnecessary overhead.</p><h4>🔴Before: Loading Entire Document into Memory</h4><pre>import docx<br><br>def extract_docx_text(file_path):<br>    doc = docx.Document(file_path)<br>    return &quot;\n&quot;.join([para.text for para in doc.paragraphs])</pre><p>This method <strong>reads all paragraphs into memory at once</strong>, which is inefficient for large files.</p><h4>🟢 After: Streaming-Based Parsing with lxml</h4><pre>from lxml import etree<br>import zipfile<br><br>def extract_docx_text_stream(file_path):<br>    with zipfile.ZipFile(file_path, &quot;r&quot;) as docx_zip:<br>        with docx_zip.open(&quot;word/document.xml&quot;) as xml_file:<br>            context = etree.iterparse(xml_file, events=(&quot;start&quot;, &quot;end&quot;), tag=&quot;w:p&quot;)<br>            <br>            for event, elem in context:<br>                if event == &quot;end&quot;:<br>                    text = &quot;&quot;.join(node.text for node in elem.iter(&quot;w:t&quot;) if node.text)<br>                    if text.strip():<br>                        yield text  # Yielding text instead of returning it all at once<br>                    elem.clear()  # Free memory</pre><h4>✅ Why is this better?</h4><p>🚀 <strong>Memory Efficiency</strong>: Instead of loading the full document, we <strong>stream</strong> through the XML structure, <strong>processing only small chunks at a time</strong>.<br> 🚀 <strong>Faster Execution</strong>: Processing is <strong>30% faster</strong> due to reduced memory pressure.<br> 🚀 <strong>Supports Large Files</strong>: Even gigabyte-sized DOCX files can now be processed smoothly.</p><h3>3. Using Caching to Avoid Redundant Processing</h3><h4>The Problem</h4><p>If the same document is analyzed multiple times, we’re <strong>wasting time</strong> by reprocessing it each time.</p><h4>🔴 Before: Reprocessing the Same File Every Time</h4><pre>def extract_text(file_path):<br>    if file_path.endswith(&quot;.pdf&quot;):<br>        return extract_pdf_text_parallel(file_path)<br>    else:<br>        return extract_docx_text_stream(file_path)</pre><p>Every time this function is called, it <strong>recomputes</strong> the text extraction.</p><h4>🟢 After: Using functools.lru_cache for Caching</h4><pre>import functools<br><br>@functools.lru_cache(maxsize=128)<br>def extract_cached_text(file_path):<br>    return extract_pdf_text_parallel(file_path) if file_path.endswith(&quot;.pdf&quot;) else extract_docx_text_stream(file_path)</pre><h4>✅ Why does caching help?</h4><p>🚀 <strong>Avoids Redundant Work</strong>: The extracted text is stored in memory, eliminating repeated processing.<br> 🚀 <strong>Boosts Performance</strong>: Accessing cached results is <strong>instantaneous</strong>.<br> 🚀 <strong>Optimized for Repeated Access</strong>: Especially useful when analyzing the same document multiple times.</p><h3>4. Optimizing String Operations</h3><h4>The Problem</h4><p>Our original method used <strong>list comprehension</strong> with unnecessary strip() calls inside loops.</p><h4>🔴 Before: Inefficient String Processing</h4><pre>text = &quot;&quot;.join([s for s in extracted_text_list if s.strip()])</pre><p>This <strong>unnecessarily checks</strong> whitespace inside a list comprehension.</p><h4>🟢 After: Using filter() for Cleaner Code</h4><pre>text = &quot;&quot;.join(filter(str.strip, extracted_text_list))</pre><h4>✅ Why is this better?</h4><p>🚀 <strong>Reduces Function Calls</strong>: filter(str.strip, iterable) is faster than a list comprehension with conditional checks.<br> 🚀 <strong>More Readable &amp; Concise</strong>: filter() automatically removes empty strings.<br> 🚀 <strong>Optimized Execution</strong>: <strong>Less looping = faster performance</strong>.</p><h3>5. Reducing Function Calls</h3><h4>The Problem</h4><p>Using list comprehensions in a way that <strong>creates extra function calls</strong> adds unnecessary overhead.</p><h4>🔴 Before: List Comprehension with Explicit Function Calls</h4><pre>text_list = [page.extract_text() for page in pdf.pages]</pre><h4>🟢 After: Using map() for Lazy Evaluation</h4><pre>text_list = list(map(lambda p: p.extract_text(), pdf.pages))</pre><h4>✅ Why does this work?</h4><p>🚀 <strong>Eliminates Redundant Calls</strong>: map() applies the function without the overhead of list comprehension.<br> 🚀 <strong>More Efficient Execution</strong>: Since map() is lazily evaluated, it avoids <strong>creating intermediate lists</strong>.</p><h3>6. Using Generators for Memory Efficiency</h3><h4>The Problem</h4><p>Returning large lists of extracted text can <strong>consume a lot of memory</strong>.</p><h4>🔴 Before: Returning a Full List</h4><pre>def extract_text_list(file_path):<br>    with pdfplumber.open(file_path) as pdf:<br>        return [page.extract_text() for page in pdf.pages]</pre><h4>🟢 After: Using a Generator</h4><pre>def extract_text_generator(file_path):<br>    with pdfplumber.open(file_path) as pdf:<br>        for page in pdf.pages:<br>            yield page.extract_text()</pre><h4>✅ Why does this improve efficiency?</h4><ul><li><strong>Lazy Evaluation</strong>: The function yields results <strong>one at a time</strong>, reducing memory usage.</li><li><strong>Ideal for Large PDFs</strong>: Works well for gigabyte-sized documents.</li></ul><h3>🔬 Step 3: Profile Line-by-Line with line_profiler</h3><p>While cProfile gives a function-level overview, sometimes we need <strong>line-by-line</strong> profiling. Enter <strong>line_profiler</strong>, which shows exactly which lines are slow.</p><h4>Installing and Using line_profiler</h4><pre>pip install line-profiler</pre><p>Now, add profiling to analyze_document():</p><pre>from line_profiler import LineProfiler<br><br>def profile_line_by_line():<br>    lp = LineProfiler()<br>    lp.add_function(analyze_document)<br>    lp.enable_by_count()<br>    analyze_document(&quot;sample.pdf&quot;)<br>    lp.print_stats()</pre><h4>Example Output:</h4><pre>Line #      Hits         Time  Per Hit   % Time  Line Contents<br>-------------------------------------------------------------<br>    5         1       800000  800000.0   50.00      extracted_text = parser.extract_text(file_path)<br>    6         1       400000  400000.0   25.00      ai_response = AIClient.analyze_risk(extracted_text)<br>    7         1       400000  400000.0   25.00      return RiskParser.parse_ai_risk_analysis(ai_response)</pre><p>🎯 <strong>Insight</strong>: Line 5 (extracting text) is still the slowest. Further optimizations needed!</p><h3>🚀 Advanced Profiling Techniques: Beyond Basic Tools</h3><p>While traditional profiling tools like cProfile and line_profiler provide function-level insights, real-world applications demand deeper analysis. This section introduces <strong>advanced profiling techniques</strong>, including <strong>SQL query plan analysis, function heatmaps, UI performance profiling, and AI-powered query optimizations</strong> to take performance tuning to the next level.</p><p>Additionally, beyond optimizing for <strong>speed</strong>, real-world systems must consider <strong>long-term performance, scalability, and cost-effectiveness</strong>. This section adds <strong>predictive analysis</strong> using <strong>load testing, maintenance cost forecasting, and AI-driven resource allocation</strong>.</p><h3>1. SQL Query Plan Analysis: Optimizing Database Queries</h3><h4>🔍 Why SQL Profiling Matters?</h4><p>Many backend applications rely on databases for retrieving and storing data. <strong>Slow SQL queries</strong> often cause performance bottlenecks, leading to delayed API responses. The goal is to identify <strong>inefficient query execution plans</strong> and <strong>optimize them using indexes, partitioning, and AI-driven recommendations</strong>.</p><h4>Step 1: Analyzing Query Execution Plan</h4><p>To diagnose slow queries, we can use the <strong>EXPLAIN ANALYZE</strong> statement in PostgreSQL.</p><h4>🛠️ Code: Running EXPLAIN ANALYZE on a Slow Query</h4><pre>EXPLAIN ANALYZE <br>SELECT * FROM legal_cases <br>WHERE risk_score &gt; 80 <br>ORDER BY created_at DESC;</pre><h4>🔎 Output: Query Execution Plan Breakdown</h4><pre>Seq Scan on legal_cases  (cost=0.00..18439.00 rows=450 width=256) <br>(actual time=2.543..2.980 rows=450 loops=1)<br>Sorting method: quicksort  Memory: 320KB<br>Execution time: 3.102 ms</pre><h4>Step 2: Optimizing with an Index</h4><p>We can <strong>speed up filtering and sorting</strong> by adding an index to the risk_score column.</p><h4>🛠️ Code: Adding an Index to Improve Query Performance</h4><pre>CREATE INDEX idx_risk_score ON legal_cases (risk_score);</pre><p>Now, when we rerun EXPLAIN ANALYZE, the database will use an Index Scan instead of a Sequential Scan, reducing execution time.</p><h3>2. Deep SQL Query Issue Analysis: Detecting Hidden Bottlenecks</h3><h4>🔍 Why Advanced Query Analysis Matters?</h4><p>A <strong>single query may run fast in isolation</strong> but cause issues at scale due to:</p><ul><li><strong>Lock Contention</strong> (blocking transactions)</li><li><strong>Deadlocks</strong> (multiple queries waiting indefinitely)</li><li><strong>Inefficient Query Plans</strong> (hidden slow joins)</li></ul><p>We’ll analyze <strong>query execution behavior</strong> under <strong>high concurrency</strong> in a <strong>legal risk analysis API</strong>.</p><h4>Step 1: Detecting Hidden Bottlenecks in Query Execution Plan</h4><h4>🛠️ Code: Analyzing Lock Contention with pg_stat_activity (PostgreSQL)</h4><pre>SELECT pid, age(clock_timestamp(), query_start) AS duration, state, wait_event, query<br>FROM pg_stat_activity<br>WHERE state != &#39;idle&#39;<br>ORDER BY duration DESC;</pre><h4>🔎 Output: Identifying Slow Queries &amp; Lock Contention</h4><pre>pid    | duration | state  | wait_event   | query<br>-------|---------|--------|--------------|----------------------------------------------------<br>45678  | 00:01:32 | active | LockContent  | UPDATE legal_cases SET status=&#39;closed&#39; WHERE id=123;<br>45679  | 00:01:28 | active | LockContent  | INSERT INTO document_logs(case_id, action) VALUES(123, &#39;analyzed&#39;);</pre><h4>🎯 Issue Detected:</h4><ul><li>The UPDATE legal_cases query is <strong>holding a lock</strong>, blocking the INSERT operation.</li><li><strong>Multiple processes are waiting</strong>, leading to <strong>slow API responses</strong>.</li></ul><h4>Step 2: Optimizing Query Execution to Prevent Blocking</h4><h4>🛠️ Code: Using Row-Level Locking to Avoid Blocking Writes</h4><pre>BEGIN;<br>SELECT * FROM legal_cases WHERE id=123 FOR UPDATE;<br>UPDATE legal_cases SET status=&#39;closed&#39; WHERE id=123;<br>COMMIT;</pre><h4>🔎 Result:</h4><ul><li>Reduces Locking Issues</li><li>Prevents Blocking Other Queries</li><li>Faster Execution Under High Concurrency</li></ul><h3>3. Time-Series Performance Monitoring: Tracking Trends Over Time</h3><h4>🔍 Why Time-Series Monitoring?</h4><p>While profiling tools like cProfile or EXPLAIN ANALYZE help us identify bottlenecks at a single point in time, they don’t show <strong>performance trends over time</strong>.</p><p><strong>Grafana</strong>, paired with <strong>Prometheus</strong>, allows us to:<br>✅ Track query execution time trends<br>✅ Monitor API response time spikes<br>✅ Set alerts for performance degradation</p><h4>Step 1: Setting Up Prometheus to Collect Metrics</h4><p>We’ll configure <strong>Prometheus</strong> to collect <strong>SQL query execution time</strong> from our FastAPI app.</p><h4>📌 Install Prometheus &amp; Set Up Exporter</h4><ol><li>Install Prometheus (If not installed):</li><li>Install prometheus_client for Python:</li></ol><pre>wget https://github.com/prometheus/prometheus/releases/latest/download/prometheus-linux-amd64.tar.gz tar xvf prometheus-linux-amd64.tar.gz cd prometheus-linux-amd64 ./prometheus --config.file=prometheus.yml</pre><pre>pip install prometheus_client</pre><h4>Step 2: Expose Query Execution Time Metrics from FastAPI</h4><p>We’ll use prometheus_client to <strong>track query execution time</strong> and expose it at /metrics.</p><h4>🛠️ Code: Configuring Prometheus to Monitor Query Execution Time</h4><p>Add the following <strong>Prometheus exporter</strong> in your FastAPI backend:</p><pre>from fastapi import FastAPI<br>from prometheus_client import start_http_server, Summary<br>import time<br>import random<br><br>app = FastAPI()<br><br># Prometheus metric to track SQL execution time<br>SQL_QUERY_LATENCY = Summary(&#39;sql_query_latency_seconds&#39;, &#39;Time spent executing SQL queries&#39;)<br><br>def log_query_performance(query_func):<br>    def wrapper(*args, **kwargs):<br>        start_time = time.time()<br>        result = query_func(*args, **kwargs)<br>        SQL_QUERY_LATENCY.observe(time.time() - start_time)  # Log query time<br>        return result<br>    return wrapper</pre><p>Now, <strong>wrap your slowest queries</strong>:</p><pre>@app.get(&quot;/high-risk-cases&quot;)<br>@log_query_performance<br>def get_high_risk_cases():<br>    return db.execute(&quot;SELECT * FROM legal_cases WHERE risk_score &gt; 80 ORDER BY created_at DESC LIMIT 50&quot;)<br><br>@app.get(&quot;/metrics&quot;)<br>def get_metrics():<br>    from prometheus_client import generate_latest<br>    return generate_latest()</pre><h4>🔎 Monitoring Data (Prometheus Metrics Format)</h4><pre>sql_query_latency_seconds_count  250<br>sql_query_latency_seconds_sum    125.00<br>sql_query_latency_seconds_bucket{le=&quot;0.1&quot;}  180<br>sql_query_latency_seconds_bucket{le=&quot;0.5&quot;}  230</pre><p>Most queries complete in &lt;500ms</p><h4>Step 3: Visualizing Query Performance in Grafana</h4><p>Once Prometheus collects performance data, you can <strong>visualize trends in Grafana</strong>:</p><ul><li><strong>Graph Query Latency Over Time</strong></li><li><strong>Detect Slow API Calls and Spikes in Load</strong></li><li><strong>Set Alerts for Performance Degradation</strong></li></ul><h4>📌 Setting Up Grafana Dashboard for Query Execution Time</h4><p><strong>1. Install Grafana</strong> (If not installed):</p><pre>wget https://dl.grafana.com/oss/release/grafana_8.5.5_amd64.deb sudo dpkg -i grafana_8.5.5_amd64.deb sudo systemctl start grafana-server</pre><p><strong>2. Add Prometheus as a Data Source</strong>:</p><ul><li>Open Grafana (http://localhost:3000)</li><li>Go to <strong>Settings &gt; Data Sources &gt; Add Prometheus</strong></li><li>Enter URL: http://localhost:9090 and save</li></ul><p><strong>3. Create a Dashboard &amp; Add a Query Panel</strong></p><ul><li>Go to <strong>Dashboards &gt; Create New Dashboard</strong></li><li>Add a <strong>new Panel</strong></li><li>Use the following <strong>PromQL Query</strong> to track SQL execution time:</li></ul><pre>rate(sql_query_latency_seconds_sum[5m]) / rate(sql_query_latency_seconds_count[5m])</pre><ul><li><strong>Save &amp; Monitor Performance Trends!</strong></li></ul><h4>🔎 Example: Time-Series Graph of Query Response Times</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EaojfHX31rmgOE14xkqDA.jpeg" /><figcaption>Example of Query Execution Time Monitoring Visualization</figcaption></figure><p>Here is a <strong>Grafana-style visualization</strong> of SQL query execution times over a <strong>24-hour period</strong>.</p><h4>Key Insights from the Chart:</h4><p>✅ <strong>Query execution time fluctuates</strong> around <strong>200ms</strong> (simulated normal distribution).<br> ✅ <strong>Alert threshold set at 500ms</strong> (red dashed line) to identify slow queries.<br> ✅ <strong>Spikes indicate potential performance issues</strong>, which should be analyzed in Prometheus/Grafana for long-term trends.</p><h3>4. Function Heatmaps for Identifying Hotspots</h3><h4>🔍 Why Use Function Heatmaps?</h4><p>Standard profiling tools show function execution times, but they <strong>don’t visualize where the most processing time is spent</strong>. Using <strong>Scalene</strong>, we can generate a <strong>function heatmap</strong> to highlight memory and CPU usage.</p><h4>Step 1: Install Scalene</h4><pre>pip install scalene</pre><h4>Step 2: Profile a Python Script</h4><h4>🛠️ Code: Running Scalene on a Slow Script</h4><pre>scalene analyze_documents.py</pre><h4>🔎 Output: Function Heatmap</h4><pre>Time%   Memory%  Function<br>-----   ------   -----------------<br>50%      10%     extract_text()<br>30%      50%     analyze_risk()</pre><h4>Interpretation:</h4><ul><li>extract_text() is using <strong>50% of total CPU time</strong> but only <strong>10% of memory</strong> → Compute-heavy function.</li><li>analyze_risk() is consuming <strong>50% of memory</strong>, indicating inefficient handling of AI responses.</li></ul><p>Optimization Strategy: We can parallelize extract_text() and optimize memory usage in analyze_risk().</p><h3>5. UI Performance Profiling with Lighthouse</h3><h4>🔍 Why UI Profiling?</h4><p>If your FastAPI app has a <strong>frontend component</strong>, optimizing API responses alone isn’t enough. <strong>Google Lighthouse</strong> helps diagnose:</p><ul><li>Render-blocking scripts</li><li>Slow API responses</li><li>Inefficient UI updates</li></ul><h4>Step 1: Running Lighthouse in Chrome</h4><ol><li>Open <strong>Chrome DevTools</strong> (Ctrl + Shift + I → Navigate to &quot;Lighthouse&quot;).</li><li>Click <strong>“Generate Report”</strong>.</li><li>Review <strong>Performance Scores</strong> and optimization recommendations.</li></ol><h4>🔎 Output: Lighthouse Performance Report</h4><pre>Performance: 68/100<br>Blocking API calls: 750ms<br>Unused JavaScript: 30KB</pre><h4>Step 2: Optimizing API Response Time</h4><p>By default, FastAPI uses json.dumps() for JSON serialization, which can be slow. We can switch to orjson, a faster JSON serializer.</p><h4>🛠️ Code: Using orjson for Faster API Responses</h4><pre>import orjson<br>from fastapi import FastAPI, Response<br><br>app = FastAPI()<br>@app.get(&quot;/legal-risk&quot;)<br>async def get_legal_risk():<br>    data = fetch_risk_data()<br>    return Response(orjson.dumps(data), media_type=&quot;application/json&quot;)</pre><h4>🔎 Improvement:</h4><pre>API Response Time: 700ms → 300ms</pre><h3>6. Using AI Tools for Automated Query Optimization</h3><h4>🔍 Why Use AI for Code Optimization?</h4><p>Traditional profiling finds performance bottlenecks, but:</p><ul><li><strong>AI can generate optimized SQL queries</strong></li><li><strong>AI can suggest indexing strategies based on real-time workloads</strong></li><li><strong>AI can refactor Python code for better efficiency</strong></li></ul><p><strong>In this section, we use:</strong><br> ✅ <strong>GitHub Copilot (VS Code AI Plugin)</strong> for Python code suggestions</p><h4>Before being optimized</h4><pre>def extract_high_risk_cases():<br>    return db.execute(&quot;SELECT * FROM legal_cases WHERE risk_score &gt; 80 ORDER BY created_at DESC&quot;)</pre><p>🔴 <strong>Problems:</strong></p><ul><li><strong>Retrieves all columns</strong> (even unused ones)</li><li><strong>No pagination → Unnecessary data transfer</strong></li><li><strong>No indexing → Slow search times</strong></li></ul><h4>AI-Suggested Optimization (GitHub Copilot / SQL Prompt AI in VS Code)</h4><pre>def extract_high_risk_cases():<br>    return db.execute(&quot;&quot;&quot;<br>        SELECT id, case_name, risk_score, created_at <br>        FROM legal_cases <br>        WHERE risk_score &gt; 80 <br>        ORDER BY created_at DESC <br>        LIMIT 100<br>    &quot;&quot;&quot;)</pre><pre>CREATE INDEX idx_risk_score ON legal_cases (risk_score);<br>CREATE INDEX idx_created_at ON legal_cases (created_at);</pre><p><strong>Improvements:</strong></p><ul><li><strong>Suggests indexing </strong>for better performance</li><li>Uses <strong>optimized query</strong> (fetches only required fields)</li><li><strong>Adds pagination</strong> to prevent large data retrieval</li><li><strong>More readable &amp; efficient code</strong></li></ul><h3>7. Predicting Long-Term Performance with Load Testing</h3><h4>🔍 Why Load Testing Matters?</h4><p>Even if an API runs fast today, it may <strong>degrade under heavy load</strong>. We need <strong>predictive load testing</strong> to:</p><ul><li>Analyze system behavior under high traffic</li><li>Predict database scaling requirements</li><li>Optimize cloud resource allocation to reduce costs</li></ul><h4>Step 1: Running Load Tests to Simulate High Traffic</h4><p>We’ll use <strong>Locust</strong>, a Python-based load-testing tool, to simulate <strong>1000 concurrent users</strong> calling our <strong>legal risk API</strong>.</p><h4>🛠️ Code: Locust Load Testing Script</h4><pre>from locust import HttpUser, task, between<br><br>class LegalRiskAPIUser(HttpUser):<br><br>    wait_time = between(1, 3)  # Simulate real user delay<br>    @task<br>    def get_high_risk_cases(self):<br>        self.client.get(&quot;/high-risk-cases&quot;)<br><br>    @task(2)  # More frequent calls to the risk analysis API<br>    def analyze_document(self):<br>        self.client.post(&quot;/analyze-document&quot;, json={&quot;file_path&quot;: &quot;sample.docx&quot;})</pre><h4>🔎 Load Test Output (Summary Statistics)</h4><pre>Users: 1000 | Requests/sec: 500 | Failure Rate: 0.2%  <br>Average Response Time: 350ms | Peak Response Time: 900ms</pre><h4>🎯 Insights:</h4><ul><li>🚀 API handles <strong>500 requests/sec</strong> with <strong>350ms avg response time</strong></li><li>⚠️ <strong>Peak latency hits 900ms under heavy load</strong> → <strong>Risk of degradation</strong></li><li>🔧 Solution: <strong>Optimize database caching &amp; increase API concurrency</strong></li></ul><h3>8. Forecasting Maintenance &amp; Operational Costs Based on Load Testing</h3><h4>🔍 Why Cost Analysis Matters?</h4><ul><li>Unoptimized scaling can increase cloud costs by 3x 🚨</li><li>Database queries under heavy load lead to expensive slowdowns</li><li>Predicting cost trends helps avoid over-provisioning resources</li></ul><h4>Step 1: Estimating Cloud Cost per API Call</h4><p>Using AWS Lambda as an example:</p><ul><li><strong>Each API request costs</strong> $0.20 per 1 million executions</li><li><strong>With 500 requests/sec</strong>, the estimated monthly cost:</li></ul><h4>🛠️ Python Code: Estimating AWS Lambda Cost for API Load</h4><pre>requests_per_sec = 500<br>seconds_per_month = 30 * 24 * 60 * 60  # 30 days in seconds<br>total_requests = requests_per_sec * seconds_per_month<br><br># AWS Lambda pricing ($0.20 per 1M requests)<br>cost_per_million = 0.20<br>estimated_cost = (total_requests / 1_000_000) * cost_per_million<br>print(f&quot;Estimated Monthly API Cost: ${estimated_cost:.2f}&quot;)</pre><h4>🔎 Output:</h4><pre>Estimated Monthly API Cost: $259.20</pre><h4>🎯 Insights:</h4><ul><li>If traffic <strong>doubles</strong>, monthly cost <strong>jumps to $518.40</strong></li><li><strong>Optimizing API calls &amp; caching</strong> can <strong>reduce costs by 30%</strong></li></ul><h4>Step 2: Forecasting Future Cloud Costs Using AI &amp; Time-Series Data</h4><p>We’ll use <strong>Prophet (Facebook AI)</strong> to <strong>predict future API costs</strong> based on increasing traffic trends.</p><h4>🛠️ Code: AI-Driven Cost Forecasting with Prophet</h4><pre>from fbprophet import Prophet<br>import pandas as pd<br>import numpy as np<br><br># Simulated monthly API cost data (past 12 months)<br>months = pd.date_range(start=&quot;2024-01-01&quot;, periods=12, freq=&quot;M&quot;)<br>api_costs = np.array([200, 210, 220, 250, 270, 290, 310, 350, 400, 450, 500, 550])<br># Prepare DataFrame for Prophet<br>df = pd.DataFrame({&quot;ds&quot;: months, &quot;y&quot;: api_costs})<br>model = Prophet()<br>model.fit(df)<br># Predict next 6 months<br>future = model.make_future_dataframe(periods=6, freq=&quot;M&quot;)<br>forecast = model.predict(future)<br># Plot the forecast<br>import matplotlib.pyplot as plt<br>plt.figure(figsize=(10,5))<br>plt.plot(df[&#39;ds&#39;], df[&#39;y&#39;], marker=&quot;o&quot;, label=&quot;Actual Cost&quot;)<br>plt.plot(forecast[&#39;ds&#39;], forecast[&#39;yhat&#39;], linestyle=&quot;--&quot;, label=&quot;Predicted Cost&quot;)<br>plt.xlabel(&quot;Month&quot;)<br>plt.ylabel(&quot;Estimated Cost ($)&quot;)<br>plt.title(&quot;AI-Driven Cloud Cost Forecasting&quot;)<br>plt.legend()<br>plt.grid()<br>plt.show()</pre><h4>🔎 Output: Prophet Cost Prediction Graph</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C2cQvcVbRD_sC-Ym" /><figcaption>Example of Future Prophet Cost Prediction</figcaption></figure><p>🚀 <strong>Predicted Cost Trend Over Next 6 Months</strong></p><ul><li>📈 <strong>API costs increasing</strong> 10–15% per month</li><li>🔧 <strong>Scaling inefficiencies</strong> will cause <strong>$1000+ monthly costs</strong></li><li>🔍 <strong>Solution:</strong> <strong>Auto-scaling &amp; query optimization</strong> to <strong>reduce cos</strong></li></ul><h3>🎉 Final Results: Performance Gains</h3><p>After applying <strong>profiling and optimizations</strong>, let’s compare performance:</p><p>Function Before Optimization After Optimization</p><p>extract_text() from 1.25s to 0.4s</p><p>analyze_risk() from 0.75s to 0.5s</p><p>parse_ai_risk_analysis() from 0.5s to 0.5s</p><p><strong>Total</strong> from <strong>2.5s</strong> to <strong>1.4s</strong> (45% faster!) ⚡</p><h3>✨ Final Thoughts</h3><p>Profiling is like <strong>an X-ray for your code, </strong>it tells you exactly where the pain points are. Instead of throwing more hardware at the problem, <strong>optimize what you already have!</strong></p><p>🔹 <strong>Use cProfile</strong> for function-level insights</p><p>🔹 <strong>Use line_profiler</strong> for detailed line-by-line breakdowns</p><p>🔹 <strong>Optimize slow functions</strong> by using <strong>parallel processing</strong> and <strong>streaming techniques</strong></p><p>🔹<strong>Use SQL Query Plans</strong> to identify inefficient database queries</p><p>🔹<strong>Generate Function Heatmaps</strong> to pinpoint high CPU/memory usage</p><p>🔹<strong>Profile UI Performance</strong> with Lighthouse for frontend optimizations</p><p>🔹<strong>Leverage AI</strong> to automatically suggest optimized SQL queries</p><p>🔹<strong>Predict Long-Term Performance with Load Testing</strong> to identify scaling risks before they happen<br> 🔹 <strong>Use Time-Series Performance Monitoring</strong> to track query &amp; API trends over time and prevent slowdowns<br> 🔹 <strong>Forecast Maintenance &amp; Operational Costs</strong> based on profiling &amp; load testing insights to optimize cloud costs</p><p>🚀 <strong>By following this guide, I improved my Legal Risk Analyzer’s speed by 45%!</strong> Try it on your own project and see the magic happen. ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91d526ae31ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles: Building Robust and Maintainable Software]]></title>
            <link>https://medium.com/@bryantjandra2003/solid-principles-building-robust-and-maintainable-software-d18d03e42372?source=rss-ef9ddc2bbc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d18d03e42372</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Bryan Tjandra]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 14:02:23 GMT</pubDate>
            <atom:updated>2025-03-22T04:03:12.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/329/0*7jwSAGmQRs7RdkJt.jpeg" /><figcaption>Source: <a href="https://any-one-can-code.medium.com/why-make-software-engineer-principles-solid-3748b6b4d010">https://any-one-can-code.medium.com/why-make-software-engineer-principles-solid-3748b6b4d010</a></figcaption></figure><p>When writing software, just having code that “works” isn’t enough. Good code should also be maintainable, scalable, and easy to extend. Since software requirements often change over time, it’s essential to write code that can adapt easily without breaking existing functionality. Otherwise, every small tweak could potentially lead to huge problems down the road.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0IYV_4YU9_FYFzUx" /><figcaption>Source: <a href="https://thenextweb.com/news/code-sloppy-unless-youre-a-computer-scientist-syndication">https://thenextweb.com/news/code-sloppy-unless-youre-a-computer-scientist-syndication</a></figcaption></figure><p>Imagine adding one small feature to your software and suddenly the whole application crashes … it’s a nightmare, right? So, what’s the solution? Follow solid software design principles to make your code reliable, maintainable, and scalable. Let’s dive deeper into some core programming concepts: <strong>Object-Oriented Design (OOP) and SOLID</strong> principles, which we’ll explore using real examples as well.</p><p>We will also explore how we applied these principles in a real-world project: a FastAPI-based document analyzer that extracts, analyzes, and parses legal risk clauses from uploaded PDF or DOCX files using AI.</p><h3>Why Follow Best Practices?</h3><p>Applying software design principles leads to:</p><ul><li><strong>Easier maintenance. </strong>Reduces technical debt and makes debugging simpler.</li><li><strong>Scalability. </strong>Accommodates future updates without rewriting large parts of the code.</li><li><strong>Improved collaboration. </strong>Enables teams to work on separate parts of a project seamlessly.</li><li><strong>Reduced risk of bugs. </strong>Enhances code reliability and consistency.</li></ul><h3>Understanding Object-Oriented Programming (OOP)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*LmxGm2Jlsg53QVwj.png" /><figcaption>Source: <a href="https://botpenguin.com/glossary/object-oriented-programming">https://botpenguin.com/glossary/object-oriented-programming</a></figcaption></figure><p>OOP is centered around objects, which are instances of classes. Classes bundle data and methods, allowing for modular and reusable code. Here are the fundamental pillars of OOP. It has four fundamental key principles:</p><h3>1. Inheritance: Reuse and Extend Code</h3><p>Inheritance allows a class (child) to derive properties and behaviors from another class (parent). This avoids redundancy and enables better code management.</p><p>In this system, you support multiple file types (PDF and DOCX), each requiring a different parsing strategy. Instead of duplicating logic, you define a shared interface (DocumentParser) and use <strong>inheritance</strong> to specialize behavior.</p><pre>from abc import ABC, abstractmethod<br><br>class DocumentParser(ABC):<br>    @abstractmethod<br>    def extract_text(self, file_path: str) -&gt; str:<br>        pass</pre><p>You then implement specialized classes:</p><pre>class PDFParser(DocumentParser):<br>    def extract_text(self, file_path: str) -&gt; str:<br>        with pdfplumber.open(file_path) as pdf:<br>            return &quot;\n&quot;.join([<br>                page.extract_text() for page in pdf.pages if page.extract_text()<br>            ])<br><br>class DOCXParser(DocumentParser):<br>    def extract_text(self, file_path: str) -&gt; str:<br>        doc = docx.Document(file_path)<br>        return &quot;\n&quot;.join([p.text for p in doc.paragraphs if p.text.strip()])</pre><p>PDFParser and DOCXParser inherit from DocumentParser, making it easy to extend functionality for more file types (e.g., .txt, .xlsx) without changing existing code. This is a perfect real-world use of <strong>inheritance</strong>.</p><p>Here is the example of the bad code</p><pre>def extract_pdf(file_path: str):<br>    # PDF parsing logic here<br>    ...<br><br>def extract_docx(file_path: str):<br>    # DOCX parsing logic here<br>    ...</pre><p>Using standalone functions for each type leads to repeated logic and makes it harder to maintain or scale.</p><p>By inheriting from a common base class, we reduce redundancy and make the code easier to maintain.</p><h3>2. Encapsulation: Data Protection</h3><p>Encapsulation wraps data and methods into a single unit (class), restricting direct access and accidental modifications. This prevents unintended modifications.</p><p>Encapsulation allows hiding complex AI communication logic from route handlers. The AIClient handles retries, API calls, and formatting. Consider this simplified example</p><pre>class AIClient:<br><br>    def __init__(self, ai_client):<br>        self.ai_client = ai_client<br><br>    def analyze_risk(text: str) -&gt; str:<br>        prompt = f&quot;{AI_RISK_ANALYSIS_PROMPT}\n\n{text}&quot;<br>        <br>        response = self.ai_client.chat.completions.create(<br>            model=&quot;qwen/qwen2.5-vl-72b-instruct:free&quot;,<br>            messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: prompt}]}],<br>        )<br>        return response.choices[0].message.content.strip()</pre><p>Now your routes don’t need to know how the AI model works. They just do:</p><pre>risks = analyzer.analyze(document_text)</pre><p>The API key, prompt design, error handling, and retries are <strong>encapsulated</strong> inside this class, making your route logic clean and focused.</p><p>How about the bad one ? here is the example</p><pre># Inside the route<br>client = OpenAI(api_key=&quot;your-key&quot;)<br>prompt = &quot;some prompt&quot; + extracted_text<br>response = client.chat.completions.create(model=&quot;...&quot;, messages=[...])<br>ai_output = response.choices[0].message.content</pre><p>Mixing business logic into route handlers increases complexity and violates separation of concerns. The API key and prompt design will be leaked as well and can be misused.</p><p>This protects the internal state from unwanted interference, making changes safer and debugging simpler.</p><h3>3. Abstraction: Hiding Complexity</h3><p>Abstraction hides the complexity of implementations and exposes only essential functionalities.</p><p>Let’s say you have a service that performs document processing:</p><pre>class DocumentProcessingService:<br>    def __init__(self, parser: DocumentParser, analyzer: RiskAnalyzer):<br>        self.parser = parser<br>        self.analyzer = analyzer<br><br>    def process(self, file_path: str) -&gt; dict:<br>        text = self.parser.extract_text(file_path)<br>        return self.analyzer.analyze(text)</pre><p>The rest of the app only talks to DocumentProcessingService. It doesn&#39;t need to know how parsing or AI work internally.</p><p>This is the bad code you need to avoid</p><pre>def process_document(file_path: str, parser: DocumentParser):<br>    if isinstance(parser, PDFParser):<br>        text = PDFParser().extract_text(file_path)<br>    else:<br>        text = DOCXParser().extract_text(file_path)<br>    return analyze_with_ai(text)</pre><p>Manually checking types defeats the purpose of abstraction and leads to rigid, hard-to-test code.</p><p>Clients using this class don’t need to know the details, making interactions simple and clear.</p><h3>4. Polymorphism: One Interface, Many Implementations</h3><p>Polymorphism allows objects to be treated as instances of their parent class, even if they belong to different child classes. Thanks to polymorphism, route logic doesn’t care if it’s working with PDFParser or DOCXParser.</p><p>Because all your parsers inherit from DocumentParser, you can treat them the same way:</p><pre>def handle_upload(file_path: str, file_type: str):<br>    parser = get_parser_for(file_type)<br>    return parser.extract_text(file_path)</pre><p>All parsers implement the same method and can be used interchangeably. Whether it’s a PDF or DOCX, your code doesn’t need to care, it just works.</p><p>Here is the bad example</p><pre>if file_type == &quot;pdf&quot;:<br>    text = extract_pdf(file_path)<br>elif file_type == &quot;docx&quot;:<br>    text = extract_docx(file_path)</pre><p>Every new format requires touching this logic, which violates Open/Closed Principle too.</p><h3>SOLID Principles: The Foundation of Clean Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*wIMbGI1XCGggcV7P5zQeZw.jpeg" /><figcaption>Source: <a href="https://www.geeksforgeeks.org/solid-principle-in-programming-understand-with-real-life-examples/">https://www.geeksforgeeks.org/solid-principle-in-programming-understand-with-real-life-examples/</a></figcaption></figure><p>SOLID is a set of five principles proposed by <strong>Robert C. Martin</strong> to create flexible and maintainable software. Let’s explore them with real-world examples.</p><h3>1. Single Responsibility Principle (SRP)</h3><p><strong>A class should only have one reason to change.</strong> This keeps responsibilities clear and avoids coupling different functionalities together.</p><p>Every class in your system has <strong>one job</strong> and one reason to change:</p><p>PDFParser / DOCXParser: Extracts text from documents</p><p>ParserFactory: Selects parser based on file extension</p><p>AIClient: Interacts with external AI</p><p>RiskParserExtracts risk clauses from AI responseAPI routesHandle request flow only</p><p><strong>Bad Example:</strong></p><pre>class DocumentManager:<br>    def extract_text(self): ...<br>    def call_ai_model(self): ...<br>    def store_result_in_db(self): ...</pre><p>Here, DocumentManager handles many tasks. This violates SRP.</p><p><strong>Better Approach:</strong></p><pre>class Parser:<br>    def extract_text(self, path): ...<br><br>class RiskAnalyzer:<br>    def analyze(self, text): ...<br><br>class StorageService:<br>    def save(self, data): ...</pre><p>Now, each class has a <strong>single responsibility</strong>.</p><h3>2. Open/Closed Principle (OCP)</h3><p><strong>Software entities should be open for extension but closed for modification.</strong></p><p>Instead of modifying a class every time requirements change, we extend it. When you want to add .txt file support:</p><pre>class TXTParser(DocumentParser):<br>    def extract_text(self, file_path: str) -&gt; str:<br>        with open(file_path, &quot;r&quot;) as file:<br>            return file.read()</pre><p>Then update your factory:</p><pre>if file_type == &quot;txt&quot;:<br>    return TXTParser()</pre><p>When new features or slight changes are required, we just extend this class rather than editing existing code, keeping the system stable and clean. You don’t change the routes, AIClient, or RiskParser,they continue to work.</p><p>Here is the bad example</p><pre># In main parser logic<br>if file_type == &quot;pdf&quot;:<br>    ...<br>elif file_type == &quot;docx&quot;:<br>    ...<br>elif file_type == &quot;txt&quot;:<br>    ...  # and so on forever</pre><p>Constantly editing existing logic makes it error-prone and hard to manage.</p><h3>3. Liskov Substitution Principle (LSP)</h3><p><strong>Subtypes must be replaceable by their base types without causing errors.</strong></p><p>Every subclass of DocumentParser <strong>can replace</strong> its parent type without breaking anything. For example:</p><pre>def process_file(parser: DocumentParser, path: str):<br>    return parser.extract_text(path)</pre><p>Subclasses behave exactly as their base classes promise. You can pass in a PDFParser, DOCXParser, or TXTParser, and it still works.</p><pre>def process_file(parser, path: str):<br>    if isinstance(parser, PDFParser):<br>        return parser.extract_text(path)<br>    else:<br>        raise Exception(&quot;Unsupported parser&quot;)</pre><p>This design doesn’t trust polymorphism and breaks substitution.</p><p>That’s clean and correct usage of LSP.</p><h3>4. Interface Segregation Principle (ISP)</h3><p><strong>A class should not be forced to implement methods it doesn’t use.</strong></p><p>You only implement interfaces that are actually needed.</p><p>Instead of forcing all document parsers to implement unrelated methods (like scan_image() or convert_to_html()), you keep the interface minimal:</p><pre>class FileHandler:<br>    def extract_text(self, file_path: str) -&gt; str:<br>        ...<br><br>    def scan_image(self, image_path: str) -&gt; str:<br>        ...<br><br>    def convert_to_html(self, html_path: str) -&gt; str:<br>        ... </pre><p>Better:</p><pre>class DocumentParser(ABC):<br>    def extract_text(self, file_path: str) -&gt; str:<br>        ...</pre><pre>class OCRScanner:<br>    def scan_image(self, image_path: str) -&gt; str:<br>        ...</pre><pre>class HTMLConverter:<br>    def convert(self, html_path: str) -&gt; str:<br>        ...</pre><p>Forcing unrelated methods increases coupling and confusion.</p><p>This class only implements methods it needs, avoiding unnecessary dependencies on unused methods.</p><h3>5. Dependency Inversion Principle (DIP)</h3><p><strong>Depend on abstractions, not concretions.</strong></p><p>High-level modules should <strong>not</strong> depend on low-level ones. Both should depend on <strong>abstractions</strong>. Instead of this:</p><p>✅ Instead of doing this because testing or switching parsers requires modifying the class itself.</p><pre>class DocumentProcessor:<br>    def __init__(self):<br>        self.parser = PDFParser()  # tightly coupled</pre><p>Do this:</p><pre>class DocumentProcessor:<br>    def __init__(self, parser: DocumentParser):<br>        self.parser = parser</pre><p>Now during testing:</p><pre>processor = DocumentProcessor(MockParser())</pre><p>This supports clean testing and future extensions.</p><h3>Additional Best Practices</h3><h3>Don’t Repeat Yourself (DRY)</h3><p>You extract common logic (like temporary file saving) to shared methods or keep route logic minimal:</p><pre>def save_temp_file(file: UploadFile) -&gt; str:<br>    with open(temp_file_path, &quot;wb&quot;) as buffer:<br>        shutil.copyfileobj(file.file, buffer)<br>    ...</pre><p>Now reused across all routes, no duplication.</p><h3>Keep It Simple, Stupid (KISS)</h3><p>Keep things simple. Complex code isn’t impressive; it’s just harder to maintain. Instead of overengineering, each part does what it’s supposed to. For example:</p><pre>if file_extension == &quot;pdf&quot;:<br>    return PDFParser()<br>elif file_extension == &quot;docx&quot;:<br>    return DocxParser()</pre><p>Another example:</p><pre>if file_type not in [&quot;pdf&quot;, &quot;docx&quot;]:<br>    raise ValueError(&quot;Unsupported format&quot;)</pre><p>Straightforward and easy to debug.</p><h3>You Aren’t Gonna Need It (YAGNI)</h3><p>Only add features when you actually need them. Avoid premature optimizations. You haven’t built logic for exporting to Excel, sending email notifications, or applying clause fixes, because you <strong>don’t need them now</strong>.</p><pre># Don&#39;t add unnecessary attributes or functions until needed<br>class Export:<br>    def report_to_excel(self, clauses:<br>       pass # TODO later<br>    def send_notification(self, clauses):<br>       pass # TODO later</pre><h3>Law of Demeter</h3><p>Your route talks directly to the main objects and avoids deep chains:</p><p>❌ Avoid:</p><pre>request.user.session.document.upload.parser.extract_text()</pre><p>✅ Use:</p><pre>parser = get_parser()<br>text = parser.extract_text()</pre><p>This reduces complexity and dependency.</p><h3>Project Structure &amp; PEP-8</h3><p>Your project follows a clean structure:</p><pre>app/<br>├── router/<br>│   └── routes.py<br>├── utils/<br>│   ├── document_processor.py<br>│   ├── ai_client.py<br>│   └── parser_factory.py<br>├── services/<br>│   ├── parsers/<br>│   │   ├── base.py<br>│   │   ├── pdf_parser.py<br>│   │   └── docx_parser.py<br>│   └── risk_analysis.py</pre><p>With naming conventions:</p><ul><li>Classes: CamelCase → AIClient, PDFParser</li><li>Variables: snake_case → temp_file_path, extracted_text</li></ul><h3>Benefits of Following Best Practices:</h3><ul><li><strong>Reduced merge conflicts</strong>: Clear, modular code reduces conflicts when merging branches.</li><li><strong>Faster Code Reviews</strong>: Consistent naming conventions and simple structures ease code review.</li><li><strong>Easier onboarding</strong>: Clear code structure helps new developers quickly understand and contribute effectively.</li></ul><p>By consistently following best practices like SOLID, we enhance code reliability, ease of maintenance, and scalability, creating software that’s robust enough to adapt and grow without headaches.</p><h3>References</h3><ul><li>Robert C. Martin — <strong>Clean Code</strong></li><li>DigitalOcean — <strong>SOLID Principles Explained</strong></li><li>W3Schools — <strong>OOP in Python</strong></li><li>Martin Fowler — <strong>Design Patterns and Best Practices</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d18d03e42372" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working in a Team: The (Not-So) Lonely Road to Better Software]]></title>
            <link>https://medium.com/@bryantjandra2003/working-in-a-team-the-not-so-lonely-road-to-better-software-515ef1272a05?source=rss-ef9ddc2bbc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/515ef1272a05</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[backlog]]></category>
            <category><![CDATA[jira]]></category>
            <category><![CDATA[teamwork]]></category>
            <dc:creator><![CDATA[Bryan Tjandra]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 12:46:46 GMT</pubDate>
            <atom:updated>2025-05-24T07:45:09.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OGvJYpqOKFRnt11Wx-jECQ.jpeg" /><figcaption>Source: <a href="https://images.app.goo.gl/vw4KxABRzjFFW9rp7">https://images.app.goo.gl/vw4KxABRzjFFW9rp7</a></figcaption></figure><h3>Teamwork in Software Development</h3><p>Developing a large-scale software application is no easy feat. Sure, you could go solo and try to build everything yourself, but if you don’t want your client breathing down your neck when the project is delayed by several months, it’s better to work as part of a team. 🤔</p><p>When working solo, you have complete control over the development process, but it also means you’re the one responsible for every single task , from backend logic to frontend design, debugging, testing, and deployment.</p><p>This can be exhausting and prone to mistakes due to a lack of diverse perspectives. On the other hand, working in a team allows multiple minds to collaborate and bring specialized expertise to the table, ensuring that the final product is robust, efficient, and delivered on time. However, it introduces its own complexities that require careful management to ensure success.</p><h3>Navigo: A Case Study</h3><p>Let’s talk about the project I’m currently working on: <strong>Navigo</strong>. The platform aims to simplify the creation and analysis of legal documents using AI, making it accessible to users without deep legal expertise. The project is vast, encompassing multiple features like a <strong>Legal Document Generator</strong>, <strong>MoU Analyzer</strong>, <strong>Legal QnA Chatbot</strong>, and more.</p><p>Each of these features addresses a different pain point in the legal domain. The <strong>Legal Document Generator</strong> helps users quickly create legal documents tailored to their specific needs, while the <strong>MoU Analyzer</strong> analyzes uploaded documents to identify potential legal risks. The <strong>Legal QnA Chatbot</strong> answers legal questions, and the <strong>Legal Document Search</strong> feature helps users find relevant legal references efficiently. With such diverse functionality, ensuring seamless integration and consistent performance across modules has been a key focus for the team.</p><h3>Coordination: A Challenge in Itself 😅</h3><p>Now, this is where things get tricky. Apart from managing tasks within my sub-team, I also have to constantly sync with the other sub-team to ensure that both teams are on the same page. There’s a lot of back-and-forth involved, especially around <strong>feature separation, tech stacks, and API contracts</strong>.</p><p>Since we’re building interconnected systems, even a small misalignment can lead to major integration issues. For example, if the API structure between the Document Generator and the MoU Analyzer changes slightly, it can cause the entire process to break. This makes <strong>continuous communication</strong> and <strong>frequent check-ins</strong> essential. We’ve had to conduct regular stand-ups, retrospectives, and cross-team discussions to stay aligned. Despite these efforts, unexpected changes still pop up during the sprint, requiring quick adaptations and additional discussions to resolve conflicts.</p><h3>Task Management: No More Excel, Please! 📊</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*F2L_TtK6Yc6hRs5E.jpg" /><figcaption>Source: <a href="https://www.timecamp.com/blog/top-timesheet-memes/">https://www.timecamp.com/blog/top-timesheet-memes/</a></figcaption></figure><p>Alright, let’s assume we’ve figured out feature separation and assigned tasks to everyone. Now comes the next challenge, <strong>how do we effectively manage and track these tasks?</strong></p><p>I mean, <strong>Excel?</strong> Nah, not happening. Nobody wants to manage a complex software development project with rows and columns. 😆 Besides, tracking issues, assigning tasks, and monitoring progress in Excel quickly becomes unmanageable as the project grows. It’s hard to visualize dependencies, track blockers, and maintain transparency about who’s working on what. As the number of tasks and contributors increases, you need a more <strong>dynamic and automated system</strong> to ensure smooth collaboration and accountability.</p><h3>Project Management with Jira</h3><p>Even a baby knows that a good project management tool is a must, although he’s probably not a project manager. 😆</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*XzV1LQyUiApDjwjHYS89gg.png" /><figcaption>Source: <a href="https://www.vivantio.com/integrations/jira/">https://www.vivantio.com/integrations/jira/</a></figcaption></figure><h3>So, what’s Jira?</h3><p>Jira, developed by Atlassian, is a powerful project management tool that helps teams organize and track their work. It offers a variety of features, such as:</p><p>✅ <strong>Issue Tracking:</strong> Create, assign, and monitor issues throughout the project lifecycle.<br>✅ <strong>Scrum Boards:</strong> Visualize sprint progress and manage backlogs effortlessly.<br>✅ <strong>Dashboards:</strong> Get a clear view of project status and bottlenecks.</p><p>What makes <strong>Jira</strong> a game-changer is its ability to adapt to different team structures and workflows. Whether you’re using Scrum, Kanban, or a hybrid methodology, Jira can be customized to reflect the way your team operates. It allows us to break down large epics into manageable tasks, assign them to team members, and track progress in real-time. The ability to set priority levels, define acceptance criteria, and visualize task dependencies ensures that we’re always aligned and focused on meeting sprint goals.</p><h3>Let’s Talk Jira: Your New Best Friend (Sometimes) 👀</h3><h3>👋 Sprint Planning &amp; Backlogs</h3><p>Ever heard of a <strong>sprint</strong>? It’s a set time period (usually a week or two) where you tackle a bunch of tasks. In <strong>Jira</strong>, you can create sprints, define a sprint goal (like “Complete user signup and login flows”), and move tasks (a.k.a. issues) from your backlog into that sprint. It might feel like extra overhead, but once you see everything neatly organized, it’s easier to spot overlapping responsibilities or tasks that might be missing.</p><p><strong>Pro Tip:</strong> Be specific with your tasks! If “Implement user login” can be split into “Design login page,” “Set up authentication API,” and “Link front-end to backend,” do it. The more granular your tasks, the easier it is to track progress.</p><p>Here is the example of the backlog, breakdown the single large task to multiple small tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymUGQG1yGhle1wpnDI_gFQ.png" /><figcaption>An example of our group’s backlog in Jira</figcaption></figure><p>Don’t forget to update the status once you’ve completed your task! Keeping the status accurate ensures that the progress report reflects the real situation. If the status isn’t updated, it might lead to confusion or give a misleading impression of where we stand. Let’s keep things clear and aligned! 😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2c6HPu6uoT4t_xwfQ3Omg.png" /><figcaption>Status of project in Jira</figcaption></figure><h3>👋 Scrum Boards</h3><p>Another thing that you need to know is <strong>Scrum Board</strong>, where tasks get grouped by status (To Do, In Progress, In Review, Done, etc). It’s kind of like a digital corkboard with sticky notes, but way more powerful. If you notice a single task is stuck in “In Progress” for days, that’s a sign you might need to jump in and help or interrupt your teammate to see if they’re buried in other work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fflBQf1FqaD7NeghzTagA.png" /><figcaption>An example of our group’s scrum board</figcaption></figure><h3>👋 Timeline Charts</h3><p>Jira’s timeline (or roadmap) offers a bird’s-eye view of what features (epics) are being worked on and when they’re supposed to be done. This is especially helpful if you’re juggling multiple sprints. Meanwhile, <strong>burndown charts</strong> show how quickly your team is finishing tasks. If your chart looks like a pancake for most of the sprint and then fall drastically at the last minute, you’re probably waiting until the 11th hour to do everything. Not ideal, but it happens!</p><p>Notice that, if sometimes you see that the span time for each task is the same, it means that the task can be done in parallel, and you don’t need to depend on the other’s task. So, there is no reason to procrastinate🤭.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wp-NFUVyWG9-Y966kSIoNQ.png" /><figcaption>An example of our sprint timeline</figcaption></figure><p>We can also zoom in to get a detailed view of each epic. For example, if I want to check the progress of the backlogs in the Legal Document Generator epic, I can easily do that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*td2vMoG9zyLmx-E90DRGYw.png" /><figcaption>An example of detailed timeline of an epic</figcaption></figure><p>As shown, there’s only one backlog still in progress for that epic, which was actually expected to be completed by the end of this second sprint. This gives us a clear picture of where we stand and helps us stay on track with our sprint goals.</p><h3>📊 Jira’s Insights Tab</h3><p>Lastly, you can track the progress of your sprint through the <strong>‘Insights’</strong> tab. To access this, simply go to the <strong>‘Board’</strong> page and click on the <strong>‘Insights’</strong> button located on the right side, next to the <strong>‘View settings’</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*ItnU62PL9QhLB5q9l73-QQ.png" /><figcaption>Sprint Insight</figcaption></figure><p>As the name suggests, the <strong>‘Insights’</strong> tab provides valuable data about how the sprint is progressing. It includes detailed information such as <strong>overall progress, burndown charts, and epic progress</strong>.</p><h4>Breaking It Down: What Can You See?</h4><p>✅ <strong>Overall Progress:</strong> This section gives you a bird’s-eye view of the sprint’s progress. You’ll see the percentage of tasks that are <strong>completed, in progress,</strong> and <strong>yet to be started</strong>.</p><p>✅ <strong>Epic Progress:</strong> This feature provides a more granular view, showing the percentage of completed tasks within a specific epic. Just to recall — an <strong>epic</strong> is a large body of work that is broken down into multiple smaller stories that contribute to completing the epic’s goal.</p><p>✅ <strong>Sprint Burndown Chart:</strong> This is a visual representation of work completed during a sprint in Agile project management. It tracks progress over time, typically updated daily. The <strong>x-axis</strong> represents time (days), while the <strong>y-axis</strong> shows the amount of work remaining (usually measured in story points).</p><h4>Sprint Recap: How Did It Go?</h4><p>As shown in the burndown chart, our team managed to complete all the targeted story points for Sprint 3, totaling <strong>59 points</strong>. However, we didn’t quite follow the ideal “linear” guideline for progress. Most of the tasks were completed during the second half of the sprint, which resulted in a less-than-smooth burndown curve.</p><p>One of the main reasons for this uneven progress was that many of the team members (including me 😅) often forgot to update the task status after completing them. This caused the burndown chart to appear asymmetrical and made it difficult to get an accurate view of real-time progress. We identified this issue during the <strong>sprint retrospective</strong> and agreed to fix it by reminding each other more frequently to update task statuses. Hopefully, this will lead to a more accurate and streamlined sprint tracking process in the future. 🤞</p><h4>Jira: Is It Really That Complex?</h4><p>Let’s be honest — Jira can feel <strong>overwhelming</strong> at first, especially for beginners who have never used a project management tool before (just like me when I started!). With its numerous features and technical terms, it can take some time to get familiar with everything. However, the good news is that there’s no shortage of <strong>tutorials and resources</strong> available online to help you get the hang of it.</p><p>Once you get comfortable with Jira, you’ll realize how <strong>powerful and versatile</strong> it is — not just for managing software development projects, but also for any field that involves project management. Whether you’re working on Agile development, marketing campaigns, or any other collaborative project, Jira can be an invaluable tool to keep everything organized and on track.</p><h3>🤕Git + Communication = Fewer Headaches</h3><p>I’m not here to discourage you from using other communication platforms like <strong>Slack, Discord, or WhatsApp</strong> to interact with your team. They’re great for quick chats, discussing project timelines, or even sharing memes to keep the team spirit high. 😆 But when it comes to <strong>discussing code</strong>, GitLab (or GitHub, depending on your platform) offers a much better, more efficient solution.</p><p>If you’re reviewing code or providing feedback on a specific change, <strong>Github’s commit and merge request comment features</strong> are designed specifically for that purpose. Take a look at the two scenarios below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Lc1IGwjj4SFuSLAFILOow.png" /><figcaption><strong>My Chat Discussing Code in Discord</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUUZMEJhtYyOwBz8b7hebQ.png" /><figcaption><strong>My Comment on Another Member’s Commit</strong></figcaption></figure><p><strong>Pro Tip:</strong> If you’re merging a feature branch, create a merge request (MR) and invite your teammates to review it. They can comment on specific lines, ask questions, and suggest changes. It’s like having a mini design review, but for code. Make sure the Quality Gate has passed and no issues founded before merging🏆</p><h3>Which One Is Better?</h3><p>The second one, right? <br>Here’s why:</p><ol><li><strong>Contextual Clarity:</strong> Instead of copying and pasting code snippets or sending screenshots to a group chat, you can <strong>comment directly on the commit or merge request</strong>. This way, the person receiving your feedback can immediately see which part of the code you’re referring to without having to switch between platforms.</li><li><strong>Living Documentation:</strong> Comments on commits and MRs serve as a form of <strong>documentation</strong>. These comments stay with the code, making it easier for both current team members and future developers to understand why certain decisions were made. It’s like leaving breadcrumbs for the next person who has to work on that piece of code.</li><li><strong>Better Traceability:</strong> Discussions and suggestions are tied directly to the codebase, ensuring that all relevant conversations remain in one place. This makes it easier to trace changes, decisions, and context down the line.</li></ol><h3>Write Meaningful Comments 📝</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B7mP39F97Ihkuic0" /><figcaption>Source: <a href="https://chromewebstore.google.com/detail/github-lgtm/bhiegncjmjcjnlgcklnhefhdlkjlkbgb?hl=jw">https://chromewebstore.google.com/detail/github-lgtm/bhiegncjmjcjnlgcklnhefhdlkjlkbgb?hl=jw</a></figcaption></figure><p>Commenting on others’ code is crucial — but make sure your comments are actually <strong>helpful and constructive</strong>. Avoid throwing around a casual <strong>“LGTM”</strong> (Looks Good To Me) without reviewing the code properly. While it’s tempting to give a quick approval, meaningful comments should:</p><p>✅ Identify potential <strong>bugs</strong> or unexpected behavior.<br>✅ Highlight areas with <strong>code smells</strong> or suggest performance improvements.<br>✅ Suggest ways to <strong>improve readability</strong> or maintainability of the code.</p><h3>Commit Messages: Another Communication Tool</h3><p>Besides commenting on commits, you can also <strong>utilize commit messages</strong> as a powerful communication medium. A well-written commit message provides clarity about the changes you made, making it easier for other team members to follow along. Trust me, <strong>good commit messages save lives</strong> — or at least save your team from hours of confusion. 😅</p><h3>Follow Conventional Commit Standards</h3><p>To maintain consistency, my team uses the <a href="https://www.conventionalcommits.org/"><strong>Conventional Commits</strong></a> format. This standard ensures that commit messages follow a structured format, which helps with automation, changelog generation, and better versioning.</p><p>When working with <strong>Test-Driven Development (TDD)</strong>, don’t forget to include tags like:</p><ul><li>[RED] – To denote failing tests.</li><li>[GREEN] – To mark tests that are passing.</li><li>[REFACTOR] – For code cleanup and optimization.</li></ul><p>Here’s a quick look at some of the commits I’ve made following these standards:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dohD_iKUh0AUMp1z5RAnWA.png" /><figcaption>Commits that I have made</figcaption></figure><h3>Don’t Be Like This People! 😅</h3><p>A poorly written or vague commit message can confuse your future self and your teammates. So, <strong>don’t be like this people, </strong>who left behind a trail of cryptic and unhelpful commit messages like:</p><ul><li>Fixed stuff</li><li>Update</li><li>Final final version for real</li><li>I have no idea what I’m doing</li></ul><p>You get the idea. 😆</p><h3>The Ups and Downs (But Mostly Ups)</h3><h3>✨Transparency</h3><p>Because everyone can see your Jira board and your commits, it’s hard to hide bottlenecks. This might feel uncomfortable at first (“everyone knows I’ve been on the same task for four days!”), but it helps address the bigger problem from the start. If you’re stuck, your teammates can jump in to help.</p><h3>✨Accountability</h3><p>With tasks clearly assigned in Jira, you won’t have that “I thought you were doing that!” confusion. You can always check who owns each task, and if it’s not done, you know exactly who to poke.</p><h3>✨Better Quality</h3><p>Frequent code reviews catch issues early, such as typos, logical errors, or design flaws you might’ve overlooked. It’s easier to fix a tiny mistake now than to patch a huge bug later.</p><h3>After Using These Two Tools for Over a Month 🚀</h3><p>After spending more than a month using <strong>Jira</strong> and <strong>Github </strong>to manage our project, I can confidently say that these tools have made a world of difference in improving our team’s productivity and communication. Each tool plays a unique role, and using them in parallel has helped us streamline our entire workflow. ich would automatically link commits to tasks, the separate use of Jira for task management and GitHub for code review has significantly improved our process.</p><h3>How Jira Transformed Our Scrum Process</h3><p>Jira has been an absolute game-changer for my team, especially during the <strong>scrum process</strong>. Its versatile features, particularly the <strong>scrum board</strong>, have significantly boosted our flexibility and transparency in managing tasks. All our backlogs are displayed in an intuitive, column-separated view that makes it easy to track the status of each task. This visual representation helps us quickly identify if someone has been stuck on a task for too long and take timely action to <strong>mitigate any potential blockers</strong>.</p><h3>Boosting Personal Productivity ⚡️</h3><p>From a personal standpoint, Jira has enhanced my workflow and overall productivity — especially when working on tasks that are <strong>highly dependent on others</strong>. For instance, when I’m working on a front-end task and I need some clarifications about the API or other back-end components, I can easily check who’s handling the back-end task related to that backlog. With that information, I can directly reach out to them and get the answers I need, eliminating delays caused by uncertainty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYQVa81RQDpHeajq1qs0tg.png" /><figcaption>My team’s backlog</figcaption></figure><p>For example, in this image I uploaded above, after I finish implementing the API that will be integrated to the frontend, my friend can now continue to the implementation of the frontend itself.</p><h3>Keeping Documentation in One Place 📝</h3><p>Another cool thing about Jira is that after decisions are made or tasks evolve, we can <strong>update the task descriptions</strong> directly in Jira. This acts as a form of living documentation that’s accessible to everyone. No need to switch to another note-taking platform or dig through endless chat threads on Slack or Discord. Everything stays in one place, making it easier to review later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FE2OsoOtW9q-vxAu7ND19w.png" /><figcaption>My Jira’s Task Description</figcaption></figure><h3>One-Stop Hub for Project Information 🎯</h3><p>If I need to know something <strong>important</strong> about the project, I don’t need to search through multiple platforms or ask around — I just head over to <strong>Jira</strong>. It centralizes all the information related to our tasks, backlog, sprint goals, and ongoing discussions. This has helped us reduce unnecessary back-and-forths and maintain better alignment as a team.</p><h3>How Github Streamlined Our Code Review Process 🧑‍💻</h3><p>While Jira takes care of our task management, <strong>Github </strong>has been just as effective in optimizing our <strong>code review and collaboration process</strong>. Commenting on <strong>merge requests (MRs)</strong> and commits has become second nature, allowing us to minimize the need for sharing screenshots or discussing code snippets on Discord. Now, all code-related conversations happen directly within Github, where they belong.</p><h3>Minimizing Noise, Maximizing Efficiency 🔥</h3><p>Previously, we often had to take screenshots of code and paste them in our team’s Discord server, which was <strong>inefficient and prone to confusion</strong>. But now, whenever a commit or merge request is pushed, team members can review and leave comments directly in Github. This keeps the context intact and allows for <strong>targeted, detailed feedback</strong> without switching between platforms.</p><h3>Github-CodeRabbit Integration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-MqtDMzUAHbe76XLkhgzQ.png" /><figcaption>Suggestion by CodeRabbit</figcaption></figure><p>One of the best decisions we made was <strong>integrating GitHub with CodeRabbit</strong>, which has drastically improved our code review process. Every time a <strong>pull request (PR)</strong> is created or updated, CodeRabbit automatically analyzes the changes and provides instant feedback on potential issues, code smells, and areas where best practices can be applied. This not only helps us catch minor mistakes early but also speeds up the review cycle by allowing our human reviewers to focus on more complex logic and architectural concerns. Plus, since CodeRabbit works directly within GitHub, we get real-time feedback without leaving the platform, making the whole process seamless and efficient.</p><p>With <strong>CodeRabbit handling the initial review</strong>, we’ve reduced a lot of manual effort, ensuring <strong>faster, more consistent reviews</strong> while maintaining high code quality. It enforces coding standards across the team and helps us keep the codebase clean and optimized. Overall, this integration has boosted our productivity, and we’re already seeing noticeable improvements in the speed and quality of our development pipeline. 🚀</p><h3>Github PR and Discord Integration</h3><p>No direct notification when a PR is being made? Integrating GitHub Pull Requests (PRs) with Discord can be a great way to keep your team notified about code changes directly in your Discord channels. There are several ways to achieve this integration, but the most common and straightforward method is to use a GitHub webhook to send PR notifications to a Discord channel.</p><p>Here’s a step-by-step guide on how to integrate GitHub PR with Discord using a webhook:</p><h4>Step 1: Create a Discord Webhook</h4><p><strong>1. Open Discord and Go to Your Server</strong>:</p><ul><li>Navigate to the server you want the PR notifications to appear in.</li></ul><p><strong>2. Create a Webhook</strong>:</p><ul><li>Go to your channel settings (click on the gear icon next to the channel name).</li><li>Under <strong>Integrations</strong>, click <strong>Webhooks</strong>.</li><li>Click <strong>Create Webhook</strong>.</li><li>Name your webhook (e.g., “GitHub PR Notifications”).</li><li>Choose the channel you want to send the PR notifications to.</li><li>Click <strong>Copy Webhook URL</strong>. You’ll need this URL for the GitHub webhook.</li></ul><h4>Step 2: Set Up GitHub Webhook for PR Events</h4><p><strong>1. Go to Your GitHub Repository</strong>:</p><ul><li>Open the repository where you want to integrate the PR notifications with Discord.</li></ul><p><strong>2. Access Repository Settings</strong>:</p><ul><li>Navigate to the <strong>Settings</strong> tab of the repository.</li><li>Scroll down to <strong>Webhooks</strong> (in the left-hand sidebar under <strong>Options</strong>).</li></ul><p><strong>3. Create a New Webhook</strong>:</p><ul><li>Click on <strong>Add webhook</strong>.</li></ul><p><strong>4. Configure the Webhook</strong>:</p><ul><li><strong>Payload URL</strong>: Paste the webhook URL you copied from Discord.</li><li><strong>Content type</strong>: Set it to application/json.</li></ul><p><strong>5. Which events would you like to trigger this webhook?:</strong></p><ul><li>Select <strong>Let me select individual events</strong>.</li><li>Choose <strong>Pull requests</strong> and any other events you want to track.</li><li>Leave <strong>Active</strong> selected so the webhook is live.</li></ul><p><strong>6. Save the Webhook</strong>:</p><ul><li>Click <strong>Add webhook</strong> to save the configuration.</li></ul><h4>Step 3: Test the Integration</h4><p><strong>1. Create a Pull Request</strong>:</p><ul><li>Once the webhook is configured, create a pull request in your GitHub repository.</li></ul><p><strong>2. Check Discord</strong>:</p><ul><li>Go to the Discord channel where you set up the webhook.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*9yo3yBATnDBRzj_acui_lA.png" /><figcaption>Discord Integration with Github Pull Request</figcaption></figure><p>You should see a message notifying you about the pull request creation or updates, such as when it is opened, closed, merged, or when there is a comment on it.</p><h3>Final Thoughts: It’s All About Collaboration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*LYIgi0R3fivJmtLRDkzUMw.png" /><figcaption>Source: <a href="https://images.app.goo.gl/yqJJpFZtu5CWWnwP8">https://images.app.goo.gl/yqJJpFZtu5CWWnwP8</a></figcaption></figure><p>Working in a team can be tricky, but with the right tools and practices, it becomes a whole lot more enjoyable. Jira helps you plan and track, Git-based reviews keep communication contextual, and your daily stand-ups make sure no one’s isolated away in their own corner. Before you know it, you’ll be delivering features faster and with fewer “Oh no, how did we miss that?” moments. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=515ef1272a05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test-Driven Development (TDD): The Secret Sauce for Bug-Free Code ]]></title>
            <link>https://medium.com/@bryantjandra2003/test-driven-development-tdd-the-secret-sauce-for-bug-free-code-c4f9befb1f5f?source=rss-ef9ddc2bbc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4f9befb1f5f</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Bryan Tjandra]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 05:33:29 GMT</pubDate>
            <atom:updated>2025-04-28T08:35:56.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*aqAoxMSZQO0tco9G-5qLNg.jpeg" /><figcaption>Source: <a href="https://devrant.com/rants/1545210/do-you-follow-test-driven-development">https://devrant.com/rants/1545210/do-you-follow-test-driven-development</a></figcaption></figure><h3>✨Introduction: Why Should You Care About TDD?</h3><p>Imagine launching a rocket without testing if it actually flies. Sounds risky, right? That’s exactly what happens when developers write code without testing first. <strong>Test-Driven Development (TDD) </strong>is the game-changing approach that helps you write clean, bug-free code from the start.</p><p>So, if you’re tired of fixing the same bugs over and over again, let’s dive into TDD and see how it can make your life as a developer <strong>way easier</strong>. 🎉</p><h3>✨ What is Test-Driven Development (TDD)?</h3><figure><img alt="Source: https://www.nimblework.com/agile/test-driven-development-tdd/" src="https://cdn-images-1.medium.com/max/489/1*msgBFnUNfeyI7Y98m1sBdA.jpeg" /><figcaption>Source: <a href="https://www.nimblework.com/agile/test-driven-development-tdd/">https://www.nimblework.com/agile/test-driven-development-tdd/</a></figcaption></figure><p>Think of TDD as <strong>writing the exam before attending the class</strong>. You write tests first, then build code to pass them. Here’s the simple <strong>Red-Green-Refactor</strong> cycle that makes TDD tick:</p><pre>+---------+       +--------+       +------------+<br>|  Write  | ----&gt; |  Make  | ----&gt; |  Refactor  |<br>|  Test   |       |  Pass  |       |    Code    |<br>|  (Red)  |       | (Green)|       | (Same Tests|<br>+---------+       +--------+       +------------+</pre><p>📌 <strong>Write a failing test</strong> → Red ❌<br>📌 <strong>Write just enough code to pass</strong> → Green ✅<br>📌 <strong>Refactor to clean things up</strong> → Polish &amp; Repeat 🔄</p><h4>✅ Why Write Tests First?</h4><p>This method forces you to think before you code, ensuring that your software works as expected <strong>before it’s deployed</strong>. No more last-minute bug hunts! 🐛</p><h4>✨ Why Should You Use TDD? (Hint: It Saves Your Sanity!)</h4><p>✅ <strong>Fewer Bugs, Less Stress</strong> — Catching bugs early prevents late night debugging marathons. <br>✅ <strong>Confidence Boost</strong> — You’ll always know your code works. No more “fingers crossed” deployments. <br>✅ <strong>Easier Maintenance</strong> — Your future self will thank you for writing clean, testable code. <br>✅ <strong>Faster Debugging</strong> — When something breaks, your tests point straight to the problem. <br>✅ <strong>Works Great with CI/CD</strong> — Perfect for automating tests and ensuring smooth deployments.</p><h3>🎯 How to Apply TDD Like a Pro</h3><p>Here’s a roadmap to getting started with TDD in your projects:</p><h4>🟢 Step 1: Start Small (Unit Testing Basics)</h4><ul><li>Pick a simple function (like adding two numbers).</li><li>Write a test before writing the function itself.</li><li>Run the test (it should fail — because there’s no function yet!).</li><li>Write the function and re-run the test until it passes.</li></ul><h4>🔵 Step 2: Apply TDD to Multiple Features</h4><ul><li>Expand TDD to at least <strong>three features</strong> in your project.</li><li>Include <strong>positive and negative test cases</strong> (what happens when things go wrong?).</li><li>Commit frequently so you can track changes.</li></ul><h4>🔴 Step 3: Achieve Mastery</h4><ul><li>Aim for <strong>90%+ test coverage</strong> on critical features.</li><li>Handle <strong>corner cases</strong> (unexpected inputs, failures, etc.).</li><li>Integrate monitoring and automated testing tools.</li><li>Reflect on how TDD improves your workflow.</li></ul><h3>🏆 Real-World Challenges (and How to Overcome Them!)</h3><p>🚧 <strong>“TDD Takes Too Much Time”</strong><br>✅ Truth: It feels slow at first, but you save hours debugging later. Think long-term! 🕰️</p><p>🚧 <strong>“Writing Tests is Boring”</strong><br>✅ Truth: Would you rather write tests now or fix the same bug <em>five times</em> later? 🤯</p><p>🚧 <strong>“I Don’t Know Where to Start”</strong><br>✅ Truth: Start with small, testable functions. Gradually expand to full features. 🌱</p><h3>✨ Real-World Implementation: TDD in Action</h3><p>Let’s walk through a real use case: building a <strong>Document Parser</strong> to extract text from PDF and DOCX files using Python. We’ll follow the TDD approach and build it in layers.Implementation of PDF Text Extraction Using TDD</p><h4>The Problem</h4><p>We need a system that:</p><ul><li>Accepts file type and path.</li><li>Selects appropriate parser (PDF or DOCX).</li><li>Returns clean text.</li><li>Handles edge cases like empty files or corrupted documents.</li></ul><h4>1. Writing the Failing Tests (RED Phase)</h4><p>In TDD, <strong>you start by writing test cases that describe how the code should behave</strong>, even before the implementation exists.</p><p>Here is an example of how to create a test, I created a test before implementing the function, ensuring that the function fails since there’s no implementation yet.</p><pre>import pytest<br>from unittest.mock import patch, MagicMock<br>from app.utils.pdf_parser import extract_text_pdf<br><br>def test_parser_factory_pdf():<br>    &quot;&quot;&quot;✅ Ensure ParserFactory returns PDFParser when given &#39;pdf&#39;.&quot;&quot;&quot;<br>    parser = ParserFactory.get_parser(&quot;pdf&quot;)<br>    assert isinstance(parser, PDFParser)</pre><p>This test expects ParserFactory.get_parser(&quot;pdf&quot;) to return a PDFParser instance. Initially, it fails because ParserFactory may not even be defined yet.</p><p><strong>Real PDF or DOCX files are heavy dependencies</strong>. In TDD, we aim to keep tests <strong>isolated and fast</strong>, so we use <strong>mocking</strong>.</p><h4>2. What is Mocking?</h4><p><strong>Mocking</strong> replaces real objects (like file readers) with fake ones that simulate their behavior.</p><p>For example:</p><pre>@patch(&quot;pdfplumber.open&quot;, return_value=mock_pdf_with_text)<br>def test_extract_text_pdf_with_text(mock_pdf_with_text):<br>    parser = PDFParser()<br>    result = parser.extract_text(&quot;dummy.pdf&quot;)<br>    assert result == &quot;Sample extracted text from PDF&quot;</pre><p>Instead of opening a real PDF, we simulate it using mock_pdf_with_text.</p><h4>🔧 Fixtures</h4><p>We define <strong>pytest fixtures</strong> to reuse common mock setups:</p><pre>@pytest.fixture<br>def mock_pdf_with_text():<br>    mock_pdf = MagicMock()<br>    mock_page = MagicMock()<br>    mock_page.extract_text.return_value = &quot;Sample extracted text from PDF&quot;<br>    mock_pdf.pages = [mock_page]<br>    mock_pdf.__enter__.return_value = mock_pdf<br>    return mock_pdf</pre><p>Fixtures allow tests to remain <strong>clean, readable</strong>, and <strong>reusable</strong>.</p><h4>3. Testing Error Handling &amp; Edge Cases</h4><p>When building a robust document parser, it’s not enough to just test the <em>happy path</em> — the cases where everything works perfectly. Real-world data is messy. Users upload corrupted files, unsupported formats, or even completely blank documents. By using <strong>Test-Driven Development (TDD)</strong>, we ensure our parser gracefully handles these edge cases with meaningful error messages.</p><p>Let’s break down what we’re testing:</p><ul><li><strong>Missing Files</strong><br> When a file doesn’t exist, pdfplumber.open throws a FileNotFoundError. We catch this and return a user-friendly message (❌ File PDF tidak ditemukan), preventing the app from crashing unexpectedly.</li></ul><pre>def test_extract_text_pdf_file_not_found():<br>    with patch(&quot;pdfplumber.open&quot;, side_effect=FileNotFoundError(&quot;File not found&quot;)):<br>        parser = PDFParser()<br>        with pytest.raises(FileNotFoundError, match=&quot;❌ File PDF tidak ditemukan: File not found&quot;):<br>            parser.extract_text(&quot;missing.pdf&quot;)</pre><ul><li><strong>Corrupted PDFs</strong><br> A malformed or unreadable PDF can raise a ValueError. Our test confirms this scenario is handled with an appropriate response: ❌ PDF rusak atau tidak dapat diproses.</li></ul><pre>def test_extract_text_pdf_invalid_file():<br>    &quot;&quot;&quot;✅ Test handling of invalid/corrupt PDF file (ValueError).&quot;&quot;&quot;<br>    with patch(&quot;pdfplumber.open&quot;, side_effect=ValueError(&quot;Invalid PDF format&quot;)):<br>        parser = PDFParser()<br>        with pytest.raises(ValueError, match=&quot;❌ PDF rusak atau tidak dapat diproses: Invalid PDF format&quot;):<br>            parser.extract_text(&quot;corrupt.pdf&quot;)</pre><ul><li><strong>Unsupported File Formats</strong><br> Users might upload .txt, .xls, or other formats. Our ParserFactory test ensures that only .pdf and .docx files are accepted, guiding users with clear feedback.</li></ul><pre>def test_parser_factory_invalid_format():<br>    &quot;&quot;&quot;✅ Ensure ParserFactory raises an error for unsupported formats.&quot;&quot;&quot;<br>    with pytest.raises(ValueError, match=&quot;❌ Format txt tidak didukung! Hanya mendukung PDF dan DOCX.&quot;):<br>        ParserFactory.get_parser(&quot;txt&quot;)</pre><ul><li><strong>Empty Documents</strong><br> A PDF might technically “exist” but contain no extractable text. Instead of silently failing or returning None, we raise a clear ValueError: ❌ Failed to extract text from the document.</li></ul><pre>@pytest.fixture<br>def mock_pdf_no_text():<br>    &quot;&quot;&quot;Mock PDF file with no extractable text.&quot;&quot;&quot;<br>    mock_pdf = MagicMock()<br>    mock_pdf.__enter__.return_value = mock_pdf<br>    mock_page = MagicMock()<br>    mock_page.extract_text.return_value = None<br>    mock_pdf.pages = [mock_page]<br>    return mock_pdf<br><br>def test_extract_text_pdf_no_text(mock_pdf_no_text):<br>    &quot;&quot;&quot;✅ Test PDF with no extractable text should raise ValueError.&quot;&quot;&quot;<br>    with patch(&quot;pdfplumber.open&quot;, return_value=mock_pdf_no_text):<br>        parser = PDFParser()<br>        <br>        with pytest.raises(ValueError) as exc_info:<br>            parser.extract_text(&quot;dummy.pdf&quot;)<br>        assert &quot;❌ Failed to extract text from the document.&quot; in str(exc_info.value)</pre><p>By simulating these scenarios with <strong>mocking and patching</strong>, we can test the behavior of our system <em>without needing real broken files</em>. This makes our test suite faster, more reliable, and easier to maintain.</p><h4>4. Applying SOLID Principles</h4><p>Even though we’re focused on testing, our implementation also adheres to good software design:</p><ul><li><strong>S (Single Responsibility)</strong>: ParserFactory only creates parsers.</li><li><strong>O (Open/Closed)</strong>: You can extend the parser by adding TXTParser, without modifying existing logic.</li><li><strong>D (Dependency Inversion)</strong>: Code relies on the abstract DocumentParser, not specific implementations.</li></ul><p>This architecture makes testing <strong>easier</strong>, since components are <strong>decoupled and replaceable.</strong></p><h4><strong>5. Writing the Function (GREEN Phase)</strong></h4><p>After defining the test cases (RED phase), it’s time to write the actual implementation that makes those tests pass — this is the <strong>GREEN phase</strong> of TDD. At this point, we focus on <strong>getting it to work</strong>, not necessarily making it perfect.</p><p>We begin with a basic working version of the parser functions:</p><ul><li>extract_text_from_pdf() handles PDF parsing using pdfplumber</li><li>extract_text_from_docx() uses the python-docx library for .docx files</li><li>The dispatcher function extract_text() decides which function to call based on file type</li></ul><pre>import pdfplumber<br>import docx<br><br>def extract_text_from_pdf(file_path: str) -&gt; str:<br>    with pdfplumber.open(file_path) as pdf:<br>        extracted_text_list = [page.extract_text() for page in pdf.pages if page.extract_text()]<br>        extracted_text = &quot;\n&quot;.join(extracted_text_list)<br>        return extracted_text.strip()<br><br>def extract_text_from_docx(file_path: str) -&gt; str:<br>    doc = docx.Document(file_path)<br>    extracted_text = &quot;\n&quot;.join([para.text for para in doc.paragraphs if para.text.strip()])<br>    return extracted_text<br><br>def extract_text(file_path: str, file_type: str) -&gt; str:<br>    file_type = file_type.lower()<br>    if file_type == &quot;pdf&quot;:<br>        return extract_text_from_pdf(file_path)<br>    elif file_type == &quot;docx&quot;:<br>        return extract_text_from_docx(file_path)<br>    else:<br>        raise ValueError(f&quot;❌ Format {file_type} tidak didukung! Hanya mendukung PDF dan DOCX.&quot;)</pre><p>But while this gets the job done, <strong>it’s not enough</strong>. We still need to handle:</p><ul><li>Missing or unreadable files</li><li>Corrupted documents</li><li>Empty content</li><li>Duplicated logic</li><li>Poor error messaging</li></ul><p>Next, we enhanced the functions to catch and re-raise exceptions with <strong>clear, user-friendly messages, </strong>critical for debugging and UX. This is especially helpful when working with unpredictable user inputs.</p><pre>import pdfplumber<br>import docx<br><br>def extract_text_from_pdf(file_path: str) -&gt; str:<br>    try:<br>        with pdfplumber.open(file_path) as pdf:<br>            extracted_text_list = [page.extract_text() for page in pdf.pages if page.extract_text()]<br>            extracted_text = &quot;\n&quot;.join(extracted_text_list)<br>            if not extracted_text.strip():<br>                raise ValueError(&quot;❌ Failed to extract text from the document.&quot;)<br>            return extracted_text.strip()<br>    except FileNotFoundError as e:<br>        raise FileNotFoundError(f&quot;❌ File PDF tidak ditemukan: {str(e)}&quot;) from e<br>    except ValueError as e:  # Catch possible corrupted file issues<br>        raise ValueError(f&quot;❌ PDF rusak atau tidak dapat diproses: {str(e)}&quot;) from e<br>    except IOError as e:  # Catch I/O errors<br>        raise IOError(f&quot;❌ Kesalahan akses file PDF: {str(e)}&quot;) from e<br>    except Exception as e:<br>        raise RuntimeError(f&quot;❌ Terjadi kesalahan saat memproses PDF: {str(e)}&quot;) from e<br>  <br>def extract_text_from_docx(file_path: str) -&gt; str:<br>    try:<br>        doc = docx.Document(file_path)<br>        extracted_text = &quot;\n&quot;.join([para.text for para in doc.paragraphs if para.text.strip()])<br>        return extracted_text.strip() if extracted_text.strip() else &quot;❌ Gagal mengekstrak teks atau dokumen kosong.&quot;<br>    except FileNotFoundError as e:<br>        raise FileNotFoundError(f&quot;❌ File DOCX tidak ditemukan: {str(e)}&quot;) from e<br>    except IOError as e:<br>        raise IOError(f&quot;❌ Kesalahan akses file DOCX: {str(e)}&quot;) from e<br>    except ValueError as e:<br>        raise ValueError(f&quot;❌ File DOCX tidak valid: {str(e)}&quot;) from e<br>    except Exception as e:<br>        raise RuntimeError(f&quot;❌ Terjadi kesalahan saat memproses DOCX: {str(e)}&quot;) from e<br><br>def extract_text(file_path: str, file_type: str) -&gt; str:<br>    file_type = file_type.lower()<br>    if file_type == &quot;pdf&quot;:<br>        return extract_text_from_pdf(file_path)<br>    elif file_type == &quot;docx&quot;:<br>        return extract_text_from_docx(file_path)<br>    else:<br>        raise ValueError(f&quot;❌ Format {file_type} tidak didukung! Hanya mendukung PDF dan DOCX.&quot;)</pre><p>After writing the function, I ran the test using</p><pre>pytest tests/test_parsers.py -v</pre><p>and it passed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Qol8H2wP6EnEgfSZgKpjA.png" /><figcaption>An example of the test’s result</figcaption></figure><p>All tests passed, confirming that our code:</p><ul><li>Works as expected</li><li>Handles edge case</li><li>Is robust and reliable</li></ul><p><strong>Checking Test Coverage with </strong><strong>pytest-cov</strong></p><p><strong>1. Install pytest-cov:</strong> First, make sure you have the pytest-cov plugin installed. You can install it using pip if it&#39;s not already installed:</p><ul><li>pip install pytest-cov</li></ul><p><strong>2. Run pytest with coverage:</strong> To see the test coverage, you can use the --cov option with pytest. Here&#39;s how you can run it:</p><ul><li>pytest --cov=your_module tests/test_parsers.py -v</li></ul><p><strong>3.</strong> Replace your_module with the name of the module or package you want to measure the coverage for (e.g., pdf_parser.py or docx_parser.py).</p><p><strong>4. View Coverage Output:</strong> After running the above command, pytest will show the coverage summary in the terminal. It will display the percentage of lines covered by your tests and which parts of the code were not covered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*1WmaTClom7iNwghmUnoN2w.png" /><figcaption>Test coverage output</figcaption></figure><p>Explanation</p><ul><li><strong>Stmts:</strong> Total number of statements in the file.</li><li><strong>Miss:</strong> Number of statements not covered by tests.</li><li><strong>Cover:</strong> The percentage of statements that are covered by tests.</li></ul><h4>6. Refactoring (REFACTOR Phase)</h4><p>Now that our code works and passes the tests, we <strong>refactor</strong> it to make it:</p><ul><li>More <strong>readable</strong></li><li>Easier to <strong>extend</strong></li><li>Aligned with <strong>SOLID principles</strong></li></ul><pre>import pdfplumber<br>import docx<br>from abc import ABC, abstractmethod<br><br>class DocumentParser(ABC):<br>    &quot;&quot;&quot;Abstract class for document parsing (SOLID - Open/Closed Principle).&quot;&quot;&quot;<br>    @abstractmethod<br>    def extract_text(self, file_path: str) -&gt; str:<br>        &quot;&quot;&quot;Extracts text from a document file.&quot;&quot;&quot;<br>        raise NotImplementedError(&quot;Subclasses must implement `extract_text`.&quot;)<br><br>class PDFParser(DocumentParser):<br>    &quot;&quot;&quot;Concrete class for parsing PDF files.&quot;&quot;&quot;<br>    def extract_text(self, file_path: str) -&gt; str:<br>        try:<br>            with pdfplumber.open(file_path) as pdf:<br>                extracted_text_list = [page.extract_text() for page in pdf.pages if page.extract_text()]<br>                extracted_text = &quot;\n&quot;.join(extracted_text_list)<br>                if not extracted_text.strip():<br>                    raise ValueError(&quot;❌ Failed to extract text from the document.&quot;)<br>                return extracted_text.strip()<br>        except FileNotFoundError as e:<br>            raise FileNotFoundError(f&quot;❌ File PDF tidak ditemukan: {str(e)}&quot;) from e<br>        except ValueError as e:  # Catch possible corrupted file issues<br>            raise ValueError(f&quot;❌ PDF rusak atau tidak dapat diproses: {str(e)}&quot;) from e<br>        except IOError as e:  # Catch I/O errors<br>            raise IOError(f&quot;❌ Kesalahan akses file PDF: {str(e)}&quot;) from e<br>        except Exception as e:<br>            raise RuntimeError(f&quot;❌ Terjadi kesalahan saat memproses PDF: {str(e)}&quot;) from e<br><br>class DOCXParser(DocumentParser):<br>    &quot;&quot;&quot;Concrete class for parsing DOCX files.&quot;&quot;&quot;<br>    def extract_text(self, file_path: str) -&gt; str:<br>        try:<br>            doc = docx.Document(file_path)<br>            extracted_text = &quot;\n&quot;.join([para.text for para in doc.paragraphs if para.text.strip()])<br>            return extracted_text.strip() if extracted_text.strip() else &quot;❌ Gagal mengekstrak teks atau dokumen kosong.&quot;<br>        except FileNotFoundError as e:<br>            raise FileNotFoundError(f&quot;❌ File DOCX tidak ditemukan: {str(e)}&quot;) from e<br>        except IOError as e:<br>            raise IOError(f&quot;❌ Kesalahan akses file DOCX: {str(e)}&quot;) from e<br>        except ValueError as e:<br>            raise ValueError(f&quot;❌ File DOCX tidak valid: {str(e)}&quot;) from e<br>        except Exception as e:<br>            raise RuntimeError(f&quot;❌ Terjadi kesalahan saat memproses DOCX: {str(e)}&quot;) from e<br><br>class ParserFactory:<br>    &quot;&quot;&quot;Factory Pattern to create document parsers (SOLID - Single Responsibility Principle).&quot;&quot;&quot;<br>    @staticmethod<br>    def get_parser(file_type: str) -&gt; DocumentParser:<br>        file_type = file_type.lower()<br>        if file_type == &quot;pdf&quot;:<br>            return PDFParser()<br>        elif file_type == &quot;docx&quot;:<br>            return DOCXParser()<br>        else:<br>            raise ValueError(f&quot;❌ Format {file_type} tidak didukung! Hanya mendukung PDF dan DOCX.&quot;)</pre><h4>Explanation</h4><ol><li><strong>Abstract Base Class (</strong><strong>DocumentParser)</strong><br>Defines a consistent interface for all parsers, allowing easy extension in the future.</li><li><strong>Separate Parser Classes (</strong><strong>PDFParser, </strong><strong>DOCXParser)</strong><br>Each file type has its own implementation. This removes conditional logic from the main function and adheres to the <strong>Single Responsibility Principle</strong>.</li><li><strong>Factory Pattern (</strong><strong>ParserFactory)</strong><br>Handles parser selection based on file type, making the code more modular and testable.</li><li><strong>Centralized Error Handling</strong><br> Every possible exception is caught and wrapped with custom messages, reducing the chances of silent failures.</li></ol><h3>Writing “Good” Tests Using F.I.R.S.T Principles</h3><p>While achieving <strong>100% code coverage</strong> is a great milestone, it doesn’t automatically mean your tests are effective. Good tests go beyond simply covering every line, they should be <strong>high quality</strong>, and that’s where the <strong>F.I.R.S.T</strong> principle comes in. This acronym outlines five key characteristics every test should follow:</p><h4>🔹 F — Fast</h4><p>Your tests should run quickly. Slow tests create bottlenecks and reduce productivity, especially during continuous integration or development cycles. Fast tests provide faster feedback, which keeps developers in flow.</p><p>I have 19 test suites, each with multiple test cases, and all of them run in just 0.30 seconds. That’s the kind of speed you want for an efficient workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Qol8H2wP6EnEgfSZgKpjA.png" /><figcaption>Example of a fast test result</figcaption></figure><h4>🔹 I — Independent</h4><p>Each test should be <strong>self-contained</strong>, meaning it doesn’t rely on the output or state of other tests. This makes debugging easier and avoids cascading failures.</p><p><strong>Example:</strong></p><pre>def test_extract_text_pdf_with_text(mock_pdf_with_text):<br>    &quot;&quot;&quot;✅ Test PDF with extractable text.&quot;&quot;&quot;<br>    with patch(&quot;pdfplumber.open&quot;, return_value=mock_pdf_with_text):<br>        parser = PDFParser()<br>        extracted_text = parser.extract_text(&quot;dummy.pdf&quot;)<br>        assert extracted_text == &quot;Sample extracted text from PDF&quot;, f&quot;Unexpected output: {extracted_text}&quot;<br><br>def test_extract_text_pdf_no_text(mock_pdf_no_text):<br>    &quot;&quot;&quot;✅ Test PDF with no extractable text should raise ValueError.&quot;&quot;&quot;<br>    with patch(&quot;pdfplumber.open&quot;, return_value=mock_pdf_no_text):<br>        parser = PDFParser()<br>        <br>        with pytest.raises(ValueError) as exc_info:<br>            parser.extract_text(&quot;dummy.pdf&quot;)<br><br>        assert &quot;❌ Failed to extract text from the document.&quot; in str(exc_info.value)<br><br>def test_extract_text_pdf_multi_page(mock_pdf_multi_page):<br>    &quot;&quot;&quot;✅ Test PDF with multiple pages.&quot;&quot;&quot;<br>    with patch(&quot;pdfplumber.open&quot;, return_value=mock_pdf_multi_page):<br>        parser = PDFParser()<br>        extracted_text = parser.extract_text(&quot;dummy.pdf&quot;)<br>        expected_text = &quot;Page 1 content\nPage 2 content&quot;<br>        assert extracted_text == expected_text, f&quot;Unexpected output: {extracted_text}&quot;</pre><p>Each test here can run independently and doesn’t rely on another’s result.</p><h4>🔹 R — Repeatable</h4><p>Tests should always return the <strong>same result</strong>, no matter when or where they are run. Randomness, time-based logic, or external dependencies can make tests flaky and unreliable.</p><p><strong>Bad Example:</strong></p><pre>def generate_random_number(minimum, maximum):<br>    return random.randint(minimum, maximum)<br><br>def test_generate_random_number():<br>    assert 50 &lt;= generate_random_number(0, 100) &lt;= 100</pre><p>This test can randomly fail, since numbers below 50 are possible. To make it repeatable, you’d need to control the randomness (e.g., with mocking or seeding).</p><h4>🔹 S — Self-Validating</h4><p>A test should automatically determine if it passes or fails — no manual checking required. Assertions like assertEqual, assert, or pytest.raises() help you meet this principle.</p><p>If a test fails, you’ll get clear output showing <strong>what went wrong</strong> and <strong>where</strong> — no need for manual inspection.</p><h4>🔹 T — Thorough</h4><p>Your tests should cover not just every line of code, but also <strong>all meaningful cases, </strong>including edge cases and failure scenarios. Just hitting 100% coverage isn’t enough if you haven’t tested what really matters.</p><p>For example:<br> When testing an input range, test not just normal values, but also boundaries, nulls, unsupported formats, and corrupted files (as demonstrated earlier in this blog).</p><h3>Monitoring Code Coverage with SonarQube</h3><p>To continuously monitor and improve the <strong>code coverage</strong> of your project, <strong>SonarQube</strong> is an excellent tool. It provides a detailed analysis of your codebase, including which lines are covered by tests and which are not. Below is an example of what the <strong>SonarQube dashboard</strong> can look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLfwerCwisNThmEEvhhVTw.png" /></figure><ul><li><strong>Clickable Folders</strong>: When you click on the folder name, SonarQube will show detailed coverage for each file, highlighting lines that are not tested.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXEguNcJKtEeyySM9pm48w.png" /></figure><ul><li><strong>Green Indicators</strong>: These show lines of code that are already covered by tests.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbCUkF7QA8VEaCUlu1T0Vw.png" /></figure><p>By integrating <strong>SonarQube</strong> into your CI/CD pipeline, you can easily track code coverage and take action to improve it. Here’s how to set it up:</p><h4>Setting Up Coverage Reporting with pytest and Cobertura Format</h4><p>In the project, the <strong>coverage report</strong> is generated in <strong>Cobertura XML format</strong>, and SonarQube uses this format for its analysis. Here’s how your <strong>.coveragerc</strong> configuration file is set up for coverage:</p><pre>[html]<br>directory = coverage<br><br>[xml]<br>output = coverage.xml  # The Cobertura-format XML report<br>[run]<br>concurrency = multiprocessing<br>parallel = true<br>sigterm = true<br>omit = tests/*  # Exclude test files from coverage analysis<br>[report]<br>exclude_lines = <br>    if __name__ == .__main__.:<br>    return<br>    def fetch_deepseek_response<br>    def deepseek_stream_response<br>    @field_validator<br>    deepseek_payload<br>omit = tests/*</pre><p>This configuration ensures that your tests are run with multiprocessing and parallelism, and it generates the <strong>coverage.xml</strong> file which SonarQube uses for its code coverage analysis.</p><h4>GitHub Actions CI Configuration</h4><p>The <strong>GitHub Actions</strong> workflow handles the integration of your tests and SonarQube analysis. Below is an explanation of how this works, using your sonar.yaml configuration.</p><h4>GitHub Actions Workflow (sonar.yaml):</h4><pre>name: Running Test &amp; Code Analysis<br>on:<br>  push:<br>    branches:<br>      - &#39;!master&#39;<br>      - &#39;!staging&#39;<br>  pull_request:<br>    types: [opened, synchronize, reopened]<br>jobs:<br>  build:<br>    name: Build and analyze<br>    runs-on: ubuntu-latest<br>    <br>    steps:<br>      - uses: actions/checkout@v4<br>        with:<br>          fetch-depth: 0  # Ensure complete history for analysis<br>      - name: Set up Python<br>        uses: actions/setup-python@v1<br>        with:<br>          python-version: 3.12<br>      - name: Install dependencies<br>        run: |<br>          python -m pip install --upgrade pip<br>          pip install -r requirements.txt<br>        run: pytest --cov=. --cov-config=.coveragerc --cov-report xml  # Run tests and generate coverage report<br>        continue-on-error: false<br>      - uses: SonarSource/sonarqube-scan-action@v4<br>        env:<br>          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}<br>          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}</pre><h4>Key Details:</h4><ul><li><strong>Run Tests (</strong><strong>pytest)</strong>:<br> The command pytest --cov=. --cov-config=.coveragerc --cov-report xml runs your tests, collects coverage data, and generates a coverage.xml file in <strong>Cobertura</strong> format.</li><li><strong>SonarQube Scan</strong>:<br> After tests are complete, the SonarQube scan is triggered using SonarSource/sonarqube-scan-action. It takes the <strong>coverage.xml</strong> file generated in the test phase and uploads it to <strong>SonarQube</strong> for analysis.</li></ul><h4>SonarQube Project Properties</h4><p>The <strong>SonarQube</strong> configuration file (sonar-project.properties) links the <strong>coverage.xml</strong> report to the analysis and excludes test files from being analyzed directly:</p><pre>sonar.projectKey=navigo-ppl<br>sonar.python.coverage.reportPaths=coverage.xml  # Path to the coverage report<br>sonar.coverage.exclusions=**/*.test_*.py  # Exclude test files from coverage analysis<br>sonar.exclusions=**/*.test_*.py  # Exclude test files from the overall analysis<br>sonar.sources=app  # The source directory to analyze<br>sonar.tests=tests  # The tests directory</pre><ul><li><strong>Coverage Report</strong>: The <strong>coverage.xml</strong> file is referenced here, pointing SonarQube to the generated test coverage data.</li><li><strong>Exclusions</strong>: The test files are excluded from the overall analysis to avoid double-counting or unnecessary analysis on testing code.</li></ul><h4>SonarQube Dashboard: Tracking Coverage</h4><p>Once integrated, SonarQube will generate a <strong>detailed coverage report</strong> in the dashboard. This includes:</p><ul><li><strong>Coverage by File</strong>: Each file’s coverage percentage is shown, helping you understand which parts of your codebase need more tests.</li><li><strong>Uncovered Lines</strong>: SonarQube highlights lines that are not covered by tests, allowing you to quickly identify weak spots in your test coverage.</li><li><strong>Green Indicators</strong>: Lines with green indicators are covered, giving you a visual representation of your test effectiveness.</li></ul><h4>Continuous Integration and Monitoring</h4><p>By integrating <strong>SonarQube</strong> into your <strong>CI/CD pipeline</strong>, you ensure that every push or pull request is automatically analyzed for <strong>test coverage</strong> and <strong>code quality</strong>. With each change, SonarQube helps track whether new code is properly tested and provides actionable insights for improvement</p><h3>Property-Based Testing (fast-check + testing)</h3><p>Wanna dive into a more advanced and useful topic? Here is one interesting insight that you can apply in your project. Let me introduce you to Property Based Testing. Why?</p><p>Imagine your RiskItem component works for the one fixture you wrote, but silently breaks on weird Unicode or several titles. Example-based tests guard a handful of paths, but property tests are better, it can assert <strong>invariants</strong> over <strong>all</strong> inputs and let a smart fuzzer find the holes.</p><p>Here are the differences</p><ol><li>Example-based test<br> • You choose several 1–3 inputs (e.g. risk-1) and assert outputs.</li><li>Property-based test<br> • You describe a <strong>rule</strong> that must hold for <strong>all</strong> possible inputs, and a generator makes hundreds of random cases for you.<br> • When a case fails, fast-check “shrinks” it to the smallest counter-example so you can reproduce the bug.</li></ol><p>Think of it as a fuzzer with brains: it keeps only the inputs that violate your property and minimises them so the failing spec stays readable.</p><h3>Wiring fast-check into a Vitest / React stack</h3><pre>pnpm add -D fast-check @fast-check/vitest</pre><p>In your vitest.config.ts (or setup file)</p><pre>// setupTests.ts<br>import &#39;@testing-library/jest-dom&#39;;   // usual RTL matchers<br>import &#39;@fast-check/vitest&#39;;         // adds .toSatisfyProperty, etc.</pre><h4>Step 1 : Model an Arbitrary for RiskyClause</h4><pre>// test/arbitraries/riskyClauseArb.ts<br>import fc from &#39;fast-check&#39;;<br>import type { RiskyClause } from &#39;@/store/useMouStore&#39;;<br><br>// ---- helpers ----------------------------------------------------<br>const shortTxt = (min = 1, max = 250) =&gt;<br>  fc.string({ minLength: min, maxLength: max });<br><br>// small chance of collision with our “Expand” button text<br>const titleArb = fc.oneof(<br>  fc.constant(&#39;Expand&#39;),<br>  fc.constant(&#39;Collapse&#39;),<br>  fc.constantFrom(...Array(20).fill(null).map(() =&gt; shortTxt(1, 60))),<br>).map(value =&gt; String(value));<br><br>// small chance of collision with our “Applied” button text<br>const revisedArb = fc.oneof(<br>  fc.constant(&#39;Applied&#39;),<br>  fc.constant(&#39;Apply Suggestion&#39;),<br>  fc.constantFrom(...Array(20).fill(null).map(() =&gt; fc.option(shortTxt(), { nil: &#39;&#39; }))),<br>).map(value =&gt; String(value));<br><br>export const riskyClauseArb: fc.Arbitrary&lt;RiskyClause&gt; = fc.record({<br>  id: fc.uuid().map(id =&gt; `risk-${id}`),<br>  sectionNumber: fc.integer({ min: 1, max: 999 }),<br>  title: titleArb,<br>  originalClause: shortTxt(),<br>  reason: shortTxt(),<br>  currentClause: shortTxt(),<br>  revisedClause: revisedArb,<br>  applied: fc.boolean(),<br>});</pre><p>fc.record guarantees every generated object is structurally valid; you can plug in stricter business rules later (.filter).</p><p><strong>Why there are collisions of several Input values?</strong> To prove your tests won’t be fooled if a title accidentally matches a button’s label.</p><h4>Step 2 : Rewrite your tests as properties</h4><pre>import { render, screen, fireEvent } from &#39;@testing-library/react&#39;;<br>import { vi, expect, describe, it } from &#39;vitest&#39;;<br>import RiskItem from &#39;./RiskItem&#39;;<br>import { riskyClauseArb } from &#39;./../__test__/arbitraries/riskyClauseArb&#39;;<br>import { RiskyClause } from &#39;@/store/useMouStore&#39;;<br>import fc from &#39;fast-check&#39;;<br>import { within } from &#39;@testing-library/react&#39;<br><br>describe(&#39;RiskItem – property tests&#39;, () =&gt; {<br>  // run 100 examples (default); bump in CI if you want harder fuzzing<br>  fc.configureGlobal({ numRuns: 100 });<br><br>  /* ❶ Checkbox toggle must call onSelect(risk.id, !isSelected) */<br>  it(&#39;always toggles correctly&#39;, () =&gt; {<br>    fc.assert(<br>      fc.property(riskyClauseArb, fc.boolean(), (risk: RiskyClause, isSel) =&gt; {<br>        const onSelect = vi.fn();<br>        const { container, unmount } = render(<br>          &lt;RiskItem<br>            risk={risk}<br>            isSelected={isSel}<br>            onSelect={onSelect}<br>            onRevise={vi.fn()}<br>            onApply={vi.fn()}<br>            isLoading={false}<br>          /&gt;<br>        );<br><br>        // only look inside *this* container<br>        fireEvent.click(within(container).getByRole(&#39;checkbox&#39;));<br>        expect(onSelect).toHaveBeenCalledOnce();<br>        expect(onSelect).toHaveBeenCalledWith(risk.id, !isSel);<br><br>        unmount();  // clean up before the next iteration<br>      })<br>    );<br>  });<br><br>  /* ❷ If risk.applied === true, the “Applied” button must be disabled */<br>  it(&#39;disables Apply when already applied&#39;, () =&gt; {<br>    fc.assert(<br>      fc.property(<br>        riskyClauseArb.filter(r =&gt; r.revisedClause !== &#39;&#39;),<br>        fc.boolean(),<br>        (risk: RiskyClause, isSel: boolean) =&gt; {<br>          risk.applied = true;<br><br>          // ① render returns { container, unmount }<br>          const { container, unmount } = render(<br>            &lt;RiskItem<br>              risk={risk}<br>              isSelected={isSel}<br>              onSelect={vi.fn()}<br>              onRevise={vi.fn()}<br>              onApply={vi.fn()}<br>              isLoading={false}<br>            /&gt;<br>          );<br><br>          // ② scope queries to this render only<br>          fireEvent.click(within(container).getByText(&#39;Expand&#39;));<br>          const appliedBtn = within(container).getByText(&#39;Applied&#39;);<br>          expect(appliedBtn).toBeDisabled();<br><br>          // ③ clean up this iteration<br>          unmount();<br>        }<br>      )<br>    );<br>  });<br><br>  it(&#39;shows loader placeholder&#39;, () =&gt; {<br>    fc.assert(<br>      fc.property(<br>        riskyClauseArb.filter(r =&gt; r.revisedClause === &#39;&#39;),<br>        fc.boolean(),<br>        (risk, isSel) =&gt; {<br>          const { container, unmount } = render(<br>            &lt;RiskItem<br>              risk={risk}<br>              isSelected={isSel}<br>              onSelect={vi.fn()}<br>              onRevise={vi.fn()}<br>              onApply={vi.fn()}<br>              isLoading={true}<br>            /&gt;<br>          );<br>  <br>          // limit queries to *this* render only<br>          fireEvent.click(within(container).getByText(&#39;Expand&#39;));<br>          expect(<br>            within(container).getByText(/Generating revision/i)<br>          ).toBeInTheDocument();<br>  <br>          unmount();           // clean up after this case<br>        }<br>      )<br>    );<br>  });<br>});</pre><h3>What changed?</h3><ol><li><strong>No hard-coded fixtures</strong> — every run uses fresh, randomly generated RiskyClauses and both true/false selections.</li><li><strong>Focus on invariants</strong> — rules that must <em>always</em> hold, not individual snapshots.</li><li><strong>Automatic edge-cases</strong> — fast-check will generate:<br> • empty titles,<br> • very long strings,<br> • non-ASCII chars,<br> • weird unicode sequences, etc.</li></ol><h4>Seeing shrinking in action</h4><p>Suppose your UI breaks for titles longer than 120 chars. Delete the maxLength: 40 guard above and re-run the suite:</p><pre>✖ property failed after 17 tests<br>Counter-example (shrunk 6 times):<br>{ title: &quot;aaaaaaaaaaaaaaaa… (121 a’s) …aaa&quot; }</pre><p>Fast-check gives you the <strong>minimal</strong> failing input so you can reproduce the bug with one deterministic case.</p><p>Total runtime barely changes; fast-check streams cases, so 100 runs of a light component are measured in milliseconds.</p><p>Now, Remove the maxLength: 60 guard on titleArb and re-run. Copy that case into a new example test, fix your UI, and watch the property suite turn green.</p><p>The result, boom:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3moLz7Wxnxk6UYtfDY6DA.png" /></figure><p>In conclusion, why do you need these property test data is because</p><ul><li><strong>Real-world data is messy.</strong> You’ll catch the Unicode, boundary, and collision bugs you’d never manually cover.</li><li><strong>Faster feedback loops.</strong> Failures point to the minimal counter-example — no more digging through hundreds of lines of logs.</li><li><strong>Stronger guarantees.</strong> Your “invariants” become your living documentation, enforced on every commit.</li></ul><p>Thus, covering all possibilities of your test case is necessary and can reduce further bug in your code.</p><h3>Benefits of Test-Driven Development (TDD)</h3><p>In my opinion, Test-Driven Development (TDD) offers several advantages for developers. One of the key benefits is how it simplifies debugging. By writing unit tests for every new method you develop, you can catch bugs early in the process. This proactive approach helps prevent larger issues from arising later, which could otherwise affect the entire program. As a result, TDD reduces the time spent on unnecessary debugging, allowing for faster development and increased productivity. Ultimately, it leads to more maintainable code and a more efficient workflow.</p><h3>Conclusion: TDD = Better Code, Happier Developers</h3><p>Test-Driven Development isn’t just a concept, it’s a <strong>superpower</strong> for developers who want to write solid, bug-free code. By involving TDD, you’ll <strong>spend less time fixing bugs</strong> and more time <strong>building awesome software</strong>. 🚀</p><p>So, what are you waiting for? Give TDD a try, and watch your development game level up! 🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4f9befb1f5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>