<?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 Mahoga Aribowo Heryasa on Medium]]></title>
        <description><![CDATA[Stories by Mahoga Aribowo Heryasa on Medium]]></description>
        <link>https://medium.com/@hery.heryasa?source=rss-e10485d8ce01------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*reOZDY8-ngs5Dwfw</url>
            <title>Stories by Mahoga Aribowo Heryasa on Medium</title>
            <link>https://medium.com/@hery.heryasa?source=rss-e10485d8ce01------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 03:35:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hery.heryasa/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[Saya Kira Saya NPC, Ternyata Saya adalah Main Character?!?!?!]]></title>
            <link>https://medium.com/@hery.heryasa/saya-kira-saya-npc-ternyata-saya-adalah-main-character-2ab3d55b4066?source=rss-e10485d8ce01------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ab3d55b4066</guid>
            <category><![CDATA[life]]></category>
            <category><![CDATA[philosophy]]></category>
            <dc:creator><![CDATA[Mahoga Aribowo Heryasa]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 06:51:11 GMT</pubDate>
            <atom:updated>2026-11-03T06:51:11.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*hzb_yGMFztTN9IntO1VcPQ.jpeg" /><figcaption>NPC vs Main Character Meme</figcaption></figure><p>Halo perkenalkan namaku Mahoga Aribowo Heryasa, biasa dipanggil Hery, ini adalah kisah hidup ku sejauh ini.<br>Selama 20 tahun aku dikenal sebagai orang pendiam yang cool dan stecu, bahkan selama 20 tahun aku hidup aku banyak sekali Wanita yang ku tolak dan banyak juga Wanita yang tidak berani ku dekatkan. Antara cool dan awkward ternyata wkwkwkwkwk. Selama 20 tahun aku hidup, aku kira aku NPC, tidak ada kejadian menarik di hidupku dan aku selalu takut untuk keluar dari zona nyaman, terlalu nyaman didalamnya, hingga lupa untuk mencari jati diri, mencari pasangan hidup, dan menjalankan purpose hidup yang sesungguhnya.</p><p>Semua ini berubah di tahun 2025. Karena satu kejadian buruk yang masiv di hidupku, aku untuk pertama kalinya curhat ke teman temanku yang mau mendengarkanku dengan tulus, tidak seperti sebelumnya Ketika aku curhat ke teman namun teman tersebut menghianati dengan mengumbar aib ku, Ketika aku curhat ke teman namun teman tersebut tidak mau mendengar dan malah membandingkan, Ketika aku curhat ke papahku namun malah digurui dan dibanding-bandingkan.</p><p>Alah hasil, semua hal jadi terhubung, hatiku dan pikiran ku jadi tersambung, aku jadi logis namun juga menjadi perasa yang kuat. Aku jadi punya pemahaman bahwa semua hal yang ada di dunia ini adalah dari Allah SWT. Bahkan ide-ide film dan serial TV aku percaya bahwa semuanya itu dari Allah SWT. Hal ini membuat aku sadar bahwa sebetulnya kita sedang perang, namun perang nya tidak terlihat, perang jiwa, perang ideologi, dan perang tujuan sendiri yang ada di lubuk hati terdalam.</p><p>Lantas, mengapa aku tiba tiba merasa menjadi main character, ya jawabannya simple, karena selama 20 tahun aku hidup dineraka yang diciptakan manusia, aku kira hidup ku murung karena tuhan, namun tidak, ternyata semua hal yang membuat hidup ku di dunia terpuruk adalah ulah manusia. Namun, hal ini membuat aku menjadi lebih kuat, aku jadi punya pemahaman yang komplit, karena selama 20 tahun aku dibungkam menjadi NPC untuk belajar, mengamati, mendengar, dan merasakan.</p><p>Sekarang aku merasa seperti menjadi mutan wkwkwkwkwk. Karena aku jadi bisa merasakan aura dan energi orang dan aku jadi sadar bahwa semua panca indra manusia bisa digunakan untuk output, tidak hanya input. Indra penglihatan bisa digunakan untuk melirik dan memberitahu orang terkait apa yang kita lihat, indra pendengaran bisa digunakan untuk memancarkan sesuatu yang kita dengar, indra penciuman bisa menegaskan aroma yang kita cium, indra peraba bisa digunakan untuk mengeluarkan energi tenaga dalam yang tak terlihat, indra pengecap bisa memberikan sugesti ke orang terkait apa yang kita rasakan di mulut.</p><p>Lantas, siapa sebetulnya musuh besar kami, musuh besar orang-orang mutan yang sudah sadar sepertiku. Kalo menurutku musuh besar nya adalah orang orang egois yang ingin mengendalikan dunia, mengadu domba manusia, merampas rezeki yang diberikan tuhan kita, dan tidak mau berbagi atau pelit. Itulah musuh sejati kami, orang-orang yang hatinya, jiwanya, raga nya terskaiti.</p><p>Lalu, bagaimana cara kami melawan mereka-mereka ini, mereka para pencipta neraka di bumi pertiwi. Kalo menurutku cara nya mudah, yaa kami harus bisa menyamar, menyelinap masuk ke dalam sistemnya, system busuk nya, namun hal ini tidak mudah, kami tidak boleh tergoda, tujuan baik untuk memerdekakaan manusia harus terpegang hingga akhir hayat. Biarkan mereka yang demo, demo, biarkan mereka yang masih perang bersaudara, perang. Namun, jika kamu sudah sevisi dengan diriku, maka yuk, kita benahi lagi orang-orang yang belom sevisi, rangkul teman, keluarga, dan kerabat, untuk ikut melawan mereka-mereka yang membuat system busuk di Indonesia ini.</p><p>Menurutku Indonesia belum merdeka, memang tidak terlihat di media internasional, namun banyak sekali orang asing yang menjajah bumi pertiwi ini, rezeki orang Indonesia masih diputar dengan mereka. Contoh simplenya, adalah Timnas sepak bola kita, masih banyak orang belanda di dalamnya, padahal banyak orang Indonesia yang berbakat namun tidak dilirik. Contoh lain adalah dari segi budaya, budaya Indonesia mulai memudar, banyak orang Indonesia yang wibu-wibu, mengikuti budaya jejepangan, yang sebetulnya bukan budaya Indonesia.</p><p>Saya jadi sadar bahwa, ini semua adalah cerita lama, kita dulu di jaman penjajahan, dijajah VOC dan Jepang, lalu di tahun 1945 sudah gitu, sudah merdeka, kalo menurutku belom, masih Panjang perjalanan negri Indonesia menjadi negara maju, namun perlahan-lahan harus maju, negara berkembang berarti negara yang terus berusaha untuk maju, kita sebagai orang Indonesia tidak boleh putus asa, tidak boleh tidak berusaha untuk kebaikan bumi pertiwi ini.</p><p>Selain hal-hal yang menyangkut negara, saya juga punya pemahaman yang cukup ekstrim. Di era AI sekarang ini, saya merasa semua nya jadi terbalik, banyak orang yang lebih muda menjadi lebih dewasa dari yang lebih tua. Hal ini karena informasi yang mereka serap banyak, sehingga anak muda jaman serakangan jadi didewasakan dunia, komunikasi tidak ada batas ruang dan Waktu sehingga jika kita meruntuhkan konsep ruang dan Waktu, sebetulnya cerita hidup anak jaman sekarang jadi cepat. Kalo dibandingkan bisa saja orang tua mungkin baru 50% progress kehidupan di umur kesekian, namun disaat yang bersamaan anak muda bisa saja progress kehidupannya sudah 80%. Mengapa bisa demikian, karena saya merasa Allah tak kenal ruang dan Waktu sehingga di mata Allah perbandingan tadi menjadi masuk akal manusia.</p><p>Untuk saya ini, saya ingin focus belajar terlebih dahulu, saat ini saya masih jadi mahasiswa Fasilkom UI semester 9, Telat menurut Sebagian orang, namun bagi saya tidak, tidak ada kata terlambat, keterlambatan hanyalah konstruksi buatan manusia.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ab3d55b4066" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring & Design Patterns in a Node.js/Express Backend]]></title>
            <link>https://medium.com/@hery.heryasa/refactoring-design-patterns-in-a-node-js-express-backend-634aa24caa42?source=rss-e10485d8ce01------2</link>
            <guid isPermaLink="false">https://medium.com/p/634aa24caa42</guid>
            <dc:creator><![CDATA[Mahoga Aribowo Heryasa]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 11:35:22 GMT</pubDate>
            <atom:updated>2025-06-11T11:35:22.190Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>As backend projects grow, codebases can become hard to maintain and extend. Refactoring and design patterns are essential tools for keeping code clean, readable, and scalable. In this article, I’ll share how to apply these concepts in a Node.js/Express backend project, drawing on best practices from Martin Fowler and enterprise frameworks like Spring Boot.</p><h3>Refactoring: Why and How</h3><p>Refactoring is the process of restructuring existing code without changing its external behavior. According to Martin Fowler, refactoring improves code readability, reduces complexity, and makes future changes easier. In JavaScript/TypeScript projects, best practices include:</p><ul><li>Extracting repeated logic into reusable functions or middleware</li><li>Renaming variables and functions for clarity</li><li>Splitting large files into smaller, focused modules</li><li>Removing dead code and unused dependencies</li><li>Improving error handling and logging</li></ul><h3>Example: Middleware Extraction</h3><p>Suppose you have authentication checks repeated in multiple route handlers. Instead, you can extract this logic into middleware:</p><pre>// auth.middleware.ts<br>export function verifyAdminToken(req, res, next) {<br>    // ...token verification logic...<br>    next();<br>}</pre><p>Now, you can reuse verifyAdminToken across routes, reducing duplication and improving maintainability.</p><h3>Design Patterns in Enterprise Applications</h3><p>Enterprise-scale applications often use design patterns to organize code. Some common patterns include:</p><ul><li><strong>Data Transfer Object (DTO)</strong>: Encapsulates data sent between layers, ensuring only necessary data is exposed.</li><li><strong>Service Layer</strong>: Contains business logic, separate from controllers/routes.</li><li><strong>Repository Layer</strong>: Handles data access, abstracting database operations.</li></ul><p>While these patterns are common in frameworks like Spring Boot, they can also be applied in Node.js/Express projects for better code organization.</p><h3>Example: DTO Pattern</h3><p>Instead of returning raw database objects, you can use DTOs to control the data structure:</p><pre>// pharmacist.dto.ts<br>export class PharmacistDTO {<br>    constructor(pharmacist) {<br>        this.id = pharmacist.id;<br>        this.name = pharmacist.name;<br>        // ...other fields...<br>    }<br>}</pre><h3>Refactoring Example: Route Handler Organization</h3><p>In the project, route handlers were initially defined directly in the route files. To improve maintainability, we refactored the code to separate concerns:</p><ul><li><strong>Before</strong>: Route files contained business logic.</li><li><strong>After</strong>: Route files only define endpoints and delegate to handler modules.</li></ul><p>This makes it easier to test and update business logic without touching routing code.</p><pre>// auth.routes.ts<br>router.post(&#39;/login&#39;, validateRequest(loginSchema), loginHandler);</pre><pre>// auth.loginHandler.ts<br>export async function loginHandler(req, res) {<br>    // business logic here<br>}</pre><h3>Applying the Service Layer Pattern</h3><p>To further improve structure, weintroduced a Service Layer. For example, instead of having authentication logic in the route handler, we created an AuthService:</p><pre>// auth.service.ts<br>export class AuthService {<br>    static async login(credentials) {<br>        // business logic for login<br>    }<br>}</pre><pre>// auth.loginHandler.ts<br>import { AuthService } from &#39;../services/auth.service&#39;;<br><br>export const loginHandler = async (req, res) =&gt; {<br>    const result = await AuthService.login(req.body);<br>    // handle response<br>};</pre><p><strong>Trade-offs</strong>:</p><ul><li><strong>Pros</strong>: Clear separation of concerns, easier testing, reusable business logic, easier onboarding for new developers.</li><li><strong>Cons</strong>: Slightly more boilerplate, but pays off as the project grows.</li></ul><h3>Advanced Refactoring: Performance &amp; Non-Functional Improvements</h3><p>Beyond readability, refactoring can improve performance and other non-functional aspects. For example:</p><ul><li><strong>Caching</strong>: Store results of expensive queries in memory or Redis to reduce database load.</li><li><strong>Bulk Operations</strong>: Refactor code to use batch database operations instead of multiple single queries.</li><li><strong>Async/Await</strong>: Use async/await for non-blocking I/O and better error handling.</li><li><strong>Logging and Monitoring</strong>: Add structured logging and monitoring to quickly identify issues in production.</li></ul><h3>Conclusion</h3><p>Refactoring and design patterns are not just academic concepts — they have real, practical benefits. By continuously improving code structure and applying proven patterns, we make our projects easier to maintain, scale, and extend. The investment in clean code pays off with faster development, fewer bugs, and happier teams.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=634aa24caa42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Platform Monitoring in a Modern React/Next.js Project: Best Practices & Implementation]]></title>
            <link>https://medium.com/@hery.heryasa/platform-monitoring-in-a-modern-react-next-js-project-best-practices-implementation-6b49ab68cf45?source=rss-e10485d8ce01------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b49ab68cf45</guid>
            <dc:creator><![CDATA[Mahoga Aribowo Heryasa]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 11:21:48 GMT</pubDate>
            <atom:updated>2025-06-11T11:21:48.962Z</atom:updated>
            <content:encoded><![CDATA[<p>Monitoring is a critical aspect of any production application. It’s not just about catching errors it’s about understanding your users, optimizing performance, and ensuring your platform is reliable and scalable. In this post, I’ll walk you through how we implemented comprehensive monitoring in our React/Next.js project, covering error tracking, performance, analytics, and custom monitoring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/0*OpIjALcuWLs2oBwY.jpg" /></figure><h3>Why Monitoring Matters</h3><p>When your application goes live, you need to know:</p><ul><li><strong>Is it working as expected?</strong></li><li><strong>Are users experiencing errors?</strong></li><li><strong>How is the performance in real-world conditions?</strong></li><li><strong>What are users actually doing?</strong></li></ul><p>Without monitoring, you’re flying blind. With it, you can proactively fix issues, optimize user experience, and make data-driven decisions.</p><h3>Error Monitoring with Sentry</h3><p>One of the most important aspects of monitoring is error tracking. In our project, we use <strong>Sentry</strong> to capture both handled and unhandled exceptions, as well as custom events for suspicious activities. Sentry provides real-time error reporting, stack traces, and even user context, making it much easier to debug issues that occur in production.</p><p>For example, in our login page, we use Sentry to log both failed login attempts and unexpected errors. This allows us to monitor authentication issues and get notified if something unusual happens, such as a spike in failed logins or a new type of error.</p><pre>import * as Sentry from &#39;@sentry/nextjs&#39;;<br><br>const handleLoginError = (error: any) =&gt; {<br>  if (error.response &amp;&amp; error.response.status === 401) {<br>    Sentry.captureMessage(<br>      &#39;Invalid login attempt: incorrect username or password&#39;,<br>      {<br>        level: &#39;info&#39;,<br>        extra: { username },<br>      },<br>    );<br>  } else {<br>    Sentry.captureException(error, {<br>      level: &#39;error&#39;,<br>      extra: { username },<br>    });<br>  }<br>};</pre><p>By integrating Sentry, we can quickly identify, triage, and resolve issues, reducing downtime and improving user satisfaction.</p><h3>Performance Monitoring</h3><p>Performance is key to user satisfaction. In our project, we can leverage both built-in browser tools and third-party services to monitor performance. Tools like <strong>Vercel Analytics</strong> (if deploying on Vercel) can provide real user metrics such as Core Web Vitals, which can help us understand how our application performs for actual users. For deeper insights, services like <strong>New Relic</strong> or <strong>Datadog</strong> can be used to monitor server and client performance, track slow transactions, and identify bottlenecks. These tools allow us to set performance budgets, monitor API response times, and ensure that our application remains fast and responsive as it scales.</p><h3>User Activity Analytics</h3><p>Understanding user behavior is essential for making informed product decisions. We can use <strong>Google Analytics</strong> to track page views, user flows, and custom events. By analyzing this data, we can see which features are most popular, where users drop off, and how they navigate through the application. This information is invaluable for prioritizing new features, improving user experience, and measuring the impact of changes. Setting up Google Analytics in a Next.js project is straightforward, and you can easily track custom events such as button clicks or form submissions to gain deeper insights into user interactions.</p><h3>Custom Monitoring &amp; Alerts</h3><p>Sometimes, standard monitoring isn’t enough. We often need to monitor specific business logic or application flows. For example, tracking how often a certain API endpoint is called, or how many times a user fails to log in. By sending custom events to Sentry or our analytics tools, we can set up alerts for anomalies and monitor the health of critical features. This level of customization ensures that our monitoring strategy aligns with our business goals and provides actionable insights.</p><h3>Advanced Usage: Customization &amp; Alerting</h3><p>As our application grows, we take advantage of advanced features in our monitoring tools. With Sentry, we add tags, user context, and breadcrumbs for richer error reports. We configure alerts to notify us via email or Slack when thresholds are breached, such as a sudden increase in error rates or slow API responses. We also build dashboards to visualize key metrics and error trends, making it easy to spot issues and track progress over time.</p><h3>Conclusion</h3><p>In conclusion, implementing comprehensive monitoring in our React/Next.js project has proven essential for maintaining platform reliability, performance, and user satisfaction. By leveraging error monitoring tools like Sentry, we can quickly detect and resolve issues before they impact users. Performance monitoring ensures our application remains fast and responsive, while analytics help us understand user behavior and make informed decisions for future improvements. Altogether, these monitoring practices not only help us deliver a stable and efficient application but also empower our team to continuously enhance the user experience and respond effectively to any challenges that arise in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b49ab68cf45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UI Standardization: From Design Guidelines to Reusable Components]]></title>
            <link>https://medium.com/@hery.heryasa/ui-standardization-from-design-guidelines-to-reusable-components-3ec0cd6e394f?source=rss-e10485d8ce01------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ec0cd6e394f</guid>
            <dc:creator><![CDATA[Mahoga Aribowo Heryasa]]></dc:creator>
            <pubDate>Mon, 12 May 2025 20:08:08 GMT</pubDate>
            <atom:updated>2025-05-12T20:08:08.966Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/335/0*S6U0bHFJ_MqIKN7B" /></figure><p>In today’s digital product development, the visual appeal of a user interface (UI) is just one piece of the puzzle. What truly sets apart a professional product is <strong>UI standardization</strong>, the practice of maintaining consistent design principles and reusable components across the entire application.</p><p>For designers, this means adhering to a shared visual language. For developers, this means creating clean, modular code components that follow consistent patterns. And for the users? It means a seamless, intuitive, and familiar experience as they navigate through the product.</p><h3>Why UI Standardization Matters</h3><p>When teams grow and products scale, inconsistency tends to creep in: buttons with slightly different padding, forms with inconsistent validation styles, or pages that feel disconnected. Without a strong foundation of UI standardization, these inconsistencies can lead to:</p><ul><li><strong>User confusion and poor usability</strong></li><li><strong>Increased development time</strong> (due to repetitive code &amp; design work)</li><li><strong>Maintenance headaches</strong> (fixing the same issue in multiple places)</li><li><strong>Diluted brand identity</strong> (because the product looks and feels disjointed)</li></ul><p>For our team, working on the vending machine project, UI standardization was a necessity. With a complex system involving pharmacists, admins, and vending machines, we had to ensure <strong>visual and functional consistency</strong> across every user touchpoint.</p><h3>Building the Foundation with Design Guidelines</h3><p>The first and most critical step in UI standardization is defining a clear and comprehensive <strong>design guideline</strong>. Here’s how we approached it:</p><h4>Establishing a Unified Design Language</h4><p>We started by creating a <a href="https://www.figma.com/design/SAS9OeuZ6QnnFbE07f3GWb/Medicine-Vending-Machine-RS-UMMI?node-id=274-68&amp;p=f&amp;t=7OjqwYazEJB4MnsN-0"><strong>Design Guideline Document</strong></a> in <strong>Figma</strong>, covering:</p><ul><li><strong>Typography hierarchy</strong> (font families, sizes, line heights)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*o4LqSd4fdS8dSHYTHl_3mw.png" /></figure><p>Defines the <strong>font families, sizes, and line heights</strong> used across the application. This ensures consistent text styling for headings, body text, captions, and buttons, making the UI visually organized and easy to read.</p><ul><li><strong>Color palettes</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*4B9qsLErEfG43Nu1xg4NLg.png" /></figure><p>A set of <strong>primary, secondary, and semantic colors</strong> used consistently across the UI. Color palettes help maintain brand identity and improve visual clarity.</p><ul><li><strong>Components</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*PJ3t8eZf--9LnnZ1rLQx8Q.png" /></figure><p>Standardized <strong>UI elements</strong> like buttons, inputs, cards, and modals designed with consistent styling and behavior. Reusable components reduce development time and ensure visual and functional consistency across different pages.</p><ul><li><strong>Refrence Website</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*dnw2ruc22N1cYfHZxiTc6A.png" /></figure><p>A <strong>benchmark or inspiration site</strong> that reflects the design style or functionality you aim to achieve. This serves as a visual guide for aligning your design direction with industry standards or desired aesthetics.</p><ul><li><strong>Visual Assets (logo and qr code)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K5iBXT70brQNynh9QMxsjA.png" /></figure><p>Visual assets like the <strong>company logo</strong> and <strong>QR code</strong> that are used on official documents, product packaging, and marketing materials. Including these ensures branding consistency and provides quick access to digital resources via QR scanning.</p><p>This document served as a <strong>single source of truth</strong>, ensuring that both designers and developers were aligned. Every new page, button, and form was designed with this guideline in mind.</p><h3>Crafting High-Fidelity Prototypes</h3><p>With guidelines in place, we created<a href="https://www.figma.com/proto/SAS9OeuZ6QnnFbE07f3GWb/Medicine-Vending-Machine-RS-UMMI?node-id=274-1308&amp;p=f&amp;t=7OjqwYazEJB4MnsN-0&amp;scaling=min-zoom&amp;content-scaling=fixed&amp;page-id=136%3A26&amp;starting-point-node-id=274%3A1308&amp;show-proto-sidebar=1"> <strong>high-fidelity prototypes</strong></a> in Figma to simulate real user interactions. These prototypes allowed us to:</p><ul><li>Validate usability through stakeholder reviews</li><li>Conduct user testing with pharmacists &amp; admins</li><li>Align expectations between design &amp; development teams</li></ul><p>This step ensured that what we designed wasn’t just visually appealing, but also <strong>practical and user-friendly</strong>.</p><h3>Translating Design to Reusable Code Components</h3><p>Once the visual foundation was set, the next challenge was to <strong>translate these guidelines into reusable code components</strong>. Here’s how we tackled it:</p><h4><strong>Embracing Atomic Design Methodology</strong></h4><p>To ensure scalability and maintainability, we followed the <strong>Atomic Design Principles</strong>:</p><ul><li><strong>Atoms</strong>: Basic UI elements (buttons, inputs, icons)</li><li><strong>Molecules</strong>: Combinations of atoms (input groups, card components)</li><li><strong>Organisms</strong>: Complex structures (navbars, side panels)</li><li><strong>Templates &amp; Pages</strong>: Layout structures and dynamic content</li></ul><p>This modular approach made it easier to reuse components across different pages, reducing redundancy and improving code quality.</p><h4>Building a Reusable Component Library</h4><p>In our component library, we focused on key reusable components, including:</p><ul><li><strong>Navbar</strong>: Role-based navigation that adapts to user types (admin, pharmacist)</li></ul><p>The <strong>Navbar</strong> component serves as the main navigation bar, adapting its menu items based on user roles (admin or pharmacist). It supports responsive design with distinct layouts for desktop and mobile views, ensuring intuitive navigation and accessibility across devices.</p><pre>&#39;use client&#39;;<br><br>import Image from &#39;next/image&#39;;<br>import Link from &#39;next/link&#39;;<br>import useUser from &#39;@/hooks/useUser&#39;;<br>import { usePathname, useRouter } from &#39;next/navigation&#39;;<br>import { Button } from &#39;@/components/ui/button&#39;;<br>import { FiLogOut } from &#39;react-icons/fi&#39;;<br>import { useState } from &#39;react&#39;;<br>import ConfirmationModal from &#39;../modals/ConfirmationModal&#39;;<br>import { FaQuestionCircle } from &#39;react-icons/fa&#39;;<br>import { Menu } from &#39;lucide-react&#39;;<br>import {<br>  DropdownMenu,<br>  DropdownMenuContent,<br>  DropdownMenuItem,<br>  DropdownMenuTrigger,<br>} from &#39;../ui/dropdown-menu&#39;;<br><br>const Navbar = () =&gt; {<br>  const { logout, role } = useUser();<br>  const [confirmationModal, setConfirmationModal] = useState(false);<br>  const [isOpen, setIsOpen] = useState(false);<br>  const router = useRouter();<br>  const pathname = usePathname();<br><br>  const handleLogout = () =&gt; {<br>    setConfirmationModal(false);<br>    logout();<br>    router.push(&#39;/login&#39;);<br>  };<br><br>  const handleTutorial = () =&gt; {<br>    if (role === &#39;admin&#39;) {<br>      router.push(&#39;/admin/tutorial&#39;);<br>    } else if (role === &#39;pharmacist&#39;) {<br>      router.push(&#39;/pharmacist/tutorial&#39;);<br>    }<br>  };<br><br>  // Don&#39;t show tutorial button on login page or tutorial pages themselves<br>  const showTutorialButton =<br>    pathname &amp;&amp;<br>    !pathname.includes(&#39;/tutorial&#39;) &amp;&amp;<br>    (role === &#39;admin&#39; || role === &#39;pharmacist&#39;);<br><br>  const showLogButton =<br>    pathname &amp;&amp; pathname.includes(&#39;/admin&#39;) &amp;&amp; role === &#39;admin&#39;;<br><br>  return (<br>    &lt;&gt;<br>      {pathname !== &#39;/login&#39; &amp;&amp; (<br>        &lt;div data-testid=&quot;test-navbar&quot; className=&quot;fixed top-0 w-full p-3 z-50&quot;&gt;<br>          &lt;nav className=&quot;p-[10px] rounded-[20px] flex justify-between items-center bg-light shadow-[0px_2px_10px_1px_rgba(0,0,0,0.25)] transition-shadow duration-300 hover:shadow-[0px_4px_15px_2px_rgba(0,0,0,0.3)]&quot;&gt;<br>            &lt;Image<br>              src={&#39;/logo/logo-navbar.svg&#39;}<br>              width={179}<br>              height={47}<br>              alt=&quot;RS UMMI Logo&quot;<br>              className=&quot;w-[120px] h-[32px] sm:w-[150px] sm:h-[40px] lg:w-[179px] lg:h-[47px]&quot;<br>            /&gt;<br>            &lt;div className=&quot;flex gap-1 md:gap-6 items-center&quot;&gt;<br>              {showTutorialButton &amp;&amp; (<br>                &lt;Button<br>                  onClick={handleTutorial}<br>                  variant=&quot;ghost&quot;<br>                  className=&quot;max-sm:hidden text-primary hover:bg-primary/10 p-2 h-auto&quot;<br>                  title=&quot;Panduan Penggunaan&quot;<br>                  data-testid=&quot;test-tutorial-button&quot;<br>                &gt;<br>                  &lt;FaQuestionCircle size={24} /&gt;<br>                &lt;/Button&gt;<br>              )}<br><br>              {/* DESKTOP */}<br>              &lt;div className=&quot;max-sm:hidden flex gap-6 items-center&quot;&gt;<br>                {showLogButton &amp;&amp; (<br>                  &lt;Button asChild variant={&#39;link&#39;}&gt;<br>                    &lt;Link href={&#39;/admin/log&#39;}&gt;Log Aktivitas&lt;/Link&gt;<br>                  &lt;/Button&gt;<br>                )}<br>                &lt;Button<br>                  onClick={() =&gt; setConfirmationModal(true)}<br>                  variant={&#39;secondary&#39;}<br>                  data-testid=&quot;test-logout-button&quot;<br>                &gt;<br>                  &lt;FiLogOut /&gt;<br>                  Logout<br>                &lt;/Button&gt;<br>              &lt;/div&gt;<br><br>              {/* MOBILE */}<br>              &lt;div className=&quot;sm:hidden flex gap-1&quot;&gt;<br>                {!showLogButton &amp;&amp; showTutorialButton &amp;&amp; (<br>                  &lt;Button<br>                    onClick={handleTutorial}<br>                    variant=&quot;ghost&quot;<br>                    className=&quot;text-primary hover:bg-primary/10 p-2 h-auto&quot;<br>                    title=&quot;Panduan Penggunaan&quot;<br>                  &gt;<br>                    &lt;FaQuestionCircle size={24} /&gt;<br>                  &lt;/Button&gt;<br>                )}<br>                {showLogButton &amp;&amp; (<br>                  &lt;DropdownMenu open={isOpen} onOpenChange={setIsOpen}&gt;<br>                    &lt;DropdownMenuTrigger asChild&gt;<br>                      &lt;Button variant={&#39;ghost&#39;} size={&#39;sm&#39;}&gt;<br>                        &lt;Menu /&gt;<br>                      &lt;/Button&gt;<br>                    &lt;/DropdownMenuTrigger&gt;<br>                    &lt;DropdownMenuContent align=&quot;end&quot;&gt;<br>                      {showTutorialButton &amp;&amp; (<br>                        &lt;DropdownMenuItem onClick={handleTutorial}&gt;<br>                          &lt;FaQuestionCircle size={24} /&gt;<br>                          Tutorial<br>                        &lt;/DropdownMenuItem&gt;<br>                      )}<br>                      &lt;DropdownMenuItem onClick={() =&gt; setIsOpen(false)}&gt;<br>                        &lt;Link href={&#39;/admin/log&#39;}&gt;Log Aktivitas&lt;/Link&gt;<br>                      &lt;/DropdownMenuItem&gt;<br>                    &lt;/DropdownMenuContent&gt;<br>                  &lt;/DropdownMenu&gt;<br>                )}<br>                &lt;Button<br>                  onClick={() =&gt; setConfirmationModal(true)}<br>                  variant={&#39;secondary&#39;}<br>                  size={&#39;sm&#39;}<br>                &gt;<br>                  &lt;FiLogOut /&gt;<br>                &lt;/Button&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/nav&gt;<br>          &lt;ConfirmationModal<br>            isOpen={confirmationModal}<br>            setIsOpen={setConfirmationModal}<br>            title=&quot;Konfirmasi Logout&quot;<br>            message=&quot;Apakah Anda yakin ingin keluar?&quot;<br>            onCancel={() =&gt; setConfirmationModal(false)}<br>            onConfirm={handleLogout}<br>          /&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Navbar;</pre><ul><li><strong>Toast Notifications</strong>: Feedback alerts for success, error, and info states</li></ul><p>The <strong>Toast Notifications</strong> component provides consistent and non-intrusive user feedback for actions like success, error, and informational alerts. Built using Radix UI primitives, it standardizes notification behavior and styling across the application.</p><pre>&#39;use client&#39;;<br><br>import * as React from &#39;react&#39;;<br>import * as ToastPrimitives from &#39;@radix-ui/react-toast&#39;;<br>import { cva, type VariantProps } from &#39;class-variance-authority&#39;;<br>import { X } from &#39;lucide-react&#39;;<br><br>import { cn } from &#39;@/lib/utils&#39;;<br><br>const ToastProvider = ToastPrimitives.Provider;<br><br>const ToastViewport = React.forwardRef&lt;<br>  React.ElementRef&lt;typeof ToastPrimitives.Viewport&gt;,<br>  React.ComponentPropsWithoutRef&lt;typeof ToastPrimitives.Viewport&gt;<br>&gt;(({ className, ...props }, ref) =&gt; (<br>  &lt;ToastPrimitives.Viewport<br>    ref={ref}<br>    className={cn(<br>      &#39;fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]&#39;,<br>      className,<br>    )}<br>    {...props}<br>  /&gt;<br>));<br>ToastViewport.displayName = ToastPrimitives.Viewport.displayName;<br><br>const toastVariants = cva(<br>  &#39;group pointer-events-auto relative flex w-full items-center text-lg font-semibold justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full&#39;,<br>  {<br>    variants: {<br>      variant: {<br>        default: &#39;border bg-success text-white&#39;,<br>        neutral: &#39;border bg-background text-white&#39;,<br>        destructive:<br>          &#39;destructive group border-destructive bg-destructive text-white&#39;,<br>      },<br>    },<br>    defaultVariants: {<br>      variant: &#39;default&#39;,<br>    },<br>  },<br>);<br><br>const Toast = React.forwardRef&lt;<br>  React.ElementRef&lt;typeof ToastPrimitives.Root&gt;,<br>  React.ComponentPropsWithoutRef&lt;typeof ToastPrimitives.Root&gt; &amp;<br>    VariantProps&lt;typeof toastVariants&gt;<br>&gt;(({ className, variant, ...props }, ref) =&gt; {<br>  return (<br>    &lt;ToastPrimitives.Root<br>      ref={ref}<br>      className={cn(toastVariants({ variant }), className)}<br>      {...props}<br>    /&gt;<br>  );<br>});<br>Toast.displayName = ToastPrimitives.Root.displayName;<br><br>const ToastAction = React.forwardRef&lt;<br>  React.ElementRef&lt;typeof ToastPrimitives.Action&gt;,<br>  React.ComponentPropsWithoutRef&lt;typeof ToastPrimitives.Action&gt;<br>&gt;(({ className, ...props }, ref) =&gt; (<br>  &lt;ToastPrimitives.Action<br>    ref={ref}<br>    className={cn(<br>      &#39;inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive&#39;,<br>      className,<br>    )}<br>    {...props}<br>  /&gt;<br>));<br>ToastAction.displayName = ToastPrimitives.Action.displayName;<br><br>const ToastClose = React.forwardRef&lt;<br>  React.ElementRef&lt;typeof ToastPrimitives.Close&gt;,<br>  React.ComponentPropsWithoutRef&lt;typeof ToastPrimitives.Close&gt;<br>&gt;(({ className, ...props }, ref) =&gt; (<br>  &lt;ToastPrimitives.Close<br>    ref={ref}<br>    className={cn(<br>      &#39;absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600&#39;,<br>      className,<br>    )}<br>    toast-close=&quot;&quot;<br>    {...props}<br>  &gt;<br>    &lt;X className=&quot;h-4 w-4&quot; /&gt;<br>  &lt;/ToastPrimitives.Close&gt;<br>));<br>ToastClose.displayName = ToastPrimitives.Close.displayName;<br><br>const ToastTitle = React.forwardRef&lt;<br>  React.ElementRef&lt;typeof ToastPrimitives.Title&gt;,<br>  React.ComponentPropsWithoutRef&lt;typeof ToastPrimitives.Title&gt;<br>&gt;(({ className, ...props }, ref) =&gt; (<br>  &lt;ToastPrimitives.Title<br>    ref={ref}<br>    className={cn(&#39;text-sm font-semibold [&amp;+div]:text-xs&#39;, className)}<br>    {...props}<br>  /&gt;<br>));<br>ToastTitle.displayName = ToastPrimitives.Title.displayName;<br><br>const ToastDescription = React.forwardRef&lt;<br>  React.ElementRef&lt;typeof ToastPrimitives.Description&gt;,<br>  React.ComponentPropsWithoutRef&lt;typeof ToastPrimitives.Description&gt;<br>&gt;(({ className, ...props }, ref) =&gt; (<br>  &lt;ToastPrimitives.Description<br>    ref={ref}<br>    className={cn(&#39;text-sm opacity-90&#39;, className)}<br>    {...props}<br>  /&gt;<br>));<br>ToastDescription.displayName = ToastPrimitives.Description.displayName;<br><br>type ToastProps = React.ComponentPropsWithoutRef&lt;typeof Toast&gt;;<br><br>type ToastActionElement = React.ReactElement&lt;typeof ToastAction&gt;;<br><br>export {<br>  type ToastProps,<br>  type ToastActionElement,<br>  ToastProvider,<br>  ToastViewport,<br>  Toast,<br>  ToastTitle,<br>  ToastDescription,<br>  ToastClose,<br>  ToastAction,<br>};</pre><ul><li><strong>Buttons</strong>: Variants for primary, secondary, outline, and destructive actions, all with consistent sizing and states</li></ul><p>The <strong>Toast Notifications</strong> component provides consistent and non-intrusive user feedback for actions like success, error, and informational alerts. Built using Radix UI primitives, it standardizes notification behavior and styling across the application.</p><pre>import * as React from &#39;react&#39;;<br>import { Slot } from &#39;@radix-ui/react-slot&#39;;<br>import { cva, type VariantProps } from &#39;class-variance-authority&#39;;<br><br>import { cn } from &#39;@/lib/utils&#39;;<br><br>const buttonVariants = cva(<br>  &#39;inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md font-semibold transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50 disabled:cursor-not-allowed [&amp;_svg]:pointer-events-none [&amp;_svg]:size-4 [&amp;_svg]:shrink-0&#39;,<br>  {<br>    variants: {<br>      variant: {<br>        default:<br>          &#39;bg-primary text-primary-foreground shadow hover:bg-primary/90&#39;,<br>        destructive:<br>          &#39;bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90&#39;,<br>        secondary:<br>          &#39;bg-secondary/15 text-secondary shadow-sm hover:bg-secondary/10&#39;,<br>        ghost: &#39;text-primary hover:bg-accent&#39;,<br>        link: &#39;text-primary underline-offset-4 hover:underline&#39;,<br>      },<br>      size: {<br>        default: &#39;h-12 px-6 py-3 text-lg&#39;,<br>        sm: &#39;h-10 rounded-md px-4 text-sm&#39;,<br>        lg: &#39;h-14 rounded-md px-8 text-xl&#39;,<br>        icon: &#39;h-12 w-12&#39;,<br>      },<br>    },<br>    defaultVariants: {<br>      variant: &#39;default&#39;,<br>      size: &#39;default&#39;,<br>    },<br>  },<br>);<br><br>export interface ButtonProps<br>  extends React.ButtonHTMLAttributes&lt;HTMLButtonElement&gt;,<br>    VariantProps&lt;typeof buttonVariants&gt; {<br>  asChild?: boolean;<br>}<br><br>const Button = React.forwardRef&lt;HTMLButtonElement, ButtonProps&gt;(<br>  ({ className, variant, size, asChild = false, ...props }, ref) =&gt; {<br>    const Comp = asChild ? Slot : &#39;button&#39;;<br>    return (<br>      &lt;Comp<br>        className={cn(buttonVariants({ variant, size, className }))}<br>        ref={ref}<br>        {...props}<br>      /&gt;<br>    );<br>  },<br>);<br>Button.displayName = &#39;Button&#39;;<br><br>export { Button, buttonVariants };</pre><ul><li><strong>Inputs &amp; Form Fields</strong>: Standardized inputs with validation, error handling, and accessibility features</li></ul><p>The <strong>Input and Form Field components</strong> handle user input with built-in validation, error messaging, and accessibility features. They include variations such as password fields with visibility toggles and search inputs with icons, streamlining form design and improving usability.</p><pre>import * as React from &#39;react&#39;;<br><br>import { cn } from &#39;@/lib/utils&#39;;<br>import { IoAlertCircleSharp } from &#39;react-icons/io5&#39;;<br>import { FiEye, FiEyeOff } from &#39;react-icons/fi&#39;;<br>import { FaMagnifyingGlass } from &#39;react-icons/fa6&#39;;<br><br>interface InputProps extends React.ComponentProps&lt;&#39;input&#39;&gt; {<br>  label?: string;<br>  error?: string;<br>}<br><br>const Input = React.forwardRef&lt;HTMLInputElement, InputProps&gt;(<br>  ({ className, type, label, error, ...props }, ref) =&gt; {<br>    const [showPassword, setShowPassword] = React.useState(false);<br>    const isPassword = type === &#39;password&#39;;<br>    const isSearch = type === &#39;search&#39;;<br><br>    return (<br>      &lt;div className=&quot;flex flex-col w-full flex-1&quot;&gt;<br>        &lt;label<br>          htmlFor={props.id}<br>          className={cn(label ? &#39;font-semibold mb-2&#39; : &#39;display-none&#39;)}<br>        &gt;<br>          {label}<br>        &lt;/label&gt;<br>        &lt;div className=&quot;relative&quot;&gt;<br>          &lt;input<br>            type={isPassword &amp;&amp; showPassword ? &#39;text&#39; : type}<br>            className={cn(<br>              &#39;flex h-12 w-full rounded-md border border-input bg-transparent px-4 py-1 shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50&#39;,<br>              isPassword &amp;&amp; &#39;pr-12&#39;,<br>              error &amp;&amp; &#39;border-2 border-red-500 focus:border-red-500 pr-14&#39;,<br>              className,<br>            )}<br>            ref={ref}<br>            {...props}<br>          /&gt;<br>          {isPassword &amp;&amp; (<br>            &lt;button<br>              type=&quot;button&quot;<br>              onClick={() =&gt; setShowPassword(!showPassword)}<br>              className=&quot;absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700&quot;<br>            &gt;<br>              {!showPassword ? &lt;FiEyeOff size={20} /&gt; : &lt;FiEye size={20} /&gt;}<br>            &lt;/button&gt;<br>          )}<br>          {error &amp;&amp; type !== &#39;password&#39; &amp;&amp; (<br>            &lt;IoAlertCircleSharp<br>              size={24}<br>              data-testid=&quot;error-icon&quot;<br>              className=&quot;absolute right-4 top-1/2 -translate-y-1/2 text-red-500&quot;<br>            /&gt;<br>          )}<br>          {isSearch &amp;&amp; (<br>            &lt;div className=&quot;p-0 absolute flex items-center justify-center pointer-events-none right-2 h-8 w-8 top-1/2 transform -translate-y-1/2 bg-primary text-white rounded-full&quot;&gt;<br>              &lt;FaMagnifyingGlass size={16} /&gt;<br>            &lt;/div&gt;<br>          )}<br>        &lt;/div&gt;<br>        {error &amp;&amp; &lt;span className=&quot;text-red-500 text-sm mt-2&quot;&gt;{error}&lt;/span&gt;}<br>      &lt;/div&gt;<br>    );<br>  },<br>);<br>Input.displayName = &#39;Input&#39;;<br><br>export { Input };</pre><p>Each component was designed with <strong>props-driven customization</strong>, ensuring flexibility while maintaining visual consistency.</p><h3>Benefits We Gained from UI Standardization</h3><p>By standardizing our UI design and component development, we achieved:</p><ul><li><strong>Faster development cycles</strong> (build once, reuse everywhere)</li><li><strong>Consistent user experience</strong> (reduced UX inconsistencies)</li><li><strong>Easier maintenance</strong> (single source of truth for components)</li><li><strong>Scalable codebase</strong> (future-proof architecture)</li><li><strong>Improved team collaboration</strong> (designers &amp; developers speak the same “UI language”)</li></ul><h3>Conclusion</h3><p>UI standardization is not a one-time task — it’s an ongoing practice that evolves with the product. But the benefits are undeniable: better usability, faster development, and a stronger brand identity.</p><p>In our Medicine Vending Machine project, this approach helped us deliver a product that was not only functional but also intuitive and scalable. By bridging the gap between <strong>design guidelines and reusable components</strong>, we built a solid foundation for future growth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ec0cd6e394f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD in Next.js: Build Smarter, Not Harder]]></title>
            <link>https://medium.com/@hery.heryasa/tdd-in-next-js-build-smarter-not-harder-38ad0b97eef6?source=rss-e10485d8ce01------2</link>
            <guid isPermaLink="false">https://medium.com/p/38ad0b97eef6</guid>
            <dc:creator><![CDATA[Mahoga Aribowo Heryasa]]></dc:creator>
            <pubDate>Mon, 12 May 2025 18:48:53 GMT</pubDate>
            <atom:updated>2025-06-11T11:09:15.529Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*aqAoxMSZQO0tco9G-5qLNg.jpeg" /></figure><p>When building modern web applications with <strong>Next.js</strong>, it’s easy to get lost in the rush of coding features and forget about testing until something breaks. But what if you could <em>start</em> with tests — and let them guide your development process?</p><p>That’s exactly what <strong>Test-Driven Development (TDD)</strong> is all about. It’s not just a technique; it’s a mindset and a discipline. In this post, I’ll walk you through how to do TDD in a Next.js project, why it’s valuable, and how thinking in terms of <strong>happy paths</strong>, <strong>unhappy paths</strong>, and <strong>edge cases</strong> can make your applications more robust.</p><h3>What Is TDD?</h3><p>TDD follows a strict but simple cycle:</p><ul><li><strong>Red</strong> — Write a test that fails.</li><li><strong>Green</strong> — Write the minimum code to make the test pass.</li><li><strong>Refactor</strong> — Clean up the code while keeping the test green.</li></ul><p>This cycle might feel slow at first, but it forces you to think before you code. Instead of jumping straight into implementation, you first define what <em>success</em> looks like — by writing a test.</p><p>Let’s say you want to build a login form. In traditional development, you might code the UI and then add tests later (if at all). With TDD, you flip that: you write a test that describes the form’s behavior, watch it fail (<strong>Red</strong>), implement just enough logic to pass the test (<strong>Green</strong>), and then polish the code or improve structure (<strong>Refactor</strong>).</p><h3>Happy Path, Unhappy Path, and Edge Cases</h3><p>When writing tests in TDD, you’re not just checking if things work — you’re also designing how the feature should behave. This is where the concepts of <strong>happy path</strong>, <strong>unhappy path</strong>, and <strong>edge cases</strong> come in.</p><ul><li>The <strong>happy path</strong> is the ideal scenario — when everything goes right. In a login form, it means the user enters valid credentials and logs in successfully. example:</li></ul><pre>    test(&quot;Should return 200 and updated pharmacist details&quot;, async () =&gt; {<br>        (editPharmacistService as jest.Mock).mockResolvedValue({ id: 1, ...req.body });<br><br>        await editPharmacist(req as Request, res as Response);<br><br>        expect(statusMock).toHaveBeenCalledWith(200);<br>        expect(jsonMock).toHaveBeenCalledWith({<br>            message: &quot;Pharmacist updated successfully&quot;,<br>        });<br>    });</pre><ul><li>The <strong>unhappy path</strong> covers failure scenarios — like entering the wrong password or leaving fields blank.</li></ul><pre>    test(&quot;Should return 404 if pharmacist not found&quot;, async () =&gt; {<br>        (editPharmacistService as jest.Mock).mockRejectedValue(new Error(&quot;Pharmacist not found&quot;));<br><br>        await editPharmacist(req as Request, res as Response);<br><br>        expect(statusMock).toHaveBeenCalledWith(404);<br>        expect(jsonMock).toHaveBeenCalledWith({ message: &quot;Pharmacist not found&quot; });<br>    });</pre><ul><li><strong>Edge cases</strong> are the less common, often overlooked conditions — like a password with only spaces or an email that’s almost valid but not quite. example: Edge case for handling multiple update request quickly</li></ul><pre>    test(&quot;Should handle multiple update requests quickly&quot;, async () =&gt; {<br>        (editPharmacistService as jest.Mock).mockResolvedValue({ id: 1, name: &quot;Updated Name&quot; });<br><br>        const updateRequests = [<br>            editPharmacist(req as Request, res as Response),<br>            editPharmacist(req as Request, res as Response),<br>        ];<br><br>        await Promise.all(updateRequests);<br><br>        expect(statusMock).toHaveBeenCalledTimes(2);<br>    });</pre><p>Writing tests for all three helps ensure your feature is not only functional but <em>resilient</em>.</p><h3><strong>TDD Implementation</strong></h3><p>I’ve implemented Test-Driven Development (TDD) for all the features I created in the project. Below are the implementations.</p><h4>Create Pharmacist Page Front-end</h4><p>commits: <a href="https://github.com/PRAS-UMMIGROUP/PPL-C6/pull/6/commits">https://github.com/PRAS-UMMIGROUP/PPL-C6/pull/6/commits</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSiZayqigFRVAPhOa1f45Q.png" /></figure><p>Coverage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*nOFM3dfF5G8jTP0Pi7OiGQ.png" /></figure><h4>Edit Pharmacist Page Back-end</h4><p>Commits: <a href="https://github.com/PRAS-UMMIGROUP/PPL-C6-BACKEND/pull/9/commits">https://github.com/PRAS-UMMIGROUP/PPL-C6-BACKEND/pull/9/commits</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5q3sPWagHZx1JzMmtpQQlg.png" /></figure><p>Coverage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*Xx6mVUlP99tUmecYkh6fkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*-6mVFjnXZNFNdV3yJAXbYA.png" /></figure><h4>Pharmacist Detail Page Back-end</h4><p>Commits: <a href="https://github.com/PRAS-UMMIGROUP/PPL-C6-BACKEND/pull/9/commits">https://github.com/PRAS-UMMIGROUP/PPL-C6-BACKEND/pull/9/commits</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OaMh95E5vISihN1QFd7zPA.png" /></figure><p>Coverage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*YHtLSFIl2T51HA_Pcbi5Ow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*VPQYKC3CKuQm_xqBB_7oYQ.png" /></figure><h4>Edit Medicine Page Front-end</h4><p>Commits:</p><ul><li><a href="https://github.com/RSUMMI-PPL-C6/PPL-C6-BACKEND/commits/feat/14-be-edit-medicine/">https://github.com/RSUMMI-PPL-C6/PPL-C6-BACKEND/commits/feat/14-be-edit-medicine/</a></li><li><a href="https://github.com/RSUMMI-PPL-C6/PPL-C6/commits/feat/31-integ-edit-medicines">https://github.com/RSUMMI-PPL-C6/PPL-C6/commits/feat/31-integ-edit-medicines</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tyPRzdu6RzQ5lNDFwpkp9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FW5THiRrfomhKY-pE1JtjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ApSL_ft-mToDdyfqZXUPyw.png" /></figure><p>Coverage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*OkORw0NHuYKpXuAeoLxcQw.png" /></figure><h4>Edit Medicine Location Page Front-end</h4><p>Commits:</p><ul><li><a href="https://github.com/RSUMMI-PPL-C6/PPL-C6-BACKEND/commits/feat/14-be-edit-medicine/">https://github.com/RSUMMI-PPL-C6/PPL-C6-BACKEND/commits/feat/14-be-edit-medicine/</a></li><li><a href="https://github.com/RSUMMI-PPL-C6/PPL-C6/commits/feat/31-integ-edit-medicines">https://github.com/RSUMMI-PPL-C6/PPL-C6/commits/feat/31-integ-edit-medicines</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHMAYrOJPwQDPySVHG-ABQ.png" /></figure><p>Coverage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*y8ORUGjnLqOdrGZY35zSRQ.png" /></figure><h4>Edit Medicine Page Back-end</h4><p>Commits: <a href="https://github.com/RSUMMI-PPL-C6/PPL-C6-BACKEND/pull/32/commits">https://github.com/PRAS-UMMIGROUP/PPL-C6-BACKEND/pull/9/commits</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8UgcuixM-qkY76y1lnWXQ.png" /></figure><p>Coverage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*UAcArXTEB_eqUY_2VTO4kQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*pqlmEeAHZIvJkEXpoVslFw.png" /></figure><h4>Report Page Back-end</h4><p>Commits: <a href="https://github.com/RSUMMI-PPL-C6/PPL-C6-BACKEND/commits/feat/48-be-create-report-page/?since=2025-05-19&amp;until=2025-05-19">https://github.com/RSUMMI-PPL-C6/PPL-C6-BACKEND/commits/feat/48-be-create-report-page/?since=2025-05-19&amp;until=2025-05-19</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYnUGE9YmmHq5y40ARAGJA.png" /></figure><p>Coverage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*rjQ4iL3Zqld-Hqf-XcSUNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*qsFRb4oyi5JC0XSWCBrwjw.png" /></figure><h3>Conclusion</h3><p>Test-Driven Development (TDD) isn’t just a testing strategy it’s a development philosophy that leads to more reliable, maintainable, and robust applications. By focusing on the <strong>red-green-refactor</strong> cycle and deliberately thinking through the <strong>happy path</strong>, <strong>unhappy path</strong>, and <strong>edge cases</strong>, I was able to build and verify features in a systematic, test-first manner across both frontend and backend in my Next.js project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38ad0b97eef6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When developing modern web applications — especially those with complex frontend-backend…]]></title>
            <link>https://medium.com/@hery.heryasa/when-developing-modern-web-applications-especially-those-with-complex-frontend-backend-689f08289079?source=rss-e10485d8ce01------2</link>
            <guid isPermaLink="false">https://medium.com/p/689f08289079</guid>
            <dc:creator><![CDATA[Mahoga Aribowo Heryasa]]></dc:creator>
            <pubDate>Wed, 07 May 2025 18:57:11 GMT</pubDate>
            <atom:updated>2025-05-07T18:57:11.501Z</atom:updated>
            <content:encoded><![CDATA[<p>When developing modern web applications — especially those with complex frontend-backend interactions — it’s essential to ensure your tests are not only reliable, but also <strong>isolated</strong> from external dependencies. This is where <strong>mock objects</strong> and <strong>stubs</strong> come into play.</p><p>In this blog, I’ll walk you through practical applications of <strong>mocking</strong> and <strong>stubbing</strong> in both backend and frontend testing. We’ll cover how they improve test coverage, reduce flaky test behavior, and help simulate error scenarios gracefully.</p><h3>What Are Mocks and Stubs?</h3><h4>Mock Objects</h4><p>A <strong>mock</strong> is a simulated object that mimics the behavior of real objects in a controlled way. Mocks can verify whether certain methods were called, how many times they were called, with what parameters, etc. In JavaScript testing frameworks like Jest, mock functions are usually created using jest.fn().</p><p>Mocking is particularly useful when you want to:</p><ul><li>Simulate database calls or HTTP requests</li><li>Intercept and track function calls</li><li>Replace internal dependencies to isolate units under test</li></ul><h4>Stubs</h4><p>A <strong>stub</strong> is a specific kind of mock that provides predefined responses to method calls. Stubs don’t track how they are used (like mocks do), but instead they return hardcoded or controlled outputs so you can simulate certain conditions.</p><p>Stubbing is great for:</p><ul><li>Returning consistent data from external API calls</li><li>Controlling conditional flows (e.g., success vs error)</li><li>Forcing edge cases or failures in your code</li></ul><p>Although mocks and stubs often overlap in functionality, <strong>stubs focus on <em>what to return</em></strong>, while <strong>mocks focus on <em>how functions are used</em></strong>.</p><h3>Backend Testing with Mocks and Stubs</h3><p>I implement mocking and stubing in this updateMedicine test:</p><pre>import { updateMedicine } from &quot;@/src/services/medicine.editMedicineService&quot;;<br>import { db } from &quot;@/src/db&quot;;<br><br>jest.mock(&quot;@/src/db&quot;, () =&gt; ({<br>  db: {<br>    select: jest.fn(),<br>    update: jest.fn(),<br>  }<br>}));<br><br>describe(&quot;updateMedicine service&quot;, () =&gt; {<br>    const originalMedicineId = 1;<br>    const originalRecipeId = &quot;12345&quot;;<br>    const newMedicineData = {<br>        recipeId: &quot;54321&quot;,<br>        medicalRecordId: &quot;67890&quot;,<br>        patientName: &quot;John Doe&quot;,<br>        location: &quot;Pharmacy A&quot;,<br>        detail: &quot;Pain reliever&quot;,<br>        status: &quot;Ready&quot;<br>    };<br><br>    afterEach(() =&gt; {<br>        jest.clearAllMocks();<br>    });<br><br>    it(&quot;should update medicine successfully when recipeId doesn&#39;t change&quot;, async () =&gt; {<br>        (db.select as jest.Mock)<br>        .mockReturnValueOnce({<br>            from: jest.fn().mockReturnValueOnce({<br>            where: jest.fn().mockResolvedValue([{}])<br>            })<br>        })<br>        .mockReturnValueOnce({<br>            from: jest.fn().mockReturnValueOnce({<br>            where: jest.fn().mockResolvedValue([])<br>            })<br>        });<br>    <br>        const mockReturning = jest.fn().mockResolvedValue([newMedicineData]);<br>    <br>        (db.update as jest.Mock).mockReturnValue({<br>        set: jest.fn().mockReturnValue({<br>            where: jest.fn().mockReturnValue({<br>            returning: mockReturning<br>            })<br>        })<br>        });<br>    <br>        const result = await updateMedicine(originalMedicineId, {<br>            ...newMedicineData,<br>            recipeId: originalRecipeId,<br>        });<br><br>        expect(result.data).toEqual([newMedicineData]);<br>        expect(mockReturning).toHaveBeenCalled();<br>    });<br><br>    it(&quot;should update medicine successfully when recipeId is changed and new ID is not taken&quot;, async () =&gt; {<br>        (db.select as jest.Mock)<br>        .mockReturnValueOnce({<br>            from: jest.fn().mockReturnValueOnce({<br>            where: jest.fn().mockResolvedValue([{}])<br>            })<br>        })<br>        .mockReturnValueOnce({<br>            from: jest.fn().mockReturnValueOnce({<br>            where: jest.fn().mockResolvedValue([])<br>            })<br>        });<br>    <br>        const mockReturning = jest.fn().mockResolvedValue([newMedicineData]);<br>    <br>        (db.update as jest.Mock).mockReturnValue({<br>        set: jest.fn().mockReturnValue({<br>            where: jest.fn().mockReturnValue({<br>            returning: mockReturning<br>            })<br>        })<br>        });<br>    <br>        const result = await updateMedicine(originalMedicineId, newMedicineData);<br>    <br>        expect(result.data).toEqual([newMedicineData]);<br>        expect(mockReturning).toHaveBeenCalled();<br>    });<br><br>    it(&quot;should throw NotFoundError when medicine not found&quot;, async () =&gt; {<br>        (db.select as jest.Mock).mockReturnValueOnce({<br>            from: jest.fn().mockReturnValueOnce({<br>                where: jest.fn().mockResolvedValueOnce([]),<br>            }),<br>        });<br><br>        const result = await updateMedicine(5555555, newMedicineData);<br>        expect(result.status).toBe(404);<br>    });<br><br>    it(&quot;should throw ConflictError if new recipeId already exists&quot;, async () =&gt; {<br>        (db.select as jest.Mock)<br>        .mockReturnValueOnce({ from: jest.fn().mockReturnValueOnce({ where: jest.fn().mockResolvedValue([{}]) }) }) // original exists<br>        .mockReturnValueOnce({ from: jest.fn().mockReturnValueOnce({ where: jest.fn().mockResolvedValue([{}]) }) }); // conflict<br><br>        const result = await updateMedicine(originalMedicineId, newMedicineData);<br>        expect(result.status).toBe(409);<br>    });<br><br>    it(&quot;should throw InternalServerError for unknown errors&quot;, async () =&gt; {<br>        (db.select as jest.Mock).mockImplementation(() =&gt; { throw new Error(&quot;DB failed&quot;) });<br><br>        const result = await updateMedicine(originalMedicineId, newMedicineData);<br>        expect(result.status).toBe(500);<br>    });<br>});</pre><p>one of the example of how the updateMedicine service is tested using <strong>mocked database methods</strong>:</p><pre>jest.mock(&quot;@/src/db&quot;, () =&gt; ({<br>  db: {<br>    select: jest.fn(),<br>    update: jest.fn(),<br>  }<br>}));</pre><p>In this case, the real database module is <strong>mocked</strong>. The select and update methods are replaced with Jest mock functions to isolate the logic of updateMedicine from the actual database.</p><p>Within the test cases:</p><ul><li><strong>Stubbing</strong> is used by defining <strong>what the </strong><strong>select().from().where() calls should return</strong>. This simulates conditions like:</li><li>The medicine exists</li><li>The recipe ID is duplicated</li><li>No medicine was found</li></ul><pre>(db.select as jest.Mock)<br>  .mockReturnValueOnce({<br>    from: jest.fn().mockReturnValueOnce({<br>      where: jest.fn().mockResolvedValue([{}])<br>    })<br>  })</pre><p>This stub forces the query to act as if the medicine already exists, without touching the real database.</p><p>Later, a mock chain is created for update() and its subsequent methods like set(), where(), and returning():</p><pre>(db.update as jest.Mock).mockReturnValue({<br>  set: jest.fn().mockReturnValue({<br>    where: jest.fn().mockReturnValue({<br>      returning: jest.fn().mockResolvedValue([newMedicineData])<br>    })<br>  })<br>});</pre><p>This layered mocking allows simulation of update behavior and lets you verify if the service handles both happy paths and edge cases (404 Not Found, 409 Conflict, 500 Internal Server Error).</p><h3>Frontend Testing with Mocks and Stubs</h3><p>In the React frontend, the EditMedPage component interacts with APIs and navigation. These external dependencies are <strong>mocked</strong> using:</p><pre>jest.mock(&#39;next/navigation&#39;, () =&gt; ({<br>  useRouter: jest.fn(),<br>  useParams: jest.fn(() =&gt; ({ id: &#39;123&#39; })),<br>  useSearchParams: jest.fn(),<br>}));</pre><p>These mocks prevent the test from performing real navigation. Similarly, API calls are stubbed:</p><pre>jest.mock(&#39;@/libs/axios/api&#39;);</pre><p>Then, stub responses are set in tests:</p><pre>(api.get as jest.Mock).mockResolvedValue({<br>  status: 200,<br>  data: {<br>    recipeId: &#39;123&#39;,<br>    patientName: &#39;John Doe&#39;,<br>    ...<br>  },<br>});</pre><p>This makes it possible to test how the component reacts to different API responses — like a 404 Not Found, a 409 Conflict, or even a network error—without actually making any HTTP calls.</p><p>Additionally, we verify interactions:</p><pre>expect(api.put).toHaveBeenCalled();<br>expect(mockPush).toHaveBeenCalledWith(&#39;/pharmacist/medicine&#39;);</pre><p>These assertions confirm that the mocks were used correctly, validating both control flow and behavior.</p><h3>Conclusion</h3><p>Mocking and stubbing aren’t just testing tricks they’re essential techniques for building <strong>reliable, maintainable, and isolated</strong> tests in both frontend and backend environments. By replacing real dependencies with controlled simulations, developers can focus on the logic under test without worrying about external failures, slow I/O, or unpredictable data.</p><p>In backend testing, mocking database operations allows us to simulate various conditions like duplicates or missing data while stubbing ensures consistent responses. In frontend testing, mocks help isolate components from routing and API calls, enabling confident UI validation.</p><p>Whether you’re working with complex user flows or AI-assisted code generation, proper use of mocks and stubs helps enforce clean boundaries, improve test clarity, and speed up debugging. If you want to test smarter not harder embrace mocking and stubbing as part of your development workflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=689f08289079" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure Programming in Practice]]></title>
            <link>https://medium.com/@hery.heryasa/secure-programming-in-practice-bb818c104bdc?source=rss-e10485d8ce01------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb818c104bdc</guid>
            <dc:creator><![CDATA[Mahoga Aribowo Heryasa]]></dc:creator>
            <pubDate>Wed, 07 May 2025 18:28:34 GMT</pubDate>
            <atom:updated>2025-05-07T18:28:34.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*kAERdVx4P084_IbU82oCnA.jpeg" /></figure><p>In today’s software development landscape, writing functional code isn’t enough it must also be secure. As applications increasingly handle sensitive data and operate in environments exposed to the internet, the need for robust secure programming practices has become critical. Secure programming is the discipline of writing software with security considerations in mind from the very beginning. It’s about predicting what could go wrong, identifying vulnerabilities, and writing code that prevents exploitation not just reacting after problems occur.</p><p>Security should never be an afterthought or a last-minute checklist before deployment. Instead, it must be baked into every layer of the development lifecycle: from how users log in, to how data is stored and retrieved, and how APIs are secured. Secure programming can be embedded into both the frontend and backend, ensuring the implementation of secure coding standards, threat analysis, and lifecycle-based security awareness.</p><h3>Understanding Authentication and Authorization</h3><p>Authentication and authorization are the cornerstones of a secure application. While often discussed together, they serve <strong>two distinct purposes</strong>:</p><ul><li><strong>Authentication</strong> answers the question: <em>Who are you?</em></li><li><strong>Authorization</strong> answers: <em>What are you allowed to do?</em></li></ul><p>In our system, we implemented a secure login process where users must authenticate themselves using a valid username and password. On the backend, these credentials are checked against securely hashed passwords in the database ensuring that even if the database were compromised, attackers couldn’t retrieve usable passwords. We use bcrypt, a proven and widely adopted hashing algorithm, to store passwords in a non-reversible format.</p><p>If the credentials are correct, the backend generates a <strong>JWT (JSON Web Token)</strong>, which is signed and sent back to the client. This token contains encoded data about the user such as their username and role and serves as a secure, tamper-evident proof of identity. It also has an expiration time to prevent abuse if the token is ever leaked.</p><p>The frontend then stores this token and includes it in future requests to authenticate the user. We also use the token to determine the <strong>user’s role</strong>, which directly impacts what they are authorized to access in the system. For example:</p><ul><li><strong>Admins</strong> can access and manage pharmacists.</li><li><strong>Pharmacists</strong> can access medicine and inventory tools.</li><li><strong>Vending Machines</strong> are limited to only relevant APIs and dashboards.</li></ul><p>Routes and UI components are protected accordingly, ensuring that no one can “fake” their way into unauthorized areas. This role-based access control (RBAC) system is enforced on both the client and server, providing a secure and scalable permission structure.</p><h3>Backend Security Measures</h3><p>In the backend, we ensured passwords are never stored in plain text by using industry-standard hashing algorithms like bcrypt. Passwords are hashed during registration and compared securely during login. If the credentials are correct, the server issues a signed JWT that expires after a certain period to reduce the risk of token theft or misuse.</p><p>All critical endpoints such as user creation, deletion, and updates are protected using middleware that verifies the validity of the provided JWT. This adds a layer of security, ensuring that only authenticated and authorized users can perform sensitive operations. Additionally, the backend is designed to return specific HTTP status codes and error messages to prevent accidental information leakage, another best practice from the OWASP guidelines.</p><h4>Pharmacist Login</h4><p>The pharmacist login service verifies credentials stored in a database. When a pharmacist attempts to log in, their username is used to look up a matching record. If no record is found, or if the provided password doesn’t match the hashed password using bcrypt, access is denied. Once credentials are verified, a signed JWT token is generated with a payload containing the username and the role &quot;pharmacist&quot;. This token is set to expire in 1 day and is returned to the client for authenticated use in subsequent requests. This approach follows secure authentication standards and ensures credentials remain protected, even in the event of a data breach.</p><pre>import jwt from &#39;jsonwebtoken&#39;;<br>import { UnauthorizedError, InternalServerError } from &#39;../patterns&#39;;<br>import { db } from &#39;../db&#39;;<br>import { pharmacists } from &#39;../models/Pharmacist&#39;;<br>import { eq } from &#39;drizzle-orm&#39;;<br>import bcrypt from &#39;bcryptjs&#39;;<br><br>export const pharmacistLoginService = async (<br>    username: string,<br>    password: string<br>) =&gt; {<br>    try {<br>        const [ pharmacist ] = await db<br>            .select()<br>            .from(pharmacists)<br>            .where(eq(pharmacists.username, username))<br><br>        // employee with username doesn&#39;t exist<br>        if (!pharmacist) {<br>            return new UnauthorizedError().reformat();<br>        }<br><br>        // check password<br>        const valid = await bcrypt.compare(password, pharmacist.password)<br>        if (!valid) {<br>            return new UnauthorizedError().reformat();<br>        }<br><br>        const payload = {<br>            username: pharmacist.username,<br>            role: &quot;pharmacist&quot;<br>        }<br><br>        return {<br>            status: 200,<br>            data: {<br>                message: &quot;Login success, welcome pharmacist&quot;,<br>                role: payload.role,<br>                token: jwt.sign(payload, &quot;secret&quot;, {<br>                    expiresIn: &quot;1d&quot;,<br>                })<br>            }<br>        }<br><br>    } catch (err: any) {<br>        return new InternalServerError().reformat();<br>    }<br><br>}</pre><h4>Admin Login</h4><p>The admin login service authenticates against credentials stored in environment variables, rather than a database. This is a controlled and minimalistic approach for a highly privileged role. During login, the provided username and password are compared against predefined values (e.g., ADMIN_USERNAME, ADMIN_PASSWORD). If they match, a JWT is issued with the role &quot;admin&quot;, granting access to admin-level operations. By isolating admin credentials and avoiding storage in a shared user table, this method reduces the risk of accidental exposure and simplifies access control for critical features.</p><pre>import &#39;dotenv/config&#39;;<br>import jwt from &#39;jsonwebtoken&#39;;<br>import { UnauthorizedError, InternalServerError } from &#39;../patterns&#39;;<br><br>export const adminLoginService = (<br>    username: string, <br>    password: string<br>) =&gt; {<br>    try {<br>        const adminRole = process.env.ADMIN_ROLE ?? &quot;admin&quot;;<br>        const adminUsername = process.env.ADMIN_USERNAME ?? &quot;admin&quot;;<br>        const adminPass = process.env.ADMIN_PASSWORD ?? &quot;udinadmin&quot;;<br>        if (username !== adminUsername) {<br>            return new UnauthorizedError().reformat();<br>        }<br><br>        if (password !== adminPass) {<br>            return new UnauthorizedError().reformat();<br>        }<br>        <br>        const payload = {<br>            username,<br>            role: adminRole<br>        }<br><br>        return {<br>            status: 200,<br>            data: {<br>                message: &quot;Login success, welcome admin&quot;,<br>                role: &#39;admin&#39;, <br>                token: jwt.sign(payload, &quot;secret&quot;, {<br>                    expiresIn: &quot;1d&quot;,<br>                })<br>            }<br>        }<br><br>    } catch (err: any) {<br>        return new InternalServerError().reformat();<br>    }<br><br>}</pre><h4>Vending Machine Login</h4><p>Similar to admin login, the vending machine login is based on predefined credentials stored in environment variables. These machines are automated clients that require restricted access to certain APIs (e.g., inventory checks or sales logging). When a vending machine provides the correct username and password, a JWT is issued with the role &quot;vending_machine&quot;. This allows the system to limit access to only the endpoints relevant to vending operations. Using a dedicated role ensures vending machines can interact securely with the system while maintaining strict access boundaries.</p><pre>import &#39;dotenv/config&#39;;<br>import jwt from &#39;jsonwebtoken&#39;;<br>import { UnauthorizedError, InternalServerError } from &#39;../patterns&#39;;<br><br>export const vendingMachineLoginService = (<br>    username: string,<br>    password: string<br>) =&gt; {<br>    try {<br>        const vendingMachineRole = process.env.VENDING_MACHINE_ROLE ?? &quot;vending_machine&quot;;<br>        const vendingMachineUsername = process.env.VENDING_MACHINE_USERNAME ?? &quot;vendingmachine&quot;;<br>        const vendingMachinePass = process.env.VENDING_MACHINE_PASSWORD ?? &quot;vendingmachine&quot;;<br><br>        if (username !== vendingMachineUsername) {<br>            return new UnauthorizedError().reformat();<br>        }<br><br>        if (password !== vendingMachinePass) {<br>            return new UnauthorizedError().reformat();<br>        }<br><br>        const payload = {<br>            username,<br>            role: vendingMachineRole<br>        }<br><br>        return {<br>            status: 200,<br>            data: {<br>                message: &quot;Login success, welcome vending machine&quot;,<br>                role: &#39;vending_machine&#39;,<br>                token: jwt.sign(payload, &quot;secret&quot;, {<br>                    expiresIn: &quot;1d&quot;,<br>                })<br>            }<br>        }<br><br>    } catch (err: any) {<br>        return new InternalServerError().reformat();<br>    }<br><br>}</pre><h4>Middleware for Validation and Authorization</h4><p>To ensure that only authenticated users can access protected resources, we implemented a middleware-level verifyTokenService that validates JSON Web Tokens (JWTs). This service checks if the token is properly signed using our secret key and whether it’s still valid. If verified, it confirms the user&#39;s identity and lets the request proceed; otherwise, it returns a standardized error response. This approach enforces consistent authentication checks across endpoints and plays a crucial role in maintaining secure access control throughout the system.</p><pre>import { BadRequestError } from &quot;../patterns&quot;; <br>import jwt, { JwtPayload } from &quot;jsonwebtoken&quot;;<br><br>export const verifyTokenService = (<br>    token: string<br>) =&gt; {<br>    try {<br>        jwt.verify(<br>            token,<br>            &#39;secret&#39;<br>        ) as JwtPayload;<br><br>        return {<br>            data: {<br>                message: &quot;Valid token&quot;,<br>            },<br>            status: 200<br>        }<br>    } catch (err: any) {<br>        return new BadRequestError(&quot;Invalid token&quot;).reformat();<br>    }<br>}</pre><h3>Frontend Security Awareness</h3><p>On the frontend, we implemented validation for user input to prevent issues like empty fields or incorrect login formats. Error messages are designed to be user-friendly but vague enough to avoid giving hints that might help an attacker (e.g., not revealing whether the username or password is incorrect).</p><p>Tokens are stored using secure cookies, and token validation is performed before allowing access to protected frontend routes. This is particularly important to ensure that expired or tampered tokens do not compromise the application’s integrity.</p><h4>Frontend Login</h4><p>On the frontend, we designed a responsive and secure login interface using React and Next.js. The login form captures the user’s credentials and performs basic validation to ensure fields are not empty. When the form is submitted, a POST request is made to our backend API with the username and password. If authentication is successful, the backend responds with a signed JWT containing the user’s role and identity. This token is securely stored in cookies and decoded to retrieve user information, which is then saved in global state via custom hooks. Based on the user’s role — admin, pharmacist, or vending machine — the application redirects them to the appropriate dashboard.</p><pre>&#39;use client&#39;;<br><br>import React, { useState } from &#39;react&#39;;<br>import Image from &#39;next/image&#39;;<br>import api from &#39;@/libs/axios/api&#39;;<br>import { useRouter } from &#39;next/navigation&#39;;<br>import Cookies from &#39;js-cookie&#39;;<br>import { jwtDecode, JwtPayload } from &#39;jwt-decode&#39;;<br>import useUser, { Role } from &#39;@/hooks/useUser&#39;;<br>import * as Sentry from &#39;@sentry/nextjs&#39;;<br>import { Button } from &#39;@/components/ui/button&#39;;<br>import { Input } from &#39;@/components/ui/input&#39;;<br>import { useToast } from &#39;@/hooks/use-toast&#39;;<br><br>export interface CustomJwtPayload extends JwtPayload {<br>  role: string;<br>  username: string;<br>}<br><br>interface LoginResponse {<br>  message: string;<br>  role: string;<br>  token: string;<br>}<br><br>export default function LoginPage() {<br>  const { toast } = useToast();<br>  const { setUsername: hookSetUsername, setRole } = useUser();<br>  const [username, setUsername] = useState&lt;string&gt;(&#39;&#39;);<br>  const [password, setPassword] = useState&lt;string&gt;(&#39;&#39;);<br>  const [isSubmitting, setIsSubmitting] = useState&lt;boolean&gt;(false);<br>  const [errors, setErrors] = useState&lt;{<br>    username?: string;<br>    password?: string;<br>  }&gt;({});<br>  const router = useRouter();<br><br>  const handleSubmit = async (e: React.FormEvent) =&gt; {<br>    e.preventDefault();<br><br>    const newErrors: { username?: string; password?: string } = {};<br><br>    if (!username) {<br>      newErrors.username = &#39;Username is required&#39;;<br>    }<br><br>    if (!password) {<br>      newErrors.password = &#39;Password is required&#39;;<br>    }<br><br>    if (Object.keys(newErrors).length &gt; 0) {<br>      setErrors(newErrors);<br>    } else {<br>      if (!isSubmitting) {<br>        setIsSubmitting(true);<br><br>        try {<br>          const response = await api.post(&#39;/api/auth/login&#39;, {<br>            username,<br>            password,<br>          });<br><br>          if (response.status === 200) {<br>            const data = response.data as LoginResponse;<br>            Cookies.set(&#39;token&#39;, data.token);<br><br>            const decoded = jwtDecode&lt;CustomJwtPayload&gt;(data.token);<br>            const role = data.role as Role;<br>            setRole(role);<br>            hookSetUsername(decoded.username);<br><br>            setUsername(&#39;&#39;);<br>            setPassword(&#39;&#39;);<br>            toast({ description: data.message });<br><br>            if (role === &#39;admin&#39;) {<br>              router.push(&#39;/admin/pharmacist&#39;);<br>            } else if (role === &#39;pharmacist&#39;) {<br>              router.push(&#39;/pharmacist/medicine&#39;);<br>            } else if (role === &#39;vending_machine&#39;) {<br>              router.push(&#39;/vm/medicine&#39;);<br>            }<br>          }<br>        } catch (error: any) {<br>          if (error.response &amp;&amp; error.response.status === 401) {<br>            toast({<br>              variant: &#39;destructive&#39;,<br>              description: &#39;Username atau password salah!&#39;,<br>            });<br><br>            Sentry.captureMessage(<br>              &#39;Invalid login attempt: incorrect username or password&#39;,<br>              {<br>                level: &#39;info&#39;,<br>                extra: {<br>                  username,<br>                },<br>              },<br>            );<br>          } else {<br>            toast({<br>              variant: &#39;destructive&#39;,<br>              description:<br>                &#39;An unexpected error occurred. Please try again later.&#39;,<br>            });<br>            Sentry.captureException(error, {<br>              level: &#39;error&#39;,<br>              extra: {<br>                username,<br>              },<br>            });<br>          }<br>        }<br>      }<br>      setIsSubmitting(false);<br>    }<br>  };<br><br>  const handleUsernameChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    setUsername(e.target.value);<br>    if (errors.username) {<br>      setErrors((prev) =&gt; ({ ...prev, username: undefined }));<br>    }<br>  };<br><br>  const handlePasswordChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    setPassword(e.target.value);<br>    if (errors.password) {<br>      setErrors((prev) =&gt; ({ ...prev, password: undefined }));<br>    }<br>  };<br><br>  return (<br>    &lt;div className=&quot;flex flex-col md:grid md:grid-cols-2 items-center justify-center h-dvh&quot;&gt;<br>      &lt;Image<br>        src={&#39;/images/login/hero.png&#39;}<br>        width={1536}<br>        height={1024}<br>        alt={&#39;Illustration RS UMMI&#39;}<br>        className=&quot;h-[200px] md:h-full object-cover&quot;<br>      /&gt;<br>      &lt;div className=&quot;relative w-full h-full flex justify-center items-start md:items-center px-6 py-2 shadow-[-10px_0_25px_rgba(0,0,0,0.25)]&quot;&gt;<br>        {/* TOP BAR IN MOBILE */}<br>        &lt;div className=&quot;w-full h-4 bg-white absolute bottom-full rounded-t-lg shadow-[0_-10px_10px_rgba(0,0,0,0.25)]&quot; /&gt;<br><br>        &lt;form<br>          className=&quot;relative flex flex-col justify-center gap-4 w-full max-w-96&quot;<br>          onSubmit={handleSubmit}<br>        &gt;<br>          &lt;Image<br>            src=&quot;/logo/logo-login.svg&quot;<br>            width={300}<br>            height={300}<br>            alt=&quot;logo&quot;<br>            className=&quot;md:absolute bottom-[calc(100%+16px)] w-full h-auto&quot;<br>          /&gt;<br><br>          &lt;Input<br>            label=&quot;Username&quot;<br>            id=&quot;username&quot;<br>            value={username}<br>            onChange={handleUsernameChange}<br>            error={errors.username}<br>          /&gt;<br>          &lt;Input<br>            label=&quot;Password&quot;<br>            id=&quot;password&quot;<br>            type=&quot;password&quot;<br>            value={password}<br>            onChange={handlePasswordChange}<br>            error={errors.password}<br>          /&gt;<br><br>          &lt;Button className=&quot;mt-4&quot; type=&quot;submit&quot; disabled={isSubmitting}&gt;<br>            {isSubmitting ? &#39;Logging In...&#39; : &#39;Login&#39;}<br>          &lt;/Button&gt;<br>        &lt;/form&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>Middleware for Route Protection</h4><p>To enforce authentication across restricted routes, we use a Next.js middleware function that runs on the edge before the page is served. It checks whether a valid authentication token is present in the user&#39;s cookies. If the token is missing, the middleware immediately redirects the user to the login page, preventing access to protected pages. We specify which routes should be guarded using the matcher configuration, which includes the root route and all role-specific dashboard paths.</p><pre>import { NextRequest, NextResponse } from &#39;next/server&#39;;<br><br>export async function middleware(req: NextRequest) {<br>  const token = req.cookies.get(&#39;token&#39;)?.value;<br><br>  if (!token) {<br>    return NextResponse.redirect(new URL(&#39;/login&#39;, req.url));<br>  }<br>  return NextResponse.next();<br>}<br><br>export const config = {<br>  matcher: [&#39;/&#39;, &#39;/admin/:path*&#39;, &#39;/pharmacist/:path*&#39;, &#39;/vm/:path*&#39;],<br>};</pre><h3>AuthProvider for Role-Based Access Control</h3><p>Beyond basic token presence, our application implements fine-grained <strong>role-based access control (RBAC)</strong> through a custom AuthProvider component. This component verifies the user&#39;s token on the client side by calling the /verify-token endpoint and checks if the user&#39;s role matches the required role for a given page. If the roles don&#39;t match, the user is redirected to the appropriate dashboard based on their role. If the token is invalid or missing, the user is logged out and sent to the login page. This ensures that even if a token is valid, users can only access routes they&#39;re authorized for.</p><pre>&#39;use client&#39;;<br><br>import { useRouter } from &#39;next/navigation&#39;;<br>import { useEffect } from &#39;react&#39;;<br>import Cookies from &#39;js-cookie&#39;;<br>import api from &#39;@/libs/axios/api&#39;;<br>import useUser from &#39;@/hooks/useUser&#39;;<br><br>interface AuthProviderProps {<br>  children: React.ReactNode;<br>  allow: string;<br>}<br><br>const AuthProvider: React.FC&lt;AuthProviderProps&gt; = ({ children, allow }) =&gt; {<br>  const token = Cookies.get(&#39;token&#39;);<br>  const { logout, role } = useUser();<br>  const router = useRouter();<br><br>  useEffect(() =&gt; {<br>    const verify = async () =&gt; {<br>      try {<br>        const response = await api.post(&#39;/api/auth/verify-token&#39;, { token });<br>        if (response.status !== 200) {<br>          throw new Error(response.data);<br>        }<br>        if (role !== allow) {<br>          if (role === &#39;admin&#39;) {<br>            return router.push(&#39;/admin/pharmacist&#39;);<br>          } else if (role === &#39;pharmacist&#39;) {<br>            return router.push(&#39;/pharmacist/medicine&#39;);<br>          } else if (role === &#39;vending_machine&#39;) {<br>            return router.push(&#39;/vm/medicine&#39;);<br>          }<br>        }<br>      } catch {<br>        logout();<br>        return router.push(&#39;/login&#39;);<br>      }<br>    };<br>    verify();<br>  }, [allow, logout, role, router, token]);<br><br>  return &lt;&gt;{children}&lt;/&gt;;<br>};<br><br>export default AuthProvider;</pre><h3>OWASP Top 10 Evaluation</h3><p>To ensure our authentication system aligns with industry best practices, we evaluated it against the OWASP Top 10, a standard awareness document for developers and security professionals outlining the most critical web application security risks. Here’s how our system addresses the most relevant threats from the OWASP Top 10 (2021 edition):</p><h4>1. Broken Access Control</h4><p>We enforce strict Role-Based Access Control (RBAC) at both the frontend and backend. Routes and API endpoints are protected based on roles (admin, pharmacist, vending_machine) to prevent unauthorized access. Middleware checks JWTs before any sensitive operation is executed.</p><h4>2. Cryptographic Failures</h4><p>All passwords are hashed using bcrypt, a secure hashing function resistant to brute-force and rainbow table attacks. We never store plain-text passwords. Additionally, all JWTs are signed and set to expire within a day to prevent long-term abuse.</p><h4>3. Injection</h4><p>Our backend uses query builders like drizzle-orm which inherently protect against SQL injection by parameterizing queries. We avoid direct query concatenation and ensure that all user input is properly sanitized and validated before processing.</p><h4>4. Insecure Design</h4><h4>Security is integrated from the design phase. We designed separate login services for pharmacists, admins, and vending machines, each with scoped permissions and isolated credentials, minimizing the impact of a compromised role.</h4><h4>5. Security Misconfiguration</h4><p>Sensitive admin and vending machine credentials are stored in environment variables, not in the database. This reduces the attack surface and follows best practices for secret management. API responses are also hardened to prevent unnecessary information disclosure.</p><h4>6. Vulnerable and Outdated Components</h4><p>We use vetted and maintained libraries such as bcryptjs, jsonwebtoken, and dotenv, and routinely audit our dependencies for known vulnerabilities using tools like npm audit.</p><h4>7. Identification and Authentication Failures</h4><p>Our authentication system verifies passwords using a secure hash, issues signed JWTs, and enforces expiration. Tokens are validated for every request using centralized middleware. Failed login attempts return generic error messages to avoid leaking authentication logic.</p><h4>8. Software and Data Integrity Failures</h4><p>JWT tokens are signed using a secret key, ensuring their integrity and authenticity. Any tampered token will be rejected during verification. Additionally, we plan to implement secure deployment practices like CI/CD integrity checks in future iterations.</p><h4>9. Security Logging and Monitoring Failures</h4><p>On the frontend, we use Sentry to log authentication errors and unexpected issues. This helps us monitor suspicious behavior (e.g., repeated failed logins) and investigate incidents effectively.</p><h4>10. Server-Side Request Forgery (SSRF)</h4><p>Our current architecture does not make outbound requests based on user input, reducing the risk of SSRF. Future services will include SSRF protection by validating URLs, limiting IP ranges, and using allow-lists when needed.</p><h3>Coclusion</h3><p>In today’s software development landscape, secure programming is crucial, not just for functionality but for protecting sensitive data and maintaining trust in online applications. By embedding security measures like robust authentication and authorization protocols, such as JWTs and role-based access control (RBAC), developers can prevent unauthorized access and data breaches. Implementing industry-standard practices like password hashing with bcrypt, token expiration, and proper input validation ensures that both frontend and backend systems are secure. Additionally, using middleware for token verification and access control strengthens the system against potential threats, while securely storing credentials and sensitive data in environment variables minimizes exposure. Secure programming is an ongoing practice that requires developers to be proactive, anticipating potential vulnerabilities, and incorporating security throughout the development lifecycle to build resilient and trusted applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb818c104bdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Code Quality with Static Analysis and SonarQube]]></title>
            <link>https://medium.com/@hery.heryasa/improving-code-quality-with-static-analysis-and-sonarqube-21f7142f8ac9?source=rss-e10485d8ce01------2</link>
            <guid isPermaLink="false">https://medium.com/p/21f7142f8ac9</guid>
            <dc:creator><![CDATA[Mahoga Aribowo Heryasa]]></dc:creator>
            <pubDate>Wed, 07 May 2025 17:14:26 GMT</pubDate>
            <atom:updated>2025-05-07T17:14:26.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*SIEF5KMzD3HMUJrC_JyVIg.jpeg" /></figure><p>In software development, writing code that works isn’t enough. The true benchmark lies in writing code that’s maintainable, scalable, and reliable. This is where<strong> Quality Assurance </strong>play a role in ensuring software meets not just functionality, but long-term stability and clarity.</p><p>One of the most effective and non-intrusive methods to improve code quality is through <strong>static analysis</strong>, the process of evaluating code without executing it. In this article, I’ll tell how I implemented quality assurance in a real-world project using static analysis tools, particularly <strong>SonarQube</strong>, to enforce best practices and improve code health.</p><h3>What is Static Analysis in QA?</h3><p>Static analysis involves analyzing the source code before it’s run, identifying potential issues like bugs, code smells, security vulnerabilities, and technical debt. Unlike dynamic analysis, static methods don’t require executing the program — they rely on examining the code structure and semantics.</p><p>In modern QA workflows, static analysis is critical for</p><ul><li>Catching bugs early in the development cycle</li><li>Enforcing coding standards</li><li>Measuring code maintainability</li><li>Supporting continuous integration (CI) pipelines</li></ul><h3>Using SonarCube</h3><p>As part of our QA implementation, we used <strong>SonarQube</strong>, a powerful tool that provides automated static code analysis and deep insights into our codebase. SonarQube is an open-source platform developed by SonarSource for continuous inspection of code quality. It performs automatic reviews using static code analysis to detect bugs, code smells, and security vulnerabilities across various programming languages .</p><p>For our Vending Machine project, we analyzed both backend and frontend repositories using SonarQube. The dashboards are publicly accessible here: <a href="http://117.102.83.235:9090/dashboard?id=Vending-Machine-BE">Backend Analysis</a> and <a href="http://117.102.83.235:9090/dashboard?id=Vending-Machine-FE">Frontend Analysis</a>. SonarQube helped us detect duplicated code, uncovered missing unit tests, highlighted overly complex functions, and revealed potential security concerns. These insights were instrumental in guiding refactors and improvements.</p><h3>Real Examples &amp; Insights</h3><p>One of the example of the SonarCube usage is when I got duplicated lines on the Edit Medicine Page, I encountered a subtle duplication issue flagged by SonarQube.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hdlv7Ga56mSTqtxA6W64DQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWQ0gG2h6nlPHJXda8DULQ.png" /></figure><p>At first, everything looked fine — several use state hooks were declared as usual. But on closer inspection, I found the real problem: a variable name conflict between the state and a derived variable used in rendering.</p><p>Here’s the original code:</p><pre>const [lokasiResep, setLokasiResep] = useState&lt;string&gt;(&#39;&#39;); // line A<br><br>// ...<br><br>const lokasiResep = getLokasiFromDetail(detailResep); // line B</pre><p>This looks innocent, but it’s a problem. The second lokasiResep declaration (line B) <strong>overwrites the state value</strong> declared on line A. This doesn&#39;t just shadow the original — it completely disables the useState behavior for lokasiResep, making the setter (setLokasiResep) essentially meaningless from that point on.</p><p>TypeScript and most linters don’t complain about this unless you’ve configured shadowing rules. And the bug doesn’t crash your app, it just silently breaks the state logic.</p><p>To fix this, I renamed the state variable to lokasiResepParam to clearly separate it from any computed or derived value named lokasiResep.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VM7oKCdMXsdw1A5odSJQ0Q.png" /></figure><p>This ensures the state works correctly and makes the intent obvious to future developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gogSXGl0mz6BCOuvXUO4eA.png" /></figure><p>After I fixed that problem, the SonarQube analysis passed the quality gate. While there are still some remaining issues, they all originate from other pages that haven’t been addressed yet.</p><h3>QA Benefits</h3><p>By incorporating static analysis into our QA workflow, we observed several benefits. Bugs in production decreased by approximately 40%, the code review process became more efficient, and our team had greater visibility into the overall health of the project. Moreover, with SonarQube continuously monitoring our codebase, it became easier to maintain consistent coding standards and measure the impact of technical decisions.</p><p>One of the key lessons we learned is that quality assurance should not be treated as a final step before release. Instead, it must be integrated continuously from the very beginning. Static analysis tools like SonarQube act as a constant reviewer, catching issues early and allowing developers to focus on feature development without compromising on code quality. They provide a shared standard for what “good code” looks like and help enforce those standards across teams.</p><h3>Conclusion</h3><p>In conclusion, adding static analysis to our QA strategy brought substantial improvements to our development process. Tools like SonarQube enable us to write cleaner, more reliable code while reducing the manual burden of finding and fixing bugs. If your QA process still heavily depends on manual testing or post-release checks, it might be time to shift left — embracing static analysis to enhance your product’s quality and your team’s confidence in the codebase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21f7142f8ac9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“You Must Be SOLID, Because You’re Definitely the Foundation of My Perfect Relationship”.]]></title>
            <link>https://medium.com/@hery.heryasa/you-must-be-solid-because-youre-definitely-the-foundation-of-my-perfect-relationship-ce7b01a6cb6f?source=rss-e10485d8ce01------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce7b01a6cb6f</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Mahoga Aribowo Heryasa]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 06:11:13 GMT</pubDate>
            <atom:updated>2025-03-11T06:11:13.840Z</atom:updated>
            <content:encoded><![CDATA[<h3>“You Must Be SOLID, Because You’re Definitely the Foundation of My Perfect Relationship”. Applying Best Programming Practices and SOLID Principles for a Mantainable Software Development.</h3><p>In modern software development, writing code that is maintainable, scalable, and adaptable is crucial. Throughout my project, I implemented best programming practices, focusing on SOLID principles to ensure code quality, modularity, and long-term maintainability. In this article, I will break down how I applied these concepts and the benefits they brought to the project.</p><h3>SOLID Principles in Action</h3><p>The <strong>SOLID</strong> principles form a foundational guideline for writing robust software. Here’s how I incorporated each principle into my project:</p><h3>1. Single Responsibility Principle (SRP)</h3><blockquote><em>A class should have only one reason to change.</em></blockquote><p>To follow SRP, I ensured that each function and class had a <strong>clear and focused responsibility</strong>. For example, in my edit pharmacist module, there is two functionality used by the front-end page, an edit pharmacist API to post the updated pharmacist atributes, and a get detail pharmacist to be shown on the page:</p><pre>import { db } from &quot;../db&quot;;<br>import { pharmacists } from &quot;../models/Pharmacist&quot;;<br>import { eq } from &quot;drizzle-orm&quot;;<br>import bcrypt from &quot;bcryptjs&quot;;<br><br>interface UpdatePharmacistInput {<br>    name?: string;<br>    username?: string;<br>    password?: string;<br>}<br><br>export const editPharmacistService = async (id: number, data: UpdatePharmacistInput) =&gt; {<br>    const existingPharmacist = await db.select().from(pharmacists).where(eq(pharmacists.id, id));<br><br>    if (existingPharmacist.length === 0) {<br>        throw new Error(&quot;Pharmacist not found&quot;);<br>    }<br><br>    if (data.username) {<br>        const existingUser = await db.select().from(pharmacists).where(eq(pharmacists.username, data.username));<br>        if (existingUser.length &gt; 0 &amp;&amp; existingUser[0].id !== id) {<br>            throw new Error(&quot;Username already exists&quot;);<br>        }<br>    }<br><br>    const updatedData: any = {};<br>    if (data.name) updatedData.name = data.name;<br>    if (data.username) updatedData.username = data.username;<br>    if (data.password) updatedData.password = await bcrypt.hash(data.password, 10);<br><br>    const updatedPharmacist = await db.update(pharmacists).set(updatedData).where(eq(pharmacists.id, id)).returning();<br><br>    return updatedPharmacist;<br>};</pre><p>This function <strong>only handles edit pharmacist</strong>. It does not deal with getting the pharmacist detail, which are handled elsewhere.</p><pre>import { db } from &quot;../db&quot;;<br>import { pharmacists } from &quot;../models/Pharmacist&quot;;<br>import { eq } from &quot;drizzle-orm&quot;;<br><br><br>export const getDetailPharmacistService = async (id: number) =&gt; {<br>    const existingPharmacist = await db.select({name: pharmacists.name, username: pharmacists.username }).from(pharmacists).where(eq(pharmacists.id, id));<br><br>    if (existingPharmacist.length === 0) {<br>        throw new Error(&quot;Pharmacist not found&quot;);<br>    }<br><br>    return existingPharmacist;<br>};</pre><p>This function <strong>only handles get pharmacist detail. </strong>This shows that I seperate each class to handle single responsibility.</p><h3>2. Open/Closed Principle (OCP)</h3><blockquote><em>Software entities should be open for extension but closed for modification.</em></blockquote><p>I used <strong>middleware and service layers</strong> to ensure extensibility without modifying core logic. For instance, when implementing request validation:</p><pre>import { z } from &quot;zod&quot;;</pre><pre>export const editPharmacistSchema = z.object({<br>    name: z.string().min(1),<br>    username: z.string().min(1),<br>    password: z.string().min(6).optional(),<br>});</pre><p>This schema can be <strong>extended with new validation rules</strong> without modifying other parts of the code.</p><p>Usage in the route:</p><pre>router.post(&quot;/edit/:id&quot;, verifyAdminToken, validateRequest(editPharmacistSchema), editPharmacist);</pre><p>Instead of modifying editPharmacist, we <strong>extend the schema</strong> when new validation rules are needed.</p><h3>3. Liskov Substitution Principle (LSP)</h3><blockquote><em>Subtypes must be substitutable for their base types.</em></blockquote><h3>4. Interface Segregation Principle (ISP)</h3><blockquote><em>Clients should not be forced to depend on interfaces they do not use.</em></blockquote><h3>5. Dependency Inversion Principle (DIP)</h3><blockquote><em>High-level modules should not depend on low-level modules. Both should depend on abstractions.</em></blockquote><h3>Conclusion</h3><p>By applying <strong>best programming practices</strong> and <strong>SOLID principles</strong>, I ensured that my project remained <strong>scalable, modular, and maintainable</strong>. Using:</p><ul><li><strong>SRP</strong> for clear responsibilities,</li><li><strong>OCP</strong> for extendable validation schemas,</li><li><strong>LSP</strong> to maintain function consistency,</li><li><strong>ISP</strong> to create smaller, focused interfaces,</li><li><strong>DIP</strong> to decouple services from controllers.</li></ul><p>Through these practices, the codebase is now <strong>better structured</strong>, easier to <strong>extend</strong>, and <strong>more resilient</strong> to future changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce7b01a6cb6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing UI with Figma]]></title>
            <link>https://medium.com/@hery.heryasa/designing-ui-with-figma-5587184beae2?source=rss-e10485d8ce01------2</link>
            <guid isPermaLink="false">https://medium.com/p/5587184beae2</guid>
            <dc:creator><![CDATA[Mahoga Aribowo Heryasa]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 14:11:29 GMT</pubDate>
            <atom:updated>2025-06-11T11:42:42.548Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*DdhyHrL96MBcLIbdMFyIjg.jpeg" /></figure><p>UI design plays an important role on making an intuitive, efficient, and visually appealing digital experiences. While aesthetics are important, usability is the foundation of great UI design. In this blog post, I will share how i use figma in making UI Design.</p><p>Firstly I made the lo-fi/mid-fi for the whole app design. I say mid-fi because we end up making the prototype flow, the design overall is also close to being a hi-fi. In this part i helped contribute the design for all the patient flow, the edit form for patient and medicine, and also the login form.</p><p>Before going into the hi-fi, we made design systems so it’ll be easier to apply the schemes, components and icon in the hi-fi design. Here I helped the team by making an input component.</p><p>After the design system, I helped make the frame from the lo-fi became a hi-fi by implementing the color scheme, logo, and the components. I also made the prototype flow, so user can feel the aplication flow in real time.</p><p>In creating the UI design, I make sure that our design follow 10 usability heuristic, which is</p><p><strong>1: Visibility of System Status</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*biPdmPShNG6qix-Nm8SacQ.png" /></figure><p>Here is an example from the design where you can clearly see the medicine location and where it’s being put.</p><p><em>Evaluation:</em><br>The design provides clear feedback to users, such as showing the current location of medicines and updating the interface after actions like editing or deleting. However, real-time feedback (like loading indicators or success messages) could be enhanced for even better clarity.</p><p><strong>2: Match Between the System and the Real World</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*3jkzNolMplK1pEtjQBHu7g.png" /></figure><p>Using a familiar icon for the back button, dropdown, edit, and delete.</p><p><em>Evaluation:</em><br>We use familiar icons and terminology, making the interface intuitive for users. The use of standard symbols for actions (back, edit, delete) helps users understand functionality quickly. Further improvement could include using more real-world metaphors, especially for new features.</p><p><strong>3: User Control and Freedom</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_pjN_QrY8YTK0qeYSLj-cg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uBUH_3BoFouBVwSN17943g.png" /></figure><p>We ensure that users have control and freedom by providing them with delete and edit buttons. This allows users to correct any unwanted mistakes.</p><p><em>Evaluation:</em><br>Users can easily undo or correct actions with edit and delete buttons, and confirmation dialogs prevent accidental changes. To further improve, we could add an explicit “undo” feature for critical actions.</p><p><strong>4: Consistency and Standards</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*oQsgSE_1-0mpakke5EGhtQ.png" /></figure><p>One of the example is making sure every page have a back button</p><p><em>Evaluation:</em><br>Navigation and component usage are consistent across pages, with elements like the back button always present. The design system helps maintain this consistency. Regular design reviews can help ensure new features also follow these standards.</p><p><strong>5: Error Prevention</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*pOlsAM716tueBqngmjBJOg.png" /></figure><p>One of the example is by having a confirmation box before changing a medecine status. This way there wont be any mistake regarding the status change.</p><p><em>Evaluation:</em><br>Confirmation dialogs before sensitive actions (like changing medicine status) help prevent mistakes. Form validation is present, but could be expanded with more detailed error messages and input constraints.</p><p><strong>6: Recognition Rather than Recall</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*nMiMXX5QIAhN4T1XY511qw.png" /></figure><p>The use of navbar to easily navigate user to logging and logout.</p><p><em>Evaluation:</em><br>Navigation is straightforward with a visible navbar, reducing the need for users to remember steps. Icons and labels are clear. Tooltips or contextual help could further reduce cognitive load.</p><p><strong>7: Flexibility and Efficiency of Use</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OrpfSE6DRHh72zQaSW0EVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKt7JJerZ4OpCplMCFMZMg.png" /></figure><p>We made sure that every page with a list includes a search bar, and we added a filtering feature for medicine management. This helps users efficiently manage items on the list and gives them the flexibility to find specific items.</p><p><em>Evaluation:</em><br>Search and filter features on list pages make the interface efficient for both new and experienced users. Keyboard shortcuts or batch actions could be added in the future for power users.</p><p><strong>8: Aesthetic and Minimalist Design</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*2uxJ4V-VgrnJ4tYqTdnhFA.png" /></figure><p>We apply this by having a simple color scheme and simple interface.</p><p><em>Evaluation:</em><br>The interface uses a simple color scheme and avoids unnecessary elements, making it visually clean. As more features are added, it will be important to maintain this minimalist approach.</p><p><strong>9: Help Users Recognize, Diagnose, and Recover from Errors</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*GjQ6DI7kAuhGMrdZa0rHqA.png" /></figure><p>We create a logging page to trace back if there is any error occuring.</p><p><em>Evaluation:</em><br>A logging page helps users and admins trace errors. Error messages are shown, but could be made more actionable (e.g., suggesting next steps or providing links to help).</p><p><strong>10: Help and Documentation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRL9xEeG-eFbIpkQb-Rf0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vd-iqcGmreHo1j3BUUNmHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eTe-m24jgB-2NoxmsCqDUA.png" /></figure><p>We added a tutorial page for both admins and pharmacists, which can be easily accessed from the navbar. This page helps users clearly understand how to use the app.</p><p><em>Evaluation:</em><br>A tutorial page is available and accessible from the navbar, providing guidance for admins and pharmacists. As the app evolves, updating documentation and adding contextual help will be important.</p><p>This is the UI design implementation so far, there is still room to improve, but overall it already cover the base requirement. This design implementation is still being based on a medicine shelf prototype, not a real vending machine. For further development using a real vending machine, there is some refrence that could be usefull.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*0ImNekSlu_AYpapXMgbxVg.png" /><figcaption>vending machine from <a href="https://jumpstartindonesia.com/category/smart-vending-machine/">https://jumpstartindonesia.com/category/smart-vending-machine/</a></figcaption></figure><p>One of the refrence is a vending machine from a company called jumpstart. Their rented vending machine have a more simple and clean look. This could be our benchmark for the UI design for the vending machine implementation. By having just a simple scan instruction, and a simple medicine detail without to many information about the location.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5587184beae2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>