<?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 I Made Surya Anahata Putra on Medium]]></title>
        <description><![CDATA[Stories by I Made Surya Anahata Putra on Medium]]></description>
        <link>https://medium.com/@suryata?source=rss-2137f06b09d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3YuDOT6H9aKOxayJYM0nYg.jpeg</url>
            <title>Stories by I Made Surya Anahata Putra on Medium</title>
            <link>https://medium.com/@suryata?source=rss-2137f06b09d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:11:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suryata/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[Untangling the Logging Spaghetti: How We Built a Sustainable Logger from the Ground Up]]></title>
            <link>https://medium.com/@suryata/untangling-the-logging-spaghetti-how-we-built-a-sustainable-logger-from-the-ground-up-494106fad467?source=rss-2137f06b09d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/494106fad467</guid>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[I Made Surya Anahata Putra]]></dc:creator>
            <pubDate>Tue, 27 May 2025 15:17:23 GMT</pubDate>
            <atom:updated>2025-05-27T16:03:09.223Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aP0lYAb0LkKpr0C-opH2qg.png" /></figure><p>Have you ever opened a codebase and found yourself lost in a maze of duplicated logic, inconsistent patterns, and tangled dependencies? That sinking feeling when you realize you need to add a new feature but can’t find a clean entry point? We faced this exact situation with our logging system. What started as a simple set of utility functions had grown into an unwieldy mess as our application expanded. This is the story of how we transformed our logging spaghetti into a robust, maintainable architecture using thoughtful design patterns and following engineering best practice.</p><h3><strong>The Challenge: Chaotic Logger Creation and Management</strong></h3><p>Recently, we faced a challenge in our project when our client requested a new feature to analyze salary slips, which would require yet another logging system. Our codebase needed to grow to accommodate this new functionality, but our existing architecture wasn’t designed for this expansion.</p><p>Looking at our existing code, I realized our approach to logging wasn’t sustainable. We had two major problems: scattered logger creation logic and inconsistent usage patterns across our application:</p><pre>// Problem 1: Scattered instantiation logic everywhere<br>// In invoice service<br>const invoiceLogger = new InvoiceLogger();<br><br>// In purchase order service  <br>const poLogger = new PurchaseOrderLogger();<br><br>// In PDF service<br>const pdfLogger = new DecryptLogger();<br><br>// Problem 2: Repeated conditional logic in utility files<br>let logger;<br>if (documentType === &#39;invoice&#39;) {<br>  logger = new InvoiceLogger();<br>} else if (documentType === &#39;purchase-order&#39;) {<br>  logger = new PurchaseOrderLogger();<br>} else {<br>  // What logger should we use?<br>  logger = new GenericLogger();<br>}</pre><p><strong>The core problems were becoming critical:</strong></p><p><strong>1.</strong> <strong>Tight Coupling</strong>: Services had to know about specific logger classes and import them directly</p><p><strong>2.</strong> <strong>Scattered Creation Logic</strong>: The same if-else logic for choosing loggers appeared in multiple files</p><p><strong>3.</strong> <strong>Maintenance Nightmare</strong>: Adding a new logger type required changes in multiple places across the codebase</p><p><strong>4.</strong> <strong>Inconsistency</strong>: Different parts of the app created loggers differently, leading to unpredictable behavior</p><p><strong>5.</strong> <strong>Error-Prone</strong>: Easy to forget importing the right logger class or using the wrong one</p><h3><strong>Refactoring: What Is It, Really?</strong></h3><p>If you’re new to software development or unfamiliar with the term “refactoring,” here’s a simple explanation. Martin Fowler, one of the pioneers in this field, defines refactoring as</p><blockquote><em>”the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure.”</em></blockquote><p>In other words, refactoring is like renovating a house while ensuring all the light switches still work, the water still runs, and everything looks the same from the outside. You’re making the internal structure better — fixing the plumbing, rewiring, reinforcing the foundation — without changing what the house does or how people interact with it.</p><p><strong>The primary goals of refactoring are to:</strong></p><p><strong>-</strong> Make code easier to understand</p><p><strong>-</strong> Make it easier to add new features</p><p><strong>-</strong> Reduce bugs and errors</p><p><strong>-</strong> Improve performance (sometimes)</p><p><strong>-</strong> Make the code more maintainable in the long run</p><p><strong>What refactoring is <em>not</em>:</strong></p><p><strong>-</strong> Adding new features</p><p><strong>-</strong> Fixing bugs (though it often makes bugs easier to find)</p><p><strong>-</strong> Complete rewrites of systems</p><p>With that understanding in place, let’s look at our strategy for tackling the logging system.</p><h3><strong>The Refactoring Strategy</strong></h3><p>I decided to refactor our logging system to be more maintainable and extensible. The goals were to:</p><p><strong>1.</strong> Eliminate code duplication</p><p><strong>2.</strong> Make it easy to add logging for new document types</p><p><strong>3.</strong> Ensure consistent logging behavior across the application</p><h3><strong>The Factory Pattern: A Solution for Object Creation</strong></h3><p>After analyzing the challenges we faced, it became clear that we needed a proven solution rather than reinventing the wheel. The <strong>Factory Pattern</strong> emerged as the perfect fit for our logging system architecture. This creational design pattern provides an elegant way to create objects without specifying the exact class of object that will be created, giving us the flexibility and maintainability we desperately needed.</p><h4><strong>What is the Factory Pattern?</strong></h4><p>The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*EiuWMKYzWX_1cTKEKuwCRg.png" /><figcaption>Factory Pattern Illustration — Refactoring Guru</figcaption></figure><p>To understand this pattern better, let’s look at the illustration above. The diagram shows a perfect real-world analogy: a logistics company that needs to deliver packages. The <em>Transport</em> interface defines a common <em>delivery()</em> method that all transportation types must implement. However, depending on the delivery requirements, the factory creates either a <em>Truck</em> (for land delivery in a box) or a <em>Ship</em> (for sea delivery in a container).</p><p>Notice how the client code doesn’t need to know whether it’s getting a truck or a ship — it just calls the <em>delivery()</em> method. The factory handles the complexity of deciding which concrete class to instantiate based on the delivery requirements. This is exactly what makes the Factory Pattern so powerful: <strong>it encapsulates object creation logic while providing a uniform interface</strong>.</p><p>In our logging context, instead of scattering logger creation logic throughout our codebase, we centralized it in a factory that knows exactly which logger to create based on the document type. Just like the logistics company doesn’t expose the complexity of choosing between trucks and ships, our <em>LoggerFactory</em> doesn’t expose the complexity of choosing between <em>InvoiceLogger </em>or<em> PurchaseOrderLogger.</em></p><h4><strong>Our Factory Pattern Implementation</strong></h4><p>Here’s how we implemented the Factory Pattern to solve these issues:</p><pre>class LoggerFactory {<br>  static createLogger(documentType) {<br>    switch (documentType.toLowerCase()) {<br>      case &#39;invoice&#39;:<br>        return InvoiceLogger.getInstance();<br>      case &#39;purchase-order&#39;:<br>        return PurchaseOrderLogger.getInstance();<br>      default:<br>        throw new Error(`Unknown document type: ${documentType}`);<br>    }<br>  }<br>}</pre><p><strong>Code Explanation:</strong></p><p><strong>-</strong> <strong>Static Method</strong>: We use <em>static createLogger()</em> so the factory can be called without instantiating the class, making it easily accessible throughout the application</p><p><strong>-</strong> <strong>Input Parameter</strong>: The <em>documentType</em> parameter is the only information the factory needs to decide which logger to create</p><p><strong>-</strong> <strong>Case Normalization</strong>: <em>toLowerCase() </em>ensures the factory works regardless of input casing (invoice, INVOICE, Invoice all work)</p><p><strong>-</strong> <strong>Singleton Integration</strong>: Each case calls g<em>etInstance()</em> to ensure we get the same logger instance for each document type</p><p><strong>-</strong> <strong>Error Handling</strong>: The <em>default</em> case throws a descriptive error for unsupported document types, making debugging easier</p><h4><strong>The Factory Pattern in Action</strong></h4><p>Now, anywhere in our application, we can get the appropriate logger with a simple, consistent interface:</p><pre>// In invoice processing service<br>const logger = LoggerFactory.createLogger(&#39;invoice&#39;);<br>logger.logUploadStart(invoiceId, partnerId, filename);<br><br>// In purchase order service<br>const logger = LoggerFactory.createLogger(&#39;purchase-order&#39;);<br>logger.logProcessingStart(purchaseOrderId);</pre><p><strong>Code Explanation:</strong></p><p><strong>-</strong> <strong>Uniform Interface</strong>: Notice how all services use the exact same pattern: <em>LoggerFactory.createLogger(type)</em>— this consistency reduces cognitive load for developers</p><p><strong>-</strong> <strong>No Direct Instantiation</strong>: Services never call <em>new InvoiceLogger()</em> directly, which means they don’t need to know about specific logger classes</p><p><strong>-</strong> P<strong>olymorphism in Action</strong>: Each logger returned has different specialized methods (<em>logUploadStart</em> vs l<em>ogProcessingStart</em>), but they all extend the same base functionality</p><p><strong>-</strong> <strong>Location Independence</strong>: This code can be in any service file, and it will always work the same way — the factory handles all the complexity</p><h3><strong>Adding New Document Types: The Real Test</strong></h3><p>When our client requested salary slip processing, adding support was incredibly simple:</p><pre>// 1. Create the new logger class<br>class SalarySlipLogger extends BaseLogger {<br>  constructor() {<br>    super(&#39;salary-slip-service&#39;, &#39;salary-slip&#39;);<br>  }<br>  <br>  static getInstance() {<br>    if (!SalarySlipLogger.instance) {<br>      SalarySlipLogger.instance = new SalarySlipLogger();<br>    }<br>    return SalarySlipLogger.instance;<br>  }<br>}<br><br>// 2. Add one line to the factory<br>class LoggerFactory {<br>  static createLogger(documentType) {<br>    switch (documentType.toLowerCase()) {<br>      case &#39;invoice&#39;:<br>        return InvoiceLogger.getInstance();<br>      case &#39;purchase-order&#39;:<br>        return PurchaseOrderLogger.getInstance();<br>      case &#39;salary-slip&#39;:  // &lt;- Only change needed!<br>        return SalarySlipLogger.getInstance();<br>      default:<br>        throw new Error(`Unknown document type: ${documentType}`);<br>    }<br>  }<br>}<br><br>// 3. Use it immediately in services<br>const logger = LoggerFactory.createLogger(&#39;salary-slip&#39;);<br>logger.logAnalysisStart(slipId, employeeId);</pre><p><strong>Step-by-step breakdown:</strong></p><p><strong>1.</strong> <strong>New Logger Creation</strong>: We follow the same pattern as existing loggers — extend <em>BaseLogger</em>, implement singleton pattern, and add specialized methods</p><p><strong>2.</strong> <strong>Factory Update</strong>: Only one line needs to be added to the factory’s switch statement — no changes to existing cases or any other code</p><p><strong>3.</strong> <strong>Immediate Usage</strong>: Any service can now request a salary slip logger using the same factory interface, and it works immediately</p><p><strong>4.</strong> <strong>Zero Breaking Changes</strong>: All existing code continues to work exactly as before — the factory pattern’s extensibility shines here</p><p>That’s it! No changes to existing services, no hunting through the codebase for logger creation logic, no risk of breaking existing functionality.</p><h3><strong>Advanced Factory Considerations</strong></h3><h4><strong>Error Handling</strong></h4><p>Our factory includes robust error handling for unknown document types:</p><pre>default:<br>  throw new Error(`Unknown document type: ${documentType}. Supported types: invoice, purchase-order, pdf, salary-slip`);</pre><p>This makes debugging much easier when someone tries to use an unsupported document type.</p><h4><strong>Extensibility</strong></h4><p>The factory pattern makes our system highly extensible. We could easily enhance it to:</p><pre>class LoggerFactory {<br>  static createLogger(documentType, options = {}) {<br>    const logger = this.getBaseLogger(documentType);<br>    <br>    if (options.enableDebug) {<br>      return new DebugLoggerDecorator(logger);<br>    }<br>    <br>    if (options.enableMetrics) {<br>      return new MetricsLoggerDecorator(logger);<br>    }<br>    <br>    return logger;<br>  }<br>}</pre><p><strong>Advanced features explained:</strong></p><p><strong>-</strong> <strong>Options Parameter</strong>: Allows optional configuration without changing the core interface</p><p><strong>-</strong> <strong>Decorator Pattern Integration</strong>: Shows how Factory Pattern can work with other patterns to add functionality</p><p><strong>-</strong> <strong>Conditional Enhancement</strong>: Based on options, we can wrap the base logger with additional capabilities</p><p><strong>-</strong> <strong>Backward Compatibility</strong>: Existing code calling <em>createLogger(‘invoice’)</em> continues to work unchanged</p><h3><strong>Why the Factory Pattern Was Perfect for Our Use Case</strong></h3><p>The Factory Pattern solved our specific challenges because:</p><p><strong>1.</strong> <strong>Document-Type Polymorphism</strong>: We needed different logger behaviors for different document types, but wanted to treat them uniformly</p><p><strong>2.</strong> <strong>Future-Proofing</strong>: We knew more document types would be added, and the factory makes this trivial</p><p><strong>3.</strong> <strong>Configuration Isolation</strong>: Each logger type has specific configuration needs, and the factory encapsulates this knowledge</p><p><strong>4.</strong> <strong>Testing</strong>: The factory makes it easy to inject mock loggers for testing different document types</p><h4><strong>Performance Impact</strong></h4><p>The Factory Pattern actually improved our performance:</p><p><strong>-</strong> <strong>Reduced Memory</strong>: No duplicate logger instances</p><p><strong>-</strong> <strong>Faster Initialization</strong>: Loggers are created only when needed</p><p><strong>-</strong> <strong>Better Caching</strong>: The factory can implement caching strategies transparently</p><h4><strong>When NOT to Use the Factory Pattern</strong></h4><p>The Factory Pattern isn’t always the right choice. Avoid it when:</p><p><strong>-</strong> You only have one type of object to create</p><p><strong>-</strong> The creation logic is very simple and unlikely to change</p><p><strong>-</strong> You need very specific control over object construction</p><p><strong>-</strong> The overhead of the factory outweighs its benefits</p><p>In our case, with multiple logger types and the certainty of future expansion, the Factory Pattern was the ideal solution.</p><h3><strong>Before vs After: Visualizing the Refactoring</strong></h3><p>Let’s look at the before and after structure:</p><h4><strong>Before: Simple But Problematic</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HR6coV_q8S1Hm6B7X8fGBQ.png" /><figcaption>Logger architecture before refactoring</figcaption></figure><h4><strong>After: Structured and Scalable</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4inLwv55zRbbSzhj-CKfA.png" /><figcaption>Logger architecture after refactoring</figcaption></figure><p>Looking at these diagrams, you might think:</p><blockquote>“Wait, this looks more complicated than before! Why would we add more classes and relationships when the original implementation was so simple?”</blockquote><p>Indeed, at first glance, the refactored version might seem unnecessarily complex. However, this complexity is deliberate and brings important benefits:</p><p><strong>1.</strong> <strong>Common behavior is defined once</strong> in the BaseLogger</p><p><strong>2.</strong> <strong>Each document type only implements what’s unique</strong> to it</p><p><strong>3.</strong> <strong>Adding new document types is straightforward</strong></p><p><strong>4.</strong> <strong>The system is easier to extend </strong>without modifying existing code</p><p>Think of it as the difference between a quick temporary fix and a thoughtful, architectural solution. The initial implementation was quick to write but would lead to long-term maintenance challenges. The refactored version required more upfront design but provides a solid foundation for future growth.</p><h3><strong>Was This Refactoring Worth It?</strong></h3><h4><strong>Benefits in Maintainability</strong></h4><p><strong>1.</strong> <strong>DRY (Don’t Repeat Yourself)</strong>: Common logging functionality is now in one place</p><p><strong>2.</strong> <strong>Single Responsibility Principle</strong>: Each class has a clear, focused purpose</p><p><strong>3.</strong> <strong>Open/Closed Principle</strong>: The system is open for extension (new document types) but closed for modification (base functionality)</p><p><strong>4.</strong> <strong>Easier Debugging</strong>: Consistent logging format makes logs easier to parse and analyze</p><h4><strong>Performance Considerations</strong></h4><p>While the primary goal was improved maintainability, there are some performance aspects worth noting:</p><p><strong>1.</strong> <strong>Memory Usage</strong>: The singleton pattern ensures we don’t create unnecessary logger instances</p><p><strong>2.</strong> <strong>Initialization Cost</strong>: Loggers are only created when needed (lazy initialization)</p><p><strong>3.</strong> <strong>No Significant Overhead</strong>: The additional abstraction layers add minimal runtime overhead</p><h4><strong>Is There a Downside?</strong></h4><p>The main trade-off is increased complexity in the codebase. We now have more classes and relationships to understand. However, this complexity is organized and documented, making it manageable for developers.</p><h3><strong>Conclusion: A Strategic Investment</strong></h3><p>Refactoring our logging system was more than just an academic exercise in applying design patterns. It was a strategic investment in the long-term health of our codebase.</p><p>The introduction of <em>BaseLogger</em>, specialized Singleton loggers (<em>InvoiceLogger</em>, <em>PurchaseOrderLogger</em>), and a <em>LoggerFactory </em>has led to:</p><ul><li>Clearer, more expressive service code.</li><li>Easier maintenance of logging features.</li><li>More consistent and analysable log output.</li><li>Better alignment with SOLID principles.</li></ul><p>While there’s always a cost to refactoring, in this instance, the benefits in terms of reduced developer friction, improved code clarity, and enhanced maintainability far outweigh the effort. It’s a testament to how thoughtful application of design patterns can address real-world challenges in a growing enterprise application. This wasn’t about chasing performance metrics but about building a more robust and developer-friendly system — and that, in itself, is a huge win.</p><p>What refactoring stories do you have? Have you used these design patterns in your work? Share your experiences through the comments bellow!</p><h4><strong>Further Reading</strong></h4><p>For those interested in learning more about the design patterns and refactoring techniques used in this project:</p><p><strong>1.</strong> <strong>Martin Fowler’s Resources</strong></p><p><strong>-</strong> Fowler, M. (2018). <em>Refactoring: Improving the Design of Existing Code (2nd Edition)</em>. Addison-Wesley Professional.</p><p><strong>-</strong> <strong>[</strong>Martin Fowler’s website<strong>](</strong>https://martinfowler.com/<strong>)</strong> — Particularly his articles on refactoring and design patterns</p><p><strong>2.</strong> <strong>Design Patterns</strong></p><p><strong>-</strong> <strong>[</strong>Refactoring Guru<strong>](</strong>https://refactoring.guru/<strong>)</strong> — Excellent visual explanations of the Singleton, Factory, Adapter, and Inheritance patterns we used</p><p>These resources were instrumental in guiding our refactoring approach and provide practical insights for similar challenges you might face in your projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=494106fad467" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Skeptic to Believer: How SOLID Slashed Our Code Duplication by Over 50%]]></title>
            <link>https://medium.com/@suryata/beyond-theory-how-solid-principles-rescued-our-codebase-from-a-54-duplication-crisis-2c707e9eda88?source=rss-2137f06b09d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c707e9eda88</guid>
            <dc:creator><![CDATA[I Made Surya Anahata Putra]]></dc:creator>
            <pubDate>Mon, 05 May 2025 17:06:00 GMT</pubDate>
            <atom:updated>2025-05-13T02:29:45.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eEZXa3JMshVSxmy2" /></figure><h4>The “Just Make It Work” Trap</h4><p>In software development, the “just make it work” approach is a tempting shortcut. We’ve all been there, pushing to finish features quickly and moving on to the next task. But as our financial document processing system grew, this approach led to a significant problem: <strong>54% code duplication</strong> in critical components.</p><p>This blog post tells the story of how we transformed our troublesome logging system by applying SOLID principles, and the remarkable impact it had on our codebase’s maintainability and extensibility.</p><h4>When Quality Gates Sound the Alarm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMFKYBwPLAqr7MvFVJxKWw.png" /><figcaption><em>Failed quality gate alarm showing 9.1% duplicated lines</em></figcaption></figure><p>Our journey began with a failed quality gate. Our code quality dashboard flashed a glaring red “Failed” notification — our codebase had 9.1% duplicated lines, far above the acceptable 3.0% threshold.</p><p>Looking deeper, two files stood out as the main reason:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gI1ropqJobchzrW-PnvZ2g.jpeg" /><figcaption>The two problematic files with high duplication</figcaption></figure><p><strong>-</strong> <strong>`</strong>src/services/purchaseOrder/purchaseOrderLogger.js<strong>`</strong> (54.0% duplicated lines)</p><p><strong>-</strong> <strong>`</strong>src/services/invoice/invoiceLogger.js<strong>`</strong> (32.7% duplicated lines)</p><p>These loggers were practically twins with different names. While duplication might seem harmless initially, it’s actually a ticking time bomb in any codebase:</p><p><strong>-</strong> When a bug appears in one logger, it’s likely present in the other too</p><p><strong>-</strong> When one logger gets improved, the other falls behind</p><p><strong>-</strong> When business requirements change, multiple implementations need updating</p><p><strong>-</strong> When new developers join the team, they must decipher the subtle differences</p><h4>Why SOLID Principles Matter</h4><p>SOLID principles often seem like abstract theory taught in software engineering courses and promptly forgotten. Many developers question whether they’re worth the effort in real-world applications.</p><p>But as Robert C. Martin (“Uncle Bob”) intended, these principles exist to create software that is:</p><p><strong>-</strong> Easy to understand</p><p><strong>-</strong> Easy to maintain</p><p><strong>-</strong> Easy to extend</p><p><strong>-</strong> Easy to test</p><p>Let’s briefly review what the SOLID acronym means:</p><p><strong>S — Single-responsibility Principle</strong>: A class should have only one reason to change.</p><p><strong>O — Open-closed Principle</strong>: Software entities should be open for extension but closed for modification.</p><p><strong>L — Liskov Substitution Principle</strong>: Objects of a superclass should be replaceable with objects of subclasses without affecting program correctness.</p><p><strong>I — Interface Segregation Principle</strong>: No client should be forced to depend on methods it doesn’t use.</p><p><strong>D — Dependency Inversion Principle</strong>: High-level modules should not depend on low-level modules. Both should depend on abstractions.</p><h4>The Logger Duplication Problem</h4><p>Let’s look at the concrete problem we faced. Our financial document processing application handles two primary document types: invoices and purchase orders. Initially, separate logging systems were created for each:</p><pre>class InvoiceLogger {<br>  static logUploadStart(invoiceId, partnerId, filename) {<br>    logger.info(&#39;Invoice upload initiated&#39;, {<br>      invoiceId, partnerId, filename, event: &#39;UPLOAD_START&#39;<br>    });<br>  }<br>  <br>  static logUploadSuccess(invoiceId, s3Url) {<br>    logger.info(&#39;Invoice uploaded to S3&#39;, {<br>      invoiceId, s3Url, event: &#39;UPLOAD_SUCCESS&#39;<br>    });<br>  }<br>  <br>  // ...and many more similar methods<br>}<br><br>// In purchaseOrderLogger.js (almost identical code!)<br>class PurchaseOrderLogger {<br>  static logUploadStart(purchaseOrderId, partnerId, filename) {<br>    logger.info(&#39;Purchase order upload initiated&#39;, {<br>      purchaseOrderId, partnerId, filename, event: &#39;UPLOAD_START&#39;<br>    });<br>  }<br>  <br>  static logUploadSuccess(purchaseOrderId, s3Url) {<br>    logger.info(&#39;Purchase order uploaded to S3&#39;, {<br>      purchaseOrderId, s3Url, event: &#39;UPLOAD_SUCCESS&#39;<br>    });<br>  }<br>  <br>  // ...and many more similar methods<br>}</pre><p>This might look innocent enough, but the duplication is obvious — the only real differences are terminology (“invoice” vs “purchase order”) and the field names.</p><h4>To SOLID or Not to SOLID?</h4><p>Before applying SOLID principles, we asked an important question: Is this complexity justified?</p><p>Not every piece of code needs to follow SOLID principles strictly. For very simple utilities or functions that are unlikely to change, over-engineering can be counterproductive.</p><p>We considered these factors:</p><p><strong>1.</strong> <strong>Change frequency</strong>: How often will we need to modify the logging behavior?</p><p><strong>2.</strong> <strong>Extension requirements</strong>: Will we need to support more document types in the future?</p><p><strong>3.</strong> <strong>Complexity cost</strong>: Will the increased structure make the codebase harder to understand?</p><p><strong>4.</strong> <strong>Maintenance impact</strong>: How much time are we spending fixing duplicate bugs?</p><p>Looking at our product roadmap, it was clear that:</p><p><strong>-</strong> We were planning to add support for more document types</p><p><strong>-</strong> We needed to standardize our logging formats for better analysis</p><p><strong>-</strong> Our team needed consistent log structures for monitoring</p><p><strong>-</strong> Engineers were spending significant time synchronizing changes between loggers</p><p>This assessment convinced us that a SOLID approach was warranted.</p><h3>How We Applied SOLID Principles</h3><p>While all SOLID principles were important in our refactoring journey, the Open-Closed Principle (OCP) proved most valuable for our evolving document processing needs. As we plan to expand our system to handle salary slips, this principle will be crucial for seamless integration.</p><h3>Open-Closed Principle: Extension Without Modification</h3><p>The Open-Closed Principle states that:</p><blockquote>&quot;Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.&quot;</blockquote><p>In practical terms, this means our code should be structured in a way that allows us to add new functionality without changing existing code.</p><p>Our logging system embodies this principle perfectly:</p><pre>/**<br> * BaseLogger - A base class for implementing logging functionality<br> * This class follows the Open/Closed principle by allowing extension<br> * without modification of the base logger behavior<br> */<br>class BaseLogger {<br>  constructor(serviceName, logFileName) {<br>    // Configuration setup...<br>  }<br>  <br>  info(message, metadata) {<br>    this.logger.info(message, metadata);<br>  }<br>  <br>  warn(message, metadata) {<br>    this.logger.warn(message, metadata);<br>  }<br>  <br>  error(message, metadata) {<br>    this.logger.error(message, metadata);<br>  }<br>  <br>  createMetadata(data, eventType) {<br>    return {<br>      ...data,<br>      event: eventType<br>    };<br>  }<br>}</pre><p><strong>Code Explanation:</strong> The <em>BaseLogger</em> class above creates a foundation that is complete in itself by providing core logging functionality (<em>info</em>, <em>warn</em>, <em>error</em>) and metadata creation. The design is intentional: by implementing all essential logging behaviors in this base class, we ensure that any child logger inherits a complete, functional implementation. This makes the class &quot;closed for modification&quot; because we won&#39;t need to change this core functionality. At the same time, the class design allows for extension through inheritance, making it &quot;open for extension.&quot;</p><h4>How OCP Makes Adding Salary Slip OCR Straightforward</h4><p>With our OCP-based architecture, adding salary slip processing requires no changes to existing code:</p><ol><li>Create a new <em>SalarySlipLogger</em> by extending <em>BaseLogger</em>:</li></ol><pre>class SalarySlipLogger extends BaseLogger {<br>  constructor() {<br>    super(&#39;salary-slip-service&#39;, &#39;salary-slip&#39;);<br>  }<br>  <br>  // New methods specific to salary slips<br>  logPersonalDataRedaction(slipId) {<br>    const metadata = this.createMetadata({ slipId }, &#39;PII_REDACTED&#39;);<br>    this.info(&#39;Personal identifiable information redacted&#39;, metadata);<br>  }<br>  <br>  logSalaryEncryption(slipId, encryptionMethod) {<br>    const metadata = this.createMetadata({ <br>      slipId, <br>      encryptionMethod <br>    }, &#39;SALARY_ENCRYPTED&#39;);<br>    <br>    this.info(&#39;Salary information encrypted&#39;, metadata);<br>  }<br>}</pre><p><strong>Code Explanation:</strong> This implementation demonstrates OCP perfectly. The <em>SalarySlipLogger</em> extends the base class to inherit all standard logging behaviors while adding specialized methods for salary slip-specific events. Notice how we&#39;re leveraging the inherited <em>createMetadata()</em> and <em>info()</em> methods from the base class. This approach ensures that all document loggers maintain a consistent structure while allowing for specialized behavior. No existing code needed to be changed - we simply extended the functionality, which is the essence of the Open-Closed Principle.</p><p>2. The existing <em>BaseLogger</em> remains <strong>untouched</strong>. We&#39;ve extended it without modifying it - the essence of OCP.</p><h4>The OCP Impact for Salary Slip OCR</h4><p>This architecture delivers significant benefits for our upcoming salary slip integration:</p><ul><li><strong>Zero risk to existing code</strong>: Since we don&#39;t modify the base logger or existing loggers, there&#39;s no risk of breaking invoices or purchase orders processing.</li><li><strong>Specialized behavior</strong>: Salary slips involve sensitive personal and financial data. We can add specialized logging methods like <em>logPersonalDataRedaction()</em> and <em>logSalaryEncryption()</em> without affecting other document types.</li><li><strong>Consistent foundation</strong>: While extending with new functionality, we maintain consistent base behavior across all loggers.</li><li><strong>Testing isolation</strong>: New salary slip functionality can be tested independently, without re-testing unmodified components.</li><li><strong>Future adaptability</strong>: As regulations around salary data change, we can adapt the <em>SalarySlipLogger</em> without touching other parts of the system.</li></ul><h3>Open-Closed Principle vs. Perfect Prediction</h3><p>An important realization was that OCP doesn&#39;t mean we need to predict every possible future extension. Rather, it means designing with the understanding that change will come, and structuring code to accommodate it.</p><p>When we initially designed our logger system, we didn&#39;t know we&#39;d need to process salary slips. But by following OCP, we created an architecture that could handle this unforeseen requirement with minimal effort.</p><h3><strong>Should Every Piece of Code Be 100% SOLID?</strong></h3><p>While refactoring, we made a conscious decision not to over-engineer. For example, we didn’t create separate classes for each type of metadata or individual message formatting. Sometimes, a simple helper method is sufficient:</p><pre>// Simple helper method - no need for a full class<br>createMetadata(data, eventType) {<br>  return {<br>    ...data,<br>    event: eventType,<br>    timestamp: new Date().toISOString()<br>  };<br>}</pre><p>SOLID principles are guidelines, not rigid rules. The key is applying them where they bring value.</p><h4>The Real-World Impact</h4><p>After implementing our refactored logging system, we ran the code quality analysis again. The results were dramatic:</p><p><strong>Before refactoring:</strong></p><p><strong>-</strong> Overall duplication rate: 9.1% ❌</p><p><strong>-</strong> purchaseOrderLogger.js: 54.0% duplication</p><p><strong>-</strong> invoiceLogger.js: 32.7% duplication</p><p><strong>After refactoring:</strong></p><ul><li>Overall duplication rate: 0% ✅</li><li>New structure has minimal duplication across all files</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t9cBs6YGbEilwVnEU6Ic0Q.png" /><figcaption>Q<em>uality gate now passes with 0% duplication</em></figcaption></figure><p>But the benefits went far beyond metrics:</p><p><strong>1. Maintenance Efficiency</strong></p><p>A real example: When we needed to add structured error logging for better error tracking, we only had to modify BaseLogger’s error method:</p><pre>// One change in BaseLogger affected all loggers<br>error(message, metadata) {<br>  if (metadata.error &amp;&amp; metadata.error instanceof Error) {<br>    metadata.errorDetails = {<br>      name: metadata.error.name,<br>      message: metadata.error.message,<br>      stack: metadata.error.stack<br>    };<br>  }<br>  this.logger.error(message, metadata);<br>}</pre><p>This change was immediately reflected across all document types without touching any specialized logger.</p><p><strong>2. Developer Onboarding Improvement</strong></p><p>The updated logging system organizes code into well-defined modules and responsibilities. This structure makes it straightforward for new developers to locate and understand the components involved in logging, enabling them to start contributing to related tasks almost immediately.</p><p><strong>3. Extensibility Proof</strong></p><p>When the business requested support for a new document type (contracts), the implementation was remarkably smooth:</p><p><strong>1.</strong> Create a new ContractLogger extending BaseLogger</p><p><strong>2.</strong> Add contract-specific logging methods</p><p><strong>3.</strong> Add a case to LoggerFactory</p><p><strong>4.</strong> No changes to existing code required</p><p>What would have previously taken days (and introduced risks to existing code) was completed in hours.</p><h4>Real Challenges We Faced</h4><p>The path wasn’t all smooth sailing. Here are some real challenges we encountered:</p><p><strong>1. Backward Compatibility</strong></p><p>We had a lot of existing code using the old logger interfaces. To maintain compatibility, we created adapter classes:</p><pre>// Adapter pattern to maintain backward compatibility<br>class InvoiceLoggerAdapter {<br>  static logUploadStart(invoiceId, partnerId, filename) {<br>    return InvoiceLogger.getInstance().logUploadStart(invoiceId, partnerId, filename);<br>  }<br>  <br>  // Adapter methods matching the original static API<br>}</pre><p>This allowed us to upgrade one component at a time without breaking the entire system.</p><p><strong>2. Increased Initial Complexity</strong></p><p>The new architecture introduced more classes and abstractions. To ensure everyone understood the design, we:</p><p><strong>-</strong> Held knowledge sharing sessions</p><p><strong>-</strong> Added clear comments explaining the structure</p><p><strong>3. Team Adaptation</strong></p><p>Some team members were initially resistant to the perceived “over-engineering.” We addressed this by:</p><p><strong>-</strong> Demonstrating concrete examples of the benefits</p><p><strong>-</strong> Creating before/after comparisons of code changes</p><p><strong>-</strong> Measuring the reduction in duplicate bug fixes</p><h4>Is SOLID Worth It?</h4><p>After this experience, we can confidently say: <strong>Yes, applying SOLID principles to real-world problems is absolutely worth it</strong> — but with some important caveats:</p><p><strong>1.</strong> <strong>Apply where appropriate</strong>: Not every piece of code needs full SOLID treatment</p><p><strong>2.</strong> <strong>Balance with pragmatism</strong>: Don’t let perfect be the enemy of good</p><p><strong>3.</strong> <strong>Consider the learning curve</strong>: Ensure the team understands why and how</p><p><strong>4.</strong> <strong>Measure the impact</strong>: Use metrics to validate improvements</p><h4>Lessons Beyond SOLID</h4><p>This refactoring journey taught us several additional lessons:</p><p><strong>1.</strong> <strong>Technical debt is expensive</strong>: The time saved by cutting corners initially cost us much more later</p><p><strong>2.</strong> <strong>Architecture matters</strong>: Good design decisions pay dividends throughout a project’s lifecycle</p><p><strong>3.</strong> <strong>Incremental improvements work</strong>: We didn’t need to rewrite everything at once</p><p><strong>4.</strong> <strong>Patterns complement principles</strong>: Design patterns (Adapter, Factory, Singleton) helped implement SOLID principles</p><h4>Conclusion: From Theory to Practice</h4><p>Our journey from 54% code duplication to a clean, maintainable architecture demonstrates that SOLID principles aren’t just academic concepts — they deliver tangible benefits in real-world projects.</p><p>The next time you encounter duplicated code or a design that’s difficult to extend, ask yourself if SOLID principles might offer a solution. They might require more thought and initial investment, but the long-term benefits to your codebase and your team’s productivity can be substantial.</p><p>Remember: Software development isn’t just about making code work today; it’s about building systems that can evolve and adapt tomorrow. SOLID principles provide a proven framework for achieving that goal.</p><p>— -</p><p><em>What’s your experience with applying SOLID principles in real projects? Have you seen similar improvements, or do you have reservations about their practical application? Share your thoughts in the comments!</em></p><p>— -</p><h4>References</h4><p><strong>1.</strong> Martin, R. C. (2000). Design Principles and Design Patterns</p><p><strong>2.</strong> Feathers, M. (2004). Working Effectively with Legacy Code</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c707e9eda88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stress Testing with K6: Is It Still Relevant in Modern Software Development?]]></title>
            <link>https://medium.com/@suryata/stress-testing-with-k6-is-it-still-relevant-in-modern-software-development-41f5dca6f1dc?source=rss-2137f06b09d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/41f5dca6f1dc</guid>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[k6-performance-testing]]></category>
            <category><![CDATA[stress-test]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[I Made Surya Anahata Putra]]></dc:creator>
            <pubDate>Thu, 01 May 2025 11:19:46 GMT</pubDate>
            <atom:updated>2025-05-01T11:22:43.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WUsPcue4nM8ws4pS" /><figcaption>stress testing illustration</figcaption></figure><p><strong>Introduction</strong><br>In an era dominated by microservices and cloud computing, developers often ask: <em>Is stress testing still relevant?</em> According to Gartner’s 2023 report, 67% of system outages are caused by unexpected traffic spikes — proof that stress testing remains critical. In this article, I’ll share a real-world case study of implementing stress testing using K6 for a Purchase Order (PO) upload API, along with actionable insights and code samples.</p><p><strong>Why K6 for Stress Testing?</strong></p><ol><li><strong>Open-Source &amp; Developer-Centric</strong>: JavaScript (ES6) syntax simplifies test scripting.</li><li><strong>Resource Efficiency</strong>: Lightweight CLI tool (no GUI overhead like JMeter).</li><li><strong>CI/CD Integration</strong>: Native support for GitHub Actions, GitLab CI, etc.</li><li><strong>Advanced Metrics</strong>: Built-in percentile calculations and custom metric support.</li></ol><p><strong>Step-by-Step Implementation</strong></p><p><strong>1. Designing the Stress Test Scenario (</strong>upload-po-stress-test.mjs<strong>)</strong></p><ul><li><strong>Ramping Load Strategy</strong> to simulate realistic traffic growth:</li></ul><pre>stages: [<br>  { duration: &#39;30s&#39;, target: 10},  // Warm-up<br>  { duration: &#39;1m&#39;, target: 100 },  // High Load<br>  { duration: &#39;1m&#39;, target: 300 }, // Extreme Load<br>]</pre><ul><li><strong>Custom Metrics &amp; Thresholds</strong>:</li></ul><pre>thresholds: {<br>  error_rate: [&#39;rate&lt;0.6&#39;], <br>  latency_p95: [&#39;p(95)&lt;3000&#39;],<br>}</pre><p><strong>2. Automating with GitHub Actions (</strong>.github/workflows/po-upload-stress-test.yml<strong>)</strong></p><ul><li><strong>K6 Installation</strong>:</li></ul><pre>- name: Install k6<br>  run: |<br>    sudo apt-get update<br>    sudo apt-get install -y k6</pre><ul><li><strong>Secure Credential Handling</strong>:</li></ul><pre>k6 run -e LOAD_CLIENT_ID=${{ secrets.LOAD_CLIENT_ID }} -e LOAD_CLIENT_SECRET=${{ secrets.LOAD_CLIENT_SECRET }} ...</pre><ul><li><strong>Dynamic File Handling</strong> using SharedArray:</li></ul><pre>const pdfFile = new SharedArray(&#39;PO PDF&#39;, () =&gt; {<br>  try {<br>    return [open(&#39;./Sample1_Bike_PO.pdf&#39;, &#39;binary&#39;)];<br>  } catch (e) {<br>    throw new Error(`File load failed: ${e.message}`);<br>  }<br>});</pre><p><strong>3. Results Analysis &amp; Reporting</strong></p><ul><li><strong>GitHub Summary Generation</strong>:</li></ul><pre>- name: Generate Summary<br>  run: |<br>    echo &quot;## Purchase Order Upload Stress Test Results&quot; &gt;&gt; $GITHUB_STEP_SUMMARY<br>    grep -A 10 &quot;Summary&quot; backend/tests/stress/upload-po-stress-test.log</pre><ul><li><strong>Custom Test Insights</strong>:</li></ul><pre>if (errRate &gt; 0.6) {<br>  console.log(&quot;⚠️ Error rate exceeds 60%! System overloaded.&quot;);<br>}</pre><p><strong>Best Practices Applied</strong></p><ol><li><strong>Multi-Phase Testing</strong>:</li></ol><ul><li>Fixed load (20 VU) → Ramping load → Stress test (300 VU).</li></ul><p><strong>2. Real-World File Simulation</strong>:</p><ul><li>Upload 5–10MB PDFs using binary handling:</li></ul><pre>const pdfData = open(‘./Sample1_Bike_PO.pdf’, ‘b’);</pre><ol><li><strong>Business-Aligned Thresholds</strong>:</li></ol><ul><li>Error rate &lt; 5% for load tests, &lt;60% for stress tests.</li><li>P95 latency &lt; 3s (aligned with PO processing SLA).</li></ul><ol><li><strong>Enhanced Observability</strong>:</li></ol><ul><li>Track custom metrics (error_rate, latency_p95).</li><li>Log failed requests with response details.</li></ul><p><strong>Is Stress Testing Still Relevant? Insights from Recent Literature</strong><br>Per the 2023 IEEE paper <em>“Load Testing in the Cloud Era”</em>, stress testing is critical to:</p><ol><li>Identify bottlenecks in distributed systems.</li><li>Validate auto-scaling configurations.</li><li>Measure recovery time post-traffic spikes.</li><li>Meet reliability standards (e.g., ISO 25010).</li></ol><p><strong>Key Outcomes</strong><br>Our K6 implementation revealed:<br>✅ Memory leaks in the upload service at 200+ VUs.<br>✅ Misconfigured API gateway timeouts.<br>✅ Infrastructure scaling limits for capacity planning.</p><p><strong>References</strong></p><ol><li>Gartner, <em>Application Performance Monitoring Report</em> (2023).</li><li>IEEE, <em>Cloud-Native Load Testing Patterns</em> (2023).</li><li>K6 Documentation v0.47.0 (2024).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41f5dca6f1dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What It Takes to Make Effective People Management and Team Dynamics in Agile Sprints]]></title>
            <link>https://medium.com/@suryata/what-it-takes-to-make-effective-people-management-and-team-dynamics-in-agile-sprints-5fee5d65ddab?source=rss-2137f06b09d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fee5d65ddab</guid>
            <dc:creator><![CDATA[I Made Surya Anahata Putra]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 16:10:55 GMT</pubDate>
            <atom:updated>2025-04-10T16:10:55.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*METDUTYhNouWNKzm" /><figcaption>image by <a href="https://unsplash.com/@priscilladupreez">Priscilla Du Preez</a><strong> </strong>on <a href="http://unsplash.com/">unsplash</a></figcaption></figure><p>Can you imagine stepping into your agile workspace where each sprint transforms challenges into opportunities for personal and team growth. As a developer working within a dynamic software engineering team, you play a crucial role in not only coding but also in fostering strong communication, collaboration, and continuous improvement within your team. This guide explores how effective people management and team dynamics can be woven into every sprint, helping the team not just meet deadlines but continuously improve and innovate.</p><h3>1. Building Meaningful Relationships in the Sprint Cycle</h3><p>In every sprint, meaningful relationships among team members are the foundation for success. Even if you’re not the designated leader, your actions can significantly enhance team cohesion:</p><ul><li><strong>Cultivating Trust and Empathy:</strong><br>Engage with your teammates during daily stand-ups, sprint planning, and retrospectives. By actively listening and showing genuine care for each other’s challenges, you build a climate of mutual respect. Trust and empathy allow for a safer space to share ideas, report blockers, and offer support when deadlines loom.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9vViR3YBey4kmeEpBq493A.png" /></figure><p>In our team, we hold stand-ups two times a week, blending synchronous (real-time) and asynchronous check-ins based on everyone’s availability and workload. As you can see in the conversation snippet, team members openly share their progress, plans, and problems, while also acknowledging personal constraints that might affect attendance or speed. By actively listening to each other’s challenges, whether over live calls or in chat threads , we demonstrate respect for each other’s time and foster a collaborative atmosphere. This blend of synchronous and async stand-ups helps maintain transparency, encourages proactive problem-solving, and cultivates a deeper sense of empathy among all members when deadlines are tight.</p><ul><li><strong>Establishing Clear Communication:</strong><br>Agile methodologies thrive on open, transparent dialogue. Whether you’re discussing task progress or brainstorming solutions, active communication during sprint meetings encourages prompt problem-solving and innovation. Regular check-ins not only help in clarifying goals but also ensure every team member’s voice is heard.</li><li><strong>Offering Consistent Support:</strong><br>Your readiness to step in and help, be it through code reviews, pair programming, or just lending an ear during tough sprints, creates a solid foundation of reliability and camaraderie within the team. This supportive culture fosters a collective drive towards success, making it easier to tackle complex software challenges together.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTKK8yqPIE7c7G0dvn1rWA.png" /><figcaption>some constructive feedback on team member works</figcaption></figure><p>Based on the picture above, I not only offered constructive feedback but also provided concrete solutions to help improve the code. For example, while I appreciated the addition of load testing and stress testing features, I noticed a recurring pattern in how the tests were being configured and run. Rather than merely pointing out the issue of code duplication, I suggested creating a helper function to handle these repeated tasks. This approach not only reduces redundancy but also ensures that future modifications become more manageable.</p><p>Furthermore, I saw an opportunity to enhance the manual trigger workflow by making it more flexible. Instead of hard-coding certain parameters, I recommended parameterizing them so the tests could be tailored to different scenarios with minimal effort. By including specific examples and code snippets, I provided actionable steps that guide the development team in implementing these improvements. This dual strategy of highlighting strengths while proposing ready-to-use solutions fosters a supportive, growth-oriented environment for everyone involved.</p><h3>2. Practical Strategies for Enhancing Team Collaboration During Sprints</h3><p>Transforming individual contributions into a seamless team effort requires practical strategies tailored to the sprint framework:</p><ul><li><strong>Participate in Routine Evaluations:</strong><br>Leverage sprint retrospectives as a chance to assess team performance. By documenting what worked well and identifying areas for improvement, you contribute to a culture of continuous learning and dynamic adjustment. These evaluations are essential for capturing sprint momentum and adapting strategies for upcoming cycles.</li><li><strong>Contribute to Innovative Engagement Practices:</strong></li></ul><p>Even as a developer, you can suggest and experiment with new tools or processes, like implementing new version control integrations or testing frameworks, that keep the team agile and responsive to change. Sustained innovation across multiple sprints can lead to breakthrough improvements in both the product and team efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sfJ5t6g0XCs4ZPv0SAieIQ.png" /><figcaption>Introducing guidelines for working with new tools</figcaption></figure><p>Based on the picture above, I introduced a new tool , Winston logger to the team, demonstrating how we can manage logs more efficiently across various environments. Rather than relying solely on basic console logs, this implementation allows us to centralize and customize log levels, making troubleshooting and monitoring far more effective. Additionally, recognizing that many team members were confused about the seeding process, I organized a comprehensive tutorial to guide everyone through the proper methods of seeding our databases. This tutorial not only clarified common misconceptions but also provided step-by-step instructions and best practices to ensure consistency and reliability in our development workflows.</p><p>This exemplifies the idea of contributing to innovative engagement practices. Even as a developer, proposing and experimenting with tools like Winston helps us refine our processes over multiple sprints, driving both product quality and team efficiency. By embracing novel solutions and sharing knowledge, we foster a culture that welcomes continuous improvement, ultimately leading to breakthrough innovations in our collective workflow.</p><ul><li><strong>Practice Servant Leadership From Within:</strong><br>Leadership is not confined to formal titles. By taking initiative to help teammates remove technical blockers or by offering constructive feedback, you embody the spirit of servant leadership. Supporting your peers paves the way for an inclusive environment where every team member thrives.</li></ul><h3>3. Applying Psychological Theories to Sprint Work</h3><p>Understanding psychological principles can enhance your approach to team collaboration and personal performance, even as a developer:</p><h4>Self-Determination Theory</h4><p>Intrinsic motivation is key in a sprint environment. When you feel autonomous in task selection, confident in your technical skills, and connected to your team’s goals, you are more likely to deliver high-quality work. This sense of ownership propels you to contribute your best under tight sprint deadlines.</p><h4>Expectation-Driven Performance</h4><p>Drawing from the Pygmalion Effect, high expectations within the team can lead to superior performance. When you and your colleagues have confidence in each other’s coding abilities and commitment, it creates a positive feedback loop where everyone is inspired to exceed expectations during each sprint.</p><h4>Social Identity Theory</h4><p>Your identity as a developer isn’t just about individual achievement , it’s also about belonging to a cohesive team. Recognizing yourself as part of a bigger, goal-oriented group can boost morale and encourage a collective drive toward sprint targets, strengthening the team’s overall identity.</p><h4>Equity Theory</h4><p>Fair workload distribution is crucial in a sprint’s fast-paced environment. When responsibilities and recognition are balanced, every team member feels valued, leading to higher job satisfaction and productivity across the board.</p><h4>Attribution Theory</h4><p>Reflect on how successes and setbacks are perceived during sprint reviews. By correctly attributing achievements to collaborative efforts or learning opportunities, and understanding challenges as areas for growth, you and your team can continuously evolve and adapt strategies for future sprints.</p><h3>4. Measuring Success Through Sprint Evaluations and Continuous Improvement</h3><p>The agile process is built on regular evaluation and adaptation. Here’s how to ensure each sprint contributes to overall team growth:</p><ul><li><strong>Understanding Your Role in People Management:</strong><br>Recognize that effective teamwork isn’t solely the leader’s responsibility. Each developer contributes to managing team dynamics by communicating, collaborating, and supporting peers throughout the sprint cycle.</li><li><strong>Participating in Systematic Sprint Assessments:</strong><br>Sprint retrospectives are valuable opportunities to review the team’s performance. Regular assessments allow you to identify what’s working well and plan actionable changes for the next sprint, ensuring sustained progress and team alignment.</li><li><strong>Fostering Continuous Innovation:</strong><br>Track the impact of new ideas and practices introduced in sprints. Continuous innovation m demonstrated through improved code quality, efficient practices, or streamlined workflows over successive sprints that indicates a robust, adaptive team culture geared toward long-term success.</li></ul><h3>Conclusion</h3><p>While you may not hold a formal leadership role, your contributions as a developer are vital in shaping effective people management and team dynamics within sprint cycles. By building meaningful relationships, actively engaging in clear communication, and supporting your teammates, you help create a work environment where collaboration and innovation flourish.</p><p>Integrating psychological insights such as Self-Determination, Expectation-Driven Performance, Social Identity, Equity, and Attribution theories into everyday sprint work empowers you and your team to perform at higher levels. Embrace continuous evaluation, foster a culture of trust and support, and let your proactive attitude transform each sprint into an opportunity for collective success.</p><p>In the agile world of software engineering, every line of code and every conversation contributes to a thriving team. By focusing on these principles, you help drive the team forward one sprint at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fee5d65ddab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Mock and Stub in Software Testing with AI Support]]></title>
            <link>https://medium.com/@suryata/what-mock-actually-do-for-your-projects-aa886db6ac09?source=rss-2137f06b09d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa886db6ac09</guid>
            <dc:creator><![CDATA[I Made Surya Anahata Putra]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 05:23:39 GMT</pubDate>
            <atom:updated>2025-03-06T05:49:17.836Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern software development, comprehensive testing is essential to guarantee code quality. However, isolating components from external dependencies like databases, external APIs, or other systems remains a significant challenge. This article explores how <strong>Mocks</strong> and <strong>Stubs</strong> can effectively address test isolation, featuring practical examples and insights into enhancing productivity through AI tools such as ChatGPT.</p><h3>Understanding Mocks and Stubs</h3><ul><li><strong>Mock</strong> is a simulated object that mimics the behavior of real components or external dependencies in a system, ensuring methods are called with expected parameters.</li><li><strong>Stub</strong> is a simple object designed to return predefined responses or data without executing actual logic or operations.</li></ul><h3>Mock Implementation in AuthService Testing (MySQL)</h3><p>Consider this example of using Jest to mock MySQL database connections:</p><pre>jest.mock(&#39;mysql2/promise&#39;);<br>mysql.createConnection.mockResolvedValue({<br>  execute: jest.fn().mockResolvedValue([[{ uuid: &#39;uuid1&#39;, client_id: &#39;client1&#39;, client_secret: &#39;secret1&#39; }]]),<br>  end: jest.fn()<br>});</pre><p>This mock ensures unit tests run independently from the actual database, increasing security, and data integrity during testing.</p><h3>Case Study: authService.test.js Using Jest and Mock</h3><p>Here’s an example of a complex test using Jest, demonstrating authentication testing by mocking MySQL:</p><pre>mysql.createConnection.mockResolvedValue({<br>  execute: jest.fn().mockResolvedValue([<br>    [{ uuid: &#39;uuid1&#39;, client_id: &#39;client1&#39;, client_secret: &#39;secret1&#39; }]<br>  ]),<br>  end: jest.fn()<br>});<br><br>const result = await authService.authenticate(&#39;client1&#39;, &#39;secret1&#39;);<br>expect(result).toEqual({<br>  uuid: &#39;uuid1&#39;,<br>  client_id: &#39;client1&#39;,<br>  client_secret: &#39;secret1&#39;<br>});</pre><p>This clearly illustrates successful isolation from external DB dependencies.</p><h3>Leveraging AI Support in Testing</h3><p>AI tools like ChatGPT and GitHub Copilot can significantly enhance testing productivity. Nevertheless, us as a developers must critically evaluate AI-generated suggestions to match project-specific needs accurately.</p><p>For instance, an initial AI-generated suggestion might look like:</p><pre>mysql.createConnection.mockResolvedValue({<br>  execute: jest.fn().mockResolvedValue([[{ /*...data*/ }]]),<br>  end: jest.fn()<br>});</pre><p>Developers refine this to precisely reflect their specific test case:</p><pre>const mockConnection = {<br>  execute: jest.fn().mockResolvedValue([<br>    [{ uuid: &#39;uuid1&#39;, client_id: &#39;client1&#39;, client_secret: &#39;secret1&#39; }]<br>  ]),<br>  end: jest.fn()<br>};<br>mysql.createConnection.mockResolvedValue(mockConnection);</pre><p>This adjustment makes the test more precise and reflective of real-world scenarios.</p><h3>Advanced Techniques for Complex Testing Scenarios</h3><p>Testing complex scenarios, such as PDF file uploads, requires advanced techniques:</p><pre>invoiceService.validatePDF.mockResolvedValue(true);<br>invoiceService.isPdfEncrypted.mockResolvedValue(false);<br>invoiceService.checkPdfIntegrity.mockResolvedValue(true);<br>invoiceService.validateSizeFile.mockResolvedValue(true);<br>invoiceService.uploadInvoice.mockResolvedValue({<br>  message: &quot;Invoice uploaded successfully&quot;,<br>  filename: &quot;invoice.pdf&quot;<br>});</pre><p>These stubs simulate comprehensive conditions, enabling thorough validation of business logic without actual external processes.</p><h3>Critical Analysis of AI Support in Testing</h3><p>AI provides valuable initial recommendations for test development, but these must be critically analyzed and modified for project-specific accuracy:</p><p><strong>Strengths of AI:</strong></p><ul><li>Accelerates initial test creation</li><li>Provides effective examples for initial reference</li></ul><p><strong>Limitations of AI:</strong></p><ul><li>Additional customization needed for complex scenarios</li><li>Limited understanding of specific project business logic</li></ul><p>Developers should consistently perform critical validation of all AI-provided code.</p><h3>Conclusion</h3><p>Mastering mock and stub techniques and strategically leveraging AI support enhances both efficiency and effectiveness in software testing, especially when addressing complex external dependencies such as databases and external APIs. Implementing these practices not only boosts software quality but also accelerates the development lifecycle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa886db6ac09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Actually TDD can do with your Code?]]></title>
            <link>https://medium.com/@suryata/what-actually-tdd-can-do-with-your-code-5ae6d0bb6433?source=rss-2137f06b09d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ae6d0bb6433</guid>
            <dc:creator><![CDATA[I Made Surya Anahata Putra]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 16:46:17 GMT</pubDate>
            <atom:updated>2025-04-08T06:58:57.971Z</atom:updated>
            <content:encoded><![CDATA[<p>Test Driven Development (TDD) is more than just a coding technique, it’s a complete development paradigm that shapes how we design, implement, and maintain our software systems. In this article, we explore the philosophy behind TDD, its practical benefits, and how its disciplined use. . We share real-world examples from our project where TDD guided the development of key features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hONEizxA4L6MGogL" /></figure><h3>What Is Test Driven Development?</h3><p>At its core, Test Driven Development (TDD) is a cyclical process built on writing tests first and then writing code to satisfy those tests. The process follows these steps:</p><ol><li><strong>Write a Failing Test (Red Phase):</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*eAQcVOBXCAVRR8G5voVstw.png" /></figure><p>Define and write tests that capture the desired functionality, including all scenarios such as success, failure, and unusual or edge cases. The new tests should initially fail, ensuring that the specification is clearly unmet.</p><p><strong>2. Write Minimal Code to Pass the Test (Green Phase):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*OYcuDVOdM15fpZRspdjZDg.png" /></figure><p>Implement the simplest possible code that makes the failing test pass. This encourages developers to focus on the requirements without over-engineering.</p><p><strong>3. Refactor and Enhance the Code (Refactor Phase):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*PoH4JSo8sLSgqFAx0yAB3w.png" /></figure><p>Once the tests pass, clean up the code, improve its structure, and ensure that design principles , such as the Single Responsibility Principle (SRP) are maintained. The test suite continues to serve as a safety net, guarding against regressions.</p><blockquote>This cycle is repeated for every new feature or bug fix, forming a comprehensive test suite that documents the design and expected behavior of the system.</blockquote><h3>The Advantages of TDD</h3><p>Embracing TDD in your development process brings several key benefits:</p><ul><li><strong>High Code Quality and Reliability:</strong><br>TDD forces you to think about all possible scenarios including edge cases, which results in code that is more modular, decoupled, and easier to test.</li><li><strong>High Code Coverage:</strong><br>By driving development with tests, the code base naturally reaches high levels of coverage. Our project consistently maintained over 90% code coverage, ensuring that almost every aspect of our application is well-verified.</li><li><strong>Refactoring Confidence:</strong><br>With a comprehensive test suite in place, you can confidently refactor code knowing that any unwanted changes in behavior will be caught immediately.</li><li><strong>Effective Documentation:</strong><br>The tests themselves serve as living documentation of how the system should behave, making it easier for new team members or future maintainers to understand the codebase.</li><li><strong>Faster Debugging and Maintenance:</strong><br>Early detection of bugs and clear separation of concerns make it easier to identify and fix issues before they escalate in production.</li><li><strong>Disciplined Development Process:</strong><br>Frequent commits and incremental changes ensure that every small addition is validated by tests, reducing the risk of integrating untested or faulty code.</li></ul><h3>TDD in Action: Our Project Case Study</h3><p>Our project implemented TDD rigorously for a range of features. Here, we dive into the details of five key features where TDD played a crucial role:</p><h3>1. Authentication (Auth) Service</h3><h4>Overview</h4><p>We redesigned our authentication process to separate the logic for authentication and invoice PDF upload. This separation are achieved by moving logic into distinct services (e.g., <strong>authService</strong> vs. <strong>invoiceService</strong>) and dedicated controllers, enables focused testing and adheres to the Single Responsibility Principle (SRP).</p><h4>What I Did</h4><ul><li><strong>Refactoring Services and Controllers:</strong><br>The authentication logic was isolated into its own service, allowing for clearer boundaries. The controller calls authService.authenticate first, and then passes control to invoiceService.uploadInvoice.</li><li><strong>Test Structure:</strong><br> Tests were organized into folders by responsibility (e.g., tests/services/, tests/controllers/, tests/routes/) so that each suite focused solely on a specific area.</li><li><strong>Code Example of Database Authentication Test:</strong></li></ul><pre>// RED phase: Writing a test for authenticating against the database using MySQL.<br>const mysql = require(&#39;mysql2/promise&#39;);<br>require(&#39;dotenv&#39;).config();<br><br>describe(&quot;Database Authentication&quot;, () =&gt; {<br>  let connection;<br><br>  beforeAll(async () =&gt; {<br>    connection = await mysql.createConnection({<br>      host: process.env.DB_HOST,<br>      port: process.env.DB_PORT,<br>      user: process.env.DB_USER,<br>      password: process.env.DB_PASSWORD,<br>      database: process.env.DB_NAME<br>    });<br>  });<br><br>  afterAll(async () =&gt; {<br>    if (connection) {<br>      await connection.end();<br>    }<br>  });<br><br>  async function authenticate(clientId, clientSecret) {<br>    const query = `<br>      SELECT client_id, client_secret <br>      FROM partner <br>      WHERE client_id = ? AND client_secret = ?<br>    `;<br>    const [rows] = await connection.execute(query, [clientId, clientSecret]);<br>    return rows.length &gt; 0 ? 200 : 401;<br>  }<br><br>  test(&quot;should return 200 OK if client_id and client_secret match&quot;, async () =&gt; {<br>    const status = await authenticate(<br>      process.env.CLIENT_ID,<br>      process.env.CLIENT_SECRET<br>    );<br>    expect(status).toBe(200);<br>  });<br><br>  test(&quot;should return 401 Unauthorized if credentials do not match&quot;, async () =&gt; {<br>    const status = await authenticate(&quot;invalid_id&quot;, &quot;invalid_secret&quot;);<br>    expect(status).toBe(401);<br>  });<br>});</pre><ul><li><strong>Bug Fixes:</strong><br>An error (“Bind parameters must not contain undefined”) was fixed by adding proper validations for the credentials before querying the database.</li></ul><h3>2. Authorization Middleware</h3><h4>Overview</h4><p>To ensure only authenticated partners can upload invoices, an authorization middleware was implemented. This middleware extracts credentials from HTTP headers, validates them using the <strong>authService</strong>, and attaches the partner’s UUID to the request object.</p><h4>What I Did</h4><ul><li><strong>Middleware Implementation:</strong><br> The authMiddleware checks for the presence of client_id and client_secret in request headers. If credentials are missing or invalid, it returns a 401 Unauthorized response.</li><li><strong>Refactored Controller:</strong><br> The invoice controller now relies on req.user populated by the middleware, ensuring that authentication is handled uniformly.</li><li><strong>Mocking and Testing:</strong><br> Tests used Jest’s mocking capabilities (jest.mock()) to simulate service behavior. For example, tests confirmed that:</li><li>A missing header leads to a 401 error.</li><li>Invalid credentials result in an error without calling the next middleware.</li><li>Valid credentials correctly set req.user and call the next handler.</li><li><strong>Test Code Snippet for Authorization Middleware:</strong></li></ul><pre>const { mockRequest, mockResponse } = require(&#39;jest-mock-req-res&#39;);<br>const authMiddleware = require(&#39;../../src/middlewares/authMiddleware&#39;);<br>const authService = require(&#39;../../src/services/authService&#39;);<br><br>jest.mock(&#39;../../src/services/authService&#39;);<br><br>describe(&#39;authMiddleware&#39;, () =&gt; {<br>  let req, res, next;<br><br>  beforeEach(() =&gt; {<br>    req = mockRequest({ headers: {} });<br>    res = mockResponse();<br>    next = jest.fn();<br>    jest.clearAllMocks();<br>  });<br><br>  test(&#39;should return 401 if credentials are missing&#39;, async () =&gt; {<br>    await authMiddleware(req, res, next);<br>    expect(res.status).toHaveBeenCalledWith(401);<br>    expect(res.json).toHaveBeenCalledWith({ message: &#39;Unauthorized: Missing credentials&#39; });<br>    expect(next).not.toHaveBeenCalled();<br>  });<br><br>  test(&#39;should return 401 if invalid credentials are provided&#39;, async () =&gt; {<br>    req.headers.client_id = &#39;invalid_id&#39;;<br>    req.headers.client_secret = &#39;invalid_secret&#39;;<br>    authService.authenticate.mockResolvedValue(null);<br><br>    await authMiddleware(req, res, next);<br><br>    expect(authService.authenticate).toHaveBeenCalledWith(&#39;invalid_id&#39;, &#39;invalid_secret&#39;);<br>    expect(res.status).toHaveBeenCalledWith(401);<br>    expect(res.json).toHaveBeenCalledWith({ message: &#39;Unauthorized: Invalid credentials&#39; });<br>    expect(next).not.toHaveBeenCalled();<br>  });<br><br>  test(&#39;should call next() if valid credentials are provided&#39;, async () =&gt; {<br>    req.headers.client_id = &#39;valid_id&#39;;<br>    req.headers.client_secret = &#39;valid_secret&#39;;<br>    const mockPartner = { uuid: &#39;partner-uuid-123&#39;, client_id: &#39;valid_id&#39;, client_secret: &#39;valid_secret&#39; };<br>    authService.authenticate.mockResolvedValue(mockPartner);<br><br>    await authMiddleware(req, res, next);<br><br>    expect(authService.authenticate).toHaveBeenCalledWith(&#39;valid_id&#39;, &#39;valid_secret&#39;);<br>    expect(req.user).toEqual(mockPartner);<br>    expect(next).toHaveBeenCalled();<br>  });<br><br>  test(&#39;should return 500 for unexpected errors&#39;, async () =&gt; {<br>    req.headers.client_id = &#39;some_id&#39;;<br>    req.headers.client_secret = &#39;some_secret&#39;;<br>    authService.authenticate.mockRejectedValue(new Error(&#39;Database error&#39;));<br><br>    await authMiddleware(req, res, next);<br><br>    expect(res.status).toHaveBeenCalledWith(500);<br>    expect(res.json).toHaveBeenCalledWith({ message: &#39;Internal Server Error&#39; });<br>    expect(next).not.toHaveBeenCalled();<br>  });<br>});</pre><ul><li><strong>Enhancements:</strong><br> The authentication logic was further refactored to ensure that when credentials are missing or invalid, the system fails gracefully.</li></ul><h3>3. Mapping and Storing Invoice Analysis Data (AzureInvoiceMapper)</h3><h4>Overview</h4><p>A key feature of our project involved integrating with Azure Form Recognizer to process OCR results for invoices. The AzureInvoiceMapper class is responsible for transforming these raw OCR results into a structured invoice model that can be saved in our database.</p><h4>What I Did</h4><ul><li><strong>Data Extraction and Validation:</strong><br> The mapper parses invoice dates, due dates, monetary values, and line items from the OCR results. It also implements validations such as:</li><li><strong>Required Partner ID:</strong> If no partner ID is provided, the mapping throws an explicit error.</li><li><strong>Invalid Date Format:</strong> If dates cannot be parsed correctly, it throws an error such as “Invalid date format”.</li><li><strong>Default Values:</strong><br> When optional fields (such as payment terms) are missing, the mapper assigns default values (e.g., “Net 30”) or computes derived values (like due dates based on invoice dates and payment terms).</li><li><strong>Mapping Line Items:</strong><br> The function extracts an array of line items from the OCR data, ensuring that details like quantity, unit price, and description are mapped correctly.</li><li><strong>Test Coverage:</strong><br> A suite of tests was written to validate:</li><li>Complete and valid mappings.</li><li>Handling of missing optional data.</li><li>Correct extraction of line items.</li><li>Proper error throwing when encountering invalid data.</li></ul><p><strong>Key Code Snippet from AzureInvoiceMapper Test:</strong></p><pre>const { AzureInvoiceMapper } = require(&#39;../../src/services/azure-invoice-mapper&#39;);<br>const { mockAzureOcrResult } = require(&#39;../mocks/azure-ocr-result&#39;);<br>const { Invoice } = require(&#39;../../src/models&#39;);<br><br>describe(&#39;AzureInvoiceMapper&#39;, () =&gt; {<br>  let mapper;<br><br>  beforeEach(() =&gt; {<br>    mapper = new AzureInvoiceMapper();<br>    jest.clearAllMocks();<br>  });<br><br>  it(&#39;should map Azure OCR result to Invoice model format&#39;, () =&gt; {<br>    const ocrResult = mockAzureOcrResult();<br>    const invoiceData = mapper.mapToInvoiceModel(ocrResult);<br>    expect(invoiceData).toBeDefined();<br>    expect(invoiceData.purchase_order_id).toBe(12345);<br>    expect(invoiceData.invoice_date).toEqual(new Date(&#39;2023-05-15&#39;));<br>    expect(invoiceData.due_date).toEqual(new Date(&#39;2023-06-15&#39;));<br>    expect(invoiceData.total_amount).toBe(110);<br>    expect(invoiceData.discount_amount).toBe(5);<br>    expect(invoiceData.payment_terms).toBe(&#39;Net 30&#39;);<br>    expect(invoiceData.status).toBe(&#39;Pending&#39;);<br>    expect(invoiceData.partner_id).toContain(&#39;contoso&#39;);<br>  });<br><br>  // Additional tests for missing fields, line items extraction, and error conditions...<br>});</pre><ul><li><strong>Improvements and Refactorings:</strong><br> The mapper was later enhanced to set default payment terms to Null when not provided and require an explicit partner ID. The uploadInvoice method was updated to validate file data and handle errors more gracefully.</li></ul><h3>4. Asynchronous Invoice Upload and UUID Migration</h3><h4>Overview</h4><p>With growing demands for scalability and security, our invoice upload process was refactored to run asynchronously and migrate from numeric IDs to universally unique identifiers (UUIDs). This change improves API responsiveness and ensures that invoice identifiers are secure and collision-resistant.</p><h4>What IDid</h4><ul><li><strong>Asynchronous Processing:</strong><br>The invoice upload flow was modified to process the invoice in the background. This was achieved by:</li><li>Initiating the upload and immediately returning a response with a status of “Processing”.</li><li>Using asynchronous processing techniques (such as Promise.race for timeout management) to avoid long-running tasks blocking the main execution thread.</li><li><strong>UUID Migration:</strong><br> The migration involved:</li><li>Changing the schema of the Invoice table to use UUIDs instead of numeric IDs.</li><li>Updating related models and queries to use UUIDs consistently.</li><li>Adjusting tests to verify that UUIDs are correctly generated and stored.</li><li><strong>Error Handling and Timeout Mechanism:</strong><br> A custom timeout mechanism was introduced to prevent asynchronous operations from hanging indefinitely. For instance, one test case verified that using a custom timeout (e.g., 5 seconds instead of the default) worked as expected.</li><li><strong>Test Code Example for Asynchronous Invoice Upload:</strong></li></ul><pre>test(&#39;should use custom timeout of 20 seconds instead of default 3&#39;, async () =&gt; {<br>  req = mockRequest({<br>    query: { customTimeout: &#39;5000&#39; }, // 5 seconds instead of default 3<br>    user: { uuid: &#39;test-uuid&#39; },<br>    file: {<br>      buffer: Buffer.from(&#39;%PDF-1.0\nValid PDF content&#39;),<br>      originalname: &#39;test.pdf&#39;,<br>      mimetype: &#39;application/pdf&#39;<br>    }<br>  });<br><br>  pdfValidationService.validatePDF.mockResolvedValue(true);<br>  pdfValidationService.isPdfEncrypted.mockResolvedValue(false);<br>  pdfValidationService.checkPdfIntegrity.mockResolvedValue(true);<br>  pdfValidationService.validateSizeFile.mockResolvedValue(true);<br><br>  const mockResult = {<br>    id: &quot;mocked-uuid-123&quot;,<br>    status: &quot;Processing&quot;,<br>    message: &quot;Success&quot;<br>  };<br><br>  invoiceService.uploadInvoice.mockResolvedValue(mockResult);<br>  await invoiceController.uploadInvoice(req, res);<br>  expect(res.status).toHaveBeenCalledWith(200);<br>  expect(res.json).toHaveBeenCalledWith({ message: mockResult });<br>});</pre><ul><li><strong>System Benefits:</strong><br> With UUIDs and asynchronous handling:</li><li><strong>Security:</strong> UUIDs are hard to guess, protecting against certain attack vectors.</li><li><strong>Scalability:</strong> The system can handle distributed databases and replication more efficiently.</li><li><strong>Resilience:</strong> Non-blocking asynchronous processing improves API responsiveness and overall user experience.</li></ul><h3>5. Uploading OCR Analysis JSON to Amazon S3</h3><h4>Overview</h4><p>To reduce the database load and support advanced debugging and audit trails, the final feature added the ability to store JSON results of OCR analysis on Amazon S3. This feature involves extending our FinancialDocumentService and S3Service.</p><h4>What We Did</h4><ul><li><strong>JSON Storage Extension:</strong><br>We added a new field analysis_json_url in our Invoice and PurchaseOrder models through database migrations. This field stores a URL pointing to the JSON result stored on S3.</li><li><strong>S3 Integration:</strong><br> The S3Service was expanded with a method uploadJsonResult() that:</li><li>Converts the JSON analysis result into a string.</li><li>Creates a unique filename (using a prefix based on document ID, or a generic prefix if none is provided).</li><li>Uploads the JSON file to a designated S3 bucket.</li><li>Returns the URL of the uploaded JSON file.</li><li><strong>Robust Error Handling:</strong><br>The integration carefully checks for issues like circular references in the JSON data, ensuring that only valid JSON is uploaded.</li><li><strong>Test Coverage:</strong><br> The test suite covers:</li><li>Successful uploads (positive cases).</li><li>Handling of null or undefined analysis results.</li><li>Edge cases like circular JSON references and very large data sets.</li><li><strong>Test Code Snippet for S3 JSON Upload:</strong></li></ul><pre>describe(&#39;FinancialDocumentService - uploadAnalysisResults&#39;, () =&gt; {<br>  let service;<br>  const mockAnalysisResults = { <br>    data: { <br>      fields: { <br>        invoiceId: { text: &#39;INV-001&#39; },<br>        total: { text: &#39;100.00&#39; }<br>      } <br>    }<br>  };<br>  const mockDocumentId = &#39;doc-123&#39;;<br>  const mockS3Url = &#39;https://example.com/analysis/doc-123-analysis.json&#39;;<br><br>  beforeEach(() =&gt; {<br>    jest.clearAllMocks();<br>    service = new FinancialDocumentService(&#39;TestDocument&#39;);<br>  });<br><br>  test(&#39;should upload analysis results to S3 and return URL&#39;, async () =&gt; {<br>    const result = await service.uploadAnalysisResults(mockAnalysisResults, mockDocumentId);<br>    expect(s3Service.uploadJsonResult).toHaveBeenCalledWith(mockAnalysisResults, mockDocumentId);<br>    expect(result).toBe(mockS3Url);<br>  });<br><br>  // Additional tests for negative and corner cases...<br>});</pre><ul><li><strong>Implementation Highlights:</strong><br>The new migration scripts, model updates, and service methods work together seamlessly to offload large OCR analysis data from the primary database to a scalable cloud storage solution, ensuring both performance and security.</li></ul><h3>Concluding Thoughts</h3><p>Test Driven Development is a transformative practice that drives better design, higher code quality, and enhanced maintainability. Our project exemplifies how disciplined TDD, with rigorous commit practices, and thorough testing across success, failure, and corner cases leads to robust and scalable features. From authentication to handling asynchronous file uploads and secure JSON storage on S3, each feature benefits from a test-first approach.</p><p>By writing tests that capture the complete expected behavior of the system, we not only improve the overall quality but also establish a safety net that significantly reduces maintenance overhead and simplifies future enhancements. Whether you are building new features or refactoring existing systems, TDD empowers you to deliver dependable, secure, and high-performing software.</p><p>Embrace TDD as a strategic approach in your development process — allow your tests to guide your implementation, and let each failing test be a stepping stone towards a better, more resilient system.</p><p>This article underscores the importance of TDD and provides a detailed walkthrough of its application in a real-world project. By incorporating these practices into your workflow, you can elevate the quality and reliability of your software while confidently navigating complex development challenges.</p><p><strong>References</strong></p><p><a href="https://www.browserstack.com/guide/what-is-test-driven-development">What is Test Driven Development (TDD)?</a> by BrowserStack</p><p><a href="https://www.youtube.com/watch?v=ln4WnxX-wrw">TDD Is The Best Design Technique</a> by Dave Farley (Modern Software Engineering)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ae6d0bb6433" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[enginee]]></title>
            <link>https://medium.com/@suryata/enginee-b91570e3db52?source=rss-2137f06b09d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b91570e3db52</guid>
            <dc:creator><![CDATA[I Made Surya Anahata Putra]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 16:46:00 GMT</pubDate>
            <atom:updated>2025-05-07T13:34:17.573Z</atom:updated>
            <content:encoded><![CDATA[<h3>From User Stories to Cyber Threats: The New Era of Software Testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x4LJ-YZ4D1LpwQ6z" /></figure><h3>Introduction</h3><p>In today’s fast-paced software development landscape, ensuring application quality and reliability is paramount. Financial applications, especially those processing sensitive documents like invoices and purchase orders, demand robust testing strategies. In this article, I’ll share insights from implementing a multi-layered testing approach in a document OCR project handling financial documents.</p><p>Our approach combines Behavior-Driven Development (BDD) for functional testing, stress testing for performance evaluation, and security penetration testing. Each methodology serves a specific purpose, creating a comprehensive quality assurance framework.</p><h3>Testing Methods Integration: A Complete View</h3><p>To understand how our testing approaches work together, the following chart illustrates the relationship between the various testing methodologies we’ve implemented:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SawZe6uSKUcwBu2S" /><figcaption><em>Testing Methods Chart</em></figcaption></figure><p>This chart demonstrates how each testing methodology addresses a different aspect of quality assurance:</p><ol><li><strong>BDD with Cucumber</strong> validates that the system functions correctly according to business requirements</li><li><strong>Stress Testing with K6</strong> ensures the system can handle expected load and identifies performance boundaries</li><li><strong>Security Testing</strong> verifies that the system is protected against common security threats</li></ol><p>Together, these testing approaches provide comprehensive coverage across functionality, performance, and security domains. They feed into our CI pipeline, creating a robust quality assurance process that addresses multiple dimensions of software quality. To better understand how each component contributes to this comprehensive strategy, let’s explore them in more detail, beginning with our approach to functional testing using Behavior-Driven Development.</p><h3>Behavior-Driven Development with Cucumber</h3><h4>What is BDD?</h4><p>Behavior-Driven Development bridges the gap between technical and non-technical stakeholders by expressing software behaviors in plain language that everyone can understand.</p><p>In our project, we implemented BDD using Cucumber.js to validate critical business workflows like retrieving purchase order status:</p><pre>Feature: Get Purchase Order Status<br>  As a partner<br>  I want to check the status of my purchase order<br>  So that I can know whether it has been processed successfully<br>Scenario: Successfully get the status of an analyzed purchase order<br>    Given a purchase order &quot;po-123&quot; exists with &quot;Analyzed&quot; status<br>    When the user requests status for purchase order &quot;po-123&quot;<br>    Then the response status for purchase order should be 200<br>    And the response should contain purchase order &quot;po-123&quot; with status &quot;Analyzed&quot;</pre><p>This feature file describes user behavior and expectations in plain English, making it accessible to business analysts, product owners, and developers alike.</p><h3>BDD Implementation</h3><p>The feature file is connected to JavaScript code through step definitions:</p><pre>// Excerpt from our step definitions file<br>When(&#39;the user requests status for purchase order {string}&#39;, async (poId) =&gt; {<br>  response = await request(app)<br>    .get(`/api/purchase-orders/status/${poId}/`)<br>    .set(headers);<br>});<br>Then(&#39;the response status for purchase order should be {int}&#39;, (statusCode) =&gt; {<br>  assert.strictEqual(response.statusCode, statusCode);<br>});<br>Then(&#39;the response should contain purchase order {string} with status {string}&#39;, (poId, status) =&gt; {<br>  const statusEnum = status === &#39;Analyzed&#39; ? <br>    DocumentStatus.ANALYZED : <br>    status === &#39;Processing&#39; ? <br>      DocumentStatus.PROCESSING : DocumentStatus.FAILED;<br>  <br>  assert.strictEqual(response.body.id, poId);<br>  assert.strictEqual(response.body.status, statusEnum);<br>});</pre><h3>Benefits of Our BDD Approach</h3><ol><li><strong>Clear Communication</strong>: The feature files serve as living documentation that non-technical stakeholders can understand.</li><li><strong>Test Coverage for Business Rules</strong>: Our BDD tests cover various scenarios including successful retrievals, error cases, and authentication requirements.</li><li><strong>Continuous Integration</strong>: BDD tests are integrated into our CI pipeline via GitHub Actions, ensuring functionality is maintained with every commit.</li></ol><p>One notable advantage we experienced was the ability to quickly onboard new team members who could understand the business requirements by reading the feature files.</p><h3>Performance Testing with K6</h3><h4>Why Stress Testing Matters</h4><p>For financial document processing systems, performance under load is critical. A system that works perfectly with a few concurrent users might crumble under production load.</p><h4>K6 Implementation</h4><p>We used K6, a modern load testing tool, to simulate various load scenarios:</p><pre>// Excerpt from our purchase order upload stress test<br>export const options = {<br>  stages: [<br>    { duration: &#39;30s&#39;, target: 10},  // Warm-up<br>    { duration: &#39;30s&#39;, target: 15},  // Load increase phase 1<br>    { duration: &#39;30s&#39;, target: 18},  // Load increase phase 2<br>    { duration: &#39;30s&#39;, target: 20},  // Load increase phase 3<br>    { duration: &#39;30s&#39;, target: 30},  // Medium load<br>    { duration: &#39;1m&#39;, target: 40 },  // Approaching high load<br>    { duration: &#39;1m&#39;, target: 60 },  // High load<br>    { duration: &#39;1m&#39;, target: 80 },  // Very high load<br>    { duration: &#39;1m&#39;, target: 100 }, // Extreme load<br>    { duration: &#39;1m&#39;, target: 300 }, // Very extreme load<br>  ],<br>  thresholds: {<br>    error_rate: [&#39;rate&lt;0.6&#39;], // fail if error rate &gt; 60%<br>    latency_p95: [&#39;p(95)&lt;3000&#39;], // fail if 95% of requests &gt; 3000ms<br>  }<br>};</pre><p>The test gradually increases load from 10 to 300 virtual users, allowing us to identify at what point performance degradation begins.</p><h3>Advanced Performance Metrics</h3><p>What makes our stress testing approach particularly valuable is the collection of detailed metrics:</p><pre>// Custom metrics for analyzing degradation patterns<br>const errorRate = new Rate(&#39;error_rate&#39;);<br>const timeoutErrors = new Counter(&#39;timeout_errors&#39;);<br>const latencyP95 = new Trend(&#39;latency_p95&#39;);<br>const requests = new Counter(&#39;requests&#39;);<br><br>// Per-stage metrics to identify precise degradation points<br>const stageErrorRates = {};<br>const stageLatencies = {};<br>const stageRequests = {};<br>const stageFailures = {};<br>const stageTimeoutErrors = {};</pre><p>We track not just overall metrics but performance at each load stage, allowing us to identify precisely when and how the system begins to degrade.</p><h3>Degradation Analysis</h3><p>The most valuable aspect of our stress testing approach is the detailed degradation analysis generated at the end of each test:</p><pre>export function handleSummary(data) {<br>  let report = &quot;\n=== Purchase Order Upload Stress Test Summary ===\n&quot;;<br>  <br>  // Analysis of timeouts and error rates<br>  const timeoutCount = data?.metrics?.timeout_errors?.values?.count ?? 0;<br>  const requestCount = data?.metrics?.requests?.values?.count ?? 0;<br>  const timeoutPercent = requestCount &gt; 0 ? <br>    (timeoutCount / requestCount * 100).toFixed(2) : &quot;0.00&quot;;<br>  <br>  // Detailed per-stage analysis to identify degradation patterns<br>  let degradationPoint = null;<br>  let crashPoint = null;<br>  <br>  for (let i = 0; i &lt; stageData.length; i++) {<br>    const stage = stageData[i];<br>    if (stage.timeouts &gt; 0) {<br>      if (degradationPoint === null) {<br>        degradationPoint = i;<br>        stageStatus = &quot;⚠️ Initial Degradation&quot;;<br>      }<br>      if (stage.errorRateValue &gt;= 0.5 &amp;&amp; crashPoint === null) {<br>        crashPoint = i;<br>        stageStatus = &quot;💥 Crash Point&quot;;<br>      }<br>    }<br>  }<br>  <br>  // Insights about system capacity<br>  if (degradationPoint !== null) {<br>    report += `🔍 System started showing signs of degradation at Stage ${degradationPoint} with ${stageData[degradationPoint].vuTarget} VUs\n`;<br>  }<br>}</pre><p>This code is designed to help us automatically review the results of our performance tests. By processing the data from our stress tests, it allows us to easily spot when the system starts to slow down or struggle as more users access it at the same time. The insights from this analysis are useful for understanding the system’s limits and knowing when improvements or upgrades might be needed.</p><p>Want to see the real results on our project? Let’s dive in!</p><h4>Stress Test Results</h4><p>We recently conducted a comprehensive stress test on our Purchase Order Upload endpoint, gradually increasing load from 10 to 300 virtual users. Here’s a summary of the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pnoc0_KuoukaOG_f" /><figcaption><em>Purchase Order Upload Stress Test Summary</em></figcaption></figure><h4>Performance Analysis by Stage</h4><p>The system demonstrated robust performance through most of the test stages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z4ddyoP1tEfjOc1b" /><figcaption><em>Purchase Order Performance Analysis by Stage</em></figcaption></figure><h4>Degradation Analysis</h4><p>The detailed analysis revealed important information about our system’s behavior under high load:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cgAQnXcVhu-ndhT-" /><figcaption><em>Purchase Order Degradation Analysis</em></figcaption></figure><h4>Key Findings</h4><ol><li><strong>Excellent Stability at Normal Load</strong>: The system handled up to 100 concurrent users with no timeouts or errors, maintaining excellent response times.</li><li><strong>Degradation Point Identified</strong>: The first signs of performance degradation appeared at 300 concurrent users, where the system experienced timeout errors (15.73% of requests).</li><li><strong>Response Delay Pattern</strong>: The primary degradation pattern was identified as timeout-based (response delay) rather than gradual performance decline, suggesting the system maintained good performance until reaching a specific bottleneck point.</li><li><strong>No Complete System Crash</strong>: Despite the significant load at 300 users, the system did not crash completely — 84.27% of requests were still processed successfully.</li><li><strong>Response Time Impact</strong>: The 95th percentile response time increased to 4888ms at maximum load, indicating that most users would experience noticeable but not catastrophic delays.</li></ol><h4>Recommendations Based on Results</h4><ol><li><strong>Optimize for 300+ Concurrent Users</strong>: Since the requirement is for 100 concurrent users, the system is currently operating within safe limits. However, if future scalability anticipates traffic reaching 300 concurrent users, we should focus on optimizing the identified bottleneck points.</li><li><strong>Implement Request Queuing</strong>: Since the degradation manifests as timeouts rather than crashes, implementing a request queuing system could help manage traffic spikes more effectively.</li><li><strong>Connection Pool Tuning</strong>: Review and optimize database connection pools to handle spikes in concurrent requests.</li></ol><p>The stress test has provided valuable data for capacity planning, helping us ensure the system can handle the expected production load with appropriate scaling and optimization.</p><h4>Stress Testing Findings</h4><p>Running these tests revealed that our system:</p><ol><li>Maintained good performance up to approximately 100 concurrent users</li><li>Started showing degradation with 300 users, primarily manifesting as increased response times and timeouts</li><li>Exhibited timeout errors in 15.73% of requests at peak load</li><li>Maintained stability without complete system crash even at maximum load</li></ol><p>This information was invaluable for capacity planning and identifying optimization opportunities.</p><h3>Security Testing with Penetration Testing</h3><h4>The Role of Security Testing</h4><p>Financial document processing systems handle sensitive information, making security testing essential. We implemented a custom authentication penetration testing script to identify security vulnerabilities.</p><h4>Python Penetration Testing Implementation</h4><p>Our penetration testing approach focuses on authentication mechanisms:</p><pre>class AuthenticationPenTester:<br>    def __init__(self, base_url=DEFAULT_BASE_URL):<br>        self.base_url = base_url;<br>        self.invoice_endpoint = f&quot;{self.base_url}{INVOICE_API_PATH}&quot;;<br>        self.po_endpoint = f&quot;{self.base_url}{PO_API_PATH}&quot;;<br>        self.vulnerabilities_found = [];<br>        self.success_count = 0;<br>        self.failure_count = 0;<br>        self.test_count = 0;<br>        <br>    def run_tests(self):<br>        &quot;&quot;&quot;Run all authentication penetration tests&quot;&quot;&quot;<br>        print(f&quot;{Fore.CYAN}🔒 AUTHENTICATION PENETRATION TESTING - OCR-Group 6-API 🔒{Style.RESET_ALL}&quot;);<br>        <br>        // Run the different test categories<br>        self.test_missing_credentials();<br>        self.test_credential_manipulation();<br>        self.test_credential_leakage();</pre><p>The script tests several security aspects:</p><ol><li><strong>Missing Credential Testing</strong>: Ensures the API properly rejects requests with missing authentication information</li><li><strong>Credential Manipulation Testing</strong>: Tests SQL injection attempts and other manipulation techniques</li><li><strong>Credential Leakage Testing</strong>: Checks if errors expose sensitive information</li></ol><pre>def test_credential_manipulation(self):<br>    &quot;&quot;&quot;Test for SQL injection and other manipulation in client credentials&quot;&quot;&quot;<br>    print(f&quot;\n{Fore.BLUE}[INFO] Testing credential manipulation vulnerabilities...{Style.RESET_ALL}&quot;);<br>    <br>    // Test payloads<br>    payloads = [<br>        {&quot;desc&quot;: &quot;SQL Injection 1&quot;, &quot;client_id&quot;: &quot;&#39; OR 1=1--&quot;, &quot;client_secret&quot;: &quot;test&quot;},<br>        {&quot;desc&quot;: &quot;SQL Injection 2&quot;, &quot;client_id&quot;: &quot;test&quot;, &quot;client_secret&quot;: &quot;&#39; OR 1=1--&quot;},<br>        {&quot;desc&quot;: &quot;SQL Injection 3&quot;, &quot;client_id&quot;: &quot;&#39; UNION SELECT * FROM partner--&quot;, &quot;client_secret&quot;: &quot;test&quot;},<br>        {&quot;desc&quot;: &quot;NoSQL Injection&quot;, &quot;client_id&quot;: &#39;{&quot;$gt&quot;:&quot;&quot;}&#39;, &quot;client_secret&quot;: &quot;test&quot;},<br>        {&quot;desc&quot;: &quot;Long String&quot;, &quot;client_id&quot;: &quot;A&quot; * 1000, &quot;client_secret&quot;: &quot;test&quot;}<br>    ];</pre><h4>Security Testing Results</h4><p>Our penetration testing identified several areas for improvement:</p><ol><li>Some error responses contained too much information that could potentially aid attackers</li><li>Certain endpoints had inconsistent authentication requirements</li><li>There were opportunities to strengthen validation against injection attempts</li></ol><h3>Challenges &amp; How We Overcame Them</h3><p>During our testing journey, we encountered several significant challenges that required creative solutions. These real-world obstacles and their resolutions provided valuable learning experiences that improved both our testing approach and the system architecture itself.</p><h4>1. External Service Dependencies During Stress Testing</h4><p><strong>Challenge</strong>: Our initial stress test implementation directly hit production dependencies like Azure Document Analysis and S3 storage services. This created several problems:</p><ul><li>Incurring unnecessary costs from thousands of API calls to paid services</li><li>Hitting rate limits on these external services</li><li>Test results being affected by external service performance rather than our system</li><li>Potential data pollution in production systems</li></ul><p><strong>Solution</strong>: We implemented a “skipAnalysis” feature in our API that bypassed external service calls during stress testing:</p><pre>// Excerpt from processInvoiceAsync with skipAnalysis parameter<br>async processInvoiceAsync(invoiceId, buffer, partnerId, originalname, uuid, skipAnalysis = false) {<br>  // ...existing code...<br>  <br>  let analysisResult;<br>  if (skipAnalysis) {<br>    // Use sample data for testing instead of calling Azure service<br>    analysisResult = await this.loadSampleData();<br>    await this.logger.logAnalysisComplete(invoiceId, &quot;Using sample data&quot;);<br>  } else {<br>    // Normal flow using Azure Document Analysis<br>    analysisResult = await this.analyzeInvoice(buffer);<br>    await this.uploadAnalysisResults(analysisResult, invoiceId);<br>    await this.logger.logAnalysisComplete(invoiceId, analysisResultsUrl);<br>  }<br>  <br>  // ...continue with common processing...<br>}</pre><p>This change allowed us to accurately measure our system’s performance without external dependencies influencing the results, while also saving on costs and preventing potential service disruptions.</p><h3>2. Feature File Maintainability in BDD</h3><p><strong>Challenge</strong>: As our project grew, we found that our Cucumber feature files were becoming difficult to maintain. Changes to the API often required updates to multiple feature files, and there was significant duplication across scenarios. Additionally, different team members were writing scenarios with inconsistent styles and levels of detail.</p><p><strong>Solution</strong>: We implemented a standardized approach to BDD scenario authoring with shared step definitions and a more consistent structure:</p><ol><li>Created a centralized step definition library for common operations:</li></ol><pre>// Common steps for authentication across feature files<br>Given(&#39;a valid authenticated {word}&#39;, async (userType) =&gt; {<br>  // Dynamic authentication setup based on user type<br>  await setupAuthenticationForUser(userType);<br>});<br>Given(&#39;an unauthenticated user&#39;, async () =&gt; {<br>  // Clear authentication headers<br>  clearAuthHeaders();<br>});</pre><ol><li>Established style guidelines for feature file creation:</li></ol><ul><li>Each feature file focuses on a single functionality</li><li>Standard “Background” sections for common setup</li><li>Consistent terminology across scenarios</li><li>Pattern of Given/When/Then that clearly separates setup, action, and verification</li></ul><p>These improvements significantly increased the maintainability of our BDD tests and made them more valuable as living documentation for the system.</p><h3>Comparing Testing Approaches</h3><p>Each testing methodology offers unique insights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrFtH6_02W-sQ6HXs6IF2A.png" /><figcaption>Characteristics of each method</figcaption></figure><h3>Integration into Development Workflow</h3><p>These tests were integrated into our CI/CD workflow using GitHub Actions:</p><pre># BDD tests run on all branches and PRs<br>name: BDD Test CI<br>on:<br>  push:<br>    branches: [&#39;**&#39;]<br>  pull_request:<br>    branches: [&#39;**&#39;]<br>jobs:<br>  run-bdd-tests:<br>    name: Run Cucumber.js BDD Tests<br>    runs-on: ubuntu-latest<br>    steps:<br>    - name: Checkout repository<br>      uses: actions/checkout@v3<br>    - name: Set up Node.js<br>      uses: actions/setup-node@v3<br>      with:<br>        node-version: &#39;20&#39;<br>    - name: Install dependencies<br>      working-directory: ./backend<br>      run: npm install<br>    - name: Run BDD tests<br>      working-directory: ./backend<br>      run: npm run test:cucumber</pre><p>The stress tests are run on demand to avoid unnecessary resource usage:</p><pre>name: Stress Test<br>on:<br>  workflow_dispatch:<br>    inputs:<br>      test_type:<br>        description: &quot;Stress test type to run&quot;<br>        required: true<br>        default: &quot;all&quot;<br>        type: choice<br>        options:<br>          - all<br>          - upload<br>          - get-by-id</pre><h3>Lessons Learned and Best Practices</h3><p>From implementing this comprehensive testing approach, we gained several valuable insights:</p><ol><li><strong>Start Simple, Then Expand</strong>: Begin with basic BDD scenarios that cover the core business functionality, then expand to edge cases.</li><li><strong>Realistic Load Testing</strong>: Configure stress tests to mirror expected production loads and then go beyond to identify breaking points.</li><li><strong>Incremental Load Steps</strong>: Use small, incremental steps in stress tests to precisely identify the point where performance degradation begins.</li><li><strong>Security Testing with Expertise</strong>: Enlist security expertise when designing penetration tests to ensure they’re thorough and ethically sound.</li><li><strong>Integrate Tests Early</strong>: Don’t leave testing until the end of development — integrate it from the beginning to catch issues early.</li><li><strong>Automated Test Reports</strong>: Generate detailed test reports like our stress test degradation analysis to provide actionable insights.</li></ol><h3>Conclusion</h3><p>A multi-layered testing approach combining BDD, stress testing, and security testing provides comprehensive quality assurance for financial document processing systems. By implementing these complementary methodologies, we were able to validate functional requirements, ensure performance under load, and strengthen security — resulting in a robust, reliable application.</p><p>Each testing methodology serves a different purpose but together they create a safety net that catches issues before they reach production, ultimately leading to higher quality software that meets both business and technical requirements.</p><p>What testing methodologies have you found most effective for your projects? Have you implemented a similar multi-layered approach? Let me know through the comments.</p><p><em>Author’s Note: This article is based on real-world implementation of testing strategies in a financial document OCR processing system. The code samples have been adapted from actual production code with sensitive information removed.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b91570e3db52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Struggling with Merge Request Reviews and Coverage Checks? Codecov AI is Your Solution!]]></title>
            <link>https://medium.com/@suryata/habit-in-software-engineering-e9632420f55a?source=rss-2137f06b09d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9632420f55a</guid>
            <dc:creator><![CDATA[I Made Surya Anahata Putra]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 16:45:45 GMT</pubDate>
            <atom:updated>2025-03-25T07:12:50.363Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="ai asistant pic" src="https://cdn-images-1.medium.com/max/626/0*z9x9lWrQvqCWROQ0" /><figcaption>source: freepik.com</figcaption></figure><p>In today’s fast-paced development environment, maintaining high code quality while fostering effective teamwork is crucial. Reviewing merge requests and checking test coverage manually can be overwhelming, especially when multiple files and complex changes are involved.</p><p>Fortunately, integrating <strong>Codecov AI</strong> into your workflow can streamline this process significantly. In this blog post, we’ll walk through setting up Codecov in your CI pipeline, configuring it properly, and integrating Codecov AI to enhance your merge request reviews. Let’s dive into how you can set it up and benefit from automated AI recommendations!</p><h3>1. Generating and Storing the Codecov Token</h3><p>Before you set up Codecov in your CI pipeline, you need a CODECOV_TOKEN. Here’s how to get it and securely store it in your GitHub repository:</p><ol><li><strong>Log In to Codecov</strong></li></ol><ul><li>Go to Codecov and sign in with your GitHub account (or any other supported provider).</li></ul><p><strong>2. Navigate to Your Repository Settings</strong></p><ul><li>From your Codecov dashboard, select the repository you want to integrate.</li><li>Go to Configuration menu.</li></ul><p><strong>3. Generate/Copy Your </strong><strong>CODECOV_TOKEN</strong></p><ul><li>Under <strong>General</strong>, find the option to generate or copy your CODECOV_TOKEN.</li><li>Copy this token to your clipboard.</li></ul><p><strong>4. Add the </strong><strong>CODECOV_TOKEN as a GitHub Secret</strong></p><ul><li>In your GitHub repository, go to <strong>Settings</strong> → <strong>Secrets and variables</strong> → <strong>Actions</strong> → <strong>New repository secret</strong>.</li><li>Set the <strong>Name</strong> to CODECOV_TOKEN (exactly matching your CI configuration).</li><li>Paste your token into the <strong>Secret</strong> field.</li><li>Click <strong>Add secret</strong>.</li></ul><p>This ensures your token is securely stored and won’t appear in logs or be exposed publicly.</p><h3>2. Setting Up Codecov in Your CI Pipeline</h3><p>To get started, add the following steps to your CI configuration file (e.g., ci.yml). This ensures that your coverage reports and test results are automatically uploaded to Codecov.</p><pre>- name: Upload coverage reports to Codecov<br>  uses: codecov/codecov-action@v5<br>  with:<br>    token: ${{ secrets.CODECOV_TOKEN }}<br>    directory: ./backend/coverage<br>    fail_ci_if_error: true  <br>    verbose: true  <br>- name: Upload test results to Codecov<br>  if: ${{ !cancelled() }}<br>  uses: codecov/test-results-action@v1<br>  with:<br>    token: ${{ secrets.CODECOV_TOKEN }}</pre><h3>Explanation:</h3><ul><li><strong>Upload Coverage Reports:</strong></li><li><strong>Token:</strong> Secures the connection with Codecov using your secret token.</li><li><strong>Directory:</strong> Specifies where your coverage reports are stored (in this case, ./backend/coverage).</li><li><strong>fail_ci_if_error:</strong> Forces the CI build to fail if there’s an error during upload, ensuring that every build has valid coverage data.</li><li><strong>verbose:</strong> Provides detailed logs to help diagnose any issues during the upload process.</li><li><strong>Upload Test Results:</strong><br> This step ensures that your test results are also uploaded to Codecov, offering a comprehensive view of your testing metrics.</li></ul><h4>Configuring Codecov with codecov.yml</h4><p>A well-configured codecov.yml file is essential to enforce your project&#39;s coverage standards. Here’s a sample configuration:</p><pre>codecov:<br>  require_ci_to_pass: yes<br>coverage:<br>  precision: 2<br>  round: down<br>  range: &quot;70...100&quot;<br>  status:<br>    project:<br>      default:<br>        target: 90%<br>        threshold: 1%<br>        if_ci_failed: error<br>        if_not_found: success<br>    patch:<br>      default:<br>        target: 90%<br>        threshold: 1%<br>        if_ci_failed: error<br>        if_not_found: success<br>parsers:<br>  gcov:<br>    branch_detection:<br>      conditional: yes<br>      loop: yes<br>      method: yes<br>      macro: no<br>comment:<br>  layout: &quot;reach,diff,flags,files,footer&quot;<br>  behavior: default<br>  require_changes: no</pre><h3>Explanation:</h3><ul><li><strong>codecov.require_ci_to_pass:</strong><br> Ensures that coverage reports are only considered valid if all CI builds pass.</li><li><strong>Coverage Settings:</strong></li><li><strong>Precision &amp; Round:</strong> Define the precision of your coverage percentage and how values are rounded.</li><li><strong>Range:</strong> Sets the acceptable range for your coverage.</li><li><strong>Status:</strong> Configures target coverage (set at 90% in this example) and error thresholds for both overall project and patch-level changes. This helps maintain high quality, even for incremental changes.</li><li><strong>Parsers:</strong><br> This section configures how Codecov interprets your coverage reports (using gcov in this case) and handles branch detection to analyze different aspects of your code paths.</li><li><strong>Comment Layout:</strong><br> Determines the layout of the automated comments that Codecov posts on merge requests. This includes overall coverage, differences from the previous commit, and any relevant flags or file changes.</li></ul><h4>Automatic Coverage Reports on Pull Requests</h4><p>Once properly configured, every time you create or update a pull request, Codecov will automatically post a clear coverage report directly within your pull request, highlighting if all lines modified or added are fully covered by tests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqzMzs825nKU3AeZoFrvbw.png" /></figure><p>You can also view a detailed breakdown of coverage metrics for each file in the Codecov dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWSazC4ON_tyZOTXAIVKEQ.png" /></figure><p>These automatic reports help your team quickly identify potential coverage gaps and ensure that each pull request meets your coverage standards before merging. By seeing a green checkmark (and “100.00%” coverage), you can be confident that the changes introduced in the pull request are thoroughly tested.</p><h4>Why This Matters</h4><ul><li><strong>Immediate Feedback</strong><br>The pull request comment from Codecov tells you at a glance whether you’ve met your coverage goals.</li><li><strong>Comprehensive View</strong><br>The dashboard screenshot shows a granular view of which lines are covered and which are not, helping you pinpoint specific files or lines needing additional tests.</li><li><strong>Enforces High Standards</strong><br>By failing the CI build if coverage requirements are not met (fail_ci_if_error: true and if_ci_failed: error), you maintain a consistently high level of code quality.</li></ul><p>In the provided images, everything is fully covered, demonstrating that the coverage and testing setup is working exactly as intended.</p><h3>3. Integrating Codecov AI for Enhanced Merge Request Reviews</h3><p>After setting up Codecov, the next step is to leverage <strong>Codecov AI</strong> to further improve your merge request process. Codecov AI provides automated, real-time recommendations on your pull requests, making it easier to identify issues and optimize your code. Follow this tutorial to use Codecov AI for your projects.</p><h4>Step 1: Setting Up Codecov AI for Your Repository</h4><ol><li>Go to the <a href="https://github.com/apps/codecov-ai/">Codecov AI App</a> on GitHub.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3LegUymyZygRc6qxb3lDQg.png" /></figure><p>2. Click <strong>Configure</strong> to link your GitHub organization.</p><p>3. Select the GitHub organization you wish to integrate with Codecov AI.</p><p>4. Choose the specific repositories you’d like to connect and click <strong>Save</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTRyEtRHBKpdNAaPxktOBw.png" /></figure><h4>Step 2: How to Use Codecov AI in Merge Requests</h4><p>In any pull request, simply add the following command in a comment:</p><pre>@codecov-ai-reviewer review</pre><p>This triggers Codecov AI to analyze your pull request, offering suggestions for improvements, ranging from enhanced test coverage to code optimization tips.</p><h4>Step 3: Understanding Recommendations from Codecov AI</h4><p>Here’s how Codecov AI helps in practice:</p><h4>Example 1: Recommendations for Improvements</h4><p>Codecov AI can pinpoint specific areas where your test implementation might be improved. For example, it may recommend using Jest’s fake timers (jest.useFakeTimers()) instead of directly mocking global objects, which ensures more consistent and reliable test results. Below is an example where Codecov AI identified a more robust approach for handling date mocks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3tDNFLP5irui4Yc22Z8jw.png" /></figure><p>In this example, the Codecov AI clearly explained why using Jest’s fake timers provides a more reliable solution and offered a suggested change that team members can apply instantly.</p><h3>Example 2: Quick Applying Suggestions</h3><p>When Codecov AI suggests improvements, team members don’t need to manually rewrite the code. Just click <strong>Commit suggestion</strong>, and then confirm by clicking <strong>Commit changes</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_eUbgItUl7Oc1pcBjw2WQ.png" /></figure><p>Once applied, it’s immediately reflected in your repository and it will be look like this in your changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CfMW5IoSzbC80L6V8OC6JA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibdleYtxNtHI4x5E5_IuGQ.png" /></figure><h3>Example 3: When No Changes Are Needed</h3><p>Sometimes, the submitted code is already optimized, and no further changes are needed. In such cases, Codecov AI clearly communicates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lg1a9i5lZa-79bc4p2lNdw.jpeg" /></figure><p>This quickly confirms your merge request is ready for approval without additional manual checks.</p><h3>Benefits of Codecov AI:</h3><ul><li><strong>Huge Time Saver</strong><br>Codecov AI significantly cuts down the time developers spend manually scrutinizing each line of code. By providing immediate feedback on coverage gaps and potential issues, it frees your team to focus on more strategic tasks like designing new features or improving application architecture.</li><li><strong>Efficient Code Reviews</strong><br>When Codecov AI highlights areas needing attention, reviewers can quickly pinpoint test deficiencies or logical errors. This accelerates the code review process and ensures that every merge request maintains a consistently high standard of quality.</li><li><strong>Scalability</strong><br>For large merge requests with extensive changes, Codecov AI’s automated insights prevent reviewers from getting overwhelmed. It efficiently surfaces only the most critical issues, making it easier to manage even the biggest codebase over time.</li><li><strong>Improved Team Collaboration</strong><br>By automatically flagging common pitfalls and suggesting improvements, Codecov AI reduces the need for multiple rounds of manual feedback. Team members spend less time waiting on one another for reviews, enabling a smoother development cycle and more cohesive collaboration.</li></ul><h3>4. Maximizing Team Efficiency with Codecov</h3><p>Integrating Codecov and Codecov AI into your workflow not only enforces high-quality standards but also boosts overall team productivity. Here’s how:</p><ul><li><strong>Consistent Quality Assurance:</strong><br>Automated feedback and coverage reports ensure that every commit and merge meets the established quality standards, reducing technical debt over time.</li><li><strong>Streamlined Merge Requests:</strong><br>With Codecov AI reviewing merge requests, potential issues are flagged early, leading to quicker, more effective code reviews.</li><li><strong>Improved Communication:</strong><br>Detailed automated comments and coverage insights serve as a communication tool, helping team members understand the impact of their changes and work more cohesively.</li><li><strong>Tool Integration:</strong><br> The seamless integration between your CI/CD pipeline, Codecov, and Codecov AI exemplifies how well-orchestrated tools can maximize teamwork — from requirements gathering to deployment.</li></ul><h3>Conclusion</h3><p>By setting up Codecov and leveraging Codecov AI, you’re not just enforcing a high standard of code quality but you’re also fostering a more efficient and collaborative team environment. The disciplined use of these tools, from CI configuration and detailed coverage settings to actionable AI insights in merge requests. it demonstrates how technology can drive productivity and maintain rigorous quality assurance.</p><p>Integrate Codecov into your workflow today and experience firsthand how automation and intelligent feedback can transform your development process for the better!</p><p>Happy coding, and may your merge requests be ever successful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9632420f55a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[theimp]]></title>
            <link>https://medium.com/@suryata/theimp-10cb56a7f5d9?source=rss-2137f06b09d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/10cb56a7f5d9</guid>
            <dc:creator><![CDATA[I Made Surya Anahata Putra]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 14:32:25 GMT</pubDate>
            <atom:updated>2025-04-10T16:41:28.942Z</atom:updated>
            <content:encoded><![CDATA[<h3>Best Practice Programming: SOLID Principles as the Foundation for Quality Software Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vWqT_i0D-v9K6C8q" /></figure><p>In modern software development, applying <strong>best practices</strong> is key to building systems that are maintainable, scalable, and robust. One of the most influential approaches is the application of the <strong>SOLID Principles</strong> , a set of object-oriented design guidelines popularized through resources like DigitalOcean and Baeldung. In this blog, we explore how SOLID is applied in a real-world project, alongside other best practices such as separation of concerns, repository and service patterns, and test-driven development.</p><h3>What is SOLID?</h3><p><strong>SOLID</strong> is an acronym that represents five foundational principles for designing effective and maintainable software:</p><ul><li><strong>S</strong>: Single Responsibility Principle (SRP)</li><li><strong>O</strong>: Open/Closed Principle (OCP)</li><li><strong>L</strong>: Liskov Substitution Principle (LSP)</li><li><strong>I</strong>: Interface Segregation Principle (ISP)</li><li><strong>D</strong>: Dependency Inversion Principle (DIP)</li></ul><p>These principles aim to reduce code complexity, enhance readability, and allow new features to be added with minimal disruption to the existing system. For further detailed insights, refer to the articles on <a href="https://www.digitalocean.com/community/conceptual-articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design">DigitalOcean</a> and <a href="https://www.baeldung.com/solid-principles">Baeldung</a> .</p><h3>1. Single Responsibility Principle (SRP)</h3><p>The <strong>Single Responsibility Principle</strong> dictates that each class should have one and only one reason to change. In our project, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwsjE_PzSKSFQ6sH_MF9Lw.png" /><figcaption>SRP Implementation</figcaption></figure><ul><li><strong>InvoiceService</strong>, <strong>InvoiceLogger</strong>, <strong>InvoiceValidator</strong>, and <strong>InvoiceResponseFormatter</strong> are each designed to handle specific responsibilities. This clear separation ensures that business logic is not mingled with logging or validation logic.</li><li>Organized folder structure with directories such as controllers, services, repositories, models, and utils demonstrates clear responsibility segregation.</li><li><strong>InvoiceLogger</strong> focuses exclusively on logging without interfering with core business logic.</li></ul><p>Implementing SRP simplifies maintenance and testing because each component is self-contained with a limited responsibility.</p><p><strong>We always follow a strict rule for applying SRP:</strong><br>Our development team enforces a disciplined approach where every component is designed with a single, well-defined responsibility. This strict adherence to SRP ensures that any modifications in one area do not inadvertently affect others. By compartmentalizing functionality, we achieve enhanced modularity, improved readability, and easier testability, ultimately leading to a more maintainable and scalable codebase.</p><h3>2. Open/Closed Principle (OCP)</h3><p>The <strong>Open/Closed Principle</strong> states that software entities should be open for extension but closed for modification. In our project:</p><ul><li><strong>InvoiceService</strong> inherits from <strong>FinancialDocumentService</strong>, allowing us to extend functionality without altering the base class.</li><li>A modular <strong>Mapper Service</strong>, such as <strong>AzureInvoiceMapper</strong>, is designed to be extended to support additional data extraction formats.</li></ul><p>By embracing OCP, new functionalities can be added with minimal risk of affecting the established functionality elsewhere in the system.</p><h3>3. Liskov Substitution Principle (LSP)</h3><p>The <strong>Liskov Substitution Principle</strong> ensures that derived classes can be substituted for their base classes without altering the correctness of the system. In this project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*5AtoH6BAS7YNvhiKa_zF8Q.png" /><figcaption>LSP Implementation</figcaption></figure><ul><li><strong>InvoiceService</strong> extends <strong>FinancialDocumentService</strong> and adds new functionalities while remaining consistent with the base contract.</li><li>The consistent application of the repository pattern ensures that repository implementations can be replaced with their subclasses without any adverse effects.</li></ul><p>This principle is crucial for ensuring that system changes or subclass substitutions do not introduce unexpected errors or behaviors.</p><h3>4. Interface Segregation Principle (ISP)</h3><p>The <strong>Interface Segregation Principle</strong> advises that many client-specific interfaces are better than one general-purpose interface. In the project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O0AwBvYTJGNh23DdXg5urg.png" /><figcaption>ISP Implementation</figcaption></figure><ul><li>Domain-specific repositories: <strong>InvoiceRepository</strong>, <strong>CustomerRepository</strong>, <strong>VendorRepository</strong>, and <strong>ItemRepository, </strong>are designed to focus on distinct domains.</li><li>Separating services for validation, logging, mapping, and invoice processing ensures that each part of the system is not burdened with irrelevant functionality.</li></ul><p>ISP leads to a more modular and maintainable codebase by avoiding large, monolithic interfaces.</p><h3>5. Dependency Inversion Principle (DIP)</h3><p>The <strong>Dependency Inversion Principle</strong> focuses on depending upon abstractions rather than concrete implementations. In our project, this is evident from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xV6_-IizKAIeyqyALxi9zA.png" /><figcaption>DIP Implementation</figcaption></figure><ul><li><strong>Dependency Injection</strong>: The <strong>InvoiceService</strong> constructor receives various dependencies (repositories, validators, analyzers) as parameters, enabling easy replacement without modifying the class itself.</li><li>The use of interfaces facilitates interaction with abstractions rather than relying on concrete implementations.</li><li>The integration of mocking in tests, for instance using mocks for winston, shows that the code relies on abstractions, thereby simplifying unit testing.</li></ul><p>Applying DIP enhances flexibility and reduces coupling between components, making the system more adaptable to change.</p><h3>Additional Best Practices</h3><p>Beyond SOLID, several other best practices contribute significantly to the success of large-scale projects:</p><ul><li><strong>Separation of Concerns (SoC):</strong> Clear folder structures (controllers, services, repositories, models, utils) ensure each part of the application handles its specific responsibility.</li><li><strong>Repository Pattern:</strong> Organizing data access through a repository layer allows for easier changes in data sources.</li><li><strong>Service Pattern:</strong> Separating business logic into service layers helps to keep controllers lean and focused.</li><li><strong>Test-Driven Development (TDD):</strong> Comprehensive unit testing ensures that any change or addition does not break existing functionality.</li></ul><p>Implementing these practices not only strengthens the software architecture but also streamlines maintenance and feature expansion.</p><h3>The Benefits of SOLID for Large-Scale Software Maintenance</h3><p>The adoption of SOLID Principles and other best practices brings numerous benefits:</p><ul><li><strong>Ease of Modification:</strong> With code separated by responsibilities, changes in one area have minimal impact on others.</li><li><strong>Flexibility in Development:</strong> New features can be integrated using extension mechanisms (inheritance or interface implementation) without affecting the core functionalities.</li><li><strong>Simplified Testing:</strong> Dependency injection and reliance on abstractions make unit testing straightforward and effective.</li><li><strong>Clear Commit Differentiation:</strong> Commit histories become more meaningful, with clear diffs that highlight improvements from applying SOLID principles and best practices.</li></ul><h3>Comparing Best Practice Implementations</h3><p>There is no one-size-fits-all solution in software design. It’s essential to evaluate various best practice implementations. For instance, consider comparing:</p><ul><li><strong>Folder and Module Structures:</strong> Determine which approaches lead to better maintainability and scalability.</li><li><strong>SOLID vs. Non-SOLID Approaches:</strong> Analyze the impact on testing, feature addition, and dependency management.</li></ul><h3>Conclusion</h3><p>Implementing <strong>best practice programming</strong> and <strong>SOLID Principles</strong> is a cornerstone for developing quality software. By separating responsibilities, allowing system extensions without modification, ensuring correct class substitution, and managing dependencies through abstractions, the following benefits can be achieved:</p><ul><li><strong>Maintainability:</strong> Easier system maintenance and testing.</li><li><strong>Scalability:</strong> A code structure that can grow effectively.</li><li><strong>Flexibility:</strong> The ability to adapt and add new features with minimal risk.</li></ul><p>Coupled with additional practices like separation of concerns, repository and service patterns, and test-driven development, these principles pave the way for robust software that stands up to the challenges of ongoing development and rapid changes.</p><p>I hope this blog serves as a helpful guide for integrating best programming practices and inspires you to apply SOLID Principles in your own projects!</p><p><em>Sourced from </em><a href="https://www.digitalocean.com/community/conceptual-articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design"><em>DigitalOcean SOLID Principles</em></a><em> and </em><a href="https://www.baeldung.com/solid-principles"><em>Baeldung SOLID Principles</em></a><em> .</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10cb56a7f5d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing SonarQube in an Express.js Project with GitHub Actions]]></title>
            <link>https://medium.com/@suryata/whativelearnedtoday-13b32f3bd130?source=rss-2137f06b09d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/13b32f3bd130</guid>
            <dc:creator><![CDATA[I Made Surya Anahata Putra]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 14:32:08 GMT</pubDate>
            <atom:updated>2025-03-04T06:30:41.590Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Maintaining code quality and security is essential for any modern web application, including those built with <strong>Express.js</strong>. One of the most powerful ways to ensure your code is reliable, secure, and easy to maintain is by using <strong>SonarQube</strong>. SonarQube is an open-source platform that performs static code analysis, identifies potential bugs, security vulnerabilities, code smells, and even measures test coverage.</p><p>In this blog post, we will discuss:</p><ol><li>Why SonarQube is beneficial for your Express.js project.</li><li>How to set up and integrate SonarQube analysis into your existing workflow.</li><li>A sample <strong>GitHub Actions</strong> workflow that automatically runs SonarQube analysis on every push and pull request.</li><li>Explanation of the SonarQube UI screenshots (Failed vs. Passed) and what they mean for your project’s code quality.</li></ol><h3>1. Why SonarQube for an Express.js Project?</h3><ol><li><strong>Early Bug Detection</strong><br>SonarQube’s static analysis helps you find and fix bugs before they cause production issues.</li><li><strong>Security Monitoring</strong><br>It detects potential vulnerabilities and security hotspots, such as places where your application could be susceptible to Denial of Service (DoS) attacks or unvalidated input.</li><li><strong>Maintaining Code Quality</strong><br>SonarQube enforces code quality standards, alerting you to code smells, duplicated code, and complex methods that can reduce maintainability.</li><li><strong>Test Coverage</strong><br>It seamlessly integrates with testing frameworks (like Jest) to display coverage metrics, helping you ensure that critical parts of your application are well-tested.</li></ol><h3>2. Setting Up SonarQube</h3><h4>2.1 Installing SonarQube</h4><p>You can install <strong>SonarQube</strong> either on your local machine or on a dedicated server. Common approaches include:</p><ul><li><strong>Using Docker</strong></li></ul><pre>docker run -d --name sonarqube -p 9000:9000 sonarqube:latest</pre><p><strong>Manual Installation</strong><br>Download the latest <a href="https://www.sonarsource.com/products/sonarqube/downloads/">SonarQube Community Edition</a> and follow the official setup instructions.</p><p>Once running, SonarQube is accessible at http://localhost:9000 (or the configured server URL).</p><h4>2.2 Creating a New Project</h4><ol><li>Open the SonarQube dashboard in your browser.</li><li>Click <strong>Create new project</strong> (or <strong>+</strong> icon).</li><li>Provide a project name and key (e.g., <strong>“express-invoice-service”</strong>).</li><li>Generate or note the <strong>SonarQube token</strong> for authentication when performing analyses.</li></ol><h3>3. Integrating SonarQube with Your Express.js Project</h3><h4>3.1 Project Structure</h4><p>Here is a simple folder structure for an Express.js project:</p><pre>express-invoice-service<br>├── controllers<br>│   └── invoiceController.js<br>├── routes<br>│   └── invoiceRoutes.js<br>├── tests<br>│   └── invoiceController.test.js<br>├── package.json<br>└── ...</pre><h4>3.2 Installing Sonar Scanner</h4><p>SonarQube requires a <strong>Sonar Scanner</strong> to analyze your code. You can install it globally or locally:</p><pre># Global install<br>npm install -g sonar-scanner</pre><pre># Or local install (recommended)<br>npm install --save-dev sonar-scanner</pre><h3>3.3 Configuring sonar-project.properties</h3><p>In your project root, create a file named sonar-project.properties:</p><pre>sonar.projectKey=express-invoice-service<br>sonar.host.url=https://sonarqube.cs.ui.ac.id<br>sonar.login=${SONAR_TOKEN}</pre><pre># Path to source code<br>sonar.sources=.<br><br># Path to tests folder<br>sonar.tests=.</pre><pre># If you have coverage reports, specify them (for example, Jest coverage)<br># sonar.javascript.lcov.reportPaths=coverage/lcov.info</pre><p>Adjust these settings based on your project’s structure and requirements.</p><p>Below is an example of the sonar- project properties:</p><pre>sonar.projectKey=your_key<br>sonar.host.url=https://sonarqube.cs.ui.ac.id<br>sonar.login=${SONAR_TOKEN}<br>sonar.sources=src<br>sonar.tests=tests<br>sonar.test.inclusions=tests/**/*.test.js<br>sonar.exclusions=src/database/**,src/models/index.js,src/config/**<br>sonar.javascript.lcov.reportPaths=./coverage/lcov.info</pre><h3>4. Automating Analysis with GitHub Actions</h3><p>Below is an example <strong>GitHub Actions</strong> workflow named SonarQube that will:</p><ul><li>Run on every push to any branch (&quot;**&quot;) and on pull requests (opened, synchronized, or reopened).</li><li>Install dependencies, run tests with coverage, build your Express.js project, and then run SonarQube analysis.</li></ul><pre>name: Sonarcube<br>on:<br>  push:<br>    branches:<br>      - &quot;**&quot;<br>  pull_request:<br>    types: [opened, synchronize, reopened]<br>jobs:<br>  build:<br>    name: Build and analyze<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v3<br>        with:<br>          fetch-depth: 0<br>      - name: Set up Node.js<br>        uses: actions/setup-node@v3<br>        with:<br>          node-version: &#39;20&#39;<br>      - name: Install dependencies<br>        working-directory: backend<br>        run: npm install<br>      - name: Run tests with coverage<br>        working-directory: backend<br>        run: npm test -- --coverage --watchAll=false<br>        env:<br>          NODE_ENV: ${{ secrets.NODE_ENV }}<br>          DB_HOST: ${{ secrets.DB_HOST }}<br>          DB_PORT: ${{ secrets.DB_PORT }}<br>          DB_USER: ${{ secrets.DB_USER }}<br>          DB_PASSWORD: ${{ secrets.DB_PASSWORD }}<br>          DB_NAME: ${{ secrets.DB_NAME }}<br>          CLIENT_ID: ${{ secrets.CLIENT_ID }}<br>          CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }}<br>      - name: Run build script<br>        working-directory: backend<br>        run: npm run build<br>      - name: Cache SonarQube packages<br>        uses: actions/cache@v3<br>        with:<br>          path: ~/.sonar/cache<br>          key: ${{ runner.os }}-sonar<br>          restore-keys: ${{ runner.os }}-sonar<br>      - name: Cache npm modules<br>        uses: actions/cache@v3<br>        with:<br>          path: ~/.npm<br>          key: ${{ runner.os }}-node-${{ hashFiles(&#39;backend/package-lock.json&#39;) }}<br>          restore-keys: ${{ runner.os }}-node<br>      - name: Run SonarQube analysis<br>        env:<br>          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}<br>        run: npx sonar-scanner<br>        working-directory: ./backend</pre><p><strong>Key points to note in this workflow</strong>:</p><ul><li><strong>Checkout</strong>: Pulls your repository code into the CI environment.</li><li><strong>Node setup</strong>: Ensures you have Node.js 20 available.</li><li><strong>Install &amp; Test</strong>: Installs your npm dependencies and runs tests (with coverage).</li><li><strong>Cache</strong>: Uses GitHub’s caching mechanism for both SonarQube packages and npm modules, speeding up subsequent builds.</li><li><strong>SonarQube Analysis</strong>: Runs the sonar-scanner command with the SonarQube token stored as a GitHub Secret.</li></ul><blockquote><strong><em>Tip:</em></strong><em> If you want to include coverage data in SonarQube, ensure you generate a </em><em>lcov.info file during tests and specify its path in </em><em>sonar-project.properties.</em></blockquote><h3>5. Example of SonarQube Implementation in Reporting Code Issues</h3><h4>5.1 Quality Gate: Failed</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9-W-trltci4cb1_Senkdg.png" /><figcaption>Security Hotspot Detected in SonarQube Results</figcaption></figure><p>When you see a <strong>Failed</strong> status in SonarQube, it often means at least one criterion in your Quality Gate isn’t met. Common reasons include:</p><ul><li><strong>Security Hotspots</strong> not reviewed.</li><li><strong>High number of code smells</strong> or <strong>bugs</strong>.</li><li><strong>Insufficient test coverage</strong> based on your configured threshold.</li></ul><p>Even if coverage is 100%, you may still fail the Quality Gate if there’s an unresolved <strong>security hotspot</strong> or a critical bug like the picture aboce.</p><h4>5.2 Fixing Security Hotspots Example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sigewnDK6A7q0iMKbaJIFQ.png" /><figcaption>Security Hotspots because there are risk of Denial of Service (DoS)</figcaption></figure><p>In the screenshot, you can see SonarQube highlighting a <em>Security Hotspot</em> in the code. A Security Hotspot is an area SonarQube flags for closer review because it could potentially introduce security risks if not handled correctly. The message “Make sure the content length limit is safe here” indicates that SonarQube has detected a place in the application where user input or file uploads might be a concern. By drawing attention to this specific line of code, SonarQube prompts developers to verify that the code follows best practices such as limiting file sizes or validating inputs thereby reducing the chance of security vulnerabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5Eqaf9U7Sb06ezwvbJ6yQ.png" /><figcaption>Try to fix the security hotspot</figcaption></figure><p>Here, a file size limit is set to 20 * 1024 * 1024, which equals 20 MB. This explicit limit helps prevent overly large files from being uploaded, a practice that mitigates risks like denial-of-service attacks or running out of server resources. The fact that SonarQube flagged this piece of code earlier is a prime example of how it guides developers to implement safer coding practices. After seeing the alert, the development team can confirm or adjust the file size limit, ensuring that the application remains secure and robust.</p><p>A typical security hotspot in an Express.js application could be:</p><ul><li><strong>File uploads</strong> with no size limit, risking a Denial of Service (DoS) attack.</li><li><strong>Unvalidated user input</strong> that might open the door to SQL injection or other exploits.</li></ul><p>SonarQube requires a <strong>manual review</strong> of security hotspots. If you deem the hotspot is safe (for instance, you have external validation), you can mark it as “Reviewed” so that your Quality Gate can pass.</p><h4>5.3 Quality Gate: Passed</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUt4xAqomcsHJ3GAauHBog.png" /><figcaption>After fixing the security Hotspot</figcaption></figure><p>In this screenshot, you can see that the SonarQube analysis now reports a “Passed” status for the project. This indicates that the previously identified security hotspot and other code issues have been addressed successfully. Once you’ve addressed all critical issues (or marked valid hotspots as safe), your Quality Gate will show <strong>Passed</strong>. This indicates:</p><ul><li><strong>No unresolved vulnerabilities</strong> or unreviewed hotspots.</li><li><strong>No critical bugs</strong> or code smells above the set threshold.</li><li><strong>Test coverage</strong> meets or exceeds your target.</li></ul><h3>6. Best Practices</h3><ol><li><strong>Integrate Early and Often</strong><br>Run SonarQube analysis in your CI/CD pipeline to catch issues early — before merging pull requests.</li><li><strong>Maintain a Healthy Coverage</strong><br>Aim for high test coverage, but also ensure the tests are meaningful. 100% coverage doesn’t necessarily guarantee bug-free code, but it’s a strong indicator of thorough testing.</li><li><strong>Address Code Smells</strong><br>Code smells often point to maintainability issues. Fixing them helps keep your code clean and easy to refactor as your project grows.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13b32f3bd130" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>