<?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 Fatih Raditya on Medium]]></title>
        <description><![CDATA[Stories by Fatih Raditya on Medium]]></description>
        <link>https://medium.com/@allusernameistaken21?source=rss-a3b288abd16b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7k98DlOKJ25FY1Kr</url>
            <title>Stories by Fatih Raditya on Medium</title>
            <link>https://medium.com/@allusernameistaken21?source=rss-a3b288abd16b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:37:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@allusernameistaken21/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[Django silk, a much more simple way to profile your django app]]></title>
            <link>https://medium.com/@allusernameistaken21/django-silk-a-much-more-simple-way-to-profile-your-django-app-eddd4a5cc587?source=rss-a3b288abd16b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eddd4a5cc587</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[profiling]]></category>
            <category><![CDATA[simple]]></category>
            <category><![CDATA[performance-testing]]></category>
            <dc:creator><![CDATA[Fatih Raditya]]></dc:creator>
            <pubDate>Mon, 19 May 2025 10:04:47 GMT</pubDate>
            <atom:updated>2025-05-19T10:04:47.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dizhiZDmMP0pdABx.png" /><figcaption>silk dashboard example</figcaption></figure><p>First of all, what is profiling? Profiling is a technique used in software development to measure and analyze the runtime behavior of a program. By profiling a program, developers can identify which parts of the program consume the most resources, such as CPU time, memory, or I/O operations. You can use this information to optimize the program, making it run faster or use fewer resources.</p><p>This blog is about doing it with django silk, if you want to know more, you can read about what profiling here,</p><p><a href="https://grafana.com/docs/grafana/latest/explore/simplified-exploration/profiles/concepts/what-is-profiling/">What is profiling? | Grafana documentation</a></p><p>Django Silk is a profiling and inspection tool specifically designed for Django applications. It helps developers identify performance bottlenecks by tracking HTTP requests, database queries, and code execution.</p><p>But why silk? because it is more simple (at least for me) for django app to use silk rather than installing other things like prometheus + grafana.</p><p>Let’s take a look at my previous article,</p><p><a href="https://medium.com/@allusernameistaken21/stress-testing-for-dummies-in-django-286e2e2ff9cb">Stress testing for dummies in django</a></p><p>That article provides a performance testing with stress testing from my localhost:8000/api/statistics.</p><p>But how do I know I need to stress test that? I use silk. And how do you use silk?</p><p>Here’s the step by step:</p><ul><li>run `pip install django-silk`</li><li>add ‘silk’ in INSTALLED_APPS in settings.py</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*PripiPp-ZJvYReOVlre8XA.png" /></figure><ul><li>add ‘silk.middleware.SilkyMiddleware’ to middleware, make sure it is the last line in middleware</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*PzVDkdjbkI-fXKWG7AYJmg.png" /></figure><ul><li>add the url path `path(‘silk/’, include(‘silk.urls’, namespace=’silk’))` in your app urls</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*U0oDDfjJMv2QEVsQ-Dd3Rw.png" /></figure><ul><li>run `python manage.py migrate silk`</li><li>run `python manage.py collectstatics`</li><li>finally, in settings.py set `debug = True`</li></ul><p>Now you just need to run your app with the usual python manage.py runserver command and hit on any api, like mentioned before, I’ve provided a stress testing article for my statistics API, so the example that I am about to show you is the statistics API. Let’s take a look</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CdacZrk0EXhrEp1cUvm7qQ.png" /><figcaption>The call made to the APIs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkRpPwGopLluXELbp9r8-w.png" /><figcaption>The methods for the API call</figcaption></figure><p>Now after I see all this, I need to further test this localhost:8000/api/statistics because I need to know how this API performs under extreme conditions with multiple users, in which I covered here</p><p><a href="https://medium.com/@allusernameistaken21/stress-testing-for-dummies-in-django-286e2e2ff9cb">Stress testing for dummies in django</a></p><p>After caching (the improvement I made after the stress test), let’s see the silk dashboard again to see if the improvements in the stress test actually applies to a real case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2hOFba0i0YCAHERwgSPmA.png" /><figcaption>Request dashboard</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Y97pKs-czl3FmdYqZGv2Q.png" /><figcaption>Profiling dashboard</figcaption></figure><p>Won’t you look at that, for the first GET or POST request, it took a while and with some queries, but after that, it’s much faster and with 0 queries, the functions in the Profiling dashboard is also only being called once, this is because of caching. So that is why profiling is important, you can see how your APIs are performing, do more tests to it (in my example I do a stress test, but you could also do a load test, penetration, and other types of advanced testing), then improve it if it is underperforming, that way you’ll soon have a good application.</p><p>But why do we do profiling first? then the tests? according to the Microsoft team, these are the steps to do a performance testing on a software</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*GaAQn1vm9PMRfs_wHczX4w.png" /></figure><p>accessible here,</p><p><a href="https://learn.microsoft.com/en-us/previous-versions/msp-n-p/bb924375(v=pandp.10)">Performance Testing Guidance for Web Applications</a></p><p>That is why both testing and profiling itself is important in a software development. I hope that after seeing this article, you’d be encouraged to do it yourself to make your app better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eddd4a5cc587" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Super simple django monitoring with sentry]]></title>
            <link>https://medium.com/@allusernameistaken21/super-simple-django-monitoring-with-sentry-a5657dc62a5b?source=rss-a3b288abd16b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5657dc62a5b</guid>
            <category><![CDATA[simple]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[easy]]></category>
            <category><![CDATA[sentry]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[Fatih Raditya]]></dc:creator>
            <pubDate>Sun, 18 May 2025 09:05:41 GMT</pubDate>
            <atom:updated>2025-05-18T09:05:41.395Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, if you are looking for a way to monitor your django application and you are new to software dev and still dont know much about monitoring then this article is for you.</p><p>What even is monitoring? monitoring is the process of continuously tracking and measuring the performance, health, and behavior of applications, systems, and infrastructure throughout the development lifecycle</p><p>Now for the setup, make sure you already have your django app ready, then proceed to here</p><p><a href="https://sentry.io/welcome/?utm_source=google&amp;utm_medium=cpc&amp;utm_id={21427619193}&amp;utm_campaign=Google_Search_Brand_SentryKW_APAC_Alpha&amp;utm_content=g&amp;utm_term=sentry&amp;gad_source=1&amp;gad_campaignid=21427619193&amp;gbraid=0AAAAADua1WIAPSbwUgMZTQEW7Z64kugJg&amp;gclid=Cj0KCQjwiqbBBhCAARIsAJSfZkZ1MNwYXuvz978p3GMWRc_8z1Mnl30V1o7ITsUOxMNE6jwqZMVkV4YaAj4AEALw_wcB">Application Performance Monitoring &amp; Error Tracking Software</a></p><p>Then create a new project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pheDZspBsIX5O5DHV4gSMw.png" /></figure><p>Here, select django and create, after that it should popup something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZUnWqbRYYonwoqHfoQEyg.png" /></figure><p>Now you just need to follow the installation guide and that’s it, you are done. Now you can use sentry to monitor if error occured in your django app or you can make a custom configuration to monitor certain features, like the example for me is that I use it to monitor if someone is logging in because I think it’s a crucial feature to monitor. How do I accomplish this goal of monitoring login api? super duper simple</p><ol><li>Import sentry_sdk</li></ol><pre>import sentry_sdk</pre><p>2. Modify my login func to send message</p><pre>def login(self, email, password):<br>        &quot;&quot;&quot;<br>        Authenticate user and generate tokens<br>        <br>        Returns:<br>            dict: JWT tokens if authentication successful<br>            None: If authentication fails<br>            dict with &#39;locked&#39; key: If account is locked<br>        &quot;&quot;&quot;<br>        # Check if account is locked<br>        is_locked, remaining_time = self.check_account_locked(email)<br>        if is_locked:<br>            minutes = remaining_time // 60<br>            seconds = remaining_time % 60<br>            time_msg = f&quot;{minutes} minutes and {seconds} seconds&quot; if minutes else f&quot;{seconds} seconds&quot;<br>            return {<br>                &#39;locked&#39;: True,<br>                &#39;message&#39;: f&quot;Account is locked due to too many failed attempts. Try again in {time_msg}.&quot;<br>            }<br>            <br>        # Get user by email<br>        user = self.user_repository.get_user_by_email(email)<br>        <br>        if not user:<br>            # Increment failed attempts even for non-existent emails to prevent enumeration<br>            self.increment_failed_attempts(email)<br>            sentry_sdk.capture_message(<br>                    f&quot;Failed login attempt: {email}&quot;, level=&quot;warning&quot;, <br>                    fingerprint=[&quot;failed-login&quot;, email]<br>                )<br>            return None<br>        <br>        # Check password<br>        if not check_password(password, user.password):<br>            self.increment_failed_attempts(email)<br>            sentry_sdk.capture_message(<br>                    f&quot;Failed login attempt: {email}&quot;, level=&quot;warning&quot;, <br>                    fingerprint=[&quot;failed-login&quot;, email]<br>                )<br>            return None<br>        <br>        # Successful login, reset failed attempts<br>        self.reset_failed_attempts(email)<br>        sentry_sdk.set_user({<br>                &quot;id&quot;: str(user.id),<br>                &quot;email&quot;: user.email,<br>            })<br>        sentry_sdk.capture_message(<br>                f&quot;User logged in: {user.email}&quot;, level=&quot;info&quot;,<br>                fingerprint=[&quot;user-login&quot;, str(user.email)]<br>            )<br>        <br>        # Generate token with user data in payload<br>        refresh = RefreshToken.for_user(user)<br>        <br>        # Menambahkan data user ke payload token<br>        refresh[&#39;name&#39;] = user.name<br>        refresh[&#39;email&#39;] = user.email<br>        refresh[&#39;role&#39;] = user.role<br>        refresh[&#39;user_id&#39;] = user.id<br>        <br>        # Hanya mengembalikan token<br>        return {<br>            &quot;access_token&quot;: str(refresh.access_token)<br>        }</pre><p>As you can see, the sentry_sdk is used to capture message whenever a user is logging in or failed to log in, we can monitor it in the project in the sentry web.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQQnu2PCkocQZfA_ZiqVoQ.png" /></figure><p>As you can see, it detects whenever a login attempt is failed and when there are succesful ones, the base settings also detects errors and exceptions as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AgQGQhwjHtFIZHKTQsGl4A.png" /></figure><p>And that’s it, super simple right, remember that you could always add more custom configurations to it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5657dc62a5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stress testing for dummies in django]]></title>
            <link>https://medium.com/@allusernameistaken21/stress-testing-for-dummies-in-django-286e2e2ff9cb?source=rss-a3b288abd16b------2</link>
            <guid isPermaLink="false">https://medium.com/p/286e2e2ff9cb</guid>
            <category><![CDATA[stress-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[performance-testing]]></category>
            <dc:creator><![CDATA[Fatih Raditya]]></dc:creator>
            <pubDate>Sun, 18 May 2025 07:18:34 GMT</pubDate>
            <atom:updated>2025-05-19T10:14:07.710Z</atom:updated>
            <content:encoded><![CDATA[<p>So what even is a stress test, or what the hell is testing anyway? so in software development, testing is essential to ensure that the software behaves as expected and is free of defects.</p><p>For example there are unit tests which tests individual components or functions to confirm it performs as expected. There’s also a usability testing in which a real user test out the whole project that you develop with the intention to gain insights on what a real user want us to improve. Also, there are performance tests in which you test the performance of your software under certain thresholds.</p><p>So now, let’s get back to the point, what is a stress test? a stress test is an example of a performance test for your software to see how it would react to an abnormally extreme condition, it pushes your software beyond its typical load. Like for example how it would react if 30 people logged in at once.</p><p>Before diving into advanced forms of testing — such as load testing, stress testing, or penetration testing — it’s crucial to <strong>analyze your application first</strong>. A helpful resource for this is the Microsoft Patterns &amp; Practices guide:</p><p><a href="https://learn.microsoft.com/en-us/previous-versions/msp-n-p/bb924375(v=pandp.10)">Performance Testing Guidance for Web Applications</a></p><p>The guide outlines a set of <strong>core performance testing activities</strong>, as shown in this image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/0*9eqTZNj9SYoGQOoi.gif" /><figcaption>Performance testing activities by Microsoft</figcaption></figure><p>A key part of step 2 — <strong>identifying performance criteria</strong> — involves a process known as <strong>profiling</strong>. What is profiling and how do I do it for my django app? well take a look at my other article here</p><p><a href="https://medium.com/@allusernameistaken21/django-silk-a-much-more-simple-way-to-profile-your-django-app-eddd4a5cc587">Django silk, a much more simple way to profile your django app</a></p><p>Now, to the main point, how does one do a stress test in django? In this example I’ll show you how to do a stress test with K6.</p><p><a href="https://k6.io/website-stress-testing/">Website Stress Testing | k6</a></p><p>First of all, you need to install k6, it depends on your OS tho</p><p><a href="https://grafana.com/docs/k6/latest/set-up/install-k6/">Install k6 | Grafana k6 documentation</a></p><p>After that then what? now you can create a test module for your API’s, for example here in my app I have an API for getting statistics, which is accessible in <a href="http://localhost:8000/api/statistics/"><strong>http://localhost:8000/api/statistics/</strong></a></p><p>Now I wanna do a stress test on that API, what should I do? its really simple, all you need to do is create the test file, let’s say we name it “<strong>Statistic-stress-test.js</strong>”</p><pre>import http from &#39;k6/http&#39;;<br>import { check, sleep } from &#39;k6&#39;;<br>import { Rate, Trend } from &#39;k6/metrics&#39;;<br><br>// Custom metrics<br>const errorRate = new Rate(&#39;error_rate&#39;);<br>const getRequestDuration = new Trend(&#39;get_request_duration&#39;);<br>const postRequestDuration = new Trend(&#39;post_request_duration&#39;);<br><br>// Test configuration<br>export const options = {<br>  stages: [<br>    { duration: &#39;30s&#39;, target: 10 }, // Ramp-up: Gradually increase to 10 users<br>    { duration: &#39;1m&#39;, target: 10 },  // Stay at 10 users for 1 minute<br>    { duration: &#39;30s&#39;, target: 50 }, // Ramp-up to 50 users<br>    { duration: &#39;1m&#39;, target: 50 },  // Stay at 50 users for 1 minute<br>    { duration: &#39;30s&#39;, target: 0 },  // Ramp-down to 0 users<br>  ],<br>  thresholds: {<br>    &#39;error_rate&#39;: [&#39;rate&lt;0.1&#39;], // Error rate should be less than 10%<br>    &#39;http_req_duration&#39;: [&#39;p(95)&lt;2000&#39;], // 95% of requests should be below 2s<br>    &#39;get_request_duration&#39;: [&#39;avg&lt;1000&#39;], // Average GET request should be under 1s<br>    &#39;post_request_duration&#39;: [&#39;avg&lt;1500&#39;], // Average POST request should be under 1.5s<br>  },<br>};<br><br>// API Key header (you&#39;ll need to replace this with your actual API key)<br>const headers = {<br>  &#39;Content-Type&#39;: &#39;application/json&#39;,<br>  &#39;X-API-Key&#39;: &#39;your-api-key-here&#39;, // Replace with your actual API key<br>};<br><br>// Sample filter data for POST requests<br>const filterSamples = [<br>  // Simple filter with just diseases<br>  {<br>    diseases: [&#39;Tuberculosis&#39;, &#39;Dengue&#39;],<br>  },<br>  // Filter with locations<br>  {<br>    locations: {<br>      provinces: [&#39;Jakarta&#39;, &#39;Bali&#39;],<br>      cities: [&#39;Jakarta Selatan&#39;, &#39;Denpasar&#39;],<br>    },<br>  },<br>  // Filter with date range<br>  {<br>    start_date: &#39;2023-01-01&#39;,<br>    end_date: &#39;2023-12-31&#39;,<br>  },<br>  // Complex filter<br>  {<br>    diseases: [&#39;Malaria&#39;, &#39;Dengue&#39;],<br>    locations: {<br>      provinces: [&#39;Jawa Barat&#39;, &#39;Jawa Timur&#39;],<br>      cities: [],<br>    },<br>    portals: [&#39;Local News A&#39;, &#39;Health Portal B&#39;],<br>    level_of_alertness: 2,<br>    start_date: &#39;2023-06-01&#39;,<br>    end_date: &#39;2023-12-31&#39;,<br>  },<br>  // Empty filter (should behave like GET)<br>  {},<br>];<br><br>export default function () {<br>  // TEST 1: GET request to get all statistics without filters<br>  const getResponse = http.get(&#39;http://localhost:8000/api/statistics/&#39;, { headers });<br>  <br>  // Track metrics for the GET request<br>  getRequestDuration.add(getResponse.timings.duration);<br>  <br>  // Verify GET response<br>  const getSuccess = check(getResponse, {<br>    &#39;GET status is 200&#39;: (r) =&gt; r.status === 200,<br>    &#39;GET response has data&#39;: (r) =&gt; r.json() &amp;&amp; Object.keys(r.json()).length &gt; 0,<br>  });<br>  <br>  // Update error rate metric<br>  errorRate.add(!getSuccess);<br>  <br>  // Small pause between requests<br>  sleep(1);<br>  <br>  // TEST 2: POST request with different filter combinations<br>  // Choose a random filter from our samples<br>  const randomFilter = filterSamples[Math.floor(Math.random() * filterSamples.length)];<br>  <br>  const postResponse = http.post(<br>    &#39;http://localhost:8000/api/statistics/&#39;,<br>    JSON.stringify(randomFilter),<br>    { headers }<br>  );<br>  <br>  // Track metrics for the POST request<br>  postRequestDuration.add(postResponse.timings.duration);<br>  <br>  // Verify POST response<br>  const postSuccess = check(postResponse, {<br>    &#39;POST status is 200&#39;: (r) =&gt; r.status === 200,<br>    &#39;POST response has data&#39;: (r) =&gt; r.json() &amp;&amp; Object.keys(r.json()).length &gt; 0,<br>  });<br>  <br>  // Update error rate metric<br>  errorRate.add(!postSuccess);<br>  <br>  // Sleep between iterations<br>  sleep(2);<br>}</pre><p>So what I’m about to explain is how the stress test works, not about how my API works, so I’ll focus on that.</p><p>First of all, we got this</p><pre>const errorRate = new Rate(&#39;error_rate&#39;);<br>const getRequestDuration = new Trend(&#39;get_request_duration&#39;);<br>const postRequestDuration = new Trend(&#39;post_request_duration&#39;);</pre><p>These are the variables that we will use to measure the performance of the API, in which the error rate should be below 10%, 95% of request should be under 2 seconds, etc, this thresholds could be customized further.</p><pre>stages: [<br>    { duration: &#39;30s&#39;, target: 10 }, // Ramp-up: Gradually increase to 10 users<br>    { duration: &#39;1m&#39;, target: 10 },  // Stay at 10 users for 1 minute<br>    { duration: &#39;30s&#39;, target: 50 }, // Ramp-up to 50 users<br>    { duration: &#39;1m&#39;, target: 50 },  // Stay at 50 users for 1 minute<br>    { duration: &#39;30s&#39;, target: 0 },  // Ramp-down to 0 users<br>  ],<br>  thresholds: {<br>    &#39;error_rate&#39;: [&#39;rate&lt;0.1&#39;], // Error rate should be less than 10%<br>    &#39;http_req_duration&#39;: [&#39;p(95)&lt;2000&#39;], // 95% of requests should be below 2s<br>    &#39;get_request_duration&#39;: [&#39;avg&lt;1000&#39;], // Average GET request should be under 1s<br>    &#39;post_request_duration&#39;: [&#39;avg&lt;1500&#39;], // Average POST request should be under 1.5s<br>  },</pre><p>Now that one defines a gradual load profile starting from 0 to 50 VUs (Virtual Users). Now the middle part is the filter which is how my API works, and finally we have this</p><pre>export default function () {<br>  // TEST 1: GET request to get all statistics without filters<br>  const getResponse = http.get(&#39;http://localhost:8000/api/statistics/&#39;, { headers });<br>  <br>  // Track metrics for the GET request<br>  getRequestDuration.add(getResponse.timings.duration);<br>  <br>  // Verify GET response<br>  const getSuccess = check(getResponse, {<br>    &#39;GET status is 200&#39;: (r) =&gt; r.status === 200,<br>    &#39;GET response has data&#39;: (r) =&gt; r.json() &amp;&amp; Object.keys(r.json()).length &gt; 0,<br>  });<br>  <br>  // Update error rate metric<br>  errorRate.add(!getSuccess);<br>  <br>  // Small pause between requests<br>  sleep(1);<br>  <br>  // TEST 2: POST request with different filter combinations<br>  // Choose a random filter from our samples<br>  const randomFilter = filterSamples[Math.floor(Math.random() * filterSamples.length)];<br>  <br>  const postResponse = http.post(<br>    &#39;http://localhost:8000/api/statistics/&#39;,<br>    JSON.stringify(randomFilter),<br>    { headers }<br>  );<br>  <br>  // Track metrics for the POST request<br>  postRequestDuration.add(postResponse.timings.duration);<br>  <br>  // Verify POST response<br>  const postSuccess = check(postResponse, {<br>    &#39;POST status is 200&#39;: (r) =&gt; r.status === 200,<br>    &#39;POST response has data&#39;: (r) =&gt; r.json() &amp;&amp; Object.keys(r.json()).length &gt; 0,<br>  });<br>  <br>  // Update error rate metric<br>  errorRate.add(!postSuccess);<br>  <br>  // Sleep between iterations<br>  sleep(2);<br>}</pre><p>That right there is the main function which tests both GET and POST endpoint for the api/statistics which measures the metric from before, now after all that is done, how do we test it? super simple, you just need to run this command</p><pre>k6 run Statistic-stress-test.js</pre><p>dont forget to run your app first. The respons should look a little bit something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*1TzfYwpo08VsKwXRHlDVNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*LSSi8EUs78TlfainEWOTpg.png" /></figure><p>And your app should run your API a lot, and I really do mean A LOT</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*5x1JI2CbL7637HUkR8IkUw.png" /></figure><p>Now, from the reports above we can see a lot of things</p><h3>What Went Well</h3><ul><li><strong>No errors occurred</strong> (0% error rate) — All requests completed successfully</li><li><strong>All checks passed</strong> (100% success rate) — All responses returned valid data with 200 status codes</li></ul><h3>Performance Issues</h3><p>The test identified several performance issues where thresholds were exceeded:</p><ol><li><strong>GET request duration</strong>:</li></ol><ul><li>Threshold: &lt; 1000ms (1 second)</li><li>Actual: 1830.59ms (1.83 seconds)</li><li><strong>Failed</strong> by 83% over target</li></ul><p><strong>2. POST request duration</strong>:</p><ul><li>Threshold: &lt; 1500ms (1.5 seconds)</li><li>Actual: 1900.94ms (1.9 seconds)</li><li><strong>Failed</strong> by 27% over target</li></ul><p><strong>3. Overall HTTP request duration</strong> (95th percentile):</p><ul><li>Threshold: &lt; 2000ms (2 seconds)</li><li>Actual: 2170ms (2.17 seconds)</li><li><strong>Failed</strong> by 8.5% over target</li></ul><h3>Other Notable Metrics</h3><ul><li>Average iteration duration: 6.73 seconds</li><li>Throughput: ~7.68 requests per second</li><li>Data transferred: 3.8 MB received, 341 KB sent</li></ul><p>So now that we know it was wayyyy above the threshold, we can try to improve it, for example, my solution to this problem is using cache, like this.</p><pre># Add caching to the StatisticsCoordinator<br>def generate_comprehensive_report(self, **filters):<br>    # Create a cache key based on the filters<br>    cache_key = f&quot;stats_report_{hash(frozenset(filters.items()))}&quot;<br>    <br>    # Check if result is in cache<br>    cached_result = self.cache_service.get(cache_key)<br>    if cached_result:<br>        return cached_result<br>        <br>    # Existing code to generate report...<br>    <br>    # Cache the result before returning<br>    self.cache_service.set(cache_key, out, timeout=3600)  # Cache for 1 hour<br>    return out</pre><p>Now let’s see if it improves?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*fn5RwXUq4QlHKZq8esiMaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wS9Ni4q2PZSvC0OIeknQug.png" /></figure><p>HOLY, IT IMPROVED, A LOT, now as you can see, this is why stress testing or other performance testing are needed, imagine if you were trying to search for something but google took 10 mins to search it, your app doesn’t just need to work, it needs to be optimized so that users are comfortable using it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=286e2e2ff9cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring With Purpose: How Design Patterns Improved My Code]]></title>
            <link>https://medium.com/@allusernameistaken21/refactoring-with-purpose-how-design-patterns-improved-my-code-e1b2c4cd58ff?source=rss-a3b288abd16b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1b2c4cd58ff</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fatih Raditya]]></dc:creator>
            <pubDate>Mon, 12 May 2025 06:39:13 GMT</pubDate>
            <atom:updated>2025-05-12T06:39:13.288Z</atom:updated>
            <content:encoded><![CDATA[<p>I used to refactor my code just to “make it cleaner” — rename some variables, split big functions, maybe move a few files around. It felt productive, but honestly, it didn’t always <em>solve</em> anything. The code still felt too long.</p><p>So I have this feature for a statistic API:</p><pre>from asyncio.log import logger<br>from collections import Counter, defaultdict<br>from datetime import datetime<br>from .interfaces import CaseRepositoryInterface<br>from .repositories import CaseRepository<br>from .services import CaseService<br>import math<br>import numpy as np<br>from .constants import PROVINCE_TO_CODE<br><br>class StatisticsCoordinator:<br>    &quot;&quot;&quot;<br>    Coordinates the generation of various statistics reports.<br>    This class acts as a facade for the statistics layer, providing a single entry point<br>    for generating comprehensive reports that include multiple statistics components.<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, case_filter_service):<br>        self.case_filter_service = case_filter_service<br>        self.prevalence = PrevalenceStatistics(CaseRepository())<br>        self.age_report = AgeGroupingReport()<br>        self.gender_report = GenderGroupingReport()<br>        self.severity_report = SeverityGroupingReport()<br>        self.severity_dates_count_report = SeverityDatesCountReport()<br>        self.national_news_report = NationalNewsStatisticsReport()<br>        self.local_portal_report = LocalPortalStatisticsReport()<br>        self.healthcare_news_report = HealthcareNewsStatisticsReport()<br>    <br>    def generate_comprehensive_report(self, **filter_params):<br>        result = {}<br>        <br>        # Filter data once<br>        filtered_cases = None<br>        <br>        if self.case_filter_service:<br>            try:<br>                filtered_cases = self.case_filter_service.filter_cases(**filter_params)<br>            except Exception as filter_error:<br>                logger.error(f&quot;Error filtering cases: {str(filter_error)}&quot;)<br>                result[&quot;error&quot;] = f&quot;Failed to filter cases: {str(filter_error)}&quot;<br>                return result<br>        <br>        # Extract date parameters from filter_params<br>        date_range = filter_params.get(&#39;date_range&#39;, {})<br>        start_date = date_range.get(&#39;start&#39;) if date_range else None<br>        <br>        # Generate each report individually with error handling<br>        report_generators = {<br>            &quot;prevalence_statistics&quot;: lambda: self.prevalence.get_prevalence_statistics(start_date),<br>            &quot;age_statistics&quot;: lambda: self.age_report.generate_report(filtered_cases=filtered_cases),<br>            &quot;gender_statistics&quot;: lambda: self.gender_report.generate_report(filtered_cases=filtered_cases),<br>            &quot;severity_statistics&quot;: lambda: self.severity_report.generate_report(filtered_cases=filtered_cases),<br>            &quot;severity_dates_count_statistics&quot;: lambda: self.severity_dates_count_report.generate_report(filtered_cases=filtered_cases),<br>            &quot;national_news_statistics&quot;: lambda: self.national_news_report.generate_report(filtered_cases=filtered_cases),<br>            &quot;local_portal_statistics&quot;: lambda: self.local_portal_report.generate_report(filtered_cases=filtered_cases),<br>            &quot;healthcare_news_statistics&quot;: lambda: self.healthcare_news_report.generate_report(filtered_cases=filtered_cases)<br>        }<br>        <br>        for key, generator in report_generators.items():<br>            try:<br>                result[key] = generator()<br>            except Exception as e:<br>                logger.error(f&quot;Error generating {key}: {str(e)}&quot;)<br>                result[key] = {&quot;error&quot;: f&quot;Failed to generate report: {str(e)}&quot;}<br>        <br>        return result<br><br>class SeverityGroupingReport:<br> <br>    def generate_report(self, filtered_cases = None):<br>        severity_counts = Counter()<br>        total_cases = 0<br>        <br>        if filtered_cases:<br>            for case in filtered_cases:<br>                total_cases += 1<br>                severity = case.get(&quot;severity&quot;)<br>                if severity is not None:<br>                    severity_counts[severity] += 1<br>        <br>        return {<br>            &quot;total_cases&quot;: total_cases,<br>            &quot;severity_counts&quot;: dict(severity_counts)<br>        }<br><br>class AgeGroupingReport:<br>    &quot;&quot;&quot;Generates age grouping statistics&quot;&quot;&quot;<br>    <br>    def generate_report(self, filtered_cases=None):<br>        &quot;&quot;&quot;Generate age grouping report&quot;&quot;&quot;<br>        age_groups = {<br>            &quot;under_12&quot;: 0,<br>            &quot;12_25&quot;: 0,<br>            &quot;26_45&quot;: 0,<br>            &quot;above_45&quot;: 0<br>        }<br><br>        if not filtered_cases:<br>            return age_groups<br>        <br>        # Track cases we&#39;ve already counted<br>        counted_cases = set()<br>        <br>        for case in filtered_cases:<br>            case_id = case.get(&quot;id&quot;)<br>            <br>            # Skip if we&#39;ve already counted this case<br>            if case_id in counted_cases:<br>                continue<br>                <br>            counted_cases.add(case_id)<br>            <br>            age = case.get(&quot;age&quot;)<br>            if age is None:<br>                continue<br>                <br>            if age &lt; 12:<br>                age_groups[&quot;under_12&quot;] += 1<br>            elif 12 &lt;= age &lt;= 25:<br>                age_groups[&quot;12_25&quot;] += 1<br>            elif 26 &lt;= age &lt;= 45:<br>                age_groups[&quot;26_45&quot;] += 1<br>            else:<br>                age_groups[&quot;above_45&quot;] += 1<br><br>        return age_groups<br><br>class SeverityDatesCountReport:<br>    def generate_report(self, filtered_cases=None):<br>        &quot;&quot;&quot;Generate severity dates count report&quot;&quot;&quot;<br>        if not filtered_cases:<br>            logger.info(&quot;No filtered cases provided. Returning empty report.&quot;)<br>            return {}<br><br>        severity_dates = defaultdict(lambda: defaultdict(int))<br><br>        for case in filtered_cases:<br>            severity = case.get(&quot;severity&quot;)<br>            date_published = case.get(&quot;news__date_published&quot;)<br><br>            # Safely format the date<br>            if isinstance(date_published, datetime):<br>                date_published = date_published.strftime(&#39;%Y-%m-%d&#39;)<br>            else:<br>                logger.warning(f&quot;Invalid or missing date_published in case: {case}&quot;)<br>                continue<br><br>            severity_dates[severity][date_published] += 1<br><br>        for severity, dates in severity_dates.items():<br>            severity_dates[severity] = dict(sorted(dates.items()))<br><br>        # Transform to the desired output format<br>        return {<br>            severity: [{&quot;date&quot;: date, &quot;count&quot;: count} for date, count in dates.items()]<br>            for severity, dates in severity_dates.items()<br>        }<br><br>class GenderGroupingReport:<br>    &quot;&quot;&quot;Generates gender distribution statistics&quot;&quot;&quot;<br><br>    def generate_report(self, filtered_cases=None):<br>        &quot;&quot;&quot;Generate gender distribution report&quot;&quot;&quot;<br>        gender_counts = Counter()<br><br>        if not filtered_cases:<br>            return {&quot;male&quot;: 0, &quot;female&quot;: 0}<br><br>        for case in filtered_cases:<br>            if case and isinstance(case, dict):<br>                gender = case.get(&quot;gender&quot;)<br>                if isinstance(gender, str):  # Pastikan gender adalah string<br>                    gender = gender.lower()<br>                    if gender in [&quot;male&quot;, &quot;female&quot;]:<br>                        gender_counts[gender] += 1<br><br>        return {<br>            &quot;male&quot;: gender_counts.get(&quot;male&quot;, 0),<br>            &quot;female&quot;: gender_counts.get(&quot;female&quot;, 0),<br>        }<br><br>class PrevalenceStatistics:<br>    def __init__(self, repository: CaseRepositoryInterface):<br>        self.repository = repository<br>        self.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>    def get_prevalence_statistics(self, start_date=None):  <br>        try:<br>            year = 2024<br>            if start_date:<br>                # Handle ISO format date strings (e.g., 2024-09-08T17:00:00.000Z)<br>                if &#39;T&#39; in start_date:<br>                    start_date = start_date.split(&#39;T&#39;)[0]<br>                <br>                start_date = datetime.strptime(start_date, &#39;%Y-%m-%d&#39;)<br>                year = start_date.year <br><br>            cases = self.repository.get_cases_by_year(year)<br>            total_cases = cases.count()<br>            <br>            population = self.POPULATION_DATA.get(year)<br>            if not population:<br>                return {<br>                &quot;year&quot;: year,<br>                &quot;total_cases&quot;: total_cases,<br>                &quot;population&quot;: &quot;Angka jiwa belum tercatat&quot;,<br>                &quot;prevalence&quot;: &quot;No Data&quot;<br>            }<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;: round(prevalence, 4)  <br>            }<br>            <br>        except Exception as e:<br>            return {&quot;error&quot;: f&quot;Error calculating prevalence: {str(e)}&quot;}<br>    <br>class NationalNewsStatisticsReport:<br>    &quot;&quot;&quot;Generates statistics about national news portals&quot;&quot;&quot;<br>    <br>    def generate_report(self, filtered_cases=None):<br>        &quot;&quot;&quot;<br>        Generate national news statistics report<br>        <br>        Returns:<br>            dict: Contains two keys:<br>                - top_national: List of portals sorted by news count<br>                - all_national: List of portals with news and disease counts<br>        &quot;&quot;&quot;<br>        # Early return for empty data<br>        if not filtered_cases:<br>            return {<br>                &quot;top_national&quot;: [],<br>                &quot;all_national&quot;: []<br>            }<br>                <br>        # Track disease counts per portal<br>        portal_diseases = defaultdict(set)<br>        # Track news counts per portal<br>        portal_counts = Counter()<br>        <br>        # Process national news only<br>        for case in filtered_cases:<br>            portal = case.get(&quot;news__portal&quot;)<br>            news_type = case.get(&quot;news__type&quot;)<br>            disease = case.get(&quot;disease__name&quot;)<br>            <br>            # Skip non-national or missing portal news<br>            if not (portal and news_type == &quot;Nasional&quot;):<br>                continue<br>                <br>            # Count this news article<br>            portal_counts[portal] += 1<br>            <br>            # Add disease if present<br>            if disease:<br>                portal_diseases[portal].add(disease)<br>        <br>        # No need to sort manually - Counter has most_common() method<br>        top_national = [<br>            {&quot;portal&quot;: portal, &quot;count&quot;: count} <br>            for portal, count in portal_counts.most_common(5)<br>        ]<br>        <br>        # Create all_national with news and disease counts<br>        all_national = [<br>            {<br>                &quot;portal&quot;: portal,<br>                &quot;news_count&quot;: count,<br>                &quot;disease_count&quot;: len(portal_diseases[portal])<br>            }<br>            for portal, count in portal_counts.items()<br>        ]<br>        <br>        return {<br>            &quot;top_national&quot;: top_national,<br>            &quot;all_national&quot;: all_national<br>        }<br><br>class HealthcareNewsStatisticsReport:<br>    &quot;&quot;&quot;Generates statistics about healthcare news portals&quot;&quot;&quot;<br><br>    def generate_report(self, filtered_cases=None):<br>        &quot;&quot;&quot;<br>        Generate healthcare news statistics report<br><br>        Returns:<br>            dict: Contains two keys:<br>                - top_healthcare: List of portals sorted by news count<br>                - all_healthcare: List of portals with news and disease counts<br>        &quot;&quot;&quot;<br>        # Early return for empty data<br>        if not filtered_cases:<br>            return {&quot;top_healthcare&quot;: [], &quot;all_healthcare&quot;: []}<br><br>        # Track disease counts per portal<br>        portal_diseases = defaultdict(set)<br>        # Track news counts per portal<br>        portal_counts = Counter()<br><br>        # Process healthcare news only<br>        for case in filtered_cases:<br>            portal = case.get(&quot;news__portal&quot;)<br>            news_type = case.get(&quot;news__type&quot;)<br>            disease = case.get(&quot;disease__name&quot;)<br><br>            # Skip non-healthcare or missing portal news<br>            if not (portal and news_type and news_type.lower() == &quot;kesehatan&quot;):<br>                continue<br><br>            # Count this news article<br>            portal_counts[portal] += 1<br><br>            # Add disease if present<br>            if disease:<br>                portal_diseases[portal].add(disease)<br><br>        # Create top_healthcare with sorted news counts<br>        top_healthcare = [<br>            {&quot;portal&quot;: portal, &quot;count&quot;: count}<br>            for portal, count in portal_counts.most_common(5)<br>        ]<br><br>        # Create all_healthcare with news and disease counts<br>        all_healthcare = [<br>            {<br>                &quot;portal&quot;: portal,<br>                &quot;news_count&quot;: count,<br>                &quot;disease_count&quot;: len(portal_diseases[portal])<br>            }<br>            for portal, count in portal_counts.items()<br>        ]<br><br>        return {&quot;top_healthcare&quot;: top_healthcare, &quot;all_healthcare&quot;: all_healthcare}<br><br>class LocalPortalStatisticsReport:<br>    &quot;&quot;&quot;Generates local portal statistics&quot;&quot;&quot;<br><br>    def generate_report(self, filtered_cases=None):<br>        &quot;&quot;&quot;<br>        Generates local portal statistics report<br><br>        Returns:<br>            dict: Contains two keys:<br>                - top_local: List of portals sorted by news count<br>                - all_local: List of portals with news and disease counts<br>        &quot;&quot;&quot;<br>        if not filtered_cases:<br>            return {<br>                &quot;top_local&quot;: [],<br>                &quot;all_local&quot;: []<br>            }<br>        <br>        portal_diseases = defaultdict(set)<br>        portal_counts = Counter()<br><br>        # Process local news only<br>        for case in filtered_cases:<br>            portal = case.get(&quot;news__portal&quot;)<br>            news_type = case.get(&quot;news__type&quot;)<br>            disease = case.get(&quot;disease__name&quot;)<br><br>            # Skip non-local or missing portal news<br>            if not (portal and news_type and news_type.lower() == &quot;lokal&quot;):<br>                continue<br><br>            # Count this news article<br>            portal_counts[portal] += 1<br><br>            # Add disease if present<br>            if disease:<br>                portal_diseases[portal].add(disease)<br>        <br>        top_local = [<br>            {&quot;portal&quot;: portal, &quot;count&quot;: count}<br>            for portal, count in portal_counts.most_common(5)<br>        ]<br><br>        all_local = [<br>            {<br>                &quot;portal&quot;: portal,<br>                &quot;news_count&quot;: count,<br>                &quot;disease_count&quot;: len(portal_diseases[portal])<br>            }<br>            for portal, count in portal_counts.items()<br>        ]<br><br>        return {<br>            &quot;top_local&quot;: top_local,<br>            &quot;all_local&quot;: all_local<br>        }<br><br>class AverageSeverityByProvince:<br>    STATUS_ENCODING = {<br>        &quot;minimal&quot;: 1,<br>        &quot;biasa&quot;: 2,<br>        &quot;bahaya&quot;: 3,<br>        &quot;katastropik&quot;: 4<br>    }<br><br>    def __init__(self, case_service):<br>        self.case_service = case_service<br>        self.PROVINCE_TO_CODE = PROVINCE_TO_CODE<br><br>    def compute(self):<br>        &quot;&quot;&quot;<br>        Hitung weighted severity score dan kategorisasi status untuk setiap provinsi.<br>        Output: list of dicts [{ &quot;id&quot;: province_code, &quot;value&quot;: float, &quot;status&quot;: str }, ...]<br>        &quot;&quot;&quot;<br>        data = self.case_service.get_status_and_province()<br>        province_scores = defaultdict(list)<br><br>        for record in data:<br>            status = record.get(&quot;status&quot;)<br>            province = record.get(&quot;location__province&quot;)<br><br>            if status and province:<br>                status = status.lower()<br>                if status in self.STATUS_ENCODING:<br>                    encoded = self.STATUS_ENCODING[status]<br>                    province_scores[province].append(encoded)<br><br>        if not province_scores:<br>            return []<br><br>        weighted_result = {}<br>        all_scores = []<br><br>        for province, scores in province_scores.items():<br>            avg = sum(scores) / len(scores)<br>            weight = math.log(len(scores) + 1)<br>            weighted_score = round(avg * weight, 2)<br>            weighted_result[province] = {&quot;value&quot;: weighted_score}<br>            all_scores.append(weighted_score)<br><br>        # Hitung kuartil dinamis<br>        q1 = np.percentile(all_scores, 25)<br>        q2 = np.percentile(all_scores, 50)<br>        q3 = np.percentile(all_scores, 75)<br><br>        # Klasifikasi berdasarkan score<br>        for province, result in weighted_result.items():<br>            score = result[&quot;value&quot;]<br>            if score &lt;= q1:<br>                result[&quot;status&quot;] = &quot;minimal&quot;<br>            elif score &lt;= q2:<br>                result[&quot;status&quot;] = &quot;biasa&quot;<br>            elif score &lt;= q3:<br>                result[&quot;status&quot;] = &quot;bahaya&quot;<br>            else:<br>                result[&quot;status&quot;] = &quot;katastropik&quot;<br>                <br>            # Add province code<br>            result[&quot;id&quot;] = self.PROVINCE_TO_CODE.get(province, province)<br><br>        # Convert dictionary to list format<br>        formatted_result = [<br>            {<br>                &quot;id&quot;: data[&quot;id&quot;],<br>                &quot;value&quot;: data[&quot;value&quot;],<br>                &quot;status&quot;: data[&quot;status&quot;]<br>            } for province, data in weighted_result.items()<br>        ]<br><br>        return formatted_result</pre><p>Yikes, that code is too long isn’t it? If another person from outside my team is reading this, they might be overwhelmed, I mean this file is over 400 lines long, not including the tests (which is over 1000 lines long). So I thought, let’s refactor this into something smaller, and that is where design pattern comes in.</p><p>What is it anyway? A design pattern is a reusable, proven solution to a common problem in software design. It’s like a blueprint for how to solve a recurring problem, offering a generalizable approach rather than a specific piece of code.</p><p>The design pattern that I will use here is a mix of Strategy and Factory pattern. For the details, you can read it here,</p><ul><li><a href="https://refactoring.guru/design-patterns/strategy">Strategy</a></li><li><a href="https://refactoring.guru/design-patterns/factory-method">Factory Method</a></li></ul><p>The problem from the long code before is that All reports (AgeGroupingReport, GenderGroupingReport, …, AverageSeverityByProvince) are defined in a single large file (pt_backend/statistics.py). StatisticsCoordinator calls each report via hard-coded lambdas.</p><p>So the plan now is to make it like this</p><pre>pt_backend/statistics/<br>├─ __init__.py<br>├─ interface.py           # ReportStrategy interface<br>├─ factory.py             # ReportFactory registry<br>├─ coordinator.py         # StatisticsCoordinator (Context)<br>└─ reports/<br>   ├─ __init__.py<br>   ├─ age_grouping.py     # AgeGroupingReport<br>   ├─ gender_grouping.py  # GenderGroupingReport<br>   ├─ severity_grouping.py<br>   ├─ severity_dates_count.py<br>   ├─ prevalence.py<br>   ├─ national_news.py<br>   ├─ local_portal.py<br>   ├─ healthcare_news.py<br>   └─ average_severity_province.py</pre><p>So for the strategy pattern, we got the interface and the concrete implementation of the logics is in the reports. Then, the factory.py is for the registry and instantiation of it all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*wwaFixnhxrHVdH4eiPtaPg.png" /><figcaption>Structure for the design pattern</figcaption></figure><p>The first thing we need to do is to implement the interface so that different reports can use that interface but implements different strats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*pAsu2t_xluBdiiMve8T99A.png" /><figcaption>Interface</figcaption></figure><p>This is the interface, we used an abstractmethod because, like mentioned before, it is for the different reports to use different strategies.</p><p>Now we implement it into the reports itself.</p><pre>from ..interface import ReportStrategy<br><br>class AgeGroupingReport(ReportStrategy):<br>    &quot;&quot;&quot;Generates age grouping statistics&quot;&quot;&quot;<br>    <br>    def generate_report(self, filtered_cases=None):<br>        &quot;&quot;&quot;Generate age grouping report&quot;&quot;&quot;<br>        age_groups = {<br>            &quot;under_12&quot;: 0,<br>            &quot;12_25&quot;: 0,<br>            &quot;26_45&quot;: 0,<br>            &quot;above_45&quot;: 0<br>        }<br><br>        if not filtered_cases:<br>            return age_groups<br>        <br>        # Track cases we&#39;ve already counted<br>        counted_cases = set()<br>        <br>        for case in filtered_cases:<br>            case_id = case.get(&quot;id&quot;)<br>            <br>            # Skip if we&#39;ve already counted this case<br>            if case_id in counted_cases:<br>                continue<br>                <br>            counted_cases.add(case_id)<br>            <br>            age = case.get(&quot;age&quot;)<br>            if age is None:<br>                continue<br>                <br>            if age &lt; 12:<br>                age_groups[&quot;under_12&quot;] += 1<br>            elif 12 &lt;= age &lt;= 25:<br>                age_groups[&quot;12_25&quot;] += 1<br>            elif 26 &lt;= age &lt;= 45:<br>                age_groups[&quot;26_45&quot;] += 1<br>            else:<br>                age_groups[&quot;above_45&quot;] += 1<br><br>        return age_groups</pre><p>That is an example for the age statistic report</p><pre>from ..interface import ReportStrategy<br>from collections import Counter<br><br>class GenderGroupingReport(ReportStrategy):<br>    &quot;&quot;&quot;Generates gender distribution statistics&quot;&quot;&quot;<br><br>    def generate_report(self, filtered_cases=None):<br>        &quot;&quot;&quot;Generate gender distribution report&quot;&quot;&quot;<br>        gender_counts = Counter()<br><br>        if not filtered_cases:<br>            return {&quot;male&quot;: 0, &quot;female&quot;: 0}<br><br>        for case in filtered_cases:<br>            if case and isinstance(case, dict):<br>                gender = case.get(&quot;gender&quot;)<br>                if isinstance(gender, str):  # Pastikan gender adalah string<br>                    gender = gender.lower()<br>                    if gender in [&quot;male&quot;, &quot;female&quot;]:<br>                        gender_counts[gender] += 1<br><br>        return {<br>            &quot;male&quot;: gender_counts.get(&quot;male&quot;, 0),<br>            &quot;female&quot;: gender_counts.get(&quot;female&quot;, 0),<br>        }</pre><p>And this one is for the gender stats, as you can see both of those report classes implements a generate_report function from the interface, but the function itself differs from each other.</p><p>Then we have this coordinator and factory,</p><pre>#coordinator.py<br>from pt_backend.statistics.factory import ReportFactory<br>from pt_backend.statistics.reports.prevalence import PrevalenceStatistics<br><br>class StatisticsCoordinator:<br>    def __init__(self, case_filter_service):<br>        self.case_filter_service = case_filter_service<br>        self.strategies = ReportFactory.get_all()<br><br>    def generate_comprehensive_report(self, **filters):<br>        # filter data<br>        try:<br>            if self.case_filter_service:<br>                filtered = self.case_filter_service.filter_cases(**filters)<br>            else:<br>                filtered = []<br>        except Exception as e:<br>            return {&quot;error&quot;: f&quot;Failed to filter cases: {e}&quot;}<br><br>        date_range = filters.get(&#39;date_range&#39;, {})<br>        start_date = date_range.get(&#39;start&#39;) if date_range else None<br><br>        out = {}<br>        for name, strategy in self.strategies.items():<br>            try:<br>                if isinstance(strategy, PrevalenceStatistics):<br>                    # Khusus untuk PrevalenceStatistics, kita perlu mengoper start_date<br>                    out[name] = strategy.generate_report(start_date=start_date)<br>                else:<br>                    # Strategy diharapkan menerima arg named filtered_cases<br>                    out[name] = strategy.generate_report(filtered_cases=filtered)<br>            except Exception as e:<br>                out[name] = {&quot;error&quot;: f&quot;Failed to generate report: {e}&quot;}<br><br>        return out</pre><pre>#factory.py<br>from pt_backend.repositories import CaseRepository<br>from pt_backend.statistics.reports.prevalence import PrevalenceStatistics<br>from pt_backend.statistics.interface import ReportStrategy<br>from pt_backend.statistics.reports.age_grouping import AgeGroupingReport<br>from pt_backend.statistics.reports.gender_grouping import GenderGroupingReport<br>from pt_backend.statistics.reports.healthcare_news import HealthcareNewsStatisticsReport<br>from pt_backend.statistics.reports.local_portal import LocalPortalStatisticsReport<br>from pt_backend.statistics.reports.national_news import NationalNewsStatisticsReport<br>from pt_backend.statistics.reports.severity_dates_count import SeverityDatesCountReport<br>from pt_backend.statistics.reports.severity_grouping import SeverityGroupingReport<br><br><br>class ReportFactory:<br>    @staticmethod<br>    def get_all() -&gt; dict[str, ReportStrategy]:<br>        return {<br>            &quot;prevalence_statistics&quot;: PrevalenceStatistics(repository=CaseRepository()),<br>            &quot;age_statistics&quot;: AgeGroupingReport(),<br>            &quot;gender_statistics&quot;: GenderGroupingReport(),<br>            &quot;severity_statistics&quot;: SeverityGroupingReport(),<br>            &quot;severity_dates_count_statistics&quot;: SeverityDatesCountReport(),<br>            &quot;national_news_statistics&quot;: NationalNewsStatisticsReport(),<br>            &quot;local_portal_statistics&quot;: LocalPortalStatisticsReport(),<br>            &quot;healthcare_news_statistics&quot;: HealthcareNewsStatisticsReport(),<br>        }</pre><p>And then that’s it, we have finished refactoring, now as this picture below shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*yemIhX8kARQrlp4FlDgraw.png" /><figcaption>Marked structure of the new statistics</figcaption></figure><p>The statistics is now more readable, and not as long as before, of course the tests needs to be separated also, so that means more readable tests too.</p><p>Now, let me tell you why strategy + factory, in the picture above, if in the future updates the app needs a new kind of stats, for example, international news. We just need to add a new report while implementing the generate_report func from the interface, then add it to the factory so that the factory loads it all.</p><p>What do we achieve with this design pattern applied?</p><ul><li>Each report becomes independent fulfilling the Open-Closed Principle, just add a new report if you need one.</li><li>The tests become simpler, because tests for eachreport is isolated</li><li>Before, a single file statistics.py is doing everything, now it is separated so that it fulfills the Single Responsibility Principle</li><li>Since the files become smaller, it improves readability and the files becomes more modular and easier to maintain</li></ul><p>What are the trade-offs from before?</p><ul><li>Well since we split the reports into smaller files, of course there will be many classes thus making the learning curve goes up a little</li><li>For the factory, if we used a naming convention, it needs to be maintained according to that</li></ul><p>And that’s it, we are done. So now, at least you know that refactoring isn’t just about making a code more “cleaner”, but its also about making your code more maintainable. There are many more design patterns, you can take a look here,</p><p><a href="https://refactoring.guru/design-patterns">Design Patterns</a></p><p>Just find the ones suiting your problem and make sure that the design pattern doesn’t make your code more complicated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1b2c4cd58ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[cMaking a secure program?]]></title>
            <link>https://medium.com/@allusernameistaken21/cmaking-a-secure-program-6a42c2144294?source=rss-a3b288abd16b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a42c2144294</guid>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Fatih Raditya]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 09:59:35 GMT</pubDate>
            <atom:updated>2025-04-27T09:59:35.529Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making a secure program?</h3><p><strong>Secure Programming</strong> bukan lagi sekadar nilai tambah, melainkan kebutuhan mendesak dalam dunia pengembangan perangkat lunak modern. Menulis kode yang hanya berfungsi dengan baik tidak cukup — keamanan harus dibangun.</p><p>Dalam artikel ini, saya akan mengupas bagaimana praktik secure programming diterapkan di <strong>Project PantauTular</strong>, berdasarkan analisis langsung terhadap codebase-nya.</p><p>Hal paling simple adalah menerapkan autentikasi dan otorisasi,</p><p>Ini adalah contoh penggunaan API Key dalam project saya</p><pre>class APIKeyAuthentication(BaseAuthentication):<br>    HEADER_NAME = &quot;X-API-KEY&quot;<br>    def authenticate(self, request):<br>        api_key = request.headers.get(self.HEADER_NAME)<br>        if not api_key:<br>            raise AuthenticationFailed(&quot;API key missing.&quot;)<br>        if not self._key_is_valid(api_key):<br>            raise AuthenticationFailed(&quot;Invalid API key.&quot;)<br>        return (AnonymousUser(), api_key)</pre><p>Ini integrated dengan django auth system dan juga melindungi endpoint kita dari akses dengan authentication_classes = [APIKeyAuthentication]</p><p>Contoh lain dari security selain autentikasi tadi adalah keamanan password pengguna, contohnya di sini adalah sebuah fitur mengganti password pengguna, cara kita mengamankan nya cukup simple dengan verify password lama nya.</p><pre>def update_user_password(self, user, current_password: str, new_password: str) -&gt; dict:<br>    if not self.repository.verify_password(user, current_password):<br>        return {&quot;success&quot;: False, &quot;error&quot;: &quot;Current password is incorrect&quot;}<br>    user.password = make_password(new_password)<br>    self.repository.save_user(user)<br>    return {&quot;success&quot;: True, &quot;message&quot;: &quot;Password successfully updated&quot;}</pre><p>Di sini saya verify password lama pengguna terlebih dahulu dan melakukan hashing dengan make_password() django.</p><p>Selain kedua tadi, ada juga input validation untuk validasi input seperti password, sehingga password pengguna jadi lebih aman dan ga ecek-ecek.</p><pre># Di authentication/serializers.py<br>class ChangePasswordSerializer(serializers.Serializer):<br>    current_password = serializers.CharField(write_only=True, required=True)<br>    new_password = serializers.CharField(write_only=True, required=True)<br>    confirm_password = serializers.CharField(write_only=True, required=True)<br><br>    def validate(self, data):<br>        if data[&#39;new_password&#39;] != data[&#39;confirm_password&#39;]:<br>            raise serializers.ValidationError({&quot;confirm_password&quot;: &quot;Password confirmation does not match.&quot;})<br>        validate_password(data[&#39;new_password&#39;], self.context[&#39;user&#39;])<br>        return data</pre><p>Ada juga OWASP (Open Web Application Security Project) dimana ini adalah community yang membantu untuk menciptakan web app yang lebih aman, di <a href="https://owasp.org/www-project-top-ten/">https://owasp.org/www-project-top-ten/</a> kita dapat melihat awareness document yang membantu kita untuk menciptakan software yang lebih aman, contohnya di sini saya menerapkan:</p><pre># Di pantau_tular/settings.py<br>REST_FRAMEWORK = {<br>    &quot;DEFAULT_THROTTLE_RATES&quot;: {<br>        &quot;user&quot;: &quot;10/min&quot;,   <br>    },<br>}<br><br># Di authentication/views.py<br>class SignupAPIView(APIView):<br>    throttle_classes = [UserRateThrottle]</pre><ul><li>Rate limiting untuk mencegah brute force attacks</li><li>Sesuai dengan OWASP A7 (2017): Tentang XSS automated tool</li></ul><pre># Di authentication/services.py<br>def validate_token(self, user, token):<br>    &quot;&quot;&quot;Validate if the token is valid for the given user&quot;&quot;&quot;<br>    if not user:<br>        return False<br>    return default_token_generator.check_token(user, token)</pre><ul><li>Implementasi safe token untuk password reset</li><li>Sesuai dengan OWASP A2 (2017): Broken Authentication</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a42c2144294" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mocking vs Stubbing in testing and their benefits]]></title>
            <link>https://medium.com/@allusernameistaken21/mocking-vs-stubbing-in-testing-and-their-benefits-b3e854db3751?source=rss-a3b288abd16b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3e854db3751</guid>
            <category><![CDATA[code-coverage]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[stub]]></category>
            <category><![CDATA[mock]]></category>
            <dc:creator><![CDATA[Fatih Raditya]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 03:51:40 GMT</pubDate>
            <atom:updated>2025-04-29T07:30:54.237Z</atom:updated>
            <content:encoded><![CDATA[<p>I have a project, a backend system designed for tracking and analyzing disease cases across Indonesia, exemplifies this critical need. This system aggregates data from various news sources, classifies disease outbreaks, and provides statistical analyses that help health authorities make informed decisions.</p><p>When testing such a system, developers face a common challenge: how to isolate components for testing without relying on external dependencies like databases, APIs, or complex calculations. This is where test doubles become invaluable.</p><h3>What Are Test Doubles?</h3><p>Test doubles are objects that stand in for real components during testing, similar to how stunt doubles stand in for actors in dangerous movie scenes. They allow developers to test code in isolation by replacing complex dependencies with simplified versions that are easier to control and verify.</p><p>The term “test double” was popularized by Gerard Meszaros in his book “xUnit Test Patterns,” drawing an analogy to stunt doubles in movies. Just as a stunt double replaces an actor for difficult scenes, a test double replaces a component for challenging test scenarios.</p><h3>The Test Double Family</h3><p>The confusion in the industry often stems from using these terms interchangeably. In reality, test doubles come in several distinct types:</p><ol><li><strong>Dummy objects</strong>: Passed around but never actually used</li><li><strong>Stubs</strong>: Provide predefined answers to method calls</li><li><strong>Spies</strong>: Record which methods were called and with what parameters</li><li><strong>Mocks</strong>: Pre-programmed with expectations about calls they should receive</li><li><strong>Fakes</strong>: Working implementations but using shortcuts unsuitable for production</li></ol><h3>From Theory to Practice: My Approach</h3><p>I have implemented a testing strategy that makes extensive use of test doubles. For example, in the statistics module that calculates disease prevalence, gender distribution, and severity analysis, we can find numerous examples of both stubbing and mocking:</p><p><strong>Example from codebase — stubs:</strong></p><pre># File: test_statistics.py<br>def test_get_prevalence_statistics_with_start_date(self):<br>    # Simple stubbing - providing test case data<br>    repository = CaseRepository()  # This acts as a stub providing test data<br>    statistics = PrevalenceStatistics(repository)<br>    <br>    start_date = &#39;2023-01-01&#39;<br>    result = statistics.get_prevalence_statistics(start_date)<br>    <br>    self.assertEqual(result[&quot;year&quot;], 2023)<br>    self.assertEqual(result[&quot;total_cases&quot;], 1)</pre><h4>When to Use Stubs</h4><ul><li>When you need to isolate the component under test from external dependencies</li><li>When you need to test how your code handles specific responses or data</li><li>When the real components are unavailable or would make testing slow/complex</li></ul><p><strong>Example from codebase — mocks:</strong></p><pre># File: test_statistics.py<br>def test_generate_comprehensive_report_with_start_date(self):<br>    # Create a mock prevalence statistics<br>    self.mock_prevalence = Mock()<br>    self.mock_prevalence.get_prevalence_statistics.return_value = {<br>        &quot;year&quot;: 2023,<br>        &quot;total_cases&quot;: 100,<br>        &quot;population&quot;: 278696200,<br>        &quot;prevalence&quot;: 0.0359<br>    }<br>    <br>    # Use the mock in the coordinator<br>    self.coordinator = StatisticsCoordinator(self.mock_case_filter_service)<br>    <br>    # Call the method with a date_range<br>    result = self.coordinator.generate_comprehensive_report(<br>        date_range={&quot;start&quot;: &quot;2023-01-01&quot;, &quot;end&quot;: None}<br>    )<br>    <br>    # Verify that get_prevalence_statistics was called with the correct parameter<br>    self.mock_prevalence.get_prevalence_statistics.assert_called_once_with(&quot;2023-01-01&quot;)</pre><h4>When to Use Mocks</h4><ul><li>When testing component interactions is more important than final results</li><li>When you need to verify order or frequency of method calls</li><li>When you need to simulate complex behaviors or exceptions</li></ul><h4>What insights can we get from those 2 tests</h4><blockquote>In the first test, the repository isn’t mocked because we wanted to use it the way it is, not to test the behaviour of the repository. The focus of the first test is the get_prevalence_statistics logic not the CaseRepository. So, we stub it.</blockquote><p>In the second test, we needed the Mock, why? because we use the get_prevalence_statistics inside of generate_comprehensive_report thus we needed to mock it, and we needed to make sure that generate_comprehensive_report called get_prevalence_statistics with the correct argument. So I hope with this explanation, you understand what is Stub and Mock.</p><h3>Benefits of Mocking and Stubbing</h3><h4>1. Isolation</h4><ul><li>Testing components in isolation regardless of external dependencies</li><li>Example from codebase: Testing StatisticsCoordinator without relying on real database operations</li></ul><h4>2. Predictability</h4><ul><li>Tests become deterministic by controlling the behavior of dependencies</li><li>Example: Mocking datetime to always return a specific date</li></ul><pre>@patch(&#39;pt_backend.statistics.datetime&#39;)<br>def test_get_prevalence_statistics_with_mocked_date(self, mock_datetime):<br>    # Mock the datetime.strptime to return a specific date<br>    mock_datetime.strptime.return_value = datetime(2023, 1, 1)</pre><h4>3. Speed</h4><ul><li>Tests run faster by avoiding expensive operations like database calls</li><li>Codebase example: Testing large datasets without actual database queries</li></ul><pre>def test_generate_report_with_large_dataset(self):<br>    &quot;&quot;&quot;Performance test: ensure the report works correctly with a large dataset.&quot;&quot;&quot;<br>    cases = [{&quot;id&quot;: i, &quot;gender&quot;: &quot;male&quot; if i % 2 == 0 else &quot;female&quot;} for i in range(1, 10001)]<br>    result = self.report.generate_report(cases)<br>    self.assertEqual(result, {&quot;male&quot;: 5000, &quot;female&quot;: 5000})</pre><h4>4. Edge Case Testing</h4><ul><li>Testing scenarios that are difficult to reproduce with real dependencies</li><li>Codebase example: Testing error handling with forced exceptions</li></ul><pre>def test_get_all_case_locations_exception(self, mock_get_all_locations):<br>    mock_get_all_locations.side_effect = Exception(&quot;Database error&quot;)<br>    response = self.client.get(&#39;/cases/locations/&#39;)</pre><h3>Conclusion</h3><ul><li>Mocking and stubbing are powerful techniques for creating reliable, maintainable</li><li>The right approach depends on what you want to test: state or behavior</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3e854db3751" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test-Driven Development in Django While Applying SOLID principles]]></title>
            <link>https://medium.com/@allusernameistaken21/test-driven-development-in-django-while-applying-solid-principles-ae5d5f3a78e3?source=rss-a3b288abd16b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae5d5f3a78e3</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[tddwithpython]]></category>
            <dc:creator><![CDATA[Fatih Raditya]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 03:20:41 GMT</pubDate>
            <atom:updated>2025-04-29T07:56:32.460Z</atom:updated>
            <content:encoded><![CDATA[<p>Django adalah framework web berbasis Python yang digunakan untuk membangun aplikasi web dengan cepat dan efisien. Django mengikuti arsitektur <strong>MVT (Model-View-Template)</strong> dan dilengkapi fitur seperti ORM, autentikasi, dan admin panel bawaan, sehingga mempermudah pengembangan tanpa harus menulis banyak kode dari nol.</p><p><strong>Apa itu TDD?</strong></p><p>Test-Driven Development atau TDD adalah metode development yang dilakukan dengan cara menulis test terlebih dahulu baru mengembangkan fitur berdasarkan test yang sudah dibuat. Siklusnya terdiri dari:</p><ol><li><strong>Red</strong> — Menulis tes yang gagal karena fitur belum ada.</li><li><strong>Green</strong> — Mengembangkan fitur minimal hingga tes berhasil.</li><li><strong>Refactor</strong> — Merapikan kode tanpa mengubah perilaku.</li></ol><p><strong>Apa itu SOLID principles?</strong></p><p>SOLID principles adalah sebuah metode desain program dengan basis OOP yang memenuhi 5 syarat berikut:</p><ul><li><strong>S</strong>ingle Responsibility Principle (SRP) → Setiap class hanya boleh memiliki satu alasan untuk berubah (satu tanggung jawab).</li><li><strong>O</strong>pen/Closed Principle (OCP) → Kode harus <strong>terbuka untuk ekstensi, tetapi tertutup untuk modifikasi</strong>.</li><li><strong>L</strong>iskov Substitution Principle (LSP) → Subclass harus bisa menggantikan superclass tanpa mengubah perilaku yang diharapkan.</li><li><strong>I</strong>nterface Segregation Principle (ISP) → Interface harus spesifik dan tidak memaksa class untuk mengimplementasikan metode yang tidak diperlukan.</li><li><strong>D</strong>ependency Inversion Principle (DIP) → Kode harus bergantung pada <strong>abstraksi</strong>, bukan implementasi konkret.</li></ul><p><strong>Contoh</strong></p><p>Di sini saya akan membuat endpoint untuk 2 hal, mendapatkan top 5 portal berita yang bertipe kesehatan serta mendapatkan statistik dari semua berita kesehatan. Kita akan membagi files menjadi seperti berikut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/0*5j7gGFeOntTuFCa8" /><figcaption>File separations</figcaption></figure><p>Ini guna menjaga code menjadi lebih maintainable. Berikutnya kita akan membuat tests untuk masing-masing. Yang akan saya contohkan di sini tidak semuanya dan hanya untuk gambaran.</p><pre>class NewsRepositoryTestCase(BaseTestCase):<br>    def setUp(self):<br>        super().setUp()<br>        self.repository = NewsRepository()<br>        self.disease = Disease.objects.create(name=&quot;COVID-19&quot;, level_of_alertness=5)<br>        self.disease2 = Disease.objects.create(name=&quot;SARS&quot;, level_of_alertness=4)<br>        self.location = Location.objects.create(<br>            latitude=-6.2088, longitude=106.8456, city=&quot;Jakarta&quot;<br>        )<br>        self.case1 = Case.objects.create(<br>            id=uuid.uuid4(), gender=&quot;Pria&quot;, age=30, city=&quot;Jakarta&quot;, status=&quot;kematian&quot;, disease=self.disease, location=self.location<br>        )<br>        self.case2 = Case.objects.create(<br>            id=uuid.uuid4(), gender=&quot;Wanita&quot;, age=25, city=&quot;Jakarta&quot;, status=&quot;terjangkit&quot;, disease=self.disease2, location=self.location<br>        )<br>        self.news1 = News.objects.create(<br>            id=uuid.uuid4(), portal=&quot;kompas.com&quot;, type=&quot;Kesehatan&quot;, title=&quot;COVID-19 Detected in Jakarta&quot;, content=&quot;COVID-19 case detected in Jakarta...&quot;, url=&quot;https://www.kompas.com/covid-jakarta&quot;, author=&quot;Dr. Joko&quot;, case=self.case1<br>        )<br>        self.news2 = News.objects.create(<br>            id=uuid.uuid4(), portal=&quot;detik.com&quot;, type=&quot;Kesehatan&quot;, title=&quot;SARS Detected in Jakarta&quot;, content=&quot;SARS case detected in Medan...&quot;, url=&quot;https://www.detik.com/sars-jakarta&quot;, author=&quot;Dr. Sari&quot;, case=self.case2<br>        )<br>        self.news3 = News.objects.create(<br>            id=uuid.uuid4(), portal=&quot;kompas.com&quot;, type=&quot;Kesehatan&quot;, title=&quot;COVID-19 Detected in Jakarta&quot;, content=&quot;COVID-19 case detected in Jakarta...&quot;, url=&quot;https://www.kompas.com/covid-jakarta&quot;, author=&quot;Dr. Joko&quot;, case=self.case1<br>        )<br>        self.news4 = News.objects.create(<br>            id=uuid.uuid4(), portal=&quot;kompas.com&quot;, type=&quot;Kesehatan&quot;, title=&quot;SARS Detected in Jakarta&quot;, content=&quot;COVID-19 case detected in Jakarta...&quot;, url=&quot;https://www.kompas.com/covid-jakarta&quot;, author=&quot;Dr. Joko&quot;, case=self.case2<br>        )<br>        self.news5 = News.objects.create(<br>            id=uuid.uuid4(), portal=&quot;WHO International&quot;, type=&quot;Kesehatan&quot;, title=&quot;COVID-19 Detected in Jakarta&quot;, content=&quot;COVID-19 case detected in Jakarta...&quot;, url=&quot;https://www.kompas.com/covid-jakarta&quot;, author=&quot;Dr. Joko&quot;, case=self.case1<br>        )<br>        self.news6 = News.objects.create(<br>            id=uuid.uuid4(), portal=&quot;Kemenkes.go.id&quot;, type=&quot;Kesehatan&quot;, title=&quot;COVID-19 Detected in Jakarta&quot;, content=&quot;COVID-19 case detected in Jakarta...&quot;, url=&quot;https://www.kompas.com/covid-jakarta&quot;, author=&quot;Dr. Joko&quot;, case=self.case1<br>        )<br>        self.news7 = News.objects.create(<br>            id=uuid.uuid4(), portal=&quot;bps.go.id&quot;, type=&quot;Kesehatan&quot;, title=&quot;COVID-19 Detected in Jakarta&quot;, content=&quot;COVID-19 case detected in Jakarta...&quot;, url=&quot;https://www.kompas.com/covid-jakarta&quot;, author=&quot;Dr. Joko&quot;, case=self.case1<br>        )<br>        self.news8 = News.objects.create(<br>            id=uuid.uuid4(), portal=&quot;bps.go.id&quot;, type=&quot;Kesehatan&quot;, title=&quot;COVID-19 Detected in Jakarta&quot;, content=&quot;COVID-19 case detected in Jakarta...&quot;, url=&quot;https://www.kompas.com/covid-jakarta&quot;, author=&quot;Dr. Joko&quot;, case=self.case1<br>        )<br>        self.news9 = News.objects.create(<br>            id=uuid.uuid4(), portal=&quot;bpjs.go.id&quot;, type=&quot;Kesehatan&quot;, title=&quot;COVID-19 Detected in Jakarta&quot;, content=&quot;COVID-19 case detected in Jakarta...&quot;, url=&quot;https://www.kompas.com/covid-jakarta&quot;, author=&quot;Dr. Joko&quot;, case=self.case1<br>        )<br>        self.news10 = News.objects.create(<br>            id=uuid.uuid4(), portal=&quot;kemenhub.go.id&quot;, type=&quot;Kesehatan&quot;, title=&quot;COVID-19 Detected in Jakarta&quot;, content=&quot;COVID-19 case detected in Jakarta...&quot;, url=&quot;https://www.kompas.com/covid-jakarta&quot;, author=&quot;Dr. Joko&quot;, case=self.case1<br>        )<br><br>    def test_get_healthcare_news_statistics(self):<br>        result = self.repository.get_healthcare_news_statistics()<br>        self.maxDiff = None<br>        self.assertEqual(result, [<br>            {&#39;portal&#39;: &#39;Kemenkes.go.id&#39;, &#39;news_count&#39;: 1, &#39;disease_count&#39;: 1},<br>            {&#39;portal&#39;: &#39;WHO International&#39;, &#39;news_count&#39;: 1, &#39;disease_count&#39;: 1},<br>            {&#39;portal&#39;: &#39;bpjs.go.id&#39;, &#39;news_count&#39;: 1, &#39;disease_count&#39;: 1},<br>            {&#39;portal&#39;: &#39;bps.go.id&#39;, &#39;news_count&#39;: 2, &#39;disease_count&#39;: 1},<br>            {&#39;portal&#39;: &#39;detik.com&#39;, &#39;news_count&#39;: 1, &#39;disease_count&#39;: 1},<br>            {&#39;portal&#39;: &#39;kemenhub.go.id&#39;, &#39;news_count&#39;: 1, &#39;disease_count&#39;: 1},<br>            {&#39;portal&#39;: &#39;kompas.com&#39;, &#39;news_count&#39;: 3, &#39;disease_count&#39;: 2}<br>        ])<br>    def test_get_top_healthcare_news_portal(self):<br>        result = self.repository.get_top_healthcare_news_portal()<br>        self.assertEqual(result, [{&#39;portal&#39;: &#39;kompas.com&#39;, &#39;count&#39;: 3}, {&#39;portal&#39;: &#39;bps.go.id&#39;, &#39;count&#39;: 2}, {&#39;portal&#39;: &#39;kemenhub.go.id&#39;, &#39;count&#39;: 1}, {&#39;portal&#39;: &#39;detik.com&#39;, &#39;count&#39;: 1}, {&#39;portal&#39;: &#39;bpjs.go.id&#39;, &#39;count&#39;: 1}])<br><br>    def test_get_top_healthcare_news_portal_empty(self):<br>        News.objects.all().delete()<br>        result = self.repository.get_top_healthcare_news_portal()<br>        self.assertEqual(result, [])<br>    <br>    def test_get_top_healthcare_news_portal_exception(self):<br>        with patch(&#39;pt_backend.models.News.objects.filter&#39;, side_effect=ObjectDoesNotExist):<br>            result = self.repository.get_top_healthcare_news_portal()<br>            self.assertEqual(result, {&quot;error&quot;: &quot;Error retrieving news&quot;})<br>    <br>    def test_get_healthcare_news_statistics_exception(self):<br>        with patch(&#39;pt_backend.models.News.objects.filter&#39;, side_effect=ObjectDoesNotExist):<br>            result = self.repository.get_healthcare_news_statistics()<br>            self.assertEqual(result, {&quot;error&quot;: &quot;Error retrieving news statistics&quot;})</pre><p>Berikutnya kita akan menerapkan implementasi untuk repository nya</p><pre>class NewsRepository:      <br>    def get_healthcare_news_statistics(self):<br>        try:<br>            news_stats = News.objects.filter(type=&quot;Kesehatan&quot;) \<br>                .values(&#39;portal&#39;) \<br>                .annotate(<br>                    news_count=Count(&#39;id&#39;),<br>                    disease_count=Count(&#39;case__disease&#39;, distinct=True)<br>                )<br><br>            results = []<br>            for stat in news_stats:<br>                results.append({<br>                    &#39;portal&#39;: stat[&#39;portal&#39;],<br>                    &#39;news_count&#39;: stat[&#39;news_count&#39;], <br>                    &#39;disease_count&#39;: stat[&#39;disease_count&#39;]<br>                })<br>            return results<br><br>        except ObjectDoesNotExist:<br>            return {&quot;error&quot;: &quot;Error retrieving news statistics&quot;}<br><br>    def get_top_healthcare_news_portal(self):<br>        try:<br>            news_stats = News.objects.filter(type=&quot;Kesehatan&quot;) \<br>                .values(&#39;portal&#39;) \<br>                .annotate(<br>                    news_count=Count(&#39;id&#39;)<br>                ) \<br>                .order_by(&#39;-news_count&#39;)[:5]<br><br>            if not news_stats:<br>                return []<br><br>            results = []<br>            for stat in news_stats:<br>                results.append({<br>                    &#39;portal&#39;: stat[&#39;portal&#39;],<br>                    &#39;count&#39;: stat[&#39;news_count&#39;]<br>                })<br>            return results<br><br>        except ObjectDoesNotExist:<br>            return {&quot;error&quot;: &quot;Error retrieving news&quot;}</pre><p>Rest of it bisa di cek di sini.</p><p><a href="https://github.com/PPL-BRIN/pantautular-be/tree/pbi-d03-olah_data_berita_kesehatan">GitHub - PPL-BRIN/pantautular-be at pbi-d03-olah_data_berita_kesehatan</a></p><h3><strong>Kenapa ini SOLID?</strong></h3><ol><li>Single Responsibility Principle (SRP)</li></ol><ul><li>NewsRepository handles only data access</li><li>NewsService handles only business logic</li><li>HealthcareNewsStatisticsView and TopHealthcareNewsPortalView handle only HTTP requests/responses</li><li>Serializers (PortalStatisticsSerializer, TopPortalSerializer) handle only data transformation</li></ul><p>2. Open/Closed Principle (OCP)</p><ul><li>Using interfaces (NewsRepositoryInterface) allows extending functionality without modifying existing code</li><li>New statistics or portal features can be added by extending existing classes</li></ul><p>3. Liskov Substitution Principle (LSP)</p><ul><li>NewsRepository implements NewsRepositoryInterface without changing the expected behavior</li><li>Any class implementing NewsRepositoryInterface can be used in NewsService</li></ul><p>4. Interface Segregation Principle (ISP)</p><ul><li>NewsRepositoryInterface is focused on news-specific methods</li><li>Views are separated based on their specific responsibilities (statistics vs top portal)</li></ul><p>5. Dependency Inversion Principle (DIP)</p><ul><li>NewsService depends on NewsRepositoryInterface (abstraction) not concrete implementation</li><li>Views depend on service interfaces rather than concrete implementations</li></ul><p>Gambarannya kurang lebih seperti ini.</p><pre>UI/API Layer (Views)<br>↓<br>Service Layer (NewsService)<br>↓<br>Repository Layer (NewsRepository)<br>↓<br>Data Layer (Models/Database)</pre><p><strong>Manfaat dibuat SOLID apa?</strong></p><ul><li>Lebih Mudah Maintain: Setiap class punya tugas spesifik. Contohnya, NewsRepository hanya urus database, NewsService hanya urus bisnis logic. Kalau ada bug, kita langsung tahu harus cek di mana.</li><li>Lebih Mudah Test: Lihat di test_views.py, kita bisa test API dan service secara terpisah karena tanggung jawabnya sudah dipisah dengan jelas.</li><li>Mudah Tambah Fitur Baru: Kalau mau tambah fitur baru (misal: untuk berita mau dibuat berdasarkan tanggal atau periode), tinggal extend saja tanpa ubah code yang sudah ada.</li><li>Tidak Takut Rusak: Karena menambah fitur baru tidak perlu mengubah code lama, risiko merusak fitur yang sudah jalan jadi minimal.</li><li>Loose Coupling: Service tidak bergantung langsung ke repository konkrit, tapi ke interface. Ini membuat code lebih flexible.</li><li>Mudah Unit Test: Lihat di NewsAPITest, kita bisa dengan mudah inject mock repository untuk testing.</li></ul><pre># 1. SRP - Setiap class punya 1 tugas<br>class NewsRepository:  # Hanya urus database<br>    def get_healthcare_news_statistics(self):<br>        # database logic<br><br>class NewsService:  # Hanya urus business logic<br>    def get_healthcare_news_statistics(self):<br>        # business logic<br><br># 2. OCP - Mudah extend tanpa ubah code lama<br>class AdvancedNewsService(NewsService):<br>    def get_news_by_date(self):  # Fitur baru<br>        # new feature logic<br><br># 3. LSP - Bisa ganti implementasi<br>class PostgresNewsRepository(NewsRepositoryInterface):<br>    # Implementasi baru, tapi service tetap jalan<br><br># 4. ISP - Interface fokus<br>class NewsRepositoryInterface:<br>    def get_healthcare_news_statistics(self):<br>        pass<br>    def get_top_healthcare_news_portal(self):<br>        pass<br>    # Hanya method yang memang dibutuhkan<br><br># 5. DIP - Dependency ke abstraction<br>class NewsService:<br>    def __init__(self, repository: NewsRepositoryInterface):<br>        # Bergantung ke interface, bukan implementasi konkrit</pre><h3>Kenapa Django yang MVT Perlu Pakai OOP?</h3><ul><li><strong>MVT sendiri tidak sepenuhnya OOP</strong>, tetapi Django menggunakan banyak konsep OOP.</li><li><strong>Pemisahan tugas (SRP) lebih jelas</strong>: Model, View, Template tetap bisa menggunakan prinsip OOP di belakangnya.</li><li><strong>Lebih modular</strong>: Memudahkan testing dan perubahan di satu bagian tanpa merusak bagian lain.</li><li><strong>Lebih scalable</strong>: Dengan OOP, kita bisa menambah fitur tanpa mengubah banyak kode.</li></ul><p><strong>Kalau gak pakai OOP, kode akan lebih sulit di-maintain</strong> karena semua logika akan bercampur dalam satu file atau fungsi besar. <strong>Semua ini memenuhi SOLID</strong> karena kita menerapkan <strong>abstraksi (DIP), pemisahan tanggung jawab (SRP), dan fleksibilitas ekstensi (OCP &amp; LSP)</strong> dalam kode kita!</p><p><strong>What about testing in frontend, are there any differences between frontend and backend tests?</strong></p><p>Saya telah membuat beberapa fitur dengan TDD, kesimpulan yang dapat saya ambil untuk TDD adalah bahwa Testing yang dibuat harus komprehensif, sehingga untuk tiap fitur akan berbeda-beda tergantung fiturnya, ada yang tidak perlu mocking atau stubbing karena tidak memiliki dependensi terhadap fitur lain, atau ada yang ternyata fitur yang sudah jadi masih tidak bisa menghandle negative atau edge case, sehinggga diperlukan edge case dan juga negative tests yang akan dipenuhi di fiturnya.</p><p>Untuk perbedaan sendiri, saat kamu mulai menuliskan tes untuk frontend, mungkin kamu merasa mirip-mirip saja dengan membuat tes untuk backend. Tapi jika kamu perhatikan, saya ada contoh di sini</p><pre>import React from &#39;react&#39;;<br>import { render, screen, fireEvent, waitFor } from &#39;@testing-library/react&#39;;<br>import &#39;@testing-library/jest-dom&#39;;<br>import PasswordSettings from &#39;../../app/components/password-settings&#39;;<br>import fetchMock from &#39;jest-fetch-mock&#39;;<br><br>// Mock the environment variables with secure protocol<br>process.env.NEXT_PUBLIC_API_URL = &#39;https://test-api&#39;;<br>process.env.NEXT_PUBLIC_API_KEY = &#39;test-api-key&#39;;<br><br>// Test constants to avoid hard-coded credentials<br>const TEST_CURRENT_PASSWORD = &#39;TestCurrentPwd&#39;;<br>const TEST_WRONG_PASSWORD = &#39;TestWrongPwd&#39;;<br>const TEST_NEW_PASSWORD = &#39;TestP@ssw0rd&#39;; // Meets requirements: 8+ chars, upper, lower, digit, symbol<br>const TEST_DIFFERENT_PASSWORD = &#39;D1fferent@Pass&#39;;<br><br>// Mock the Button component<br>jest.mock(&#39;../../app/components/ui-profile/button&#39;, () =&gt; ({<br>  Button: ({ children, className, onClick, disabled, type }: any) =&gt; (<br>    &lt;button <br>      className={className} <br>      onClick={onClick} <br>      disabled={disabled} <br>      type={type}<br>      data-testid=&quot;button&quot;<br>    &gt;<br>      {children}<br>    &lt;/button&gt;<br>  ),<br>}));<br><br>// Mock the Input component<br>jest.mock(&#39;../../app/components/ui-profile/input&#39;, () =&gt; ({<br>  Input: ({ id, type, placeholder, className, value, onChange, required }: any) =&gt; (<br>    &lt;input<br>      id={id}<br>      type={type}<br>      placeholder={placeholder}<br>      className={className}<br>      value={value}<br>      onChange={onChange}<br>      required={required}<br>      data-testid={`input-${id}`}<br>    /&gt;<br>  ),<br>}));<br><br>// Mock the CheckIcon component<br>jest.mock(&#39;../../app/components/ui-profile/Checkicon&#39;, () =&gt; ({<br>  CheckIcon: ({ isChecked }: { isChecked: boolean }) =&gt; (<br>    &lt;div data-testid=&quot;check-icon&quot; data-checked={isChecked ? &#39;true&#39; : &#39;false&#39;}&gt;<br>      {isChecked ? &#39;✅&#39; : &#39;⭕&#39;}<br>    &lt;/div&gt;<br>  ),<br>}));<br><br>// Setup fetch mock<br>fetchMock.enableMocks();<br><br>describe(&#39;PasswordSettings Component&#39;, () =&gt; {<br>  const mockOnClose = jest.fn();<br><br>  beforeEach(() =&gt; {<br>    fetchMock.resetMocks();<br>    render(&lt;PasswordSettings onClose={mockOnClose} /&gt;);<br>  });<br><br>  afterEach(() =&gt; {<br>    jest.clearAllMocks();<br>  });<br><br>  it(&#39;renders password settings modal with title and data-testid&#39;, () =&gt; {<br>    // Should have data-testid for the ProfileIcon.test.tsx<br>    const modal = screen.getByTestId(&#39;password-settings&#39;);<br>    expect(modal).toBeInTheDocument();<br><br>    const heading = screen.getByRole(&#39;heading&#39;, { name: &#39;Ubah Kata Sandi&#39; });<br>    expect(heading).toBeInTheDocument();<br>  });<br><br>  it(&#39;displays all password requirements with correct check icons&#39;, () =&gt; {<br>    expect(screen.getByText(&#39;Kata sandi harus terdiri dari setidaknya 8 karakter&#39;)).toBeInTheDocument();<br>    expect(screen.getByText(&#39;Kata sandi harus terdiri dari setidaknya 1 huruf kapital&#39;)).toBeInTheDocument();<br>    expect(screen.getByText(&#39;Kata sandi harus terdiri dari setidaknya 1 huruf kecil&#39;)).toBeInTheDocument();<br>    expect(screen.getByText(&#39;Kata sandi harus terdiri dari setidaknya 1 angka&#39;)).toBeInTheDocument();<br>    expect(screen.getByText(&#39;Kata sandi harus terdiri dari setidaknya 1 simbol khusus&#39;)).toBeInTheDocument();<br>    <br>    // All check icons should be unchecked initially<br>    const checkIcons = screen.getAllByTestId(&#39;check-icon&#39;);<br>    checkIcons.forEach(icon =&gt; {<br>      expect(icon.getAttribute(&#39;data-checked&#39;)).toBe(&#39;false&#39;);<br>    });<br>  });<br><br>  it(&#39;renders password form fields with correct attributes&#39;, () =&gt; {<br>    const currentPasswordInput = screen.getByTestId(&#39;input-current-password&#39;);<br>    expect(currentPasswordInput).toBeInTheDocument();<br>    expect(currentPasswordInput).toHaveAttribute(&#39;type&#39;, &#39;password&#39;);<br>    expect(currentPasswordInput).toHaveAttribute(&#39;required&#39;);<br><br>    const newPasswordInput = screen.getByTestId(&#39;input-new-password&#39;);<br>    expect(newPasswordInput).toBeInTheDocument();<br>    expect(newPasswordInput).toHaveAttribute(&#39;type&#39;, &#39;password&#39;);<br>    <br>    const confirmPasswordInput = screen.getByTestId(&#39;input-confirm-password&#39;);<br>    expect(confirmPasswordInput).toBeInTheDocument();<br>    expect(confirmPasswordInput).toHaveAttribute(&#39;type&#39;, &#39;password&#39;);<br>  });<br><br>  it(&#39;updates check icons when password meets requirements&#39;, () =&gt; {<br>    const newPasswordInput = screen.getByTestId(&#39;input-new-password&#39;);<br>    <br>    // Type a password that meets all requirements<br>    fireEvent.change(newPasswordInput, { target: { value: TEST_NEW_PASSWORD } });<br>    <br>    // Check that all validation icons are checked<br>    const checkIcons = screen.getAllByTestId(&#39;check-icon&#39;);<br>    // First 5 icons should be checked (for password requirements)<br>    for (let i = 0; i &lt; 5; i++) {<br>      expect(checkIcons[i].getAttribute(&#39;data-checked&#39;)).toBe(&#39;true&#39;);<br>    }<br>  });<br><br>  it(&#39;shows error when passwords do not match&#39;, () =&gt; {<br>    const newPasswordInput = screen.getByTestId(&#39;input-new-password&#39;);<br>    const confirmPasswordInput = screen.getByTestId(&#39;input-confirm-password&#39;);<br>    <br>    // Type different passwords<br>    fireEvent.change(newPasswordInput, { target: { value: TEST_NEW_PASSWORD } });<br>    fireEvent.change(confirmPasswordInput, { target: { value: TEST_DIFFERENT_PASSWORD } });<br>    <br>    // Error message should be displayed<br>    const errorMessage = screen.getByText(&#39;Konfirmasi kata sandi tidak sesuai&#39;);<br>    expect(errorMessage).toBeInTheDocument();<br>  });<br>  <br>  it(&#39;disables submit button when form is invalid&#39;, () =&gt; {<br>    const currentPasswordInput = screen.getByTestId(&#39;input-current-password&#39;);<br>    const submitButton = screen.getByTestId(&#39;button&#39;);<br>    <br>    // Initially button should be disabled<br>    expect(submitButton).toBeDisabled();<br>    <br>    // Add current password but no new password<br>    fireEvent.change(currentPasswordInput, { target: { value: TEST_CURRENT_PASSWORD } });<br>    expect(submitButton).toBeDisabled();<br>  });<br><br>  it(&#39;enables submit button when form is valid&#39;, () =&gt; {<br>    const currentPasswordInput = screen.getByTestId(&#39;input-current-password&#39;);<br>    const newPasswordInput = screen.getByTestId(&#39;input-new-password&#39;);<br>    const confirmPasswordInput = screen.getByTestId(&#39;input-confirm-password&#39;);<br>    const submitButton = screen.getByTestId(&#39;button&#39;);<br>    <br>    // Fill in all fields with valid data<br>    fireEvent.change(currentPasswordInput, { target: { value: TEST_CURRENT_PASSWORD } });<br>    fireEvent.change(newPasswordInput, { target: { value: TEST_NEW_PASSWORD } });<br>    fireEvent.change(confirmPasswordInput, { target: { value: TEST_NEW_PASSWORD } });<br>    <br>    // Button should be enabled<br>    expect(submitButton).not.toBeDisabled();<br>  });<br><br>  it(&#39;calls API and shows success message on successful form submission&#39;, async () =&gt; {<br>    fetchMock.mockResponseOnce(JSON.stringify({ message: &#39;Kata sandi berhasil diubah&#39; }), { status: 200 });<br>    <br>    const currentPasswordInput = screen.getByTestId(&#39;input-current-password&#39;);<br>    const newPasswordInput = screen.getByTestId(&#39;input-new-password&#39;);<br>    const confirmPasswordInput = screen.getByTestId(&#39;input-confirm-password&#39;);<br>    const submitButton = screen.getByTestId(&#39;button&#39;);<br>    <br>    // Fill in all fields with valid data<br>    fireEvent.change(currentPasswordInput, { target: { value: TEST_CURRENT_PASSWORD } });<br>    fireEvent.change(newPasswordInput, { target: { value: TEST_NEW_PASSWORD } });<br>    fireEvent.change(confirmPasswordInput, { target: { value: TEST_NEW_PASSWORD } });<br>    <br>    // Submit the form<br>    fireEvent.click(submitButton);<br>    <br>    // Check that the API was called with correct data using HTTPS<br>    await waitFor(() =&gt; {<br>      expect(fetchMock).toHaveBeenCalledWith(<br>        `${process.env.NEXT_PUBLIC_API_URL}/api/change-password`,<br>        expect.objectContaining({<br>          method: &#39;POST&#39;,<br>          headers: expect.objectContaining({<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            &#39;X-API-KEY&#39;: process.env.NEXT_PUBLIC_API_KEY<br>          }),<br>          body: JSON.stringify({<br>            current_password: TEST_CURRENT_PASSWORD,<br>            new_password: TEST_NEW_PASSWORD,<br>            confirm_password: TEST_NEW_PASSWORD<br>          })<br>        })<br>      );<br>    });<br>    <br>    // Success message should be displayed<br>    await waitFor(() =&gt; {<br>      const successMessage = screen.getByText(&#39;Kata sandi berhasil diubah&#39;);<br>      expect(successMessage).toBeInTheDocument();<br>    });<br>  });<br><br>  it(&#39;displays error message when API returns error&#39;, async () =&gt; {<br>    fetchMock.mockResponseOnce(JSON.stringify({ error: &#39;Current password is incorrect&#39; }), { status: 400 });<br>    <br>    const currentPasswordInput = screen.getByTestId(&#39;input-current-password&#39;);<br>    const newPasswordInput = screen.getByTestId(&#39;input-new-password&#39;);<br>    const confirmPasswordInput = screen.getByTestId(&#39;input-confirm-password&#39;);<br>    const submitButton = screen.getByTestId(&#39;button&#39;);<br>    <br>    // Fill in all fields with valid data<br>    fireEvent.change(currentPasswordInput, { target: { value: TEST_WRONG_PASSWORD } });<br>    fireEvent.change(newPasswordInput, { target: { value: TEST_NEW_PASSWORD } });<br>    fireEvent.change(confirmPasswordInput, { target: { value: TEST_NEW_PASSWORD } });<br>    <br>    // Submit the form<br>    fireEvent.click(submitButton);<br>    <br>    // Error message should be displayed<br>    await waitFor(() =&gt; {<br>      const errorMessage = screen.getByText(&#39;Current password is incorrect&#39;);<br>      expect(errorMessage).toBeInTheDocument();<br>    });<br>  });<br><br>  it(&#39;closes the modal when close button is clicked&#39;, () =&gt; {<br>    const closeButton = screen.getByRole(&#39;button&#39;, { name: &#39;&#39; }); // The X button has no text<br>    fireEvent.click(closeButton);<br>    expect(mockOnClose).toHaveBeenCalled();<br>  });<br>});</pre><p>Test nya agak sedikit panjang, tapi ini adalah sebuah contoh dari test frontend untuk sebuah menu yang menampilkan form pergantian password, jika dibandingkan dengan test Backend tentunya yang di test akan berbeda. Apa bedanya? test Backend biasanya akan mengetes fungsi yang kita buat apakah sudah benar, jika ada input a keluar b jika ada input x keluar y, dan sebagainya. Sedangkan untuk test frontend, ini lebih ke apakah tampilan yang ditampilkan sudah sesuai, apakah ada keberadaan dari suatu elemen di halaman, apakah element memiliki konfigurasi tertentu, jika ada button apakah button berhasil ditekan, jika ada error apakah menampilkan, dan sebagainya.</p><p>Contoh di sini</p><pre>it(&#39;closes the modal when close button is clicked&#39;, () =&gt; {<br>  const closeButton = screen.getByRole(&#39;button&#39;, { name: &#39;&#39; }); // The X button has no text<br>  fireEvent.click(closeButton);<br>  expect(mockOnClose).toHaveBeenCalled();<br>});</pre><p>ini adalah test untuk melihat apakah closeButton berhasil ditekan.</p><pre>it(&#39;enables submit button when form is valid&#39;, () =&gt; {<br>    const currentPasswordInput = screen.getByTestId(&#39;input-current-password&#39;);<br>    const newPasswordInput = screen.getByTestId(&#39;input-new-password&#39;);<br>    const confirmPasswordInput = screen.getByTestId(&#39;input-confirm-password&#39;);<br>    const submitButton = screen.getByTestId(&#39;button&#39;);<br>    <br>    // Fill in all fields with valid data<br>    fireEvent.change(currentPasswordInput, { target: { value: TEST_CURRENT_PASSWORD } });<br>    fireEvent.change(newPasswordInput, { target: { value: TEST_NEW_PASSWORD } });<br>    fireEvent.change(confirmPasswordInput, { target: { value: TEST_NEW_PASSWORD } });<br>    <br>    // Button should be enabled<br>    expect(submitButton).not.toBeDisabled();<br>  });</pre><p>submitButton tidak bisa ditekan jika semua field di form belum valid, oleh karena itu test ini menguji apakah jika form sudah valid, submit button sudah bisa ditekan apa belum.</p><p>Jadi kesimpulannya, perbedaan tes FE dan BE adalah apa yang diujinya, di frontend fokus ke halamannya, apakah button bisa ditekan jika form belum valid, apakah form sudah dimuat dengan benar, dll. Sedangkan di backend lebih ke fungsionalitas suatu method, apakah kita berhasil get data tanpa param, get data dengan param, apakah jika param salah bisa diambil datanya, dll.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae5d5f3a78e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Quality with SonarQube]]></title>
            <link>https://medium.com/@allusernameistaken21/software-quality-with-sonarqube-405b33419ba4?source=rss-a3b288abd16b------2</link>
            <guid isPermaLink="false">https://medium.com/p/405b33419ba4</guid>
            <category><![CDATA[code-coverage]]></category>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Fatih Raditya]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 07:12:07 GMT</pubDate>
            <atom:updated>2025-03-05T16:29:13.946Z</atom:updated>
            <content:encoded><![CDATA[<p>In the fast-paced world of software development, maintaining <strong>high code quality</strong> is just as important as delivering new features. Poorly written code can lead to <strong>bugs, security vulnerabilities, and technical debt</strong>, making maintenance costly and frustrating. This is where <strong>SonarQube</strong> comes into play — a powerful tool designed to <strong>automate code analysis</strong> (Static Analysis) and enforce best practices to ensure software quality.</p><h3>The Challenge: Ensuring Code Quality</h3><p>Writing code is easy. Writing <strong>clean, maintainable, and secure code</strong> — that’s the real challenge. Without proper quality checks, software projects can quickly become a tangled mess, leading to:<br>✔️ <strong>Bugs that are hard to detect</strong><br>✔️ <strong>Security vulnerabilities exposing sensitive data</strong><br>✔️ <strong>Unmaintainable code that slows development</strong></p><p>Developers need <strong>an automated system</strong> to <strong>analyze, monitor, and enforce quality standards</strong> — and that’s exactly what <strong>SonarQube</strong> provides.</p><h3>What is SonarQube?</h3><p><strong>SonarQube</strong> is an <strong>open-source, continuous inspection tool</strong> that helps developers and organizations maintain <strong>high code quality and security standards</strong>. It analyzes source code and detects issues in various categories, such as:<br>🔍 <strong>Code Smells</strong> — Poor coding practices that reduce maintainability<br>🔍 <strong>Bugs</strong> — Potential errors that may cause unexpected behavior<br>🔍 <strong>Security Vulnerabilities</strong> — Flaws that expose software to cyber threats<br>🔍 <strong>Code Duplication</strong> — Repeated blocks of code that increase complexity<br>🔍 <strong>Technical Debt</strong> — Areas that require refactoring for long-term maintainability</p><p>By integrating SonarQube into the development workflow, teams can <strong>identify problems early</strong> and <strong>enforce coding standards automatically</strong>.</p><h3>Why SonarQube Matters</h3><p>Using SonarQube is not just about <strong>finding problems</strong> — it’s about <strong>building a culture of clean coding</strong>. With <strong>real-time feedback, automated analysis, and actionable insights.</strong> For me personally, it helps me:<br>✅ <strong>Write better, more maintainable code</strong><br>✅ <strong>Prevent bugs and security vulnerabilities</strong></p><h3><strong>Now, how do we import our GitHub repositories into SonarQube?</strong></h3><p>SonarQube have explained on how to setup and import your Github App into it.</p><ul><li><a href="https://docs.sonarsource.com/sonarqube-server/10.6/devops-platform-integration/github-integration/setting-up-at-global-level/introduction/">Global GitHub integration setup &amp; SonarQube</a></li><li><a href="https://docs.sonarsource.com/sonarqube-server/10.6/devops-platform-integration/github-integration/importing-github-repositories/">Importing your GitHub repositories into SonarQube</a></li></ul><p>Now, after all that, we can check our push and pull request on GitHub if it passed SonarQube checks. This is an example of a Django Model that I made.</p><pre>from django.db import models<br>import uuid<br><br># Create your models here.<br>class User(models.Model):<br>    id = models.AutoField(primary_key=True)<br>    name = models.CharField(max_length=255)<br>    password = models.CharField(max_length=255)<br>    role = models.CharField(max_length=255)  # Sesuai dengan ERD<br>    email = models.EmailField(unique=True)<br><br>    def has_role(self, role_name):<br>        return self.role == role_name<br><br>    def account_exist(self, email):<br>        return User.objects.filter(email=email).exists()<br><br>    def update_password(self, email, new_password):<br>        user = User.objects.get(email=email)<br>        user.password = new_password<br>        user.save()<br><br>    def __str__(self):<br>        return self.name<br><br><br>class Role(models.Model):<br>    id = models.AutoField(primary_key=True)<br>    name = models.CharField(max_length=255, unique=True)<br><br>    def has_permission(self, perm_name):<br>        return self.permissions.filter(name=perm_name).exists()<br><br>    def __str__(self):<br>        return self.name<br><br><br>class Permission(models.Model):<br>    id = models.AutoField(primary_key=True)<br>    name = models.CharField(max_length=255, unique=True)<br>    description = models.TextField()<br><br>    def __str__(self):<br>        return self.name<br><br><br>class UserRole(models.Model):<br>    user = models.ForeignKey(User, on_delete=models.CASCADE)<br>    role = models.ForeignKey(Role, on_delete=models.CASCADE)<br><br>    class Meta:<br>        unique_together = (&quot;user&quot;, &quot;role&quot;)<br><br><br>class RolePermission(models.Model):<br>    role = models.ForeignKey(Role, on_delete=models.CASCADE)<br>    permission = models.ForeignKey(Permission, on_delete=models.CASCADE)<br><br>    class Meta:<br>        unique_together = (&quot;role&quot;, &quot;permission&quot;)<br><br><br>class HealthProtocol(models.Model):<br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    title = models.CharField(max_length=255)<br>    url = models.URLField()<br><br>    def __str__(self):<br>        return self.title<br><br><br>class Disease(models.Model):<br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    name = models.CharField(max_length=255)<br>    level_of_alertness = models.IntegerField()<br><br>    def get_disease_by_id(disease_id):<br>        return Disease.objects.filter(disease_id=disease_id).first()<br><br>    def get_disease_cases(self):<br>        return self.case_set.all()  # Mengambil semua kasus terkait penyakit ini<br><br>    def __str__(self):<br>        return self.name<br><br><br>class HealthProtocolDisease(models.Model):<br>    health_protocol = models.ForeignKey(HealthProtocol, on_delete=models.CASCADE)<br>    disease = models.ForeignKey(Disease, on_delete=models.CASCADE)<br><br>    class Meta:<br>        unique_together = (&quot;health_protocol&quot;, &quot;disease&quot;)<br><br><br>class Case(models.Model):<br>    STATUS_CHOICES = [<br>        (&quot;confirmed&quot;, &quot;Confirmed&quot;),<br>        (&quot;recovered&quot;, &quot;Recovered&quot;),<br>        (&quot;deceased&quot;, &quot;Deceased&quot;),<br>    ]<br><br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    gender = models.CharField(max_length=10)<br>    age = models.IntegerField()<br>    city = models.CharField(max_length=255)<br>    status = models.CharField(max_length=20, choices=STATUS_CHOICES)<br>    disease = models.ForeignKey(Disease, on_delete=models.CASCADE)<br><br>    def get_all_cases_locations():<br>        return Location.objects.filter(case__isnull=False)<br><br>    def __str__(self):<br>        return f&quot;Case {self.id} - {self.city}&quot;<br><br><br>class Location(models.Model):<br>    latitude = models.DecimalField(max_digits=8, decimal_places=6)<br>    longitude = models.DecimalField(max_digits=9, decimal_places=6)<br>    name = models.CharField(max_length=255, unique=True)<br>    case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name=&quot;locations&quot;)<br><br>    def get_location_by_name(name):<br>        return Location.objects.filter(name=name).first()<br><br>    def get_all_locations():<br>        return Location.objects.all()<br><br>    def __str__(self):<br>        return self.name<br><br><br>class News(models.Model):<br>    portal = models.CharField(max_length=255)<br>    news_type = models.CharField(max_length=100)<br>    content = models.TextField()<br>    url = models.URLField()<br>    author = models.CharField(max_length=255)<br>    title = models.CharField(max_length=255)<br>    release_date = models.DateTimeField()<br><br>    def get_all_sumber_berita_nasional_detail():<br>        return News.objects.filter(news_type=&quot;Nasional&quot;)<br><br>    def get_all_sumber_berita_lokal_detail():<br>        return News.objects.filter(news_type=&quot;Lokal&quot;)<br><br>    def get_all_sumber_berita_kesehatan_detail():<br>        return News.objects.filter(news_type=&quot;Kesehatan&quot;)<br><br>    def __str__(self):<br>        return self.title</pre><p>Now when we push it, SonarQube will check it. As shown in the picture below, the checks failed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55aLcMREa8o6vyweGASQzQ.png" /><figcaption>Code did not pass SonarQube’s Quality Gate</figcaption></figure><p>And we can see the details about what makes it fail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGr0MlpdF6E9Iwkr9gYPGg.png" /><figcaption>SonarQube dashboard information</figcaption></figure><p>Now we just need to fix it according to the checks that failed to pass.</p><pre>from django.db import models<br>import uuid<br>from django.contrib.auth.hashers import make_password<br><br>class User(models.Model):<br>    id = models.AutoField(primary_key=True)<br>    name = models.CharField(max_length=255)<br>    password = models.CharField(max_length=255)<br>    role = models.CharField(max_length=255)<br>    email = models.EmailField(unique=True)<br><br>    def has_role(self, role_name):<br>        return self.role == role_name<br><br>    def update_password(self, new_password):<br>        self.password = make_password(new_password)<br>        self.save()<br><br>    def __str__(self):<br>        return self.name<br><br>class Role(models.Model):<br>    id = models.AutoField(primary_key=True)<br>    name = models.CharField(max_length=255, unique=True)<br><br>    def __str__(self):<br>        return self.name<br><br>class Permission(models.Model):<br>    id = models.AutoField(primary_key=True)<br>    name = models.CharField(max_length=255, unique=True)<br>    description = models.TextField()<br><br>    def __str__(self):<br>        return self.name<br><br>class UserRole(models.Model):<br>    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name=&quot;roles&quot;)<br>    role = models.ForeignKey(Role, on_delete=models.CASCADE, related_name=&quot;users&quot;)<br><br>    class Meta:<br>        unique_together = (&quot;user&quot;, &quot;role&quot;)<br><br>class RolePermission(models.Model):<br>    role = models.ForeignKey(Role, on_delete=models.CASCADE, related_name=&quot;permissions&quot;)<br>    permission = models.ForeignKey(Permission, on_delete=models.CASCADE, related_name=&quot;roles&quot;)<br><br>    class Meta:<br>        unique_together = (&quot;role&quot;, &quot;permission&quot;)<br><br>class HealthProtocol(models.Model):<br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    title = models.CharField(max_length=255)<br>    url = models.URLField()<br><br>    def __str__(self):<br>        return self.title<br><br>class Disease(models.Model):<br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    name = models.CharField(max_length=255)<br>    level_of_alertness = models.IntegerField()<br><br>    @staticmethod<br>    def get_disease_by_id(disease_id):<br>        return Disease.objects.filter(id=disease_id).first()<br>    <br>    @staticmethod<br>    def get_disease_cases(self):<br>        return self.cases.all()<br>    <br>    def __str__(self):<br>        return self.name<br><br>class HealthProtocolDisease(models.Model):<br>    health_protocol = models.ForeignKey(HealthProtocol, on_delete=models.CASCADE, related_name=&quot;diseases&quot;)<br>    disease = models.ForeignKey(Disease, on_delete=models.CASCADE, related_name=&quot;protocols&quot;)<br><br>    class Meta:<br>        unique_together = (&quot;health_protocol&quot;, &quot;disease&quot;)<br><br>class Location(models.Model):<br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    latitude = models.DecimalField(max_digits=8, decimal_places=6)<br>    longitude = models.DecimalField(max_digits=9, decimal_places=6)<br>    name = models.CharField(max_length=255, unique=True)<br><br>    @staticmethod<br>    def get_location_by_name(name):<br>        return Location.objects.filter(name=name).first()<br><br>    @staticmethod<br>    def get_all_locations():<br>        return Location.objects.all()<br><br>    def __str__(self):<br>        return self.name<br><br>    def __str__(self):<br>        return self.name<br><br>class Case(models.Model):<br>    STATUS_CHOICES = [<br>        (&quot;confirmed&quot;, &quot;Confirmed&quot;),<br>        (&quot;recovered&quot;, &quot;Recovered&quot;),<br>        (&quot;deceased&quot;, &quot;Deceased&quot;),<br>    ]<br><br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    gender = models.CharField(max_length=10)<br>    age = models.IntegerField()<br>    city = models.CharField(max_length=255)<br>    status = models.CharField(max_length=20, choices=STATUS_CHOICES)<br>    disease = models.ForeignKey(Disease, on_delete=models.CASCADE, related_name=&quot;cases&quot;)<br>    location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name=&quot;cases&quot;)<br><br>    def get_all_locations(self):<br>        return Location.objects.filter(cases__disease=self).distinct()<br>    <br>    def __str__(self):<br>        return f&quot;Case {self.id} - {self.city}&quot;<br><br>class News(models.Model):<br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    portal = models.CharField(max_length=255)<br>    title = models.CharField(max_length=255)<br>    type = models.CharField(max_length=255)<br>    content = models.TextField()<br>    url = models.URLField()<br>    author = models.CharField(max_length=255)<br>    date_published = models.DateTimeField(auto_now_add=True)<br>    case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name=&quot;news&quot;)<br><br>    def __str__(self):<br>        return self.title</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4xI-K_aGmGgax5kN83sxQ.png" /><figcaption>All checks passed</figcaption></figure><p>And Tada!, all the checks have passed. SonarQube can also be used for checking code coverage, but since this is a python model, I’ll just give a picture for code coverage in frontend with NextJS with Jest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*qgQyecawR408Af3lscrF6w.jpeg" /></figure><h3>Conclusion</h3><p>Software quality is <strong>not optional</strong> — it’s a necessity. SonarQube acts as a <strong>guardian of code quality</strong>, ensuring that applications are <strong>secure, maintainable, and efficient</strong>. Whether you’re an individual developer or part of a large enterprise, integrating SonarQube into your workflow is a game-changer for writing <strong>clean, reliable, and high-quality software</strong>.</p><p>💡 <strong>So, the next time you push code, ask yourself — will it pass the SonarQube test?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=405b33419ba4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principle in NextJS with Amcharts]]></title>
            <link>https://medium.com/@allusernameistaken21/solid-principle-in-nextjs-with-amcharts-aa5402fae6e9?source=rss-a3b288abd16b------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa5402fae6e9</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Fatih Raditya]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 06:27:10 GMT</pubDate>
            <atom:updated>2025-03-05T16:49:57.194Z</atom:updated>
            <content:encoded><![CDATA[<p>Programming is an ever-evolving discipline, where code efficiency, maintainability, and scalability are crucial. As developers, we often face challenges — spaghetti code, tightly coupled dependencies, and brittle architectures that break at the slightest modification. This is where software design principles come in, guiding us to write clean, robust, and scalable code.</p><p>One such set of principles stands out in the world of object-oriented programming: <strong>SOLID</strong>.</p><p>But what exactly is <strong>SOLID</strong>?</p><p>SOLID is an acronym representing five key principles introduced by <strong>Robert C. Martin (Uncle Bob)</strong>. These principles serve as a foundation for building software that is not only functional but also flexible and maintainable. Each letter in SOLID stands for a distinct design principle:</p><ol><li><strong>S — Single Responsibility Principle (SRP)</strong><br><em>A class should have only one reason to change.</em><br>This means that every class should focus on a single functionality. Mixing multiple responsibilities in one class can lead to complex and hard-to-maintain code.</li><li><strong>O — Open/Closed Principle (OCP)</strong><br><em>Software entities should be open for extension but closed for modification.</em><br>This encourages designing systems where adding new features doesn’t require modifying existing code, reducing the risk of introducing bugs.</li><li><strong>L — Liskov Substitution Principle (LSP)</strong><br><em>Subtypes must be substitutable for their base types.</em><br>In simpler terms, derived classes should be able to replace their base classes without affecting the correctness of the program.</li><li><strong>I — Interface Segregation Principle (ISP)</strong><br><em>Clients should not be forced to depend on interfaces they do not use.</em><br>Instead of having large, monolithic interfaces, it’s better to split them into smaller, more specific ones to avoid unnecessary dependencies.</li><li><strong>D — Dependency Inversion Principle (DIP)</strong><br><em>High-level modules should not depend on low-level modules. Both should depend on abstractions.</em><br>This principle promotes loose coupling by ensuring that classes depend on abstract concepts rather than concrete implementations.</li></ol><p>By following SOLID principles, developers can create systems that are <strong>scalable, maintainable, and testable</strong>. They help reduce technical debt, making the code easier to refactor and extend over time.</p><p>Whether you’re building a small application or a large enterprise system, embracing SOLID principles is a step toward writing better, more sustainable code.</p><p><strong>Conclusion</strong><br>Programming is not just about getting things to work; it’s about writing code that lasts. SOLID principles offer a roadmap to achieving clean architecture, making software development a more structured and enjoyable experience.</p><p>Now, as you write your next piece of code, ask yourself: <strong>Is it SOLID?</strong></p><p>Here is an example</p><pre>&quot;use client&quot;;<br><br>import React, { useEffect, useRef } from &quot;react&quot;;<br>import * as am5 from &quot;@amcharts/amcharts5&quot;;<br>import * as am5map from &quot;@amcharts/amcharts5/map&quot;;<br>import am5geodata_indonesiaLow from &quot;@amcharts/amcharts5-geodata/indonesiaLow&quot;;<br>import am5themes_Animated from &quot;@amcharts/amcharts5/themes/Animated&quot;;<br><br>interface IndonesiaMapProps {<br>  readonly onError: (message: string) =&gt; void; // Callback untuk menangani error<br>}<br><br>export default function IndonesiaMap({ onError }: IndonesiaMapProps) {<br>  const chartRef = useRef&lt;am5.Root | null&gt;(null);<br><br>  useEffect(() =&gt; {<br><br>    try {<br>      if (!chartRef.current) {<br>        const root = am5.Root.new(&quot;chartdiv&quot;);<br>        chartRef.current = root;<br>        root.setThemes([am5themes_Animated.new(root)]);<br><br>        const chart = root.container.children.push(<br>          am5map.MapChart.new(root, {<br>            panX: &quot;translateX&quot;,<br>            panY: &quot;translateY&quot;,<br>            projection: am5map.geoMercator(),<br>            homeGeoPoint: { longitude: 118, latitude: -2 },<br>          })<br>        );<br><br>        if (!chart) throw new Error(&quot;Gagal memuat peta. Silakan coba lagi.&quot;);<br><br>        const polygonSeries = chart.series.push(<br>          am5map.MapPolygonSeries.new(root, {<br>            geoJSON: am5geodata_indonesiaLow,<br>            exclude: [&quot;MY-12&quot;, &quot;MY-13&quot;, &quot;BN&quot;, &quot;TL&quot;],<br>          })<br>        );<br><br>        polygonSeries.mapPolygons.template.setAll({<br>          tooltipText: &quot;{name}&quot;,<br>          toggleKey: &quot;active&quot;,<br>          interactive: true,<br>          fill: am5.color(0xdddddd),<br>          strokeWidth: 0.5,<br>          stroke: am5.color(0x999999),<br>        });<br><br>        polygonSeries.mapPolygons.template.states.create(&quot;hover&quot;, {<br>          fill: am5.color(0xbbbbbb),<br>        });<br><br>        chart.set(&quot;zoomControl&quot;, am5map.ZoomControl.new(root, {}));<br>        chart.chartContainer.get(&quot;background&quot;).events.on(&quot;click&quot;, () =&gt; {<br>          chart.goHome();<br>        });<br><br>        chart.appear(1000, 100);<br>      }<br>    } catch (err) {<br>      onError(&quot;Gagal memuat peta. Silakan coba lagi.&quot;);<br>    }<br>  }, []);<br><br>  return &lt;div id=&quot;chartdiv&quot; data-testid=&quot;chartdiv&quot; style={{ width: &quot;100%&quot;, height: &quot;500px&quot; }}&gt;&lt;/div&gt;;<br>}</pre><p>The code above only applies some of SOLID principles:</p><h4>1. Single Responsibility Principle (SRP) — ✅ Followed</h4><p>💡 <em>“A class should have only one reason to change.”</em></p><p><strong>IndonesiaMap</strong> component adheres to SRP because it focuses on a single responsibility: <strong>rendering an interactive map of Indonesia using amCharts 5</strong>. The logic is well-encapsulated within the component, and it does not handle unrelated concerns like data fetching, user authentication, or complex business logic.</p><p>The only <strong>two responsibilities</strong> that are present are:</p><ul><li><strong>Rendering the map</strong> using amCharts</li><li><strong>Error handling</strong> through the onError callback</li></ul><p>Since error handling is a minor side concern and does not interfere with the primary function of rendering the map, it still maintains a <strong>single, primary responsibility</strong>.</p><h4>2. Interface Segregation Principle (ISP) — ✅ Followed</h4><p>💡 <em>“Clients should not be forced to depend on interfaces they do not use.”</em></p><p>In your component, the <strong>only prop</strong> it receives is onError: (message: string) =&gt; void. This follows ISP because:</p><ul><li>The component only expects the <strong>necessary</strong> data (an error callback).</li><li>It doesn’t rely on a large, generic interface with unnecessary props.</li><li>It does <strong>not</strong> force consumers of the component to provide unused or irrelevant data.</li></ul><p>If IndonesiaMap had a bloated interface with unnecessary props (e.g., onLoad, themeConfig, customStyles, regionFilter, etc.), it would <strong>violate ISP</strong>. But here, the interface is <strong>clean and focused</strong>, making it compliant.</p><p><strong>What about the other three?</strong></p><ul><li>❌OCP: If we wanted to extend functionality (e.g., adding custom styles, markers, or new map data), we might have to modify the component itself rather than extending it via abstraction. A more OCP-friendly approach would involve dependency injection for map configuration.</li><li>❌LSP: There are no subclass relationships here, so LSP is irrelevant. If IndonesiaMap was a subclass of a more general MapComponent, we&#39;d check if it still worked when swapped.</li><li>❌DIP: The component directly depends on amCharts (am5 library). A more SOLID approach would be to inject a MapService or an abstraction instead of being tightly coupled to amCharts.</li></ul><p>Now we shall refactor the code to make sure it fulfills the rest of the SOLID principle</p><pre>&quot;use client&quot;;<br><br>import React, { useEffect, useRef } from &quot;react&quot;;<br>import * as am5 from &quot;@amcharts/amcharts5&quot;;<br>import * as am5map from &quot;@amcharts/amcharts5/map&quot;;<br>import am5geodata_indonesiaLow from &quot;@amcharts/amcharts5-geodata/indonesiaLow&quot;;<br>import am5themes_Animated from &quot;@amcharts/amcharts5/themes/Animated&quot;;<br><br>interface IndonesiaMapProps {<br>  readonly onError: (message: string) =&gt; void;<br>}<br><br>interface MapProvider {<br>  initialize(containerId: string): void;<br>}<br><br>class AmChartsMapProvider implements MapProvider {<br>  private root!: am5.Root;<br>  private chart!: am5map.MapChart;<br>  private onError: (message: string) =&gt; void;<br><br>  constructor(onError: (message: string) =&gt; void) {<br>    this.onError = onError;<br>  }<br><br>  initialize(containerId: string): void {<br>    try {<br>      this.root = am5.Root.new(containerId);<br>      this.root.setThemes([am5themes_Animated.new(this.root)]);<br>      this.chart = this.createMapChart();<br>      this.configureSeries();<br>      this.addInteractivity();<br>    } catch (err) {<br>      this.onError(&quot;Gagal memuat peta. Silakan coba lagi.&quot;);<br>    }<br>  }<br><br>  private createMapChart(): am5map.MapChart {<br>    return this.root.container.children.push(<br>      am5map.MapChart.new(this.root, {<br>        panX: &quot;translateX&quot;,<br>        panY: &quot;translateY&quot;,<br>        projection: am5map.geoMercator(),<br>        homeGeoPoint: { longitude: 118, latitude: -2 },<br>      })<br>    );<br>  }<br><br>  private configureSeries(): void {<br>    const polygonSeries = this.chart.series.push(<br>      am5map.MapPolygonSeries.new(this.root, {<br>        geoJSON: am5geodata_indonesiaLow,<br>        exclude: [&quot;MY-12&quot;, &quot;MY-13&quot;, &quot;BN&quot;, &quot;TL&quot;],<br>      })<br>    );<br><br>    polygonSeries.mapPolygons.template.setAll({<br>      tooltipText: &quot;{name}&quot;,<br>      toggleKey: &quot;active&quot;,<br>      interactive: true,<br>      fill: am5.color(0xdddddd),<br>      strokeWidth: 0.5,<br>      stroke: am5.color(0x999999),<br>    });<br><br>    polygonSeries.mapPolygons.template.states.create(&quot;hover&quot;, {<br>      fill: am5.color(0xbbbbbb),<br>    });<br>  }<br><br>  private addInteractivity(): void {<br>    this.chart.set(&quot;zoomControl&quot;, am5map.ZoomControl.new(this.root, {}));<br>    this.chart.chartContainer.get(&quot;background&quot;).events.on(&quot;click&quot;, () =&gt; {<br>      this.chart.goHome();<br>    });<br>    this.chart.appear(1000, 100);<br>  }<br>}<br><br>export default function IndonesiaMap({ onError }: IndonesiaMapProps) {<br>  const chartRef = useRef&lt;MapProvider | null&gt;(null);<br><br>  useEffect(() =&gt; {<br>    if (!chartRef.current) {<br>      chartRef.current = new AmChartsMapProvider(onError);<br>      chartRef.current.initialize(&quot;chartdiv&quot;);<br>    }<br>  }, [onError]);<br><br>  return &lt;div id=&quot;chartdiv&quot; data-testid=&quot;chartdiv&quot; style={{ width: &quot;100%&quot;, height: &quot;500px&quot; }}&gt;&lt;/div&gt;;<br>}</pre><h3><strong>Why Do We Need To Make It Object Oriented (OO)?</strong></h3><p>Wait, since NextJS is a react framework which is component-based, hooks, etc, we don’t really need to do OO right?</p><p>Well, it depends, if your code is something that is needed to be constantly updated, add features, refactor, etc, making your code OO can give several benefits such as:</p><ul><li>Modularity &amp; Reusability<br>With classes, it’s easier to reuse and extendable</li><li>Easier Maintenance<br>If there are changes in the logic of the map, we just need to change the <strong>AmChartsMapProvider </strong>without the need to touch <strong>IndonesiaMap </strong>.</li></ul><p>But you need to note that are cons to using OO in NextJS:</p><ul><li>Code is overstructured for simple cases</li><li>Complexity</li><li>Counts as an overhead if only used once</li></ul><p>Now back to SOLID, why is this piece of code SOLID?</p><h4>1. Single Responsibility Principle (SRP) — ✅ Followed</h4><p>💡 <em>“A class should have only one reason to change.”</em></p><ul><li><strong>IndonesiaMap Component: </strong>Responsible for rendering the map container and initializing the map provider.</li><li><strong>AmChartsMapProvider Class:</strong>Encapsulates the logic for initializing and configuring the amCharts map.</li></ul><p>The separation ensures that UI rendering (IndonesiaMap) and map logic (AmChartsMapProvider) are <strong>independent</strong>, making the code <strong>more modular</strong> and <strong>easier to maintain</strong>.</p><h4>2. Open/Closed Principle (OCP) — ✅ Followed</h4><p>💡 <em>“Software entities should be open for extension but closed for modification.”</em></p><ul><li>If you want to <strong>extend</strong> the map (e.g., use a different mapping library or add features), you can <strong>create a new class implementing </strong><strong>MapProvider</strong> without modifying existing code.</li><li>The IndonesiaMap component <strong>does not depend on amCharts directly</strong>—it depends on the MapProvider <strong>interface</strong>, making it <strong>open for extension</strong>.</li></ul><p>✅ <strong>Compliant because new map providers can be added without modifying </strong><strong>IndonesiaMap</strong>.</p><h4>3. Liskov Substitution Principle (LSP) — ✅ Followed</h4><p>💡 <em>“Subtypes must be substitutable for their base types.”</em></p><ul><li>AmChartsMapProvider implements MapProvider, meaning any <strong>other implementation</strong> (e.g., LeafletMapProvider, GoogleMapsProvider) could be used <strong>without breaking</strong> IndonesiaMap.</li><li>IndonesiaMap depends on MapProvider, so we can <strong>swap </strong><strong>AmChartsMapProvider with another provider</strong> easily.</li></ul><p>✅ <strong>Compliant because </strong><strong>IndonesiaMap doesn&#39;t care which map provider is used, as long as it implements </strong><strong>MapProvider.</strong></p><h4>4. Interface Segregation Principle (ISP) — ✅ Followed</h4><p>💡 <em>“Clients should not be forced to depend on interfaces they do not use.”</em></p><p>Since Interface that is known in SOLID and the interface in NextJS is different, the ISP here is mostly applied in the class, like SRP.</p><ul><li><strong>createMapChart()</strong> → Only handles charts.</li><li><strong>configureSeries()</strong> → Only handles map configuration.</li><li><strong>addInteractivity()</strong> → Only handles interactivity with users.</li></ul><p>✅ <strong>Compliant because the interface is minimal and focused.</strong></p><h4>5. Dependency Inversion Principle (DIP) — ✅ Followed</h4><p>💡 <em>“High-level modules should not depend on low-level modules. Both should depend on abstractions.”</em></p><ul><li>IndonesiaMap <strong>does not directly depend on </strong><strong>AmCharts</strong>.</li><li>Instead, it depends on MapProvider (<strong>an abstraction</strong>).</li><li>AmChartsMapProvider implements MapProvider, following <strong>dependency injection</strong>.</li></ul><p>✅ <strong>Compliant because </strong><strong>IndonesiaMap does not directly depend on amCharts, making it easier to replace.</strong></p><p>So now, we have fully applied the SOLID principle to this IndonesiaMap component for NextJS with amcharts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa5402fae6e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Team Project Development?]]></title>
            <link>https://medium.com/@allusernameistaken21/managing-backlogs-effectively-with-notion-0c0a75c6c9db?source=rss-a3b288abd16b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c0a75c6c9db</guid>
            <category><![CDATA[sprint-planning]]></category>
            <category><![CDATA[backlog-management]]></category>
            <category><![CDATA[notion]]></category>
            <category><![CDATA[scrum]]></category>
            <dc:creator><![CDATA[Fatih Raditya]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 08:22:16 GMT</pubDate>
            <atom:updated>2025-04-10T04:09:34.029Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Bekerja sama dalam suatu tim dapat menjadi membingungkan bagi beberapa orang karena tidak tahu bagaimana pembagiant tugas yang efektif dan semuanya mendapatkan porsi kerja yang sama. Karena jika nanti pembagian task tidak sesuai, bisa jadi ada pekerjaan yang menjadi dependent untuk pekerjaan orang lain dan workflow tidak lancar. Kita dapat mengatasi hal tersebut dengan merencanakan hal menggunakan notion.</p><h3>Why Use Notion for Backlog Management?</h3><p>Notion bisa membuat backlogs dan breakdown backlogs yang ada menjadi task-task yang lebih kecil</p><h3>Setting Up a Backlog in Notion</h3><p>Di notion akan ada pilihan untuk membuat project dan tasks, yang nantinya dapat diisi seperti berikut</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lEZKIRkWtFpzF4_c14K_Zw.png" /><figcaption>Setting Up a Backlog in Notion</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjOkaAf9L_KU8c_mSoz2SQ.png" /><figcaption>Tasks are linked to backlog</figcaption></figure><h3>How to manage these backlogs and tasks?</h3><p>Salah satu cara paling efektif untuk menyelesaikan tasks yang ada adalah dengan mengambil satu task dalam satu waktu, setelah menyelesaikan task yang diambil barulah ambil task lain yang sekiranya tidak memiliki dependensi ke task lain atau berhubungan dengan task kamu sebelumnya.</p><p>Dengan begitu, ini akan mengurangi kemungkinan adanya tasks yang dependent satu sama lain sehingga tidak bingung dalam mengerjakan dan memastikan bahwa developers di tim dapat bobot yang sama.</p><h3><strong>How do I know what to do next?</strong></h3><p>Yah, membagi task tidak akan menjamin 100% bahwa tidak akan ada dependensi yang terjadi, jika begitu, bagaimana jika kita mengerjakan task lanjutan dari rekan kita? bagaimana cara kita tahu apakah ada yang perlu ditambahkan atau di edit? Di situlah version control seperti GitHub menjadi berguna.</p><h3><strong>Breakdown branches for each features</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*bbsAUVLU4s0hjPf4n6EwMg.png" /><figcaption>branch examples</figcaption></figure><p>Pembagian branch seperti ini dapat membantu menyelesaikan fitur-fitur yang sudah dibagi di task yang diberikan untuk tiap anggota, dimana setiap anggota akan mengerjakan fitur di branch masing-masing fitur dan nanti semua fitur tadi di merge ke backlog utamanya.</p><h3><strong>Giving clear commit messages</strong></h3><p>Tim harus sepakat untuk memberikan commit message yang jelas sehingga untuk setiap commit dan push, anggota tim lainnya tahu apa yang sedang dikerjakan. Contohnya seperti berikut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mI359Wb3zWXWXfnV1z6_0w.png" /><figcaption>GitHub commits example</figcaption></figure><p>Dapat dilihat bahwa diberikan label yang menandakan pekerjaan yang dilakukan, RED untuk pembuatan tests, GREEN untuk implementasi fitur agar pass test nya, REFACTOR untuk perubahan/restrukturisasi kode, dan OPTIMIZATION untuk optimasi kode. Dengan tag seperti ini serta message yang diberikan setelah tag juga membant usudah dapat membantu mendapatkan gambaran apa yang dikerjakan, message yang diberikan setelah tag juga membantu memberikan gambaran lebih jauh lagi.</p><h3><strong>Pull Requests and Merging</strong></h3><p>Seperti disebutkan di atas, kita akan memisahkan fitur menjadi branch-branch yang lebih kecil dan akan menyatukannya di branch backlog nya, bagaimana supaya kita tahu bahwa fitur yang dibuat sudah sesuai tanpa perlu mengecek seluruh codebase, kita dapat membuat persetujuan kelompok untuk format dari pull request, misalnya dengan memberikan detail pekerjaan kita di Pull Request message, contohnya seperti berikut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*REQmRbH5Oplwr_VuFz79QA.png" /><figcaption>PR summary</figcaption></figure><p>Dengan PR seperti ini, anggota tim dapat mengetahui pekerjaan apa saja yang telah kita lakukan dan bagaimana cara menjalankannya. Lebih lanjut lagi, anggota tim lain juga dapat memberikan saran dan komentar terhadap pekerjaan kita:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*DdLw0WqR6ruLx_wsLQhHRg.png" /><figcaption>PR feedback</figcaption></figure><p>Nah, di contoh di atas, anggota tim saya menyarankan fitur untuk di optimize dimana repository yang awalnya menggunakan dua query dapat menjadi satu query saja.</p><h3>Conclusion</h3><p>Kita sudah berhasil memanfaatkan notion dan github PR sebagai tools untuk kerja dalam sebuah tim. Di sini tim saya sudah membuat kesepakatan bahwa task hanya diambil satu dan dapat mengambil task baru jika dan hanya jika task sebelumnya selesai dan anggota tim lain memberikan persetujuan. Selain itu, tim saya juga sudah menerapkan kesepakatan terkait commit message dan juga Pull Request summary yang dapat membantu memberikan gambaran besar tentang apa yang dikerjakan anggota lainnya, dan dengan disiplin seperti ini tim kami menjadi lebih aktif dan dapat memberikan feedback kepada anggota lain dengan lebih mudah karena sudah dapat gambaran dari apa yang dikerjakan. Kami juga belum mengalami issue setelah menyepakati workflow seperti ini.</p><p>Kamu dapat mengubah kesepakatan bersama tentang bagaimana cara menggunakan tools-tools tadi untuk workflow yang sesuai dengan tim kamu.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c0a75c6c9db" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>