<?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 Alvaro Luqman on Medium]]></title>
        <description><![CDATA[Stories by Alvaro Luqman on Medium]]></description>
        <link>https://medium.com/@alvaro.luqman?source=rss-9fbfc9137678------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yMelXX1TXI_YHGei</url>
            <title>Stories by Alvaro Luqman on Medium</title>
            <link>https://medium.com/@alvaro.luqman?source=rss-9fbfc9137678------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:08:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alvaro.luqman/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[Security Analysis of PantauTular Project]]></title>
            <link>https://medium.com/@alvaro.luqman/security-analysis-of-pantautular-project-8ad7cf557b64?source=rss-9fbfc9137678------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ad7cf557b64</guid>
            <dc:creator><![CDATA[Alvaro Luqman]]></dc:creator>
            <pubDate>Wed, 28 May 2025 08:43:43 GMT</pubDate>
            <atom:updated>2025-05-28T11:36:47.899Z</atom:updated>
            <content:encoded><![CDATA[<p>In developing the PantauTular project — a web application designed to visualize disease outbreaks across Indonesia — security is a foundational pillar. It is crucial that the application is built with robust security measures. This article presents a security analysis of the project, benchmarking its architecture and implementation against the OWASP Top 10, the industry standard for identifying critical web application security risks.</p><h3>OWASP Top 10 Application</h3><p>Benchmarking my application’s security infrastructure to OWASP’s Top 10 helps identify potential vulnerabilities early in the development lifecycle. Each of the top 10 security risks — ranging from injection attacks to broken access control — serves as a checkpoint to assess PantauTular’s resilience against common and critical threats. The following section maps the top 3 significant OWASP categories to relevant features or components in the PantauTular system, analyzing whether the necessary countermeasures are in place or if improvements are needed.</p><h3>Broken Access Control: Configuring Cross-Origin Resource Sharing</h3><p>In the ever-evolving landscape of web security, Cross-Origin Resource Sharing (CORS) configuration plays a crucial role in protecting web applications from potential security threats. This section focuses on how proper CORS configuration in the Django application aligns with OWASP Top 10 security principles, particularly addressing Broken Access Control (A01:2021)</p><p>The application implements a robust CORS configuration that demonstrates security best practices:</p><pre>CORS_ALLOWED_ORIGINS = [<br>    &quot;https://pantautular.netlify.app&quot;,<br>]</pre><p>The current configuration implements a strict allowlist approach, which is a fundamental security principle. By explicitly defining allowed origins, we prevent unauthorized domains from making requests to our API, even if they have access to our API key. This is particularly important because,</p><ul><li>It prevents malicious websites from making unauthorized API calls to our backend</li><li>It reduces the risk of Cross-Site Request Forgery (CSRF) attacks</li><li>It ensures that only trusted domains can interact with our application’s resources</li></ul><p>Here’s a new polished section you can directly add to your Medium article under a new heading. It aligns your CSP implementation with the OWASP Top 10, highlights your proactive approach, and complements the existing section on CORS and Broken Access Control:</p><h3>Injection Mitigation and Security Misconfiguration: Implementing a Content Security Policy (CSP)</h3><p>In addition to safeguarding against Broken Access Control, the <strong>PantauTular</strong> project takes active steps to address two other critical categories from the <a href="https://owasp.org/Top10/">OWASP Top 10</a> — namely, <strong>A03:2021 — Injection</strong> and <strong>A05:2021 — Security Misconfiguration</strong>. One of the most effective measures taken to counter these threats was the implementation of a <strong>Content Security Policy (CSP)</strong> header in the backend.</p><h4>Why CSP Matters in OWASP Context</h4><p>CSP is a defense-in-depth mechanism that reduces the risk of <strong>Cross-Site Scripting (XSS)</strong>, which falls under the broader category of injection attacks. By restricting which content sources are trusted and executable, CSP mitigates malicious script execution even in cases where input sanitization may fail. Therefore:</p><ul><li>Under <strong>A03:2021 — Injection</strong>, CSP helps <strong>contain the damage</strong> of XSS attacks by preventing the browser from loading or executing untrusted scripts.</li><li>Under <strong>A05:2021 — Security Misconfiguration</strong>, failing to implement headers like CSP is a common oversight. By including CSP in our HTTP response headers, we proactively close off that avenue of attack.</li></ul><h4>How It Was Implemented</h4><p>Using the insights provided by <strong>Aikido Security</strong>, a DAST (Dynamic Application Security Testing) scan identified that our application lacked a CSP header — a critical gap that could leave it open to client-side attacks like data theft, session hijacking, or malware distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*aczag2X5-u5evgQt.png" /></figure><p>To resolve this, a properly scoped CSP header was added to the backend, explicitly defining safe sources for scripts, styles, and other resources. The implementation commits can be found here:</p><ul><li><a href="https://github.com/PPL-BRIN/pantautular-be/commit/67b855233d70b821b827d566e6229b6e374ddfe9">CSP header addition — part 1</a></li><li><a href="https://github.com/PPL-BRIN/pantautular-be/commit/f4cd53e293d8502e8dd50765ef62671ad8407e53">CSP header refinement — part 2</a></li></ul><h4>Result: Hardening the Application</h4><p>Following the CSP implementation, a rerun of the DAST scan confirmed that the <strong>critical vulnerability was resolved</strong>. No further issues regarding missing security headers were reported. This change not only mitigates XSS but also reflects a configuration best practice encouraged by OWASP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*LzUDF8SdncdIsER1.png" /></figure><h3>Secure Handling of Secrets and Environment Variables</h3><p>A critical yet often overlooked aspect of web application security is <strong>the management of environment variables and secret keys</strong>. In the <strong>PantauTular</strong> project, careful attention was given to how sensitive data — such as API keys, database credentials, and third-party tokens — is stored and accessed across the development, staging, and production environments.</p><h4>OWASP Relevance: Security Misconfiguration and Cryptographic Failures</h4><p>Secure handling of environment variables directly addresses two categories from the <a href="https://owasp.org/Top10/">OWASP Top 10</a>:</p><ul><li><strong>A02:2021 — Cryptographic Failures</strong>: Hardcoding secrets or failing to securely manage keys often leads to exposure of sensitive data, especially during code commits or deployment. This category includes failures in protecting data in transit, at rest, or during authentication flows.</li><li><strong>A05:2021 — Security Misconfiguration</strong>: Leaving sensitive values in plain text, storing them in source code, or exposing them in logs or frontend bundles constitutes a configuration flaw. Managing secrets securely through environment variables is a key preventive control.</li></ul><h4>Implementation in PantauTular</h4><p>To align with these security standards, the following practices were applied in the project:</p><ul><li><strong>Use of </strong><strong>.env Files:</strong> All sensitive values (e.g., database credentials, third-party API keys, and Django secret keys) are stored in environment-specific .env files that are <strong>excluded from version control</strong> using .gitignore.</li><li><strong>Runtime Configuration Separation:</strong> Environment variables are injected during runtime using system-level configuration or deployment platform tooling (e.g., Railway for backend, Netlify for frontend). This allows different values for development, staging, and production without changing the codebase.</li><li><strong>Secret Key Isolation:</strong> Critical secrets such as DJANGO_SECRET_KEY and PostgreSQL access credentials are never hardcoded. Instead, they are accessed at runtime via environment variables using os.environ.get() in Django.</li><li><strong>Frontend Security:</strong> On the frontend (Next.js), only <strong>non-sensitive public environment variables</strong> (prefixed with NEXT_PUBLIC_) are exposed, ensuring that backend secrets remain hidden from client-side access.</li></ul><p>Next.Js settings:</p><pre>NEXT_PUBLIC_API_URL = https://pantautular-be-pbi-c01.up.railway.app<br>NEXT_PUBLIC_API_KEY = -I60gpBOcqRcylybyWYFCeo7dlXb8DQSOtnGtUauokg<br>SENTRY_AUTH_TOKEN = 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<br>NEW_RELIC_AI_MONITORING_ENABLED=true <br>NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED=100k <br>NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED=10k <br>NEW_RELIC_APP_NAME=PantauTular-FE <br>NEW_RELIC_LICENSE_KEY=546f3633836e49c4b73f59a2e5ffd63fFFFFNRAL node -r newrelic YOUR_MAIN_FILENAME.jsAnd in Django settings:</pre><p>And in Django settings:</p><pre>DATABASE_URL=postgresql://postgres:faekThdThKUxgWmPMjAbhORtYHuuprZq@yamanote.proxy.rlwy.net:16271/railway<br>DB_HOST=yamanote.proxy.rlwy.net<br>DB_PORT=16271<br>SECRET_KEY=django-insecure-8j+#sbe$%%g-+&amp;jas6jxg7i*e!z6r*d3uy)74t$p@5pfmtmwtu<br>SECRET_API_KEY=-I60gpBOcqRcylybyWYFCeo7dlXb8DQSOtnGtUauokg<br>NEW_RELIC_CONFIG_FILE=newrelic.ini newrelic-admin run-program python manage.py runserver<br>POSTGRES_USER=postgres<br>POSTGRES_PASSWORD=postgres<br>POSTGRES_DB=pantautular<br>PORT=8000<br>FE_URL=https://pantautular.netlify.app</pre><h4>Result: A More Secure Configuration Pipeline</h4><p>By segregating configuration from code and eliminating hardcoded secrets, PantauTular reduces the risk of data leaks, secret key exposure, and misconfigurations during deployment. This setup aligns directly with <strong>OWASP’s recommendations</strong> for secure application deployment and secret management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ad7cf557b64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stress and Penetration Testing]]></title>
            <link>https://medium.com/@alvaro.luqman/stress-and-penetration-testing-7a656955512d?source=rss-9fbfc9137678------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a656955512d</guid>
            <dc:creator><![CDATA[Alvaro Luqman]]></dc:creator>
            <pubDate>Wed, 28 May 2025 08:43:04 GMT</pubDate>
            <atom:updated>2025-05-28T11:27:00.881Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stress Testing with K6 and Grafana</h3><p>In this performance testing session, I utilized <strong>K6</strong> in conjunction with <strong>Grafana</strong> to simulate high-traffic conditions and assess the robustness of our application. The integration of these tools offered an efficient workflow, allowing me to record live user interactions directly. This streamlined the process — rather than manually scripting every user action, I could simply perform the intended task, and K6 would convert that session into a runnable test script.</p><h4>Test Scenario and Setup</h4><p>The goal of this stress test was to simulate a typical user journey under heavy load, specifically <strong>focusing on logging in and accessing the map feature of our application</strong>. Once the script was generated from my recorded session, I configured the test to run with 20 virtual users. Over the course of the test, these users made a total of 19,560 requests, averaging 58 requests per second.</p><h4>Key Results</h4><p>The outcome of the test was largely positive. Of the 19,560 total requests, about 1,600 failed — meaning approximately 91.8% of requests were successful. More importantly, the test achieved a perfect score across several key performance indicators evaluated by Grafana:</p><ul><li><strong>Metric Names</strong>: Assesses the total number of custom metrics and forces a naming convention</li><li><strong>Metric Tags</strong>: Assesses the total number of metric tags</li><li><strong>Third Party Content</strong>: Assesses the usage of third-party domains Load</li><li><strong>Generator CPU Usage</strong>: Assesses the CPU usage of cloud load generators.</li><li><strong>Load Generator Memory Usage</strong>: Assesses the memory usage of cloud load generators.</li></ul><p>The system maintained proper naming conventions for custom metrics, used consistent tagging, avoided unnecessary reliance on third-party domains, and demonstrated efficient use of both CPU and memory on the cloud-based load generators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EC8WrKU58r0WHJm7TTpsWw.png" /><figcaption>Performance overview</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a5c2v29Ram9cyqT-PQN3fg.png" /><figcaption>Cloud insights</figcaption></figure><h4>Analyzing the Failures</h4><p>The 1,600 failed requests all resulted in HTTP 429 errors, which indicate “Too Many Requests.” These failures occurred exclusively when attempting to hit the login endpoint. This behavior was not only anticipated but reassuring—our application includes a rate-limiting mechanism precisely to mitigate spam and brute-force login attempts. The system correctly throttled these excessive login requests, validating that this protective layer is functioning as intended.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQ5ELDxih54svnZ_4l6mGA.png" /></figure><h4>The Map Feature Under Load</h4><p>Perhaps the most encouraging result came from testing the map feature. All requests to this endpoint returned a 200 OK status, confirming that the system handled over 18,000 high-frequency requests to one of its most data-intensive features without faltering. Given the importance of this component in the user experience, its stability under stress suggests our infrastructure is well-prepared to handle real-world demand spikes.</p><h3>Addressing Security Vulnerabilities in My Web Application with Aikido Security</h3><p>Before initiating any manual penetration testing on my application, it was critical to first verify whether any security vulnerabilities were already present. Identifying and resolving these issues early would prevent redundant effort and strengthen the overall security posture of the system.</p><p>To achieve this, I employed both <strong>Static Application Security Testing (SAST)</strong> and <strong>Dynamic Application Security Testing (DAST)</strong> using <a href="https://aikido.dev/">Aikido Security</a> — a developer-friendly platform designed to continuously scan for security issues across the codebase and during runtime.</p><p>I applied these security scans on both the frontend and backend components of my application. One significant vulnerability immediately stood out: <strong>the backend was missing a Content Security Policy (CSP) header</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5_y88gN6CBIjoFXWg8eb7Q.png" /><figcaption>Critical alert on missing CSP header</figcaption></figure><h4>Why CSP Matters</h4><p>A <strong>Content Security Policy (CSP)</strong> is a powerful HTTP security header that acts as a mitigation layer against various types of attacks, most notably <strong>Cross-Site Scripting (XSS)</strong>, <strong>clickjacking</strong>, and <strong>data injection</strong>. Without a proper CSP in place, web applications are exposed to threats such as:</p><ul><li><strong>Account takeovers</strong></li><li><strong>Sensitive data theft</strong></li><li><strong>Site defacement</strong></li><li><strong>Malware distribution</strong></li></ul><p>The absence of a CSP header in the backend was flagged as a <strong>critical vulnerability</strong> by Aikido Security’s DAST. This meant that malicious actors could potentially exploit content injection vectors to hijack sessions or deliver harmful scripts to users.</p><h4>Implementing a CSP Header</h4><p>To address this vulnerability, I implemented a CSP header directly in the backend of the application. The changes were committed to the backend repository and can be viewed in the following GitHub commits:</p><ul><li><a href="https://github.com/PPL-BRIN/pantautular-be/commit/67b855233d70b821b827d566e6229b6e374ddfe9">Commit: Add CSP header implementation (part 1)</a></li><li><a href="https://github.com/PPL-BRIN/pantautular-be/commit/f4cd53e293d8502e8dd50765ef62671ad8407e53">Commit: Adjust CSP header rules (part 2)</a></li></ul><p>These changes define strict rules that govern which scripts, styles, images, and other resources are allowed to be loaded and executed by the browser. By specifying trusted sources only, the application significantly reduces the surface area for client-side attacks.</p><h4>Post-Remediation Results</h4><p>After deploying the updated backend with the CSP header in place, I reran the DAST using Aikido Security. The result? <strong>The critical vulnerability related to the missing CSP header was resolved</strong>. The scan reported no further critical issues of this nature, validating the effectiveness of the patch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*FErvFNfNyi46_H0MxEdleA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a656955512d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Usability Testing on PantauTular Application]]></title>
            <link>https://medium.com/@alvaro.luqman/usability-testing-on-pantautular-application-5249bc33dbd2?source=rss-9fbfc9137678------2</link>
            <guid isPermaLink="false">https://medium.com/p/5249bc33dbd2</guid>
            <dc:creator><![CDATA[Alvaro Luqman]]></dc:creator>
            <pubDate>Tue, 27 May 2025 15:09:59 GMT</pubDate>
            <atom:updated>2025-05-27T15:09:59.423Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating software isn’t just about writing code — it’s about solving real-world problems for real people. With PantauTular, the goal was to empower users to monitor disease outbreaks across Indonesia using a map-based interface and a data-rich dashboard. But before launching more advanced features or polishing the design further, we needed to ask a fundamental question: <strong>could users actually use what we built — without our help?</strong></p><p>To answer that, I turned to usability testing. Over the course of several sessions, I watched as users explored the application for the first time, navigated its maps, filtered through outbreaks, and attempted to draw conclusions from the data. What I discovered was illuminating — not just in terms of what worked, but also where my team had fallen short in anticipating user expectations.</p><h3>Testing PantauTular: Context and Purpose</h3><p>PantauTular is a disease monitoring platform that visualizes cases of illness across Indonesian regions. The application centers around two main features: an interactive map with zooming, filtering, and environmental data layers (such as humidity and precipitation) and a dashboard offering graphs and tables that display case trends over time.</p><p>I designed a set of goal-based scenario tasks that mimicked real-life use cases. The objective was to understand not only whether users could complete these tasks but also how intuitively they could do so and what pain points emerged along the way.</p><h4>Scenario 1: Investigating Specific Disease Cases</h4><p>In the first scenario, I asked users to investigate a specific disease outbreak (e.g., malaria cases<em>)</em>. The task was to apply filters on the map by disease type, then click on a case marker to view its details. This scenario mirrors a common real-world use case — when local health officials or researchers need to quickly assess outbreaks in their area of responsibility. It tests the discoverability and usability of the map filters and pop-up information windows, which are essential for users making time-sensitive, location-specific decisions.</p><h4>Scenario 2: Understanding Overall Disease Trends</h4><p>The second scenario focused on interpreting trends using the dashboard. Users were instructed to switch from the map to the dashboard, filter for <em>respiratory diseases (</em>e.g., covid-19<em>)</em>, and observe the changes in the dashboard. This task reflects a real-world analytical need where decision-makers or epidemiologists track long-term patterns to plan interventions or allocate resources. It tested not only the clarity of data visualization but also how easily users could navigate between the map and the dashboard and apply filters consistently.</p><h4>Scenario 3: Using the ‘Find Me’ Feature</h4><p>For the third task, we wanted to simulate a situation where a user — such as a concerned citizen or field health worker — wants to know if any disease cases have been reported near them. The user was instructed to use the ‘Find Me’ feature and check if any markers appeared close to their location. This scenario highlights the app’s potential value for hyperlocal awareness and personal safety while also testing whether the geolocation feature behaves as expected and whether nearby data is presented clearly and accessibly.</p><h4>Scenario 4: Exploring Environmental Factors</h4><p>This scenario explored the intersection between disease and environmental conditions. Users were asked to use one of the environmental map layers on the map (humidity, precipitation, or temperature). The goal was to see whether users could not only activate relevant layers but also use them to interpret disease distribution contextually. This is a powerful real-world use case for researchers and public health analysts who aim to understand how climate factors influence outbreaks — essential for prediction and prevention strategies.</p><h4>Scenario 5: Cross-Verification Between Map and Dashboard</h4><p>In the final scenario, we simulated a more complex analytical workflow. Users were first asked to filter the map based on a certain news anchor and observe the number of cases. Then, they had to switch to the dashboard to apply the exact same filter and confirm the data visually. This scenario reflects how professionals often move between high-level data summaries and geographic visualizations to validate findings or communicate insights. It tested whether the two views in PantauTular felt connected and consistent and whether filters applied in one view were easy to replicate in the other.</p><h3>Participants and Methodology</h3><p>The usability tests were moderated and conducted in person or remotely. A total of 7 participants included a mix of health-concerned individuals, tech-savvy users, and individuals unfamiliar with data visualization tools. Each session lasted around 20 to 30 minutes and involved walking users through a brief introduction, then allowing them to execute five realistic tasks using a deployed version of PantauTular on a laptop or tablet.</p><p>With the help of the Microsoft Clarity tool, I was able to monitor user’s behaviour through out the whole test. The tool provided with session replays, and mouse click indicators to pin point where users are clicking.</p><p>Importantly, I didn’t offer tutorials or detailed explanations. I provided only basic context: what the application was for and what general goals they should try to accomplish. This approach helped to understand how discoverable and intuitive the interface truly was.</p><h3>Observations from the Field: The Pain Points</h3><p>From the very first session, patterns began to emerge. The good news: many core features performed well. Users responded positively to the map visualization and its interactive UI. They enjoyed navigating and exploring the map and overall became the most liked and approved feature of the application.</p><p>However, the main concern doesn’t lie in what the user likes but rather in what the user dislikes or at least has a struggle with when attempting to use the features. The result of the usability test showed some common concern among all the participants. Below are some of the major ones.</p><h4>Hidden Map Layer Button</h4><p>By default, the button to access the map layers is hidden. Users must click the main map button in order to show them. This became an issue as users struggled to find the button for the severity, humidity, temperature, and precipitation when executing the fourth scenario, where users are tasked to enable either one of those map layer features. This ultimately led to one of our test participants failing to properly execute said task.</p><h4>Closing Case Detail Pop-Up</h4><p>Our map contains markers that depict a certain disease case. Users can hover over the marker to open up a pop-up that shows details regarding the disease case. The thing that bothers users is that, to close the pop-up, users need to scroll up and manually hover their mouse over the ‘X’ located on the top right of the pop-up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hkVbA-sodF-IerIeSITVA.png" /><figcaption>Users have to click ‘X’ to close the case detail pop-up</figcaption></figure><p>Most of our participants believe it would be much more convenient if we could simply just click outside of the pop-up to close it, just like how it works in most other apps.</p><h4>Irresponsive Dashboard Filter Form</h4><p>Although this issue was discovered in one out of the seven test participants, it needs to be brought to attention due to how severe it is. The filter form on the dashboard page doesn&#39;t seem to be responsive. This caused a visual irritation when one of our test participants was executing the second and fifth tasks. The picture below shows how the form blocks the view on the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qvwqogc5siQk3STA3eER3w.png" /><figcaption>Filter Form blocking the dashboard graphs</figcaption></figure><h4>Other Small Issues</h4><p>Aside from the major ones, some users brought up small issues such as:</p><ul><li>Map filter form should automatically close after applying filter</li><li>Button label for ‘Find Me’ button on the Map</li></ul><h3>Applying Improvements</h3><p>With the test result, I could finally pin point all the issues and immidiately work on fixing and improving the application’s feature. Here’s what I’ve done.</p><h4>Pre-Opened Map Layer Buttons</h4><p>To counter the issue where users struggle to find the map layer button, while keeping the design as close to the prototype, I’ve decided to make the map layer buttons visible as soon as users open the map feature. With this, user won’t struggle as much as they used to, now that they can easily navigate and access the map layers.</p><h4>Easy Pop-Up Close</h4><p>Another improvement that I’ve applied is that now users can just simply click anywhere on the screen, outside of the pop-up window, to easily close the case detail. This makes the user’s experience more intuitive, and allows them to navigate over the map much more conviniently.</p><h4>Responsive Dashboard Filter Form</h4><p>The issue that I found with the dashboard’s filter form, is that it contained the ‘fixed’ html/css attribute. This makes the dashboard unresponsive to changes in screen size. I quickly understood that the initial implementation was to make the dashboard filter form stay in the given position, even if the users scroll down the dashboard page. Thus, I simply replaced the ‘fixed’ position attribute with ‘sticky’. This allows the filter form to stay in place while being responsive at the same time.</p><h4>Other Changes</h4><p>Aside from those changes, I’ve also applied these changes that is according to the other pain points mentioned above:</p><ul><li>Map filter closes automatically after applyying filter</li><li>‘Find Me’ button now has a button label</li></ul><h3>Conclusion</h3><p>The test has shown that our application is still far from polished. Even with only 7 participants, we were able to identify issues that may or may not arise in future test. Hopefully with the given improvements, PantauTular will be one step close into becoming a well developed application that provides the best user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5249bc33dbd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Unit Testing with Mocks and Stubs: A Real-World Case Study with AmCharts]]></title>
            <link>https://medium.com/@alvaro.luqman/mastering-unit-testing-with-mocks-and-stubs-a-real-world-case-study-with-amcharts-d1e779974ea9?source=rss-9fbfc9137678------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1e779974ea9</guid>
            <dc:creator><![CDATA[Alvaro Luqman]]></dc:creator>
            <pubDate>Sun, 18 May 2025 15:13:42 GMT</pubDate>
            <atom:updated>2025-05-18T15:13:42.552Z</atom:updated>
            <content:encoded><![CDATA[<p>Unit testing stands as one of the foundational pillars of modern software development. The principle is straightforward: isolate small units of code and verify they behave as expected. However, this simplicity quickly evaporates when those units interact with complex external dependencies — third-party APIs, visual rendering libraries, or distributed systems.</p><p>Enter mocks and stubs — powerful tools that allow developers to simulate these dependencies without actually invoking them. But what makes these techniques so essential, and how do they play out in real-world applications?</p><h3>The Problem: Integration Testing Disguised as Unit Testing</h3><p>Consider a seemingly innocent visualization component that renders disease outbreak data on an interactive map using AmCharts. Without proper isolation, testing this component can quickly become problematic:</p><pre>// Without mocks - a brittle integration test<br>test(&#39;map should display disease outbreaks&#39;, async () =&gt; {<br> // Renders actual AmCharts library<br> render(&lt;DiseaseOutbreakMap locations={mockLocations} /&gt;);<br> <br> // Wait for actual chart rendering and DOM operations<br> await waitFor(() =&gt; screen.getByTestId(&#39;map-container&#39;));<br> <br> // Try to verify points are displayed<br> const points = document.querySelectorAll(&#39;.am5-Point&#39;);<br> expect(points.length).toBe(mockLocations.length);<br>});</pre><p>This test faces multiple challenges:</p><p>1. <strong>Dependency on DOM</strong>: Requires a DOM environment to render actual chart elements<br>2. <strong>Fragility</strong>: Breaks if AmCharts changes its internal structure or class names<br>3. <strong>Performance</strong>: Slow execution due to actual rendering operations<br>4. <strong>Determinism</strong>: May behave differently in various environments<br>5. <strong>Focus</strong>: Tests the library implementation, not your code</p><p>The result? Unreliable tests that fail mysteriously, taking minutes instead of milliseconds to run.</p><h3>The Solution: Surgical Precision with Mocks and Stubs</h3><p>I transform the approach using proper isolation techniques. In a real-world project like PantauTular (a disease surveillance dashboard), we can see how this is handled effectively:</p><pre>// From a real project: mocking the entire chart library<br>jest.mock(&quot;@amcharts/amcharts5&quot;, () =&gt; ({<br> __esModule: true,<br> Root: {<br> new: jest.fn().mockImplementation(() =&gt; ({<br> setThemes: jest.fn(),<br> container: {<br> children: { push: jest.fn() },<br> },<br> dispose: jest.fn(),<br> })),<br> },<br> Circle: {<br> new: jest.fn().mockImplementation(() =&gt; ({<br> // Simplified mock implementation<br> })),<br> },<br> // Other components mocked similarly<br>}));</pre><p>This approach replaces the entire AmCharts library with lightweight stubs that simulate its behavior without actually rendering anything.</p><p>The resulting test becomes focused on what truly matters — your code:</p><pre>// With mocks - a precise unit test<br>test(&#39;populateLocations should add location markers to the map&#39;, () =&gt; {<br> // Create service with mocked dependencies<br> const mapService = new MapChartService();<br> const mockLocations = [<br> { id: 1, latitude: -6.2, longitude: 106.8 },<br> { id: 2, latitude: -6.9, longitude: 107.6 }<br> ];<br> <br> // Call the method under test<br> mapService.populateLocations(mockLocations);<br> <br> // Verify interactions with the mocked dependencies<br> expect(mockDataPush).toHaveBeenCalledTimes(2);<br>});</pre><h3>Comparing the Two Worlds</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FGrFVd%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FGrFVd%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FGrFVd%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/29ec8b5213b46b23eef371873486008b/href">https://medium.com/media/29ec8b5213b46b23eef371873486008b/href</a></iframe><h3>The Hidden Benefits: Testing the Untestable</h3><p>In disease surveillance dashboards like PantauTular, certain components might seem impossible to test in isolation — such as map controls, heatmap layers, or clustering algorithms. Mocks and stubs make testing these scenarios not only possible but straightforward.</p><p>Here’s how PantauTular tests complex error handling in its map visualization service:</p><pre>it(&#39;should handle chart initialization errors&#39;, async () =&gt; {<br> // Setup spy to capture error handling<br> const onErrorMock = jest.fn();<br> const mapService = new MapChartService(onErrorMock);<br> <br> // Force element to be null to simulate DOM error<br> document.getElementById = jest.fn().mockReturnValue(null);<br> <br> // Call method that should handle the error<br> mapService.initialize(&#39;non-existent-element&#39;, { defaultZoom: 1 });<br> <br> // Verify error was handled correctly<br> expect(onErrorMock).toHaveBeenCalledWith(<br> expect.stringContaining(&#39;Failed to initialize chart&#39;)<br> );<br>});</pre><p>This test simulates a scenario where the DOM element doesn’t exist — something that would be difficult to test without mocks.</p><h3>Leveraging AI for Mock Generation</h3><p>The most tedious part of this approach? Creating the mocks themselves. Complex libraries like AmCharts may have hundreds of methods and properties that need stubbing, added to the lack of testing documentation from AmCharts themselves.</p><p>Modern AI tools can generate these mocks automatically by analyzing your imports and the library’s type definitions:</p><pre>// AI-generated mock for AmCharts circle component<br>const mockCircle = {<br> root: null,<br> config: {},<br> type: &quot;Circle&quot;,<br> events: {<br> on: jest.fn().mockImplementation((event, callback) =&gt; {<br> if (event === &quot;pointerover&quot;) {<br> callback({ target: { dataItem: { dataContext: { id: &quot;test-id&quot; } } } });<br> }<br> })<br> },<br> show: jest.fn(),<br> hide: jest.fn(),<br> set: jest.fn(),<br> dispose: jest.fn()<br>};</pre><p>These AI-generated mocks can then be refined based on your specific needs, dramatically reducing the boilerplate code you need to write.</p><h3>Real-World Example: Testing the PantauTular Map Integration</h3><p>This is how I set up the PantauTular project to handle testing its AmCharts integration. This disease surveillance dashboard displays outbreak data on an interactive map, with multiple data layers and interactive features.</p><h4>The Production Code:</h4><pre>// Simplified version of actual production code<br>export class MapChartService {<br> private root: am5.Root | null = null;<br> private chart: am5map.MapChart | null = null;<br> <br> initialize(containerId: string, config: MapConfig): void {<br> try {<br> // Create root element<br> this.root = am5.Root.new(containerId);<br> <br> // Set themes<br> this.root.setThemes([am5themes_Animated.new(this.root)]);<br> <br> // Create chart<br> this.chart = this.root.container.children.push(<br> am5map.MapChart.new(this.root, {<br> projection: am5map.geoMercator(),<br> // …other configuration<br> })<br> );<br> <br> // Setup map features<br> this.setupMapFeatures();<br> } catch (error) {<br> console.error(&quot;Failed to initialize chart:&quot;, error);<br> // Additional error handling<br> }<br> }<br> <br> populateLocations(locations: MapLocation[]): void {<br> if (!this.chart) return;<br> <br> // Clear existing data<br> this.pointSeries.data.clear();<br> <br> // Add location markers<br> locations.forEach(location =&gt; {<br> this.pointSeries.data.push({<br> longitude: location.longitude,<br> latitude: location.latitude,<br> // Other properties<br> });<br> });<br> }<br> <br> // Other methods<br>}</pre><h4>The Test Code:</h4><pre>describe(&#39;MapChartService&#39;, () =&gt; {<br> // Setup common mocks<br> const mockChildrenPush = jest.fn();<br> const mockDataPush = jest.fn();<br> const mockDataClear = jest.fn();<br> <br> beforeEach(() =&gt; {<br> jest.clearAllMocks();<br> });<br> <br> it(&#39;should initialize map chart correctly&#39;, () =&gt; {<br> const mapService = new MapChartService();<br> mapService.initialize(&#39;test-container&#39;, { defaultZoom: 1 });<br> <br> // Verify root was created<br> expect(am5.Root.new).toHaveBeenCalledWith(&#39;test-container&#39;);<br> <br> // Verify chart was created with correct configuration<br> expect(mockChildrenPush).toHaveBeenCalled();<br> });<br> <br> it(&#39;should add location markers when populating locations&#39;, () =&gt; {<br> const mapService = new MapChartService();<br> mapService.initialize(&#39;test-container&#39;, { defaultZoom: 1 });<br> <br> const mockLocations = [<br> { id: 1, latitude: -6.2, longitude: 106.8 },<br> { id: 2, latitude: -6.9, longitude: 107.6 }<br> ];<br> <br> mapService.populateLocations(mockLocations);<br> <br> // Verify data was cleared before adding new points<br> expect(mockDataClear).toHaveBeenCalled();<br> <br> // Verify each location was added to the series<br> expect(mockDataPush).toHaveBeenCalledTimes(2);<br> });<br>});</pre><h3>From Testing Pain to Testing Pleasure</h3><p>Without mocks and stubs, testing AmCharts integration would be nearly impossible. The library creates complex DOM structures, requires specific browser features, and operates asynchronously — a perfect storm for flaky tests.</p><p>By using mocks:</p><p>1. <strong>Tests run in any environmen</strong>t: No need for browser capabilities or DOM<br>2. <strong>Tests complete in milliseconds</strong>: No actual rendering or HTTP requests<br>3. <strong>Edge cases are testable</strong>: Error scenarios can be simulated easily<br>4. <strong>Focus remains on business logic</strong>: Tests verify handling of geo-data, not AmCharts internals</p><h3>Conclusion: Invest in Isolation for Testing Success</h3><p>Modern web applications rarely exist in isolation — they integrate with countless libraries, APIs, and services. Effective testing requires the ability to simulate these dependencies, focusing on what you control while assuming external components work as advertised.</p><p>Mocks and stubs provide exactly this capability, allowing you to:</p><p>1. Isolate your code from external dependencies<br>2. Accelerate test execution by avoiding real implementations<br>3. Simulate edge cases and error scenarios<br>4. Validate behavior without testing implementation details</p><p>By investing in proper testing isolation, you’ll create tests that are faster, more reliable, and more focused — giving you the confidence to evolve your codebase with speed and safety.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1e779974ea9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining PantauTular Development with CI/CD, Docker, and GitHub Actions]]></title>
            <link>https://medium.com/@alvaro.luqman/streamlining-pantautular-development-with-ci-cd-docker-and-github-actions-11b8425787f2?source=rss-9fbfc9137678------2</link>
            <guid isPermaLink="false">https://medium.com/p/11b8425787f2</guid>
            <dc:creator><![CDATA[Alvaro Luqman]]></dc:creator>
            <pubDate>Fri, 16 May 2025 15:02:46 GMT</pubDate>
            <atom:updated>2025-05-17T06:56:27.229Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploying modern web applications involves more than just writing clean code — it demands streamlined infrastructure, efficient containerization, and automated workflows. In this article, I’ll walk you through how I built and deployed a production-grade application using Docker, covering everything from image optimization to automated health checks and CI/CD workflows. The goal? Drastically reduce image size, improve deployment speed, and maintain operational reliability — all while following industry best practices. Whether you’re deploying a Next.js frontend, a Django backend, or both, the principles covered here will help you ship faster and smarter.</p><h3>Docker Setup</h3><p>At the core of my deployment pipeline is Docker, which encapsulates both the frontend and backend services of the application. Initially, I started with basic Dockerfiles that worked — but were far from efficient. The images were unnecessarily large, lacked health checks, and offered no layer reusability. This not only slowed down deployments but also inflated cloud storage costs and created friction in local development workflows.</p><p>To address these challenges, I approached Docker setup with a performance-first mindset:</p><ul><li>Optimize image sizes to avoid bloated containers.</li><li>Leverage multi-stage builds for better separation of concerns.</li><li>Add health checks for production observability.</li><li>Automate builds and tagging for seamless version control.</li></ul><p>What follows is a deep dive into the specific techniques I used to refine the Docker configuration, especially for the frontend, where size and speed are critical. From enabling Next.js’s standalone output mode to using Alpine-based images and caching strategies, each choice contributed to a final result: a highly optimized and production-ready container environment.</p><h3>Frontend Docker Image Optimization</h3><p>Docker images can quickly grow to unmanageable sizes, especially for JavaScript applications with large dependency trees. In this case, I tackled the frontend of the application with an image size of approximately 2GB, which is excessive for a web application. Through strategic optimization techniques, the size can be reduced by up to 85–90%, resulting in faster deployments, reduced storage costs, and improved performance.</p><h4><strong>The Multi-Stage Build Approach</strong></h4><p>The cornerstone of the optimization strategy is the implementation of a three-stage build process:</p><p><strong>Stage 1: Dependencies Layer</strong></p><pre>FROM node:18-alpine AS deps<br>WORKDIR /app<br>COPY package.json package-lock.json* ./<br>RUN npm ci</pre><p>This initial stage focuses exclusively on installing dependencies. By isolating this step, we leverage Docker’s layer caching mechanism effectively. Dependencies change less frequently than application code, so this layer will be rebuilt only when package files change, saving significant time during iterative development.</p><p><strong>Stage 2: Builder Layer</strong></p><pre>FROM node:18-alpine AS builder<br>WORKDIR /app<br>COPY - from=deps /app/node_modules ./node_modules<br>COPY . .<br>RUN npm run build</pre><p>The builder stage inherits only the necessary node_modules from the previous stage and adds the application source code. This stage handles the compilation and optimization of the Next.js application. By separating this from the final image, we ensure that build tools and development dependencies don’t bloat our production container.</p><p><strong>Stage 3: Runner Layer</strong></p><pre>FROM node:18-alpine AS runner<br>WORKDIR /app<br>ENV NODE_ENV production<br># User creation and permissions setup<br>COPY - from=builder /app/public ./public<br>COPY - from=builder /app/.next/standalone ./<br>COPY - from=builder /app/.next/static ./.next/static</pre><p>The final stage creates a lean production image containing only the artifacts necessary to run the application. This approach dramatically reduces the image size by excluding:</p><ul><li>Source code files</li><li>Development dependencies</li><li>Build tools</li><li>Test files</li><li>Configuration files not needed in production</li></ul><h4><strong>Next.js Standalone Output Mode</strong></h4><p>A critical optimization was enabling Next.js standalone output mode by adding this configuration to next.config.ts:</p><pre>output: &#39;standalone&#39;</pre><p>This configuration instructs Next.js to create a minimal, self-contained production build that:</p><ul><li>Includes only the necessary Node.js runtime code</li><li>Bundles required dependencies</li><li>Eliminates unnecessary files and modules</li><li>Creates a server.js file that can run directly without requiring the Next.js framework to be installed</li></ul><p>The standalone output is specifically designed for containerized environments, reducing the final bundle size significantly compared to traditional Next.js deployments.</p><h4><strong>Additional Optimization Techniques</strong></h4><p>Several other techniques further reduced the image size:</p><ol><li><strong>Minimal package installation</strong>: Using apk — no-cache add curl prevents the Alpine package manager from creating additional cache layers.</li><li><strong>Direct command execution</strong>: Using CMD [“node”, “server.js”] instead of npm scripts eliminates an additional shell process and reduces complexity.</li><li><strong>Selective file copying</strong>: Only copying specific directories from the build output rather than entire project folders significantly reduces the final image size.</li><li><strong>Alpine Linux base</strong>: Using the Alpine variant of Node.js provides a much smaller base image compared to Debian-based alternatives.</li></ol><h4>Results and Benefits</h4><p>The optimized Docker image got reduced to 234MB, representing approximately an 89% reduction from the original 2GB size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*64NoOzr2KNckqY8pW7ZlIg.png" /><figcaption>The before (tagged latest) vs the after (tagged optimized) optimization of the image</figcaption></figure><p>This optimization delivers several key benefits:</p><ul><li>Faster deployments: Smaller images transfer more quickly between registries and hosts</li><li>Reduced storage costs: Cloud providers charge for container storage</li><li>Improved startup time: Containers initialize faster with fewer files to load</li><li>Reduced resource usage: Less disk space and memory consumption</li></ul><p>By implementing these optimization techniques, we’ve created a production-ready Docker image that follows industry best practices for containerized Next.js applications, balancing performance, security, and efficiency.</p><h3>Docker Health Checks</h3><p>Docker health checks provide crucial container monitoring capabilities, enabling automated detection of application failures. For both frontend and backend, I implemented a robust health check mechanism to ensure reliable operation in production environments.</p><h4>Frontend Implementation Strategy</h4><p>The health check was integrated through a concise HEALTHCHECK instruction in our Dockerfile:</p><pre>HEALTHCHECK - interval=30s - timeout=5s - start-period=30s - retries=3 \<br>CMD curl -f http://localhost:3000/ || exit 1</pre><p>This single directive establishes a complete monitoring solution with carefully calibrated parameters:</p><ul><li>Interval (30s): Checks execute every 30 seconds, balancing responsiveness with minimal performance impact</li><li>Timeout (5s): Each check must complete within 5 seconds to avoid false negatives from temporary slowdowns</li><li>Start Period (30s): Provides adequate initialization time for the Next.js application before assessment begins</li><li>Retries (3): Prevents transient issues from triggering unnecessary container restarts</li></ul><p>The health check leverages curl to perform HTTP requests against the application’s root endpoint. This approach:</p><ol><li>Verifies the Node.js process is running</li><li>Confirms the HTTP server is accepting connections</li><li>Validates that the Next.js application is properly rendering content</li></ol><p>To support this functionality, I added curl to our Alpine-based image:</p><pre>RUN apk - no-cache add curl</pre><p>The — no-cache flag optimizes image size by preventing the creation of additional package cache layers.</p><h4>Backend Implementation Strategy</h4><p>The health check integration followed a three-pronged approach: creating an endpoint in Django, configuring Docker’s health check mechanism, and ensuring proper database connectivity verification.</p><p>A dedicated endpoint was created at /health/ to respond to health check requests. This endpoint performs a critical function: verifying database connectivity. The implementation looks like:</p><pre>def health_check(request):<br>    db_healthy = True<br>    try:<br>        connections[&#39;default&#39;].cursor()<br>    except OperationalError:<br>        db_healthy = False<br>    <br>    status = 200 if db_healthy else 500<br>    <br>    health_data = {<br>        &#39;status&#39;: &#39;healthy&#39; if db_healthy else &#39;unhealthy&#39;,<br>        &#39;database&#39;: &#39;connected&#39; if db_healthy else &#39;disconnected&#39;,<br>        &#39;timestamp&#39;: datetime.now().isoformat()<br>    }<br>    <br>    return JsonResponse(health_data, status=status)</pre><p>This endpoint returns a 200 status code when healthy and 500 when unhealthy, along with a JSON response containing connection status details.</p><p>Health checks were integrated at the Docker level through two configurations. The first configuration is applied directly at the Dockerfile as shown below:</p><pre>HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \<br>CMD curl -f http://localhost:${PORT:-8000}/health/ || exit 1</pre><p>This directive instructs Docker to probe the /health/ endpoint every 30 seconds, allowing 30 seconds for initial startup, and marking the container unhealthy after 3 failed attempts.</p><p>The second configuration is applied at the .yaml file:</p><pre>   healthcheck:<br>     test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;-f&quot;, &quot;http://localhost:8000/health/&quot;]<br>     interval: 30s<br>     timeout: 5s<br>     retries: 3<br>     start_period: 30s</pre><h3>Automated Workflows Implementation</h3><p>In today’s fast-paced development environment, automation is key to maintaining quality while accelerating delivery. The Django backend and Next.js frontend application now leverages several GitHub Actions workflows that handle everything from testing to deployment with minimal human intervention.</p><h4>SonarQube Static Analysis</h4><p>To enforce code quality, I integrated SonarQube into the workflow using GitHub’s native integration — no custom .yaml scripts required. Static analysis runs automatically on every merge request to <strong>staging or </strong><strong>main</strong>, providing immediate feedback within the GitHub UI.</p><p>Key metrics like code coverage, bugs, vulnerabilities, and duplication are surfaced directly in pull requests, helping catch issues early in the development cycle.</p><p>This setup ensures:</p><ul><li>Continuous quality checks without manual setup</li><li>Early detection of code smells and security flaws</li><li>Better-informed code reviews with in-context analysis</li></ul><p>By combining SonarQube with CI/CD and test automation, we’ve built a workflow that prioritizes clean, secure, and maintainable code.</p><h4>Continuous Integration and Deployment</h4><p>The newly implemented Railway deployment workflow automates the entire release process to our production environment. This workflow triggers on pushes to the main branch, running tests before deploying to Railway’s platform. It handles database migrations and static file collection, ensuring a smooth deployment process with proper verification steps.</p><p>The frontend already has an automated Netlify workflow using the GitHub-Netlify integration, thus removes the need to create a manual workflow script.</p><h4>Semantic Versioning Automation</h4><p>Perhaps the most innovative addition is the automated release workflow that implements semantic versioning based on conventional commits. This system analyzes commit messages since the last release, determining whether to bump the major, minor, or patch version based on the types of changes made.</p><p>The workflow supports both standard conventional commits (feat:, fix:) and TDD-style messages (red:, green:, refactor:), making it flexible for different development methodologies. When a version change is warranted, it automatically:</p><ol><li>Updates the VERSION file</li><li>Generates categorized changelog entries</li><li>Creates Git tags and GitHub releases</li><li>Triggers Docker image builds with appropriate version tags</li></ol><h4>Docker Image Management</h4><p>The Docker build and publish workflow creates optimized container images for each release. It implements layer caching, vulnerability scanning, and proper tagging conventions. The workflow automatically publishes images to GitHub Container Registry, making them immediately available for deployment.</p><h4>Benefits and Impact</h4><p>These workflows have transformed the development process by:</p><ul><li>Eliminating manual version management</li><li>Ensuring consistent documentation through automated changelogs</li><li>Reducing deployment errors through standardized processes</li><li>Improving security with automated vulnerability scanning</li><li>Supporting both conventional and TDD development styles</li></ul><p>By investing in these automation workflows, we’ve created a development pipeline that allows engineers to focus on writing code while ensuring quality, consistency, and reliability throughout the software lifecycle.</p><h3>Conclusion</h3><p>Optimizing Docker setup isn’t just a technical enhancement — it’s a strategic move that impacts every stage of the development lifecycle. By reducing the frontend Docker image from 2GB to just 234MB, implementing health checks, and automating the workflows through GitHub Actions, I’ve achieved a deployment pipeline that’s fast, reliable, and scalable.</p><p>These optimizations led to tangible benefits:</p><ul><li>Faster deployments and rollbacks</li><li>Lower cloud infrastructure costs</li><li>Improved observability and uptime</li><li>Seamless CI/CD with semantic versioning and changelogs</li></ul><p>Most importantly, this setup creates space for developers to focus on building features rather than fighting infrastructure issues. Whether you’re scaling a startup product or maintaining an enterprise-grade platform, these practices lay the groundwork for efficient, production-ready deployments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11b8425787f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PantauTular Platform Monitoring]]></title>
            <link>https://medium.com/@alvaro.luqman/pantautular-platform-monitoring-3fc1567baba5?source=rss-9fbfc9137678------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fc1567baba5</guid>
            <dc:creator><![CDATA[Alvaro Luqman]]></dc:creator>
            <pubDate>Thu, 15 May 2025 05:10:07 GMT</pubDate>
            <atom:updated>2025-05-15T05:10:07.337Z</atom:updated>
            <content:encoded><![CDATA[<p>In developing our application, we recognized early that robust monitoring would be critical to ensure optimal performance, reliability, and user experience. Rather than treating monitoring as an afterthought, we established a comprehensive monitoring strategy centered on Sentry for error tracking and performance monitoring.</p><p>This article details our implementation journey and demonstrates how the monitoring configuration has directly benefited the project.</p><h4>Error Monitoring</h4><p>To ensure robust error tracking in our project, we integrated Sentry as our monitoring solution. Sentry alerts us immediately whenever the application encounters an error, allowing us to take swift and informed corrective action. It provides detailed reports that include the time of occurrence, the specific part of the codebase responsible, and other relevant contextual data.</p><p>When linked with <strong>GitHub</strong>, Sentry can even identify the commit that likely introduced the issue — streamlining the debugging process. Additionally, for each detected error, Sentry offers <strong>session replays</strong>, which visually reconstruct the user’s interaction leading up to the error. This feature has been invaluable to help replicate issues, understand their root causes, and resolve them more efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XYKhji8cDRWCG1VJV_nDqA.png" /><figcaption>Sentry’s detailed error tracking</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EwDEIjfIFZWpPIldYRvz9Q.png" /><figcaption>Sentry’s session replay</figcaption></figure><h4>Performance Monitoring</h4><p>Incorporating Web Vitals into our monitoring strategy provides a comprehensive view of the real-world performance of our application, beyond just error logging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x5k-_BdpayVBN4_mt8987A.png" /><figcaption>Sentry’s Frontend Performance Monitoring</figcaption></figure><p>Each metric represents a specific aspect of user experience that, when monitored collectively, helps ensure that the application remains fast, responsive, and visually stable.</p><ul><li><strong>Largest Contentful Paint (LCP)</strong> measures the time it takes for the largest visible element (often a hero image or block of text) to fully render on the screen. It directly reflects the loading experience and perceived speed, which are critical for user retention.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*tlJgFJqQn8a0kh_qNg3Big.png" /><figcaption>Largest Contentful Paint Stats</figcaption></figure><ul><li><strong>First Contentful Paint (FCP)</strong> captures how quickly users see the first visual feedback from the page, indicating that the app is responding. A poor FCP can make the application feel sluggish or broken, especially on slower networks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*0KjLQDxUD0PhvIvofQQFvQ.png" /><figcaption>First Contentful Paint Stats</figcaption></figure><ul><li><strong>Interaction to Next Paint (INP)</strong> measures the delay between user interactions (like clicks or taps) and the next visual update. It’s a vital metric for responsiveness and interactivity, especially in dynamic web apps like Pantautular.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*4OT2YTop0V-11TYI4kxtFA.png" /><figcaption>Interaction to Next Paint Stats</figcaption></figure><ul><li><strong>Cumulative Layout Shift (CLS)</strong> quantifies unexpected visual shifts during page load. A stable layout is key to a smooth experience — high CLS can cause users to click on the wrong elements or lose their place while reading.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*LLcpm4h-opYq4dYQa8ayFQ.png" /><figcaption>Cumulative Layout Shift Stats</figcaption></figure><ul><li><strong>Time to First Byte (TTFB)</strong> indicates the time it takes for the server to respond with the first byte of data. It reflects backend performance and impacts all subsequent rendering metrics. A slow TTFB often points to server-side bottlenecks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*ZaFvtDw_brJYjJqxZPM_EA.png" /><figcaption>Time to First Byte Stats</figcaption></figure><p>By tracking these Web Vital metrics, our team gains visibility into both front-end and back-end performance, allowing us to catch performance regressions early, correlate performance issues with user behavior, and make informed decisions for optimization — all of which are essential for delivering a polished and reliable application.</p><h4>Customized Dashboard</h4><p>Sentry allows teams to build custom dashboards tailored to specific performance and error-monitoring needs. By selecting relevant metrics and visual components, such as charts and tables, teams can consolidate insights into one centralized view. For example, as shown in the image, the dashboard displays key performance indicators like Overall LCP, FCP, and CLS, alongside metrics such as page load over time, slow page navigations, and top user issues. This setup helps teams quickly spot trends, anomalies, and regional performance disparities (e.g., LCP by country). Additionally, components like “Issues Assigned to Me” and “Slowest Page Loads” offer direct insights into ownership and performance bottlenecks. These custom dashboards empower teams to prioritize performance work, track regressions, and make data-driven decisions — all without navigating through multiple views.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xuxs3sJ3q23qGUH-07un8Q.png" /><figcaption>Custom Sentry Dashboard</figcaption></figure><h4>Alerting Strategy</h4><p>Utilizing Sentry’s Alerts module enables our team to receive real-time notifications whenever a critical error or issue requires attention. These alerts can be fully customized to monitor a wide range of events, including application errors, session crashes, performance degradation, uptime incidents, and even user-defined metrics. For instance, I configured an alert specifically to track session crash rates. The alert was set up with three severity levels:</p><ul><li><strong>Critical</strong>: Triggered when Crash-Free Sessions fall below 50%</li><li><strong>Warning</strong>: Triggered when Crash-Free Sessions fall below 95%</li><li><strong>Resolved</strong>: Triggered when Crash-Free Sessions rise above 95%</li></ul><p>This setup ensures that our team stays informed about potential stability issues and can take immediate action when the status drops to <em>Warning</em> or <em>Critical</em>, thereby improving response time and maintaining application reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ou4tXErDq-zOJlvSBjdfQA.png" /><figcaption>Crash Free Session Alert set up</figcaption></figure><p>Another valuable use of the Alerts module is monitoring high-priority errors that directly impact the user experience. In our application, these include critical issues such as failure to load data on the map or dashboard pages, rendering problems, navigation errors, and malfunctions in core features. By setting alerts for these specific scenarios, we can ensure that the team is immediately notified and able to respond swiftly to minimize user disruption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPKmOQa8ISmNh30f4PdrXw.png" /><figcaption>Alert to track high priority errors</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fc1567baba5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teamwork with Tools in Pantautular Project]]></title>
            <link>https://medium.com/@alvaro.luqman/teamwork-with-tools-in-pantautular-project-75e32990a783?source=rss-9fbfc9137678------2</link>
            <guid isPermaLink="false">https://medium.com/p/75e32990a783</guid>
            <dc:creator><![CDATA[Alvaro Luqman]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 14:20:53 GMT</pubDate>
            <atom:updated>2025-05-14T07:39:33.439Z</atom:updated>
            <content:encoded><![CDATA[<p>Teams in modern software development employ a variety of tools to increase output, simplify cooperation, guarantee code quality, and accelerate deployment. In this article, I will discuss a broad list of tools used during the development of the Pantautular application that significantly helped the members of my team.</p><h3>Project Management &amp; Collaboration</h3><p>My team makes use of Notion, which is a cloud-based, adaptive productivity application that combines note-taking, task management, project planning, and knowledge management within one environment. It facilitates the organization of information, idea capturing, and collaboration. Essentially, Notion is an online canvas where individuals can build personal systems for all sorts of uses, ranging from personal organization to project management.</p><p>In our project, we use Notion to do the following:</p><ul><li>List down all the ‘Product Backlog Items’ (PBI)</li><li>Determine story points of each PBI</li><li>Break and list down PBI into tasks</li><li>Give each task a priority and dependency value</li><li>Keep track of task progress and assignee</li></ul><h3>Version Control &amp; Collaboration</h3><p>We keep our version control and collaboration with the help of GitHub. With the help of GitHub, we can keep our codebase well managed using Git together with a solid platform for collaboration among teams, issue tracking, and continuous integration.</p><p>GitHub is of central significance to us for keeping code quality as well as coordinating teamwork in the Pantautular project. This is how we use GitHub:</p><ul><li><strong>Branching Strategy</strong>: We have a structured branching model with which we keep development environments:<br>- main: Kept for production code.<br>- staging: Used for pre-release testing and Sprint Review.<br>- PBI-[number]-[title] branches: Used for single features or fixes of specific PBIs, all from staging.</li><li><strong>Pull Requests (PRs)</strong>: A new feature or bug fix is introduced through a pull request. This enables:<br>- Code Reviews: Team members review other team members’ code to ensure quality and consistency.<br>- Discussion: We can directly comment on lines of code, ask questions, or request changes before merging.</li><li><strong>CI/CD Integration</strong>: GitHub is linked to deployment platforms (like Railway for the backend and Netlify for the frontend) to deployment procedures upon merging to specific branches.</li></ul><p>With a good use of GitHub, the development process remains organized, trackable, and collaborative; keeps everyone on board; and, in turn, retains the codebase.</p><h3>Testing &amp; Quality Assurance</h3><p>We also wrote unit tests for our frontend and backend so that each part of the application functions as expected and also to catch bugs early in development.</p><p><strong>Frontend Testing using Jest:<br></strong>On the frontend, we use Jest, a powerful JavaScript testing framework. It allows us to write unit tests for individual components and utility functions in our Next.js application. These tests are utilized to ensure that:</p><ul><li>UI components render correctly under different circumstances.</li><li>Business logic works as intended.</li><li>Refactoring doesn’t introduce regressions.</li></ul><p><strong>Backend Testing with Django Test Framework:<br></strong>In the backend, we utilize Django’s Test Case module to write unit and integration tests for our REST API endpoints. These tests confirm:</p><ul><li>API endpoints return correct status codes and data.</li><li>Data handling, filtering, and validation logic are correct.</li></ul><p>With automated testing as part of our development cycle, we make the code more stable and reduce the likelihood of bugs reaching production. This also gives us confidence to iterate quickly, knowing that existing features are being constantly verified.</p><h3><strong>Development Environments</strong></h3><p>The majority of our members prefer using Visual Studio Code (VS Code) as their code editor. It is a very lightweight, highly extensible IDE with a broad extension ecosystem that makes it suitable for both frontend and backend development. One specific extension that we use is GitHub Copilot, which is an AI coding assistant that suggests whole lines or blocks of code and speeds up the development process while reducing boilerplate work.</p><p>Personally, I work with Cursor AI, a GPT-based developer IDE. Cursor offers end-to-end code comprehension and in-line AI feedback tailored to your codebase. It helps me with:</p><ul><li>Coming up with or rewriting functions with natural language suggestions.</li><li>Navigating complex code constructs better.</li><li>Improving debugging and issue resolution with conversational AI.</li><li>Generate comprehensive tests</li><li>Analyze code architecture and performance</li></ul><p>These development tools, coupled with version control and collaboration via GitHub, allow our team to code more reliably and efficiently. Having a uniform setup among the team members also makes pair programming, debugging, and onboarding much simpler.</p><h3>Cross-Platform Integration</h3><p>Our team utilizes a broad selection of software integrations to further increase our productivity. This ensures that the development is transparent throughout the whole team and that we deliver a polished product.</p><p>One of the integrations applied is the GitHub-Discord integration. With the current configuration, this integration sends notifications in the form of messages for every GitHub commit and merge request in our team’s Discord server. The messages are also linked with the commit or merge request link too, so the team can also navigate to the respective GitHub page if needed.</p><p>Another integration is the SonarQube integration. This is integrated into our GitHub repositories, and a SonarQube check will be triggered when any of the team members initiate a merge request. Once triggered, the app will analyze the latest commit of the branch that will be merged and provide the results for the following fields:</p><ul><li>Code issues (code smells, etc.)</li><li>Security Hotspots</li><li>Code Coverage</li><li>Code Duplications</li></ul><h3>How it Impacted our Team</h3><p>With the given tools that our team has integrated and applied in our project development, we’ve tackled a bunch of problems that we’ve experienced throughout the semester.</p><h4>Easy Task Tracking and Organization</h4><p>The use of Notion enabled us to efficiently manage tasks and set clear priorities. This significantly improved our ability to identify high-dependency tasks that required immediate attention. Additionally, we were able to monitor task progress and provide timely reminders to assignees to ensure deadlines were met.</p><h4>Improved Communication &amp; Transparency</h4><p>By leveraging Discord as our primary communication channel, our team maintained seamless and asynchronous communication. It became our digital office — where we could quickly share updates, resolve conflicts, and conduct sprint discussions. Features such as pinned messages and thread conversations helped in organizing discussions and referencing them when needed. When combined with GitHub integrations, Discord provided a centralized stream of updates — ensuring that no changes or decisions went unnoticed by any member. From time to time, we managed to reduce conflicts that arise during the merging process, which shows how impactful both Discord and its integrations are.</p><h4>Provide High Quality Code</h4><p>The integration of AI tools such as ChatGPT, Claude, Cursor, and GitHub Copilot has greatly enhanced our ability to produce clean, well-structured code. These tools have been instrumental not only in generating functions and improving code quality but also in refactoring our codebase efficiently. In addition, we leveraged AI tools to analyze our code for potential issues such as code smells and areas for improvement. This proactive approach helped us maintain high standards throughout development. Overall, the use of AI significantly boosted our productivity — enabling us to complete tasks on time, resolve errors swiftly, and generate effective unit tests with ease.</p><h4>Increased Code Confidence with Static Analysis</h4><p>Integrating SonarQube into our development workflow significantly increased our confidence in the quality and reliability of our code. Each pull request underwent automated static code analysis before it could be merged, ensuring that potential issues were identified early in the process. This proactive approach allowed us to catch hidden bugs and security vulnerabilities that might have otherwise gone unnoticed. Over time, the presence of SonarQube encouraged the entire team to adopt cleaner coding practices, as we became more aware of code smells and technical debt. Moreover, the integration fostered a culture of accountability — every team member was motivated to meet the quality standards set by SonarQube before submitting their code for review, leading to more consistent and maintainable code across the project.</p><h4>Cultivated a Culture of Peer Review</h4><p>The use of GitHub pull requests (PRs) in our workflow went beyond their technical function and played a vital role in fostering a culture of collaborative learning within the team. PRs became a space for open dialogue, where team members could learn from each other’s implementations and exchange suggestions for improvement. This process proved especially beneficial for members, who were able to accelerate their growth by receiving constructive, real-time feedback from other peers. Over time, it cultivated a habit of reading, reviewing, and understanding code written by others — enhancing team cohesion and promoting a sense of shared ownership over the entire codebase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75e32990a783" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quality Assurance Implementation in Pantautular Project]]></title>
            <link>https://medium.com/@alvaro.luqman/quality-assurance-implementation-in-pantautular-project-7ee07d448ecb?source=rss-9fbfc9137678------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ee07d448ecb</guid>
            <dc:creator><![CDATA[Alvaro Luqman]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 13:22:47 GMT</pubDate>
            <atom:updated>2025-05-19T11:07:11.300Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will discuss my approach to quality assurance. I’ll focus on static analysis, code coverage, and continuous improvement. This is all possible thanks to tools like SonarQube and implementing thorough testing practices.</p><h3>Quality Assurance Strategy</h3><p>The quality assurance follows the shift-left approach, which incorporates testing and quality checks early in the development process rather than as an afterthought. This methodology ensures that errors are identified and resolved as quickly as possible, reducing technical issues and preventing problems from stacking.</p><p>The strategy tracks the following metrics:</p><ul><li>Code coverage</li><li>Code smells and maintainability</li><li>Duplications</li><li>Security vulnerabilities</li></ul><p>These metrics provide a comprehensive view of code quality while also providing practical recommendations for improvement. The constant checking of these metrics ensures that the application not only works as intended but also remains sustainable and scalable over time.</p><h3>Tools and Infrastructure</h3><h4>SonarQube Implementation</h4><p>SonarQube is the foundation of the quality assurance architecture. It includes complete static code analysis and a dashboard for quality metrics. SonarQube does the following:</p><ul><li>Analyze code on every GitHub commit during the merging process.</li><li>Identify security vulnerabilities and code smells</li><li>Measure technical issues accumulation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8rvBr_wUUoETP1vXD8rLQ.png" /><figcaption>SonarQube analysis during merging: <a href="https://github.com/PPL-BRIN/pantautular-be/pull/60">https://github.com/PPL-BRIN/pantautular-be/pull/60</a></figcaption></figure><h4>Testing Framework Setup</h4><p>For code coverage and functional testing on both the frontend and backend, I made use of Jest and Django’s Test, respectively.</p><p>I’ve configured Jest to ensure 100% and detailed code coverage during every test. The backend part has been set up similarly; thus, both frameworks will always get a 100% code coverage report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*05_WO4jLB0cKlsV2UkaX_g.png" /><figcaption>Code coverage example on frontend using Jest</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*7bsQ0Eq0NIizeFYSxCyzRA.png" /><figcaption>Code coverage example on backend using Django’s test</figcaption></figure><h3>The Impact on PantauTular Project</h3><p>Using static analysis tools like SonarQube, I ensure high code quality by aligning with its standards across key metrics such as bugs, code smells, security vulnerabilities, test coverage, and maintainability. This process has greatly enhanced the clarity, reliability, and overall structure of my code. Below, I outline how SonarQube has helped me identify and improve critical areas in my projects.</p><h4>Removing Code Duplications</h4><p>SonarQube effectively detects duplicated blocks of code, which are often overlooked during development. By identifying these repetitions, I was able to refactor my codebase to promote reuse and simplify maintenance. This not only reduced redundancy but also improved overall readability and made future updates less error-prone.</p><p>One evident example is when I attempted to refactor my map chart service on my frontend. The goal of the refactor is to reduce the complexity of the service, from a monolithic 1200 lines of code to separated sub-services, thus ensuring a more scalable and maintainable service. During this process, SonarQube detected a code duplication on one of the sub-services that&#39;s responsible for handling map layers. Thanks to it, I was able to resolve this duplication and increase the quality of my code. Here is the related git commit: <a href="https://github.com/PPL-BRIN/pantautular-fe/pull/108/commits/2dcb5639c7032189de328421102810fec702230d">https://github.com/PPL-BRIN/pantautular-fe/pull/108/commits/2dcb5639c7032189de328421102810fec702230d</a></p><h4>Strengthening Security</h4><p>SonarQube highlights potential security vulnerabilities early in the development cycle, such as injection flaws, insecure configurations, or unvalidated inputs. Addressing these issues has helped me write more secure and robust applications, following best practices to protect against common threats and ensure data integrity.</p><p>During the implementation of the Docker workflow for my backend service, I added health checks to monitor the application’s state. To support this, I created a new view specifically for handling the health check endpoint. Upon committing the changes, SonarQube flagged a security issue: I had forgotten to explicitly specify the allowed HTTP method for that view using the decorator,@require_http_methods([&#39;GET&#39;]) . This restriction is important because, without it, the endpoint could unintentionally accept and process requests using other methods such as POST or PUT, which could expose the application to misuse or denial-of-service scenarios. Here is the related commit: <a href="https://github.com/PPL-BRIN/pantautular-be/pull/109/commits/0ff4e8b425a47abbad95bba215a25e5718319591">https://github.com/PPL-BRIN/pantautular-be/pull/109/commits/0ff4e8b425a47abbad95bba215a25e5718319591</a></p><h4>Fix Code Smells</h4><p>Code smells indicate areas of the code that may work functionally but are poorly structured or difficult to understand. SonarQube helped me identify such areas — like overly complex methods or poor naming conventions — and guided me in refactoring them. This led to cleaner, more maintainable code that’s easier for others (and my future self) to read and build upon.</p><p>There are a number of code smell issues that I’ve encountered throughout the development of this project. The types of code smells are ones such as unused/useless variables, incorrect fallback handling, and others.</p><p>Here are some commit examples where I attempted to fix code smells detected by SonarQube:</p><ul><li><strong>Unused Variables: </strong><a href="https://github.com/PPL-BRIN/pantautular-fe/pull/65/commits/90046278714c58901a80afaa93a365bbe9a3839b">https://github.com/PPL-BRIN/pantautular-fe/pull/65/commits/90046278714c58901a80afaa93a365bbe9a3839b</a></li><li><strong>Incorrect Fallback Handling: </strong><a href="https://github.com/PPL-BRIN/pantautular-fe/pull/109/commits/1472c20a2c0a601087c5d601d2dcaf82b7636ed0">https://github.com/PPL-BRIN/pantautular-fe/pull/109/commits/1472c20a2c0a601087c5d601d2dcaf82b7636ed0</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ee07d448ecb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practice Programming & SOLID Principles on Pantautular’s Frontend Development]]></title>
            <link>https://medium.com/@alvaro.luqman/best-practice-programming-solid-principles-on-pantautulars-frontend-development-5e71b368e785?source=rss-9fbfc9137678------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e71b368e785</guid>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Alvaro Luqman]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 06:22:21 GMT</pubDate>
            <atom:updated>2025-05-15T05:32:50.844Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll discuss a real-world refactoring of a React component that implements AmCharts for map visualization and see how applying SOLID principles dramatically improved the code structure, maintainability, and extensibility.</p><p>The commit we’ll analyze transformed a humongous 170+ line React component into a well-structured, modular implementation with clear separation of concerns. Let’s dive into how each SOLID principle was applied and the benefits that emerged from this refactoring.</p><h3>The Original Implementation: A Monolithic Component</h3><p>Let’s first look at the original implementation. The `MapPage` component was a monolithic 174-line component that mixed multiple concerns:</p><ul><li>Component rendering</li><li>Library integration (AmCharts)</li><li>Data management</li><li>Cleanup logic</li></ul><p>This violates several SOLID principles, particularly SRP. The component was doing way too much, making it difficult to test, maintain, or extend.</p><pre>// Original implementation (abbreviated)<br>export default function MapPage() {<br>  const chartRef = useRef&lt;am5.Root | null&gt;(null);<br><br>  useEffect(() =&gt; {<br>    if (!chartRef.current) return;<br><br>    const root = am5.Root.new(&quot;chartdiv&quot;)<br>    chartRef.current = root;<br>    root.setThemes([am5themes_Animated.new(root)]);<br><br>    let chart = root.container.children.push(<br>      am5map.MapChart.new(root, {<br>        // Chart configuration...<br>      })<br>    );<br><br>    // [160+ more lines of AmCharts setup]<br>    <br>    return () =&gt; {<br>      if (chartRef.current) {<br>        chartRef.current.dispose();<br>        chartRef.current = null;<br>      }<br>    };<br>  }, []);<br><br>  return (<br>    &lt;div id=&quot;chartdiv&quot; data-testid=&quot;map-container&quot; style={{ width: &quot;100%&quot;, height: &quot;550px&quot; }} /&gt;<br>  );<br>}</pre><p>This implementation has several issues:</p><p>1. Poor Separation of Concerns: UI rendering, data management, and library integration are all mixed together.</p><p>2. Hard-coded Configuration: Map settings and data are hard-coded within the component.</p><p>3. Difficult Testing: The monolithic nature makes unit testing nearly impossible.</p><p>4. Poor Reusability: The component cannot be easily reused with different data or configurations.</p><h3>Early-Sprint Application of SOLID Principles</h3><p>Now I’ll discuss how the refactored code addresses these issues by applying SOLID principles.</p><h4>1. Single Responsibility Principle (SRP)</h4><p>The refactoring splits the monolithic component into multiple files, each with a single responsibility:</p><p>- IndonesiaMap.tsx: Presentation component (renders the DOM)</p><p>- useIndonesiaMap.ts: Custom hook for map lifecycle management</p><p>- mapChartService.ts: Service for AmCharts integration</p><p>- types/index.ts: Type definitions</p><p>- data/indonesiaLocations.ts: Data separated from components</p><p>This is a look at the IndonesiaMap component:</p><pre>// components/IndonesiaMap.tsx - Presentation component<br>import React from &quot;react&quot;;<br>import { useIndonesiaMap } from &quot;../hooks/useIndonesiaMap&quot;;<br>import { MapLocation, MapConfig } from &quot;../types&quot;;<br><br>interface IndonesiaMapProps {<br>  locations: MapLocation[];<br>  config?: Partial&lt;MapConfig&gt;;<br>  height?: string;<br>  width?: string;<br>}<br><br>export const IndonesiaMap: React.FC&lt;IndonesiaMapProps&gt; = ({<br>  locations,<br>  config = {},<br>  height = &quot;550px&quot;,<br>  width = &quot;100%&quot;,<br>}) =&gt; {<br>  const mapContainerId = &quot;chartdiv&quot;;<br>  const fullConfig: MapConfig = {<br>    zoomLevel: config.zoomLevel ?? 2,<br>    centerPoint: config.centerPoint ?? { longitude: 113.9213, latitude: 0.7893 }<br>  };<br><br>  useIndonesiaMap(mapContainerId, locations, fullConfig);<br><br>  return (<br>    &lt;div<br>      id={mapContainerId}<br>      data-testid=&quot;map-container&quot;<br>      style={{ width, height }}<br>    /&gt;<br>  );<br>};</pre><p>This component is now only responsible for rendering the DOM element and handling props. All the AmCharts integration logic has been moved to the service and hook.</p><p>The custom useIndonesiaMap.tsx hook now manages the lifecycle:</p><pre>// hooks/useIndonesiaMap.ts<br>import { useEffect, useRef } from &quot;react&quot;;<br>import { MapChartService } from &quot;../services/mapChartService&quot;;<br>import { MapLocation, MapConfig } from &quot;../types&quot;;<br><br>export const useIndonesiaMap = (<br>  containerId: string,<br>  locations: MapLocation[],<br>  config: MapConfig<br>) =&gt; {<br>  const mapServiceRef = useRef&lt;MapChartService | null&gt;(null);<br><br>  useEffect(() =&gt; {<br>    // Create a new map service if it doesn&#39;t exist<br>    if (!mapServiceRef.current) {<br>      mapServiceRef.current = new MapChartService();<br>      <br>      // Initialize the chart<br>      mapServiceRef.current.initialize(containerId, config);<br>      <br>      // Add location data<br>      mapServiceRef.current.populateLocations(locations);<br>    }<br><br>    // Cleanup function<br>    return () =&gt; {<br>      if (mapServiceRef.current) {<br>        mapServiceRef.current.dispose();<br>        mapServiceRef.current = null;<br>      }<br>    };<br>  }, [containerId, locations, config]);<br><br>  return { mapService: mapServiceRef.current };<br>};</pre><p>The hook is only responsible for managing the lifecycle of the map service, handling initialization, and cleanup.</p><p>The mapChartService service handles all AmCharts-specific code:</p><pre>// services/mapChartService.ts (abbreviated)<br>export class MapChartService {<br>  private root: am5.Root | null = null;<br>  private chart: am5map.MapChart | null = null;<br>  private pointSeries: am5map.ClusteredPointSeries | null = null;<br><br>  initialize(containerId: string, config: MapConfig): void {<br>    // AmCharts initialization<br>  }<br><br>  private setupZoomControl(): void {<br>    // Zoom control setup<br>  }<br><br>  private setupPolygonSeries(): void {<br>    // Polygon series setup<br>  }<br>  <br>  // Other methods...<br><br>  populateLocations(locations: MapLocation[]): void {<br>    // Location data population<br>  }<br><br>  dispose(): void {<br>    // Cleanup logic<br>  }<br>}</pre><p>This service is only responsible for interfacing with AmCharts, providing a clean API for the rest of the application.</p><h4>2. Open/Closed Principle (OCP)</h4><p>The refactored code is now much more extensible. New features can be added without modifying existing code:</p><p><strong>1. The `IndonesiaMap` component accepts configurable props with sensible defaults:</strong></p><pre>interface IndonesiaMapProps {<br>  locations: MapLocation[];<br>  config?: Partial&lt;MapConfig&gt;;<br>  height?: string;<br>  width?: string;<br>}</pre><p><strong>2. The default configuration is centralized and can be overridden:</strong></p><pre>const fullConfig: MapConfig = {<br>  zoomLevel: config.zoomLevel ?? 2,<br>  centerPoint: config.centerPoint ?? { longitude: 113.9213, latitude: 0.7893 }<br>};</pre><p>This makes it possible to extend the component’s functionality by passing different props without changing its implementation.</p><p><strong>3. The service methods are broken down into smaller, private methods that can be overridden in subclasses if needed:</strong></p><pre>initialize(containerId: string, config: MapConfig): void {<br>  // Create root element<br>  this.root = am5.Root.new(containerId);<br>  <br>  // Rest of the implementation...<br>  <br>  // Setup methods can be overridden in subclasses<br>  this.setupZoomControl();<br>  this.setupPolygonSeries();<br>  this.setupPointSeries();<br>}</pre><h4>3. Dependency Inversion Principle (DIP)</h4><p>The refactored code now depends on abstractions rather than concrete implementations:</p><ul><li>The `IndonesiaMap` component depends on the `useIndonesiaMap` hook, not directly on AmCharts</li><li>The hook depends on the `MapChartService` interface, not its implementation details</li><li>Data is passed in as props, not hard-coded in the component</li></ul><p>This inversion of dependencies makes the code more testable and flexible.</p><h3>Late-Sprint Application of SOLID Principles</h3><p>During the fourth sprint, I realized that the implementation of the map chart service — responsible for generating the map UI — had grown into an overly complex and monolithic structure, reaching over 1,200 lines of code. It combined multiple responsibilities, including base map generation, layer rendering, legend UI, tooltip generation, and various smaller yet essential utilities. This tightly coupled design made the codebase difficult to maintain, test, and scale. Thus, a huge refactoring has been done, applying SOLID principles and design patterns to achieve a more maintainable and scalable code architecture.</p><h4>1. Single Responsibility Principle (SRP)</h4><p>The introduction of MapChartManager and supporting classes (LayerManager, SeriesFactory, LegendBuilder, and TooltipService) demonstrates clear application of SRP. Each class has a well-defined responsibility:</p><ul><li>MapChartManager: Handles overall map initialization and orchestrates other components</li><li>LayerManager: Manages visibility and data for different map layers</li><li>SeriesFactory: Creates different types of map series (humidity, temperature, severity, etc.)</li><li>LegendBuilder: Constructs legends for different map visualizations</li><li>TooltipService: Handles creation and management of tooltips</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*_70JKUKhzSX0NILLG-0ovg.png" /><figcaption>Map service architecture</figcaption></figure><p>This separation of concerns has improved the codebase by moving layer management logic from UI components (like HumidityButton and TemperatureButton) into specialized service classes.</p><h4>2. Open/Closed Principle (OCP)</h4><p>The new architecture is designed to be open for extension but closed for modification.</p><ul><li>New map layers can be added by extending the SeriesFactory without modifying existing code</li><li>New legend types can be added to LegendBuilder without changing existing implementation</li><li>The UI components like buttons no longer need to change when map layer logic is updated</li></ul><h4>3. Dependency Inversion Principle (DIP)</h4><p>The code now relies on abstractions rather than concrete implementations.</p><ul><li>MapChartService acts as a facade that delegates to MapChartManager</li><li>Components depend on abstract interfaces rather than directly manipulating map features</li><li>The UI layer is decoupled from the direct map implementation details</li></ul><h3>Best Practices Applied</h3><h4>1. Modular Design</h4><p>The refactoring introduces a modular architecture where each component is self-contained and has a specific purpose. This makes the codebase more maintainable, as developers can focus on specific modules without understanding the entire system.</p><h4>2. Facade Pattern</h4><p>MapChartService now serves as a facade, providing a simplified interface to the complex subsystem with MapChartManager and related classes. This pattern reduces coupling between the UI layer and the map visualization implementation.</p><pre>import { MapLocation, MapConfig, ProvinceData } from &quot;../types&quot;;<br>import { MapChartManager } from &quot;./map&quot;;<br><br>/**<br> * Main MapChartService class - acts as a facade for the map chart subsystem<br> * This version has been refactored for better maintainability using a more modular architecture<br> */<br>export class MapChartService {<br>  private readonly mapManager: MapChartManager;<br><br>  constructor(onError?: (message: string) =&gt; void) {<br>    this.mapManager = new MapChartManager(onError);<br>  }<br><br>  /**<br>   * Initialize the map chart<br>   */<br>  initialize(containerId: string, config: MapConfig): void {<br>    this.mapManager.initialize(containerId, config);<br>  }<br><br>  /**<br>   * Clean up resources when component is unmounted<br>   */<br>  dispose(): void {<br>    this.mapManager.dispose();<br>  }<br><br>  /**<br>   * Populate map with location points<br>   */<br>  populateLocations(locations: MapLocation[]): void {<br>    this.mapManager.populateLocations(locations);<br>  }<br><br>  /**<br>   * Get the count of points currently in view<br>   */<br>  get countSelectedPoints(): number {<br>    return this.mapManager.countSelectedPoints;<br>  }<br><br>  /**<br>   * Zoom to a specific location on the map<br>   */<br>  zoomToLocation(latitude: number, longitude: number): void {<br>    this.mapManager.zoomToLocation(latitude, longitude);<br>  }<br><br>  /**<br>   * Populate humidity data for provinces<br>   */<br>  populateProvinceHumidityData(provinceHumidityData: ProvinceData[]): void {<br>    this.mapManager.populateProvinceHumidityData(provinceHumidityData);<br>  }<br><br>  /**<br>   * Populate precipitation data for provinces<br>   */<br>  populateProvincePrecipitationData(provincePrecipitationData: ProvinceData[]): void {<br>    this.mapManager.populateProvincePrecipitationData(provincePrecipitationData);<br>  }<br><br>  /**<br>   * Populate temperature data for provinces<br>   */<br>  populateProvinceTemperatureData(provinceTemperatureData: ProvinceData[]): void {<br>    this.mapManager.populateProvinceTemperatureData(provinceTemperatureData);<br>  }<br><br>  /**<br>   * Populate severity data for provinces<br>   */<br>  populateProvinceSeverityData(provinceSeverityData: ProvinceData[]): void {<br>    this.mapManager.populateProvinceSeverityData(provinceSeverityData);<br>  }<br><br>  /**<br>   * Show humidity layer on the map<br>   */<br>  showHumidityLayer(): void {<br>    this.mapManager.toggleLayers(true, true, true, false, true, false, false);<br>  }<br><br>  /**<br>   * Hide humidity layer on the map<br>   */<br>  hideHumidityLayer(): void {<br>    this.mapManager.toggleLayers(true, true, true, false, false, false, false);<br>  }<br><br>  /** <br>   * Show precipitation layer on the map<br>   */<br>  showPrecipitationLayer(): void {<br>    this.mapManager.toggleLayers(true, true, true, true, false, false, false);<br>  }<br><br>  /** <br>   * Hide precipitation layer on the map<br>   */<br>  hidePrecipitationLayer(): void {<br>    this.mapManager.toggleLayers(true, true, true, false, false, false, false);<br>  }<br>  <br>  /**<br>   * Show temperature layer on the map<br>   */<br>  showTemperatureLayer(): void {<br>    this.mapManager.toggleLayers(true, true, true, false, false, true, false);<br>  }<br><br>  /**<br>   * Hide temperature layer on the map<br>   */<br>  hideTemperatureLayer(): void {<br>    this.mapManager.toggleLayers(true, true, true, false, false, false, false);<br>  }<br><br>  /**<br>   * Show severity layer on the map<br>   */<br>  showSeverityLayer(): void {<br>    this.mapManager.toggleLayers(true, true, true, false, false, false, true);<br>  }<br><br>  /**<br>   * Hide severity layer on the map<br>   */<br>  hideSeverityLayer(): void {<br>    this.mapManager.toggleLayers(true, true, true, false, false, false, false);<br>  }<br><br>  /**<br>   * Hide all theme layers on the map<br>   */<br>  hideAllLayers(): void {<br>    this.mapManager.toggleLayers(true, true, true, false, false, false, false);<br>  }<br><br>  /**<br>   * Toggle the visibility of map layers<br>   */<br>  toggleLayers(<br>    showBase: boolean, <br>    showHighlight: boolean, <br>    showPoints: boolean, <br>    showPrecipitation: boolean, <br>    showHumidity: boolean, <br>    showTemperature: boolean, <br>    showSeverity: boolean<br>  ): void {<br>    this.mapManager.toggleLayers(<br>      showBase, <br>      showHighlight, <br>      showPoints, <br>      showPrecipitation, <br>      showHumidity, <br>      showTemperature, <br>      showSeverity<br>    );<br>  }<br>}</pre><h4>3. Factory Pattern</h4><p>The SeriesFactory class demonstrates the factory pattern by encapsulating the creation logic for different types of map series. This centralizes creation logic and standardizes how series are configured.</p><h4>4. Error Handling</h4><p>The implementation includes proper error handling, such as try-catch blocks in tooltips and initialization code, improving the robustness of the application.</p><h3>Conclusion</h3><p>This refactoring demonstrates that SOLID principles can be effectively applied to frontend development, even when working with stateful, imperative libraries like AmCharts. By separating concerns, defining clear interfaces, and inverting dependencies, the code became more maintainable, testable, and extensible.</p><h3>Related Github Commit</h3><ul><li>Early-Sprint: <a href="https://github.com/PPL-BRIN/pantautular-fe/commit/f680f22fcac60b7636bdca5cbf5af39d68f946dc">https://github.com/PPL-BRIN/pantautular-fe/commit/f680f22fcac60b7636bdca5cbf5af39d68f946dc</a></li><li>Late-Sprint: <a href="https://github.com/PPL-BRIN/pantautular-fe/commit/81bc077b0e270bd1362d764d05d44935879fa526">https://github.com/PPL-BRIN/pantautular-fe/commit/81bc077b0e270bd1362d764d05d44935879fa526</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e71b368e785" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practice Programming & SOLID Principles on Pantautular’s Backend Development]]></title>
            <link>https://medium.com/@alvaro.luqman/best-practice-programming-solid-principles-on-pantautulars-backend-development-9bfffc50b74e?source=rss-9fbfc9137678------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bfffc50b74e</guid>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Alvaro Luqman]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 05:52:26 GMT</pubDate>
            <atom:updated>2025-03-25T05:56:13.160Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll discuss the architecture of Pantautular, a disease surveillance platform developed in Indonesia, focusing on how it implements software engineering best practices—particularly SOLID principles—to create a robust, maintainable system.</p><h3>SOLID Principles in Practice</h3><p>I will discuss how each of the SOLID principles is applied in the Pantautular codebase:</p><h4>1. Single Responsibility Principle (SRP)</h4><p>The SRP states that a class should have only one reason to change. In Pantautular, this is evident in the clear separation of repositories, services, and views:</p><pre># Repository handles data access only<br>class CaseRepository(CaseRepositoryInterface):<br>    def get_all_locations(self):<br>        return Case.get_all_locations()<br>    def get_prevalence(self, year=None):<br>        POPULATION_DATA = {<br>            2019: 266911.9,<br>            2020: 270203.9,<br>            2021: 272682.5,<br>            2022: 275773.8,  <br>            2023: 278696.2,  <br>            2024: 281603.8,   <br>        }<br>        <br>        if year is None:<br>            year = 2024<br>            <br>        try:<br>            total_cases = Case.objects.filter(<br>                news__date_published__year=year<br>            ).distinct().count()<br>            <br>            population = POPULATION_DATA.get(year)<br>            if not population:<br>                return {&quot;error&quot;: f&quot;Population data not available for year {year}&quot;}<br>            <br>            population = int(population * 1_000)  <br>            <br>            prevalence = (total_cases / population) * 100<br>            <br>            return {<br>                &quot;year&quot;: year,<br>                &quot;total_cases&quot;: total_cases,<br>                &quot;population&quot;: population,<br>                &quot;prevalence&quot;: prevalence<br>            }<br>            <br>        except Exception as e:<br>            return {&quot;error&quot;: f&quot;Error calculating prevalence: {str(e)}&quot;}</pre><pre># Service layer handles business logic<br>class CaseService:<br>    def __init__(self, repository, cache_service):<br>        self.repository = repository<br>        self.cache_service = cache_service<br><br>    def get_all_case_locations(self):<br>        # Try to get from cache first<br>        cached_locations = self.cache_service.get(&#39;all_case_locations&#39;)<br>        if cached_locations:<br>            return cached_locations<br>        <br>        # If not in cache, get from repository and cache it<br>        locations = self.repository.get_all_locations()<br>        self.cache_service.set(&#39;all_case_locations&#39;, locations, 3600)  # Cache for 1 hour<br>        return locations</pre><pre># View handles HTTP concerns only<br>class PrevalenceView(APIView):<br>    def get(self, request):<br>        try:    <br>            repository = CaseRepository()<br>            result = repository.get_prevalence()<br>            <br>            if &quot;error&quot; in result:<br>                return Response(<br>                    {&quot;error&quot;: result[&quot;error&quot;]}, <br>                    status=status.HTTP_404_NOT_FOUND<br>                )<br>            <br>            serializer = PrevalenceSerializer(data=result)<br>            if serializer.is_valid():<br>                return Response(serializer.data, status=status.HTTP_200_OK)<br>            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br>            <br>        except ValueError as e:<br>            return Response(<br>                {&quot;error&quot;: str(e)}, <br>                status=status.HTTP_400_BAD_REQUEST<br>            )</pre><p><strong>Benefits of Implementation:</strong></p><ul><li>Testability: Each component can be tested in isolation, as demonstrated by the comprehensive test suite that includes specific tests for repositories, services, and views.</li><li>Maintainability: When a change is needed, only the relevant component needs modification.</li><li>Readability: New developers can quickly understand the system by following the clear separation of concerns.</li></ul><h4>2. Open/Closed Principle (OCP)</h4><p>The OCP states that software entities should be open for extension but closed for modification. Pantautular achieves this through its extensive use of interfaces and abstract classes:</p><pre># Abstract base class defines the contract<br>class CaseRepositoryInterface(ABC):<br>    @abstractmethod<br>    def get_all_locations(self):<br>        pass</pre><pre># Implementation adheres to the interface<br>class CaseRepository(CaseRepositoryInterface):<br>    def get_all_locations(self):<br>        # Implementation details...</pre><p>This approach means that new repository implementations can be added without changing existing code, and client code doesn’t need to change when repository implementations change.</p><p><strong>Benefits of Implementation:</strong></p><ul><li>Extensibility: When a new data source is needed, simply create a new repository implementation.</li><li>Stability: Core components remain unchanged when extensions are added.</li><li>Plug-and-play architecture: Components can be swapped with minimal impact on the overall system.</li></ul><h4>3. Liskov Substitution Principle (LSP)</h4><p>The LSP states that subtypes must be substitutable for their base types. In Pantautular, repository implementations adhere strictly to their interfaces:</p><pre>class CaseRepositoryInterface(ABC):<br>    @abstractmethod<br>    def get_all_locations(self):<br>        pass  # pragma: no cover<br>        <br>    @abstractmethod<br>    def get_prevalence(self, year=None):<br>        pass  # pragma: no cover</pre><pre>class CaseRepository(CaseRepositoryInterface):<br>    def get_all_locations(self):<br>        return Case.get_all_locations()<br>        <br>    def get_prevalence(self, year=None):<br>        # Implementation details...</pre><p>Any service using CaseRepositoryInterface can work with any implementation of CaseRepository without knowing the specific implementation details.</p><p><strong>Benefits in Action:</strong></p><ul><li>Interchangeability: Different repository implementations can be used interchangeably.</li><li>Future-proofing: As data sources evolve, new repository implementations can seamlessly replace old ones.</li></ul><h4>4. Interface Segregation Principle (ISP)</h4><p>The ISP states that clients should not be forced to depend on interfaces they do not use. Pantautular applies this by creating focused, purpose-specific interfaces:</p><pre># Focused on case-related data access<br>class CaseRepositoryInterface(ABC):<br>    @abstractmethod<br>    def get_all_locations(self):<br>        pass<br>        <br>    @abstractmethod<br>    def get_prevalence(self, year=None):<br>        pass</pre><pre># Separate interface for news-related concerns<br>class NewsRepositoryInterface(ABC):<br>    @abstractmethod<br>    def get_healthcare_news_statistics(self):<br>        pass</pre><p>Rather than having one monolithic repository interface, there are several specialized interfaces focused on specific domain concerns.</p><p><strong>Benefits in Action:</strong></p><ul><li>Modularity: Components only depend on the interfaces they actually need.</li><li>Clear boundaries: Domain concerns are properly segregated.</li></ul><h4>5. Dependency Inversion Principle (DIP)</h4><p>The DIP states that high-level modules should not depend on low-level modules; both should depend on abstractions. Pantautular implements this principle by having its services depend on repository interfaces rather than concrete implementations:</p><pre>class CaseService:<br>    def __init__(self, repository, cache_service):<br>        self.repository = repository  # Depends on interface, not implementation<br>        self.cache_service = cache_service</pre><p><strong>Benefits in Action:</strong></p><ul><li>Flexibility: Different repository implementations can be injected.</li><li>Testability: Dependencies can be easily mocked for testing.</li><li>Reduced coupling: High-level components are isolated from changes in low-level components.</li></ul><h3>Beyond SOLID: Code Layers</h3><p>While SOLID principles form the foundation, Pantautular employs additional patterns that complement and enhance the architecture:</p><h4>The Repository Layer</h4><pre>def get_prevalence(self, year=None):<br>    POPULATION_DATA = {<br>        2019: 266911.9,<br>        2020: 270203.9,<br>        2021: 272682.5,<br>        2022: 275773.8,  <br>        2023: 278696.2,  <br>        2024: 281603.8,   <br>    }<br>    <br>    if year is None:<br>        year = 2024<br>        <br>    try:<br>        total_cases = Case.objects.filter(<br>            news__date_published__year=year<br>        ).distinct().count()<br>        <br>        population = POPULATION_DATA.get(year)<br>        if not population:<br>            return {&quot;error&quot;: f&quot;Population data not available for year {year}&quot;}<br>        <br>        population = int(population * 1_000)  <br>        <br>        prevalence = (total_cases / population) * 100<br>        <br>        return {<br>            &quot;year&quot;: year,<br>            &quot;total_cases&quot;: total_cases,<br>            &quot;population&quot;: population,<br>            &quot;prevalence&quot;: prevalence<br>        }<br>        <br>    except Exception as e:<br>        return {&quot;error&quot;: f&quot;Error calculating prevalence: {str(e)}&quot;}</pre><h4>The Serialization Layer</h4><pre>class PrevalenceSerializer(serializers.Serializer):<br>    year = serializers.IntegerField()<br>    total_cases = serializers.IntegerField()<br>    population = serializers.IntegerField()<br>    prevalence = serializers.FloatField()</pre><h4>The View Layer</h4><pre>class PrevalenceView(APIView):<br>    def get(self, request):<br>        try:    <br>            repository = CaseRepository()<br>            result = repository.get_prevalence()<br>            <br>            if &quot;error&quot; in result:<br>                return Response(<br>                    {&quot;error&quot;: result[&quot;error&quot;]}, <br>                    status=status.HTTP_404_NOT_FOUND<br>                )<br>            <br>            serializer = PrevalenceSerializer(data=result)<br>            if serializer.is_valid():<br>                return Response(serializer.data, status=status.HTTP_200_OK)<br>            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br>            <br>        except ValueError as e:<br>            return Response(<br>                {&quot;error&quot;: str(e)}, <br>                status=status.HTTP_400_BAD_REQUEST<br>            )</pre><h3>Conclusion</h3><p>The Pantautular system demonstrates how applying SOLID principles and complementary design patterns can create a robust, flexible architecture for public health surveillance. By separating concerns, depending on abstractions, and designing for testability, the system is well-positioned to evolve and adapt to new requirements.</p><p>For developers working on similar systems, the architectural patterns demonstrated in Pantautular (hopefully) provide valuable lessons on building resilient, maintainable software for public health.</p><h3>Related Github Commits:</h3><ul><li><a href="https://github.com/PPL-BRIN/pantautular-be/commit/f747602433157acebf6189c666dd012b26e0dae9">https://github.com/PPL-BRIN/pantautular-be/commit/f747602433157acebf6189c666dd012b26e0dae9</a></li><li><a href="https://github.com/PPL-BRIN/pantautular-be/commit/1896975b39e005d8763f5badc9163657b248543b">https://github.com/PPL-BRIN/pantautular-be/commit/1896975b39e005d8763f5badc9163657b248543b</a></li><li><a href="https://github.com/PPL-BRIN/pantautular-be/commit/fa46d109dbb82ef36cfb3f1282a0e826ef8618a5">https://github.com/PPL-BRIN/pantautular-be/commit/fa46d109dbb82ef36cfb3f1282a0e826ef8618a5</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bfffc50b74e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>