<?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 William on Medium]]></title>
        <description><![CDATA[Stories by William on Medium]]></description>
        <link>https://medium.com/@sunsetheus?source=rss-63e584266b01------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*F1tvqS682QEcVhn5</url>
            <title>Stories by William on Medium</title>
            <link>https://medium.com/@sunsetheus?source=rss-63e584266b01------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:51:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sunsetheus/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[Testing Spring Boot APIs Without Postman? Just Swagger It!]]></title>
            <link>https://medium.com/@sunsetheus/testing-spring-boot-apis-without-postman-just-swagger-it-6449322dd7d0?source=rss-63e584266b01------2</link>
            <guid isPermaLink="false">https://medium.com/p/6449322dd7d0</guid>
            <dc:creator><![CDATA[William]]></dc:creator>
            <pubDate>Tue, 27 May 2025 16:22:41 GMT</pubDate>
            <atom:updated>2025-05-27T16:22:41.531Z</atom:updated>
            <content:encoded><![CDATA[<img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6449322dd7d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test-Driven Development in Spring Boot: A Practical Guide with Real Examples]]></title>
            <link>https://medium.com/@sunsetheus/test-driven-development-in-spring-boot-a-practical-guide-with-real-examples-235fd24d3918?source=rss-63e584266b01------2</link>
            <guid isPermaLink="false">https://medium.com/p/235fd24d3918</guid>
            <dc:creator><![CDATA[William]]></dc:creator>
            <pubDate>Thu, 15 May 2025 07:38:43 GMT</pubDate>
            <atom:updated>2025-05-15T07:38:43.566Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the ever-evolving landscape of software development, methodologies that ensure code quality and reliability are invaluable. Test-Driven Development (TDD) stands out as one of these methodologies, offering a structured approach to writing code that meets requirements and maintains robustness over time. This article explores TDD with a focus on Spring Boot applications, using a practical example from a talent pool management system to demonstrate principles and implementation.</p><h3>What is TDD and Why Is It Important?</h3><p>Test-Driven Development is a software development approach where tests are written before the actual code. It follows a simple yet powerful cycle: write a failing test, implement the minimum code to make it pass, then refactor while ensuring tests continue to pass.</p><p>TDD is more than just a testing strategy; it’s a design methodology that promotes:</p><ul><li><strong>Cleaner architecture</strong>: By forcing you to think about how your code will be used before writing it</li><li><strong>Improved code quality</strong>: Through continuous verification and refactoring</li><li><strong>Better documentation</strong>: Tests serve as executable specifications</li><li><strong>Fewer bugs</strong>: Issues are caught early in the development cycle</li><li><strong>Confidence in changes</strong>: The test suite provides immediate feedback when code is modified</li></ul><p>In today’s fast-paced development environments, TDD has become essential for maintaining quality while delivering features rapidly.</p><h3>The Relationship Between TDD and Unit Testing</h3><p>While TDD and unit testing are related concepts, they’re not identical:</p><ul><li><strong>Unit testing</strong> is the practice of testing individual components or “units” of code in isolation</li><li><strong>TDD</strong> is a development process that uses unit tests as its primary vehicle</li></ul><p>TDD relies heavily on unit tests but extends beyond them to influence the entire development workflow. In TDD, the unit tests drive the design and implementation of the code, rather than simply verifying what has already been written.</p><h3>The FIRST Principles of Good TDD</h3><p>Good TDD follows the FIRST principles — a set of criteria that help ensure unit tests are effective and valuable:</p><h4>F — Fast</h4><p>Tests should execute quickly. Slow tests discourage frequent running and delay feedback.</p><p><strong>Example in ExperienceTest.java:</strong></p><pre>@Test<br>void testTitleEmpty() {<br>    // Simple validation test that executes quickly<br>    User user = createUser();<br>    Experience experience = Experience.builder()<br>            .title(&quot;&quot;)<br>            .company(&quot;Tech Company&quot;)<br>            // ... other properties<br>            .build();<br>    <br>    Set&lt;ConstraintViolation&lt;Experience&gt;&gt; violations = validator.validate(experience);<br>    assertFalse(violations.isEmpty());<br>}</pre><p>These validation tests run in milliseconds because they don’t involve databases or external services.</p><h4>I — Independent</h4><p>Tests should not depend on each other. Each test should be able to run alone or in any order.</p><p><strong>Example in ExperienceTest.java:</strong></p><pre>@Nested<br>class TitleAttributeTests {<br>    // Tests for title field<br>}<br><br>@Nested<br>class CompanyAttributeTests {<br>    // Tests for company field <br>}</pre><p>Each nested test class and method is self-contained and doesn’t rely on state from other tests.</p><h4>R — Repeatable</h4><p>Tests should produce the same results regardless of the environment or external factors.</p><p><strong>Example in ExperienceTest.java:</strong></p><pre>@Test<br>void testEndDateBeforeStartDate() {<br>    // Uses fixed dates that will always produce the same result<br>    Experience experience = Experience.builder()<br>            .startDate(LocalDate.of(2020, 5, 1))<br>            .endDate(LocalDate.of(2020, 4, 30))<br>            // ... other properties<br>            .build();<br>            <br>    assertTrue(experience.isEndDateBeforeStartDate());<br>}</pre><h4>S — Self-validating</h4><p>Tests should automatically determine if they pass or fail without manual inspection.</p><p><strong>Example in ExperienceTest.java:</strong></p><pre>@Test<br>void testUserNull() {<br>    Experience experience = Experience.builder()<br>            // ... properties<br>            .user(null)<br>            .build();<br><br>    Set&lt;ConstraintViolation&lt;Experience&gt;&gt; violations = validator.validate(experience);<br>    assertFalse(violations.isEmpty());<br>    assertTrue(violations.stream().anyMatch(v -&gt; v.getMessage().contains(&quot;Talent (User) is required&quot;)));<br>}</pre><h3>T — Timely</h3><p>Tests should be written at the right time — before implementing production code in TDD.</p><p>In proper TDD practice, each test in ExperienceTest.java would have been written before implementing the corresponding validation or business logic in the Experience model.</p><h4>The TDD Cycle</h4><p>TDD follows a simple but effective cycle:</p><h4>1. Red: Write a Failing Test</h4><p>Start by writing a test that defines the expected behavior, which will initially fail because the code doesn’t exist yet.</p><h4>2. Green: Write the Minimum Code to Pass</h4><p>Implement just enough code to make the test pass, without worrying about elegance or completeness.</p><h4>3. Refactor: Clean Up the Code</h4><p>Once the test passes, improve the code’s structure without changing its behavior, ensuring tests still pass.</p><h4>4. Repeat</h4><h3>Implementing TDD in Spring Boot: The Experience Model Test Case</h3><p>Let’s examine how TDD is implemented in our Spring Boot application using the ExperienceTest.java example:</p><h4>Step 1: Setting Up the Testing Environment</h4><pre>private static Validator validator;<br><br>@BeforeAll<br>static void setupValidator() {<br>    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();<br>    validator = factory.getValidator();<br>}</pre><p>This setup initializes a Bean Validation validator that will be used to test model constraints.</p><h4>Step 2: Creating Test Fixtures</h4><pre>private User createUser() {<br>    return User.builder()<br>            .firstName(&quot;first&quot;)<br>            .lastName(&quot;Smith&quot;)<br>            // ... other properties<br>            .build();<br>}</pre><p>The method creates reusable test data, improving test readability and maintainability.</p><h4>Step 3: Testing Basic Object Creation</h4><pre>@Test<br>void testEmptyConstructor() {<br>    Experience experience = new Experience();<br>    assertNotNull(experience, &quot;Experience object should be created with empty constructor&quot;);<br>}</pre><p>Even simple tests like this are valuable, ensuring that basic functionality works as expected.</p><h4>Step 4: Testing Validation Rules</h4><pre>@Test<br>void testCompanyEmpty() {<br>    User user = createUser();<br><br>    Experience experience = Experience.builder()<br>            .title(&quot;Software Engineer&quot;)<br>            .company(&quot;&quot;) // Empty company name<br>            // ... other properties<br>            .build();<br><br>    Set&lt;ConstraintViolation&lt;Experience&gt;&gt; violations = validator.validate(experience);<br><br>    assertFalse(violations.isEmpty());<br>    assertTrue(violations.stream().anyMatch(v -&gt; v.getMessage().contains(&quot;Company is required&quot;)));<br>}</pre><p>This test verifies that validation constraints on the company field work correctly.</p><h4>Step 5: Testing Business Logic</h4><pre>@Test<br>void testEndDateBeforeStartDate() {<br>    User user = createUser();<br><br>    Experience experience = Experience.builder()<br>            .title(&quot;Software Engineer&quot;)<br>            .company(&quot;Tech Company&quot;)<br>            .employmentType(EmploymentType.FULL_TIME)<br>            .startDate(LocalDate.of(2020, 5, 1))<br>            .endDate(LocalDate.of(2020, 4, 30)) // End date before start date<br>            .location(&quot;San Francisco&quot;)<br>            .locationType(LocationType.ON_SITE)<br>            .user(user)<br>            .build();<br><br>    // Check the custom validation method directly<br>    assertTrue(experience.isEndDateBeforeStartDate(), &quot;Should return true when endDate is before startDate&quot;);<br><br>    // Also validate with the validator to ensure the constraint annotation works<br>    Set&lt;ConstraintViolation&lt;Experience&gt;&gt; violations = validator.validate(experience);<br>    assertFalse(violations.isEmpty());<br>    assertTrue(violations.stream().anyMatch(v -&gt; v.getMessage().contains(&quot;End date must not be earlier than start date&quot;)));<br>}</pre><p>This test validates both the method behavior and the constraint annotation.</p><h3>Benefits for Development and Maintenance</h3><h4>Improved Development Cycle</h4><p>TDD offers significant benefits throughout the development lifecycle:</p><ol><li><strong>Clearer requirements</strong>: Writing tests first forces clarification of requirements</li><li><strong>Faster feedback</strong>: Issues are identified early in development</li><li><strong>Reduced debugging time</strong>: Tests pinpoint problems precisely</li><li><strong>Improved design</strong>: Code tends to be more modular and loosely coupled</li><li><strong>Built-in regression testing</strong>: Changes don’t break existing functionality</li></ol><h3>Maintenance and Iteration</h3><p>As seen in the ExperienceTest.java example, comprehensive tests make maintenance easier:</p><ol><li><strong>Safe refactoring</strong>: Tests catch unintended side effects</li><li><strong>Documentation</strong>: Tests show how code should behave</li><li><strong>Onboarding</strong>: New developers can understand code behavior by reading tests</li><li><strong>Confidence in changes</strong>: Tests verify that changes don’t break existing functionality</li></ol><h3>Modern TDD Techniques and Best Practices</h3><h3>Introduction: From Traditional TDD to ATDD</h3><p>In the evolving landscape of software development methodologies, Test-Driven Development (TDD) has undergone significant transformation. While the traditional “Red-Green-Refactor” cycle remains valuable, modern applications with complex business requirements demand a more comprehensive approach. This is where Acceptance Test-Driven Development (ATDD) comes in — a methodology that extends TDD by starting with acceptance criteria that define the behavior of features from the user’s perspective.</p><p>The password reset functionality in our talent pool application provides an excellent case study for examining how ATDD enhances the traditional TDD approach with modern techniques.</p><h3>The ATDD Advantage: Why It Outperforms Traditional TDD</h3><h3>1. Business-First Testing Approach</h3><p>Traditional TDD often begins at the code level, focusing on technical implementation. ATDD, however, starts with business requirements expressed as acceptance criteria:</p><pre>[+] Talent dapat meminta reset password dengan memasukkan email yang terdaftar<br>[-] Jika email tidak valid atau tidak terdaftar, maka sistem menampilkan pesan error<br>[+] Jika email valid dan terdaftar, sistem mengirimkan tautan reset password ke email tersebut</pre><p>These criteria become the foundation for our tests before we write a single line of implementation code. This ensures that development efforts align directly with business value.</p><h3>2. Clearer Stakeholder Communication</h3><p>ATDD creates a shared language between technical and non-technical stakeholders. In our password reset feature, the acceptance criteria are understandable to product managers and developers alike, facilitating better collaboration and fewer misunderstandings.</p><h3>3. Comprehensive Test Coverage by Design</h3><p>ATDD naturally leads to more complete test coverage because tests are derived from acceptance criteria that already consider both success and failure scenarios. Notice how our AuthenticationServiceTest includes tests for both valid and invalid tokens:</p><pre>@Test<br>void resetPasswordWithToken_shouldUpdatePasswordAndMarkTokenUsed() {<br>    // Test for successful password reset<br>}<br><br>@Test<br>void resetPasswordWithToken_shouldThrowIfTokenInvalid() {<br>    // Test for invalid token handling<br>}</pre><blockquote>This comprehensive approach is built into ATDD from the start, whereas traditional TDD might focus initially on the happy path.</blockquote><h3>4. Reduced Over-Engineering</h3><p>By focusing on acceptance criteria, ATDD helps prevent developers from building features or handling edge cases that aren’t actually required, leading to more efficient development.</p><h3>Modern ATDD Techniques in Practice</h3><p>Let’s examine how modern ATDD techniques are applied in our password reset implementation.</p><h3>1. Behavior-Focused Test Naming</h3><p>Modern ATDD emphasizes test names that clearly express the expected behavior:</p><pre>void resetPasswordWithToken_shouldUpdatePasswordAndMarkTokenUsed()<br>void resetPasswordWithToken_shouldThrowIfTokenInvalid()</pre><p>These names map directly to our acceptance criteria and serve as documentation of expected system behavior.</p><h3>2. Arrange-Act-Assert Pattern</h3><p>Our tests follow a clear structure that improves readability:</p><pre>@Test<br>void resetPasswordWithToken_shouldUpdatePasswordAndMarkTokenUsed() {<br>    // Arrange<br>    String token = &quot;abc&quot;;<br>    String newPassword = &quot;Dummy123#&quot;;<br>    String encodedPassword = &quot;Dummy123#&quot;;<br>    String email = &quot;user@email.com&quot;;<br>    PasswordResetToken resetToken = PasswordResetToken.builder()<br>            .token(token)<br>            .email(email)<br>            .expiryDate(LocalDateTime.now().plusMinutes(10))<br>            .used(false)<br>            .build();<br>    User user = new User();<br>    user.setEmail(email);<br><br>    when(passwordResetTokenRepository.findByToken(token)).thenReturn(Optional.of(resetToken));<br>    when(userRepository.findByEmail(email)).thenReturn(Optional.of(user));<br>    when(passwordEncoder.encode(newPassword)).thenReturn(encodedPassword);<br><br>    // Act<br>    authenticationService.resetPasswordWithToken(token, newPassword);<br><br>    // Assert<br>    verify(userRepository).save(user);<br>    verify(passwordResetTokenRepository).save(resetToken);<br>    assertThat(user.getPassword()).isEqualTo(encodedPassword);<br>    assertThat(resetToken.isUsed()).isTrue();<br>}</pre><p>This structure makes tests more understandable and maintainable.</p><h3>3. Fluent Assertions</h3><p>Modern testing frameworks provide fluent assertion libraries that enhance readability:</p><pre>assertThat(user.getPassword()).isEqualTo(encodedPassword);<br>assertThat(resetToken.isUsed()).isTrue();<br><br>assertThatThrownBy(() -&gt; authenticationService.resetPasswordWithToken(&quot;notfound&quot;, &quot;pw&quot;))<br>        .isInstanceOf(IllegalArgumentException.class)<br>        .hasMessageContaining(&quot;Token tidak valid&quot;);</pre><p>These assertions read almost like plain English, making tests understandable even to those less familiar with the codebase.</p><h3>4. Comprehensive Scenario Testing</h3><p>Modern ATDD doesn’t just test the happy path but comprehensively covers different scenarios:</p><pre>// Testing valid reset scenario<br>@Test<br>void resetPasswordWithToken_shouldUpdatePasswordAndMarkTokenUsed() {<br>    // Implementation<br>}<br><br>// Testing invalid token scenario<br>@Test<br>void resetPasswordWithToken_shouldThrowIfTokenInvalid() {<br>    when(passwordResetTokenRepository.findByToken(&quot;notfound&quot;)).thenReturn(Optional.empty());<br>    assertThatThrownBy(() -&gt; authenticationService.resetPasswordWithToken(&quot;notfound&quot;, &quot;pw&quot;))<br>            .isInstanceOf(IllegalArgumentException.class)<br>            .hasMessageContaining(&quot;Token tidak valid&quot;);<br>}</pre><h3>Mapping Tests to Acceptance Criteria</h3><p>Let’s see how our tests map directly to the password reset acceptance criteria:</p><p>1. <strong>“Jika tautan sudah kedaluwarsa atau tidak valid, maka sistem menampilkan pesan error”</strong></p><ul><li>Covered by:</li></ul><pre>@Test<br>void resetPasswordWithToken_shouldThrowIfTokenInvalid() {<br>    when(passwordResetTokenRepository.findByToken(&quot;notfound&quot;)).thenReturn(Optional.empty());<br>    assertThatThrownBy(() -&gt; authenticationService.resetPasswordWithToken(&quot;notfound&quot;, &quot;pw&quot;))<br>            .isInstanceOf(IllegalArgumentException.class)<br>            .hasMessageContaining(&quot;Token tidak valid&quot;);<br>}</pre><p>2. <strong>Talent dapat membuat password baru dengan mengisi form yang terdiri dari password baru”</strong></p><ul><li>Covered by:</li></ul><pre>@Test<br>void resetPasswordWithToken_shouldUpdatePasswordAndMarkTokenUsed() {<br>    // Test implementation<br>}</pre><p><strong>“Jika password valid dan konfirmasi cocok, sistem menyimpan password baru”</strong></p><ul><li>Covered by assertions in resetPasswordWithToken_shouldUpdatePasswordAndMarkTokenUsed:</li></ul><pre>verify(userRepository).save(user);<br>assertThat(user.getPassword()).isEqualTo(encodedPassword);</pre><h3>ATDD’s Impact on Development Process</h3><p>Implementing ATDD transforms the development process in several key ways:</p><h3>1. Requirements Clarity Before Implementation</h3><p>ATDD forces clarification of requirements before coding begins. For example, the acceptance criteria specify that the system should display error messages for invalid tokens, which guided the implementation of appropriate exception handling.</p><h3>2. Collaborative Development</h3><p>ATDD encourages collaboration between developers, QA, and business stakeholders. The acceptance criteria for the password reset feature were likely defined collaboratively, ensuring that everyone understood what was being built.</p><h3>3. Continuous Validation</h3><p>As the code evolves, the ATDD tests continuously validate that the implementation meets the acceptance criteria, preventing regression and ensuring that business requirements are always satisfied.</p><h3>Conclusion: ATDD as a Modern TDD Evolution</h3><p>ATDD represents a natural evolution of Test-Driven Development that addresses many of the limitations of traditional TDD. By starting with acceptance criteria and working backward to implementation, ATDD ensures that development efforts remain focused on delivering business value.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=235fd24d3918" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Quality Starts with Static Analysis: Why It Matters and How to Apply It in CI/CD]]></title>
            <link>https://medium.com/@sunsetheus/code-quality-starts-with-static-analysis-why-it-matters-and-how-to-apply-it-in-ci-cd-55b9b3612995?source=rss-63e584266b01------2</link>
            <guid isPermaLink="false">https://medium.com/p/55b9b3612995</guid>
            <dc:creator><![CDATA[William]]></dc:creator>
            <pubDate>Thu, 15 May 2025 07:20:03 GMT</pubDate>
            <atom:updated>2025-05-15T07:20:03.981Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In modern software development, <strong>code quality</strong> isn’t just a nice-to-have — it’s a fundamental necessity. As codebases grow and teams scale, maintaining consistent quality becomes more complex and critical. One of the most powerful, yet often underrated techniques to ensure quality is <strong>Static Analysis</strong>.</p><h3>What is Static Analysis?</h3><p><strong>Static Analysis</strong> is the process of analyzing source code without executing it. It evaluates the structure, style, and potential flaws in your code by scanning it directly — unlike dynamic testing, which requires your code to run.</p><blockquote>Think of it as a preflight check for your code, catching issues before they turn into bugs or technical debt.</blockquote><h3>Why Is It Important?</h3><p>Here’s why static analysis matters:</p><ul><li><strong>Early Bug Detection</strong>: Find errors and bad practices <em>before</em> they become runtime issues.</li><li><strong>Enforces Standards</strong>: Ensures team members follow consistent code conventions.</li><li><strong>Saves Time</strong>: Reduces debugging and review cycles.</li><li><strong>Improves Maintainability</strong>: Encourages clean, readable, and modular code.</li><li><strong>Integrates Easily with CI/CD</strong>: Automate checks with every commit or merge.</li></ul><p>In short, it acts like a silent guardian for your codebase.</p><h3>What’s the Role of Static Analysis in QA?</h3><p>While <strong>QA (Quality Assurance)</strong> is often associated with testing, it actually covers a wider scope — including <em>preventing defects</em>. Static analysis is a QA practice that <strong>prevents issues before they enter production</strong>, making it proactive rather than reactive.</p><p>Static analysis complements:</p><ul><li>Unit and integration tests (dynamic)</li><li>Manual and exploratory testing (human-driven)</li><li>Code reviews (peer-driven)</li></ul><p>It’s a key part of <strong>Shift Left Testing</strong> — catching problems as early as possible in the development lifecycle.</p><h3>What Are Some Common Static Analysis Standards?</h3><p>Static analysis tools typically enforce the following checks:</p><h4>1. Unused Imports or Variables</h4><p><strong>What it is:</strong> Static analysis tools flag imports or declared variables that aren’t referenced in the code. These unused elements add noise, increase compilation time, and may indicate incomplete refactoring.</p><p><strong>Violation Example:</strong></p><pre>import java.util.ArrayList; // Never used<br>import java.util.stream.Collectors; // Never used<br><br>public class JwtService {<br>    private String unusedVariable = &quot;This is never referenced&quot;; // Violation<br>    <br>    public String generateToken() {<br>        // Implementation without using the imports or variable<br>    }<br>}</pre><p><strong>Why it’s a problem:</strong> These imports and the unused variable add unnecessary code that must be maintained. When other developers see these imports, they might assume they’re needed for the implementation, causing confusion.</p><p><strong>Example from the codebase:</strong> The JwtService class demonstrates good import practices where all imports are actually used:</p><pre>import io.jsonwebtoken.Claims;<br>import io.jsonwebtoken.Jwts;<br>import io.jsonwebtoken.SignatureAlgorithm;<br>import io.jsonwebtoken.io.Decoders;<br>import io.jsonwebtoken.security.Keys;</pre><p>Each imported class serves a specific purpose in the JWT implementation. For example:</p><pre>Claims is used in the extractClaim and extractAllClaims methods<br>Jwts is used to build and parse JWT tokens<br>SignatureAlgorithm defines the signing algorithm (HS256)</pre><h4>2. Dead or Unreachable Code</h4><p><strong>What it is:</strong> Code that can never be executed. This often occurs after refactoring when certain branches become impossible to reach but aren’t removed.</p><p><strong>Violation Example:</strong></p><pre>public boolean checkValidity(String token) {<br>    return true;<br>    // This code will never run<br>    if (token == null) {<br>        return false;<br>    }<br>}</pre><p><strong>Why it’s a problem:</strong> Dead code confuses developers, creates maintenance burdens, and can hide logical errors. In this example, important validation logic will never run.</p><p><strong>Example from the codebase:</strong> The JwtService class avoids unreachable code by maintaining clean method flows:</p><pre>public boolean isTokenExpired(String token) {<br>    return extractExpiration(token).before(new Date());<br>}</pre><h4>3. Code Complexity</h4><p><strong>What it is:</strong> Code with high cyclomatic complexity — too many decision points, nested loops, or conditional branches</p><p><strong>Violation Example:</strong></p><pre>public boolean validateToken(String token, User user) {<br>    if (token != null) {<br>        if (token.length() &gt; 10) {<br>            if (user != null) {<br>                if (user.getEmail() != null) {<br>                    if (user.getEmail().equals(extractUsername(token))) {<br>                        if (!isTokenExpired(token)) {<br>                            return true;<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    }<br>    return false;<br>}</pre><p><strong>Why it’s a problem:</strong> Deeply nested conditionals create code that’s difficult to understand, test, and maintain. The example above has 6 levels of nesting!</p><p><strong>Good Implementation in the Repo:</strong></p><pre>public boolean isTokenValid(String token, UserDetails userDetails) {<br>    final String username = extractUsername(token);<br>    return (username.equals(userDetails.getUsername())) &amp;&amp; !isTokenExpired(token);<br>}</pre><p><strong>Proper implementation details:</strong> This validation method maintains low complexity by:</p><ol><li>Using an early return pattern to handle the null case immediately</li><li>Using logical operators to combine conditions rather than nesting if-statements</li><li>Having a clear, single responsibility (checking date order)</li><li>Keeping the cyclomatic complexity to just 2 (two possible paths through the code)</li></ol><p>The method is easy to understand and test because of its simple structure and focused responsibility.</p><h4>4. Null Pointer Risks</h4><p><strong>What it is:</strong> Null pointer risks occur when code attempts to perform operations on objects that could be null, potentially causing NullPointerExceptions at runtime. These exceptions can crash applications and create frustrating user experiences.</p><p><strong>Violation Example:</strong></p><pre>// Bad implementation with null pointer risk<br>public boolean isEndDateBeforeStartDate() {<br>    // No null check - will throw NPE if endDate is null<br>    return endDate.isBefore(startDate);<br>}</pre><blockquote>In this example, if endDate is null (which is a valid state since it’s not marked as @NotNull in the class), calling isBefore() on it would throw a NullPointerException.</blockquote><p><strong>Good Implementation in the Repo:</strong></p><pre>@AssertFalse(message = &quot;End date must not be earlier than start date&quot;)<br>public boolean isEndDateBeforeStartDate() {<br>    if (endDate == null) {<br>        return false;<br>    }<br>    return startDate != null &amp;&amp; endDate.isBefore(startDate);<br>}</pre><p>The implementation in the repository correctly handles null values by:</p><ol><li>First checking if endDate is null and returning false if it is</li><li>Using the &amp;&amp; operator for short-circuit evaluation to ensure startDate is not null before calling isBefore()</li></ol><h4>5. Security Issues</h4><p><strong>What it is:</strong> Code patterns that could introduce security vulnerabilities.</p><p><strong>Violation Example:</strong></p><pre>public class InsecureJwtService {<br>    // Hardcoded secret - major security issue<br>    private static final String SECRET_KEY = &quot;mysupersecretkey123456789abcdefghijklmnop&quot;;<br>    <br>    public String generateToken() {<br>        return Jwts.builder()<br>                .signWith(Keys.hmacShaKeyFor(SECRET_KEY.getBytes()))<br>                .compact();<br>    }<br>}</pre><p><strong>Why it’s a problem:</strong> This code has two major security issues:</p><ol><li>The hardcoded secret key would be exposed in source code repositories</li><li>Tokens without expiration create permanent access credentials</li></ol><p><strong>Good Implementation in the Repo:</strong></p><pre>@Value(&quot;${security.jwt.secret-key}&quot;)<br>private String secretKey;<br><br>private Key getSignInKey() {<br>    byte[] keyBytes = Decoders.BASE64.decode(secretKey);<br>    return Keys.hmacShaKeyFor(keyBytes);<br>}</pre><p><strong>Proper implementation details:</strong> The JwtService implements security best practices:</p><ol><li>Externalizes the secret key to configuration (using Spring’s @Value)</li><li>This allows different keys for different environments (dev/test/prod)</li><li>Sets proper token expiration to limit the access window</li><li>Uses appropriate secure signing algorithms (HS256)</li></ol><p>This approach enhances security by keeping secrets out of code and implementing proper JWT lifecycle management.</p><h3>Example: Applying Static Analysis in a Java Project</h3><p>Static analysis is commonly integrated using Gradle or Maven. Tools like <strong>SonarCloud</strong> can hook into your CI/CD pipeline and scan each commit for violations. Some IDEs (like IntelliJ or VS Code) can also provide real-time static analysis feedback as you write code.</p><pre>jacocoTestCoverageVerification {<br> violationRules {<br>  rule {<br>   limit {<br>    minimum = 1.0 // 100% coverage<br>   }<br>  }<br> }<br>}<br><br>check.dependsOn jacocoTestCoverageVerification</pre><p>This configuration makes sure that all your code paths are covered by tests before merging to main branches.</p><p>Here’s a real-world example of a <strong>CI/CD guard</strong> in action. In the screenshot below, the build failed because the project’s test coverage fell short of the enforced threshold:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ROGC2vgawN0O6Y5z0e6c8w.png" /></figure><blockquote><em>Rule violated for bundle talentPool: instructions covered ratio is 0.8, but expected minimum is 1.0</em></blockquote><p>This means that only <strong>80%</strong> of the code was covered by tests, while the configured <strong>minimum threshold was 100%</strong>. The task jacocoTestCoverageVerification triggered a failure, ensuring that no pull request or deployment could proceed without full test coverage.</p><p>This kind of guardrail ensures not only that tests are written but that <strong>all critical paths are verified</strong>, which is especially crucial for teams practicing <strong>Test-Driven Development (TDD)</strong>. It also helps catch gaps early in development, reducing the risk of introducing undetected bugs into production.</p><p>By embedding this rule into the CI/CD pipeline (e.g., GitHub Actions, GitLab CI), teams can automate quality enforcement without relying on manual reviews or post-merge checks.</p><h3>Going Beyond Static Analysis: AI-Powered Quality Tools</h3><p>Static analysis is essential, but it’s not the only tool in your QA arsenal.</p><p>Thanks to advances in <strong>AI and LLMs</strong>, we now have tools that go beyond syntax and style. They help catch logical flaws, suggest improvements, and even auto-review code:</p><p><strong>CodeRabbit: </strong>AI code reviewer that reviews PRs automatically and explains code in plain English. Excellent for early feedback and learning.</p><p><strong>GitHub Copilot: </strong>Suggests inline code completions and refactors based on learned patterns.</p><p>For further info, you can check <a href="https://medium.com/@sunsetheus/is-static-analysis-enough-why-coderabbit-might-be-the-missing-piece-a491404669a0">https://medium.com/@sunsetheus/is-static-analysis-enough-why-coderabbit-might-be-the-missing-piece-a491404669a0</a></p><h3>Conclusion</h3><p>Static analysis is not just a technical formality — it’s a powerful discipline that keeps your codebase clean, secure, and maintainable. When combined with CI/CD practices and augmented with modern AI tools, it creates a comprehensive quality pipeline that scales with your team.</p><p>Investing in static analysis is one of the most cost-effective ways to <strong>reduce bugs, save time, and ship with confidence</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55b9b3612995" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing Bad Tests: How Prompt Engineering and Literature Can Save You]]></title>
            <link>https://medium.com/@sunsetheus/stop-writing-bad-tests-how-prompt-engineering-and-literature-can-save-you-a19555acaf21?source=rss-63e584266b01------2</link>
            <guid isPermaLink="false">https://medium.com/p/a19555acaf21</guid>
            <dc:creator><![CDATA[William]]></dc:creator>
            <pubDate>Thu, 08 May 2025 06:15:01 GMT</pubDate>
            <atom:updated>2025-05-08T06:45:15.510Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Software testing is often seen as a secondary task — something developers do after writing the “real” code. But in reality, testing is where confidence in your system is built, bugs are caught early, and long-term maintainability is ensured.</p><p>The quality of your tests doesn’t come from intuition alone. It comes from understanding foundational concepts like mocks and stubs , knowing when to use them (and when not to), and leveraging modern practices such as prompt engineering for smarter test creation.</p><p>Beyond that, staying informed through literature and best practice guides — including critiques on outdated patterns like @Autowired — plays a crucial role in writing tests that are not only effective but also maintainable and scalable.</p><p>In this article, we’ll walk through how these elements combine to help you stop writing bad tests and start building better ones — one iteration at a time.</p><h3>Understanding Stubs vs Mocks</h3><p>Let’s start with two fundamental tools in unit testing: stubs and mocks.</p><h3><strong>Stubs</strong></h3><p>A <strong>stub </strong>provides predefined responses to method calls. It doesn’t care how many times a method is called or what arguments are used — it simply returns a fixed value.</p><p>Stubs help simulate data so you can focus on testing the behavior of the object under test without relying on external dependencies.</p><pre>when(experienceRepository.save(any(Experience.class))).thenReturn(experience);</pre><p>✅ Use stubs when:</p><ul><li>You want to simulate return values</li><li>You’re focused on verifying output/state</li><li>Your logic doesn’t depend on interaction patterns</li></ul><h3>Mocks</h3><p>A <strong>mock</strong>, on the other hand, verifies interactions. You set expectations on how many times a method should be called and with what parameters.</p><pre>verify(experienceRepository).findByUserId(userId);</pre><p>✅ Use mocks when:</p><ul><li>You want to verify that a method was called</li><li>You’re testing side effects or integration points</li><li>Behavior verification matters more than return values</li></ul><blockquote><strong>Key Takeaway</strong>:</blockquote><blockquote><strong>Stub</strong> = Data Simulation — — — — <strong>Mock</strong> = Behavior Verification</blockquote><h3>Test Lifecycle: Stubs vs Mocks</h3><p>Understanding the test lifecycle helps write better tests by clarifying what each phase does.</p><h3>Stubs</h3><ol><li>Setup — Create object under test and its stub collaborators.</li><li>Exercise — Run the functionality.</li><li>Verify state — Use asserts to check object’s state.</li><li>Teardown — Clean up resources.</li></ol><p>Used when you only care about what happens at the end</p><h3>Mocks</h3><ol><li>Setup data — Prepare object under test.</li><li>Setup expectations — Define expected method calls.</li><li>Exercise — Run the functionality.</li><li>Verify expectations — Confirm correct methods were invoked.</li><li>Verify state — Optionally check final state.</li><li>Teardown — Clean up</li></ol><p>Used when you care about how something happened, not just what.</p><h3>Prompt Engineering for Test Creation (Red Phase)</h3><p>In Test-Driven Development (TDD) , the Red Phase is where you write a failing test before implementing any logic. But writing a good failing test isn’t always easy — especially when you’re starting from scratch.</p><p>That’s where prompt engineering comes in.</p><p>By crafting clear and structured prompts, even AI can help you generate comprehensive tests that follow best practices and cover edge cases you might not have considered.</p><p>Let’s explore how different levels of prompts yield vastly different results — and how to improve your prompts iteratively to build better, more maintainable tests.</p><h3>Case 1: Incomplete Prompt</h3><blockquote>“Write a unit test for Experience class using JUnit and Mockito.”</blockquote><p>Output (Simplified):</p><pre>@Test<br>void testExperienceCreation() {<br>    Experience experience = new Experience();<br>    assertNotNull(experience);<br>}</pre><p>Critique:</p><ul><li>Too vague — doesn’t specify fields, validations, or expected behavior.</li><li>Lacks real-world scenarios like null checks, field constraints, or validation rules.</li><li>Not aligned with TDD principles — no assertion that would initially fail.</li><li>Doesn’t use AssertJ or any readable assertions.</li></ul><p>This is a bad prompt because it produces minimal output with little testing value</p><h3>Case 2: Improved &amp; Detailed Prompt (Recommended)</h3><blockquote>You are a Java backend developer with expertise in unit testing using JUnit 5, Mockito, and AssertJ.</blockquote><blockquote>I’m following Test-Driven Development (TDD), and I’m currently at the **Red Phase**. This means I haven’t written the actual implementation yet, but I want to write the tests first.</blockquote><blockquote>The class I am going to implement is called `Experience`, which represents professional work experience in a Spring Boot application. Based on typical validation patterns in Spring Boot applications, it should include:</blockquote><blockquote>### Expected Features of the `Experience` class:<br>1. Fields:<br> — title: String (required, max 50 characters)<br> — company: String (required, max 50 characters)<br> — employmentType: EmploymentType (required, enum)<br> — startDate: LocalDate (required)<br> — endDate: LocalDate (optional)<br> — location: String (required, max 50 characters)<br> — locationType: LocationType (required, enum)<br> — user: User (required, many-to-one relationship)<br> — lastModifiedDate: LocalDateTime (auto-updated, must not be in the future)</blockquote><blockquote>2. Validations:<br> — endDate must not be before startDate (custom validation method: `isEndDateBeforeStartDate`)<br> — lastModifiedDate must not be in the future</blockquote><blockquote>3. Custom Validation Method:<br> — public boolean isEndDateBeforeStartDate()</blockquote><blockquote>Your task is to generate a comprehensive **unit test class** for this model using:<br>- JUnit 5<br>- Mockito (if needed to mock dependencies like User)<br>- AssertJ (`org.assertj.core.api.Assertions`) for readable assertions</blockquote><blockquote>Scenarios to cover:<br>Positive case: All fields are valid and within constraints <br>Negative case: Missing required fields (title, company, etc.) <br>Negative case: endDate is before startDate <br>Edge case: endDate is null (still employed) <br>Edge case: startDate equals endDate <br>Validation failure: lastModifiedDate is in the future</blockquote><blockquote>Include expected validation messages where applicable, such as:<br>- “Title is required”<br>- “Company must not exceed 50 characters”<br>- “End date must not be earlier than start date”<br>- “Last modified date cannot be in the future”</blockquote><blockquote>Also test the custom validation method:<br>- endDate = null → returns false<br>- endDate &lt; startDate → returns true<br>- endDate &gt;= startDate → returns false</blockquote><blockquote>Assume that all validations use standard Spring annotations like:<br><a href="http://twitter.com/NotBlank">@NotBlank</a>, <a href="http://twitter.com/Size">@Size</a>, <a href="http://twitter.com/NotNull">@NotNull</a>, <a href="http://twitter.com/PastOrPresent">@PastOrPresent</a>, <a href="http://twitter.com/AssertFalse">@AssertFalse</a></blockquote><blockquote>Generate the full test class including imports and comments.</blockquote><h4>Define the Role Clearly</h4><p>This helps set the context and tone. The more specific the role, the better the results. You’re not just asking for code — you’re asking for professional-grade implementation</p><h4>Specify the Development Approach</h4><p>Clarifying your development methodology ensures the response includes:</p><ul><li>Failing assertions</li><li>No assumptions about implementation details</li><li>A focus on validation and structure, not logic</li></ul><h4>Describe the Class and Its Features in Detail</h4><p>Be explicit about:</p><ul><li>Fields and their types</li><li>Constraints (max length, required/optional)</li><li>Relationships (e.g., @ManyToOne)</li><li>Validation rules</li></ul><h4>List the Tools and Libraries You’re Using</h4><ul><li>JUnit 5</li><li>Mockito</li><li>AssertJ”</li></ul><p>Specifying tools ensures:</p><ul><li>Correct imports and syntax</li><li>Use of best practices (e.g., assertThat() instead of assertTrue())</li><li>Proper mocking strategy (Mockito.mock(User.class))</li></ul><h4>Enumerate Test Scenarios Explicitly</h4><ul><li>Positive case</li><li>Missing required fields</li><li>endDate before startDate</li><li>endDate is null</li><li>startDate equals endDate</li><li>lastModifiedDate in future”</li></ul><p>Listing scenarios ensures coverage. Without it, AI or developers may miss edge cases.</p><p>Use bullet points or emojis to make them easy to scan:</p><ul><li>Positive case</li><li>Negative case</li><li>Edge case</li></ul><h4>Include Expected Validation Message</h4><ul><li>Title is required’</li><li>‘End date must not be earlier than start date’”</li></ul><p>This makes tests more realistic and aligned with typical Spring Boot validation patterns using annotations like @NotBlank, @Size, and @AssertFalse.</p><p>It also gives clarity on what kind of error handling will eventually be implemented.</p><h4>Mention Custom Methods and Their Behavior</h4><ul><li>endDate = null → returns false</li><li>endDate &lt; startDate → returns true</li><li>endDate &gt;= startDate → returns false”</li></ul><p>Custom methods are often overlooked in generated tests. By specifying expected behavior, you ensure they’re included and tested correctly.</p><h4>Clarify Assumptions About Validation Frameworks</h4><p>This avoids confusion between manual validation checks and annotation-based validation. It also ensures the correct use of ValidatorFactory and ConstraintViolation.</p><pre>// specify your package name here<br><br>import ...<br><br>class ExperienceTest {<br><br>    private static Validator validator;<br><br>    // change to personalized developer&#39;s data<br>    private User createUser() {<br>        return User.builder()<br>                .firstName(&quot;first&quot;)<br>                .lastName(&quot;Smith&quot;)<br>                .email(&quot;william@gmial.com&quot;)<br>                .phoneNumber(&quot;1234567890&quot;)<br>                .photo(&quot;profile-photo.jpg&quot;)<br>                .aboutMe(&quot;I am a software developer.&quot;)<br>                .nik(&quot;1234567890123456&quot;)<br>                .npwp(&quot;987654321098765&quot;)<br>                .photoKtp(&quot;ktp-photo.jpg&quot;)<br>                .photoNpwp(&quot;npwp-photo.jpg&quot;)<br>                .photoIjazah(&quot;ijazah-photo.jpg&quot;)<br>                .experienceYears(5)<br>                .skkLevel(&quot;Level 3&quot;)<br>                .currentLocation(&quot;Jakarta&quot;)<br>                .preferredLocations(Arrays.asList(&quot;Bandung&quot;, &quot;Surabaya&quot;))<br>                .skill(&quot;Java, Spring Boot, Microservices&quot;)<br>                .password(&quot;password&quot;)<br>                .price(1000000)<br>                .build();<br>    }<br><br>    @BeforeAll<br>    static void setupValidator() {<br>        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();<br>        validator = factory.getValidator();<br>    }<br><br>    @Test<br>    void testEmptyConstructor() {<br>        Experience experience = new Experience();<br>        assertNotNull(experience, &quot;Experience object should be created with empty constructor&quot;);<br>    }<br><br>    @Test<br>    void testFullValidParameters() {<br>        User user = createUser();<br><br>        Experience experience = Experience.builder()<br>                .title(&quot;Software Engineer&quot;)<br>                .company(&quot;Tech Company&quot;)<br>                .employmentType(EmploymentType.FULL_TIME)<br>                .startDate(LocalDate.of(2020, 5, 1))<br>                .endDate(LocalDate.of(2022, 5, 1))<br>                .location(&quot;San Francisco&quot;)<br>                .locationType(LocationType.ON_SITE)<br>                .user(user)<br>                .build();<br><br>        Set&lt;ConstraintViolation&lt;Experience&gt;&gt; violations = validator.validate(experience);<br>        assertTrue(violations.isEmpty(), &quot;Valid experience should have no violations&quot;);<br>    }<br><br>    @Nested<br>    class TitleAttributeTests {<br>        @Test<br>        void testTitleEmpty() {<br>            User user = createUser();<br><br>            Experience experience = Experience.builder()<br>                    .title(&quot;&quot;)<br>                    .company(&quot;Tech Company&quot;)<br>                    .employmentType(EmploymentType.FULL_TIME)<br>                    .startDate(LocalDate.of(2020, 5, 1))<br>                    .location(&quot;San Francisco&quot;)<br>                    .locationType(LocationType.ON_SITE)<br>                    .user(user)<br>                    .build();<br><br>            Set&lt;ConstraintViolation&lt;Experience&gt;&gt; violations = validator.validate(experience);<br><br>            assertFalse(violations.isEmpty());<br>            assertTrue(violations.stream().anyMatch(v -&gt; v.getMessage().contains(&quot;Title is required&quot;)));<br>        }<br><br>        @Test<br>        void testTitleMaxLength() {<br>            User user = createUser();<br><br>            String maxLengthTitle = &quot;A&quot;.repeat(50);<br>            Experience experience = Experience.builder()<br>                    .title(maxLengthTitle)<br>                    .company(&quot;Tech Company&quot;)<br>                    .employmentType(EmploymentType.FULL_TIME)<br>                    .startDate(LocalDate.of(2020, 5, 1))<br>                    .location(&quot;San Francisco&quot;)<br>                    .locationType(LocationType.ON_SITE)<br>                    .user(user)<br>                    .build();<br><br>            Set&lt;ConstraintViolation&lt;Experience&gt;&gt; violations = validator.validate(experience);<br><br>            assertTrue(violations.isEmpty(), &quot;Title at max length is considered valid&quot;);<br>        }<br><br>.....<br>}</pre><p>Critique:</p><ol><li><strong>Repetitive Code</strong>: Many tests repeat the creation of Experience objects with slight variations. This makes the code harder to maintain and increases the risk of inconsistencies.</li><li><strong>Improvement</strong>: Extract a helper method to create Experience objects with default values, and allow overriding specific attributes as needed.</li></ol><p>And you need to prompt again. This iterative process mirrors code refactoring: initial drafts improve over time with feedback and iteration.</p><h3>Literature Review: The Case Against @Autowired</h3><p>(literature soruce: <a href="https://www.researchgate.net/publication/374761096_An_Extensive_Review_of_Spring_Boot_Testing_Based_on_Business_Requirements_of_the_Software">https://www.researchgate.net/publication/374761096_An_Extensive_Review_of_Spring_Boot_Testing_Based_on_Business_Requirements_of_the_Software</a>)</p><p>In older Spring Boot applications, it’s common to see developers relying heavily on field injection using @Autowired. At first glance, this seems convenient: Spring magically wires dependencies behind the scenes, reducing boilerplate and letting you focus on your logic.</p><p>But convenience comes at a cost.</p><pre>import org.springframework.beans.factory.annotation.Autowired; <br><br>@RunWith(SpringRunner.class) <br>@SpringBootTest <br>public class MyTest { <br>  @Autowired <br>  private Environment environment; <br><br>  @Test <br>  public void testConfiguration() { <br>    if (environment.acceptsProfiles(&quot;test&quot;)) { <br>      // Your test configuration code here <br>    } <br>  } <br>} </pre><blockquote>This pattern appears in countless codebases. It works. But as your application scales and testing becomes more critical, the hidden drawbacks of field injection start to show.</blockquote><h3>The Hidden Costs of @Autowired</h3><p>Despite being widely used, @Autowired—especially when applied to fields—introduces several issues:</p><h4>1. Tight Coupling</h4><p>Field injection makes it harder to replace dependencies, especially during testing. Swapping a mock or stub becomes cumbersome without framework-specific features.</p><h4>2. Hidden Dependencies</h4><p>Dependencies aren’t obvious. A reader (or tester) of your class has no idea what’s required unless they look at the private fields. This violates the principle of explicit contracts.</p><h4>3. Testing Complexity</h4><p>Unit testing becomes trickier. Field injection often relies on reflection or Spring’s internal wiring, which means simple tests without Spring’s context become harder to write.</p><h4>4. Poor Maintainability</h4><p>Over time, hidden and tightly coupled dependencies make your codebase harder to refactor. You become more dependent on Spring’s lifecycle instead of writing plain, testable Java.</p><h3>Constructor Injection: A Modern Alternative</h3><p>The solution? Use <strong>constructor-based dependency injection</strong>. It’s explicit, cleaner, and plays well with unit testing.</p><pre>@RunWith(SpringRunner.class)<br>@SpringBootTest<br>public class MyTest {<br><br>    private final Environment environment;<br><br>    public MyTest(Environment environment) {<br>        this.environment = environment;<br>    }<br><br>    @Test<br>    public void testConfiguration() {<br>        if (environment.acceptsProfiles(&quot;test&quot;)) {<br>            // Your test configuration code here<br>        }<br>    }<br>}</pre><h3>Why Constructor Injection Is Better</h3><h4><strong>1. Explicit Dependencies</strong></h4><p>You immediately see what the class needs to work. No guessing or scanning through annotations.</p><h4><strong>2. Easier Testing</strong></h4><p>You can easily mock or stub dependencies without using Spring at all.</p><h4><strong>3. Immutability</strong></h4><p>Fields can be marked as final, making your classes safer and more predictable.</p><h4><strong>4. Framework-Agnostic</strong></h4><p>Constructor injection decouples your code from the framework. You can test or even run the class outside of Spring.</p><p>Spring Baeldung’s official blog <a href="https://www.baeldung.com/java-spring-field-injection-cons">warns against field injection </a>, citing these exact issues.</p><h3>Conclusion: Testing Is More Than Writing Tests</h3><p>Software testing might seem straightforward at first glance, but diving into literature reveals nuances that can make or break your test strategy.</p><p>From understanding stubs vs mocks , improving test generation through smart prompting , and moving away from outdated patterns like @Autowired, we’ve seen that:</p><ul><li>Testing is an evolving practice</li><li>Prompting requires iteration , just like coding</li><li>Literature guides best practices</li><li>Maintainability starts with good design</li></ul><p>So next time you write a test, ask yourself:</p><blockquote>“Am I writing a test — or am I building confidence in my system?”</blockquote><p>Because real quality comes from knowledge, not just coverage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a19555acaf21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Static Analysis Enough? Why Coderabbit Might Be the Missing Piece]]></title>
            <link>https://medium.com/@sunsetheus/is-static-analysis-enough-why-coderabbit-might-be-the-missing-piece-a491404669a0?source=rss-63e584266b01------2</link>
            <guid isPermaLink="false">https://medium.com/p/a491404669a0</guid>
            <dc:creator><![CDATA[William]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 06:51:13 GMT</pubDate>
            <atom:updated>2025-04-29T06:51:13.499Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s fast-paced software development world, static analysis has become a cornerstone of code quality assurance. It’s a tool that developers swear by — automatically scanning codebases for bugs, vulnerabilities, and inefficiencies without even running the program. But as powerful as static analysis is, it’s not without its limitations. Enter Coderabbit , a rising star in the realm of code quality tools. Is it time to rethink how we approach code analysis? Let’s dive in.</p><h3>The Comfort Zone of Static Analysis</h3><p>Static analysis tools have earned their place in the developer toolkit for good reason. They analyze code <em>statically </em>— without executing it — to identify potential issues early in the development process. Here’s why developers love them:</p><ol><li><strong>Early Detection</strong>: Static analysis catches bugs before they make it to production, saving time and resources.</li><li><strong>Scalability</strong>: These tools can scan large codebases quickly, making them ideal for enterprise-level projects.</li><li><strong>Consistency</strong>: They apply predefined rulesets uniformly across the codebase, ensuring compliance with coding standards.</li></ol><blockquote>But here’s the catch: because static analysis operates on <em>static </em>code, it has inherent limitations. It can’t account for dynamic behavior, runtime conditions, or non-deterministic scenarios. This is where things get interesting — and where <strong><em>Coderabbit </em></strong>steps in.</blockquote><h3>The Achilles’ Heel of Static Analysis</h3><p>Static analysis tools are deterministic by nature. They analyze code based on fixed rules and patterns, which makes them predictable but also rigid. Here’s what they often miss:</p><ol><li><strong>Dynamic Behavior</strong>: Static analysis can’t simulate how your code behaves under real-world conditions. For example, it might not catch race conditions, memory leaks, or edge cases that only occur during execution.</li><li><strong>Contextual Understanding</strong>: While static tools excel at syntax and structure, they struggle with understanding the broader context of your application. For instance, they might flag a piece of code as inefficient without realizing it’s optimized for a specific use case.</li><li><strong>Non-Deterministic Scenarios</strong>: Modern applications are increasingly complex, with asynchronous operations, distributed systems, and unpredictable user inputs. Static analysis simply isn’t designed to handle these nuances.</li></ol><p>This is where non-deterministic analysis comes into play. Unlike static analysis, non-deterministic tools like <strong><em>Coderabbit </em></strong>focus on runtime behavior, real-world usage patterns, and adaptive learning. They don’t just analyze code — they interact with it.</p><h3>What Makes Coderabbit Different?</h3><p>Coderabbit isn’t just another static analysis tool — it’s a game-changer. Here’s how it stands out:</p><ol><li><strong>Runtime Insights</strong>: Coderabbit works dynamically, analyzing code as it runs. This allows it to uncover issues that static analysis tools would never detect, such as performance bottlenecks under heavy load or unexpected API responses.</li><li><strong>Adaptive Learning</strong>: Unlike static tools that rely on predefined rules, Coderabbit uses machine learning to adapt to your codebase. It learns from your application’s behavior over time, offering increasingly accurate insights.</li><li><strong>Developer-Centric Approach</strong>: Coderabbit doesn’t just flag issues — it provides actionable recommendations. It helps you refactor code, optimize performance, and even suggests alternative implementations.</li></ol><h3>When Static Analysis Falls Short</h3><p>Let’s look at a practical example where static analysis fails but Coderabbit shines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HA-Pp2If_apoob9JAae0ZQ.png" /></figure><p>In the screenshot above, I am working in a class called RecommendationServiceImpl, editing a method that retrieves a Recommendation entity by ID. The code correctly uses the repository to fetch the entity and throws an exception if the entity is not found:</p><pre>Recommendation recommendation = recommendationRepository.findById(id)<br>    .orElseThrow(() -&gt; new EntityNotFoundException(&quot;Experience with ID &quot; + id + &quot; not found&quot;));</pre><p>At a glance, the code is syntactically correct, compiles just fine, and even passes unit tests — if those tests don’t explicitly check the exception message. However, there’s a subtle but critical problem:</p><blockquote><em>The error message incorrectly references “Experience” instead of “Recommendation”.</em></blockquote><p>This is a classic case of a <strong>logic error introduced via copy-paste</strong>. I (of course I am) likely copied a similar line from another service (like ExperienceServiceImpl) and forgot to update the entity name in the exception message.</p><h3>Why You Need Both</h3><p>Rather than choosing between static analysis and Coderabbit, the smart move is to use them together. Think of static analysis as your first line of defense — it catches low-hanging fruit and enforces coding standards. Coderabbit, on the other hand, acts as your second pair of eyes, diving deeper into runtime behavior and uncovering hidden issues.</p><p>Here’s how they complement each other:</p><ul><li><strong>Static Analysis</strong>: Ensures code quality and compliance with best practices.</li><li><strong>Coderabbit</strong>: Provides runtime insights, adaptive learning, and actionable recommendations.</li></ul><p><strong>Add Coderabbit</strong></p><ul><li>Go to <a href="https://www.coderabbit.ai/">https://www.coderabbit.ai/</a></li><li>Click <strong>Login</strong> or <strong>Create an account</strong> (you can log in using GitHub).</li><li>Click <strong>Add Repositories</strong> from the dashboard.</li><li>You’ll be redirected to GitHub to authorize access.</li><li>Choose the organization and repositories you want to connect — and you’re done! Coderabbit will start reviewing your pull requests automatically.</li></ul><h3>Additional Setup for Frontend Projects</h3><p>For frontend projects (like React, Vue, etc.), you’ll need to add a .coderabbit.yaml config file to the root of your repository.</p><p>Here’s a sample configuration:</p><pre># yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json<br>language: &#39;en-US&#39;<br>early_access: false<br>reviews:<br>  profile: &#39;chill&#39;<br>  request_changes_workflow: false<br>  high_level_summary: true<br>  poem: true<br>  review_status: true<br>  collapse_walkthrough: false<br>  auto_review:<br>    enabled: true<br>    drafts: false<br>    base_branches:<br>      - &#39;dev&#39;<br>chat:<br>  auto_reply: true</pre><h3>Conclusion: The Future of Code Quality</h3><p>Static analysis has served us well, but it’s time to acknowledge its limitations. As applications grow more complex and dynamic, tools like Coderabbit are becoming indispensable. They bridge the gap between static code analysis and real-world behavior, offering a more holistic approach to code quality.</p><p>So, is static analysis still necessary? Absolutely. But if you want to take your code quality to the next level, it’s worth exploring what Coderabbit can do for you. After all, in the ever-evolving world of software development, staying ahead means embracing both the tried-and-true and the cutting-edge.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a491404669a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Security as Your App’s Bodyguard: Stopping OWASP Threats at the Door]]></title>
            <link>https://medium.com/@sunsetheus/spring-security-as-your-apps-bodyguard-stopping-owasp-threats-at-the-door-32431af91271?source=rss-63e584266b01------2</link>
            <guid isPermaLink="false">https://medium.com/p/32431af91271</guid>
            <dc:creator><![CDATA[William]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 04:58:04 GMT</pubDate>
            <atom:updated>2025-05-15T05:28:13.897Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>In today’s interconnected digital world, security is no longer an afterthought — it’s a necessity. Whether you’re building a Spring Boot backend or a React frontend, understanding and mitigating potential threats is critical to protecting your application from malicious actors. One of the most common frameworks for securing Java-based applications is Spring Security , which acts as your app’s bodyguard by stopping OWASP (Open Web Application Security Project) threats before they can do harm.</p><p>In this article, we’ll explore how to secure your Spring Boot and React application using industry-standard practices. We’ll cover the bare minimum requirements for both frontend and backend, explain how Spring Security integrates with OWASP recommendations, and analyze potential security issues throughout the Software Development Life Cycle (SDLC).</p><h3>Introduction: The Importance of Security in Your Project</h3><p>Every project, no matter how small, is vulnerable to security threats if not properly protected. Some common risks include:</p><ul><li>Unauthorized access : Attackers gaining access to sensitive data.</li><li>Data breaches : Exposure of user credentials, personal information, or financial data.</li><li>Injection attacks : Malicious code injected into your system via SQL, NoSQL, or other means.</li><li>Cross-Site Scripting (XSS) : Injected scripts that execute in users’ browsers.</li><li>Cross-Site Request Forgery (CSRF) : Unauthorized commands executed on behalf of authenticated users.</li></ul><p>To mitigate these risks, it’s essential to implement robust security measures. For Spring Boot applications, Spring Security provides a powerful framework to protect your backend. On the frontend, tools like React Context and Higher-Order Components (HOCs) can ensure secure user authentication and authorization.</p><h3>Standard Security Practices for Spring Boot and React</h3><h4>Backend: Spring Security</h4><p>The backend is the heart of your application, and securing it is paramount. Here’s how you can set up a secure backend using Spring Security:</p><h4>1. Bare Minimum Backend Security</h4><p>At a minimum, your backend should:</p><ul><li>Use JWT (JSON Web Tokens) for stateless authentication.</li><li>Enforce role-based access control (RBAC).</li><li>Protect against OWASP Top 10 vulnerabilities.</li></ul><h4>2. Folder Structure for Security Configurations</h4><p>Organize your backend security setup with the following structure:</p><pre>src/main/java/com/example/config/<br>├── SecurityConfiguration.java      // Main security configuration<br>├── JwtAuthenticationFilter.java    // JWT token validation<br>├── AppConfiguration.java           // General application configuration</pre><h4>3. Middleware for Authentication and Authorization</h4><p>Spring Security acts as middleware to handle authentication and authorization. Key components include:</p><ul><li>Authentication : Verifying user credentials.</li><li>Authorization : Ensuring users have permission to access specific resources.</li><li>JWT Integration : Securing API endpoints with tokens.</li></ul><p>For example, you can configure Spring Security to:</p><ul><li>Require authentication for all routes except /api/auth/login and /api/auth/register.</li><li>Validate JWT tokens for protected routes.</li></ul><h3>OWASP Threats and Spring Security Integration</h3><p>We will explore how our Spring Boot application addresses common security threats outlined in the OWASP Top 10, and how Spring Security helps mitigate these risks. Understanding these threats is crucial for maintaining a secure backend architecture.</p><h4>1. Broken Authentication</h4><p><strong>Threat</strong>: Attackers can compromise authentication through credential stuffing, brute force, and session management flaws.</p><p><strong>Our Implementation</strong>:</p><pre>@Configuration<br>public class ApplicationConfiguration {<br>    @Bean<br>    public BCryptPasswordEncoder passwordEncoder() {<br>        return new BCryptPasswordEncoder();<br>    }<br>    <br>    // Authentication provider configuration<br>    @Bean<br>    public AuthenticationProvider authenticationProvider() {<br>        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();<br>        authProvider.setUserDetailsService(userDetailsService());<br>        authProvider.setPasswordEncoder(passwordEncoder());<br>        return authProvider;<br>    }<br>}</pre><p>Our application uses BCrypt for password hashing and implements JWT-based stateless authentication, preventing session fixation attacks. The AuthenticationService handles login attempts and securely stores user credentials.</p><p><strong>Impact if Unaddressed</strong>: Unauthorized access to user accounts, potential data breaches, and compromise of sensitive user information.</p><h4>2. Cross-Site Request Forgery (CSRF)</h4><p><strong>Threat</strong>: Attackers trick authenticated users into executing unwanted actions on websites they’re logged into.</p><p><strong>Our Implementation</strong>:</p><pre>@Configuration<br>@EnableWebSecurity<br>public class SecurityConfiguration {<br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>        http<br>            .csrf(AbstractHttpConfigurer::disable)  // Disabled for APIs using JWT<br>            // Other security configurations<br>    }<br>}</pre><h4>3. Broken Access Control</h4><p><strong>Threat</strong>: Improper restrictions on authenticated users accessing unauthorized resources.</p><p><strong>Our Implementation</strong>:</p><pre>http.authorizeHttpRequests(auth -&gt; auth<br>    .requestMatchers(&quot;/api/auth/**&quot;).permitAll()<br>    .requestMatchers(&quot;/api/users/contractor&quot;).permitAll()<br>    .requestMatchers(&quot;/api/email&quot;).permitAll()<br>    .requestMatchers(&quot;/api/**&quot;).authenticated()<br>    .requestMatchers(&quot;/actuator/**&quot;).permitAll()<br>    .anyRequest().denyAll()<br>)</pre><p>While CSRF protection is disabled, our application uses token-based authentication (JWT) which is inherently resistant to CSRF attacks as each request must include the authorization header.</p><p><strong>Impact if Unaddressed</strong>: Unauthorized operations performed on behalf of authenticated users.</p><h4>4. Security Misconfiguration</h4><p><strong>Threat</strong>: Improper configuration of application, frameworks, servers, or platforms exposing vulnerabilities.</p><p><strong>Our Implementation</strong>:</p><pre>@Bean<br>public CorsConfigurationSource corsConfigurationSource() {<br>    CorsConfiguration configuration = new CorsConfiguration();<br>    configuration.setAllowedOrigins(List.of(<br>        &quot;http://localhost:5173&quot;,<br>        &quot;http://localhost:8080&quot;, <br>        &quot;https://rencanakanid-stg.netlify.app/&quot;, <br>        &quot;https://rencanakan-system.netlify.app/&quot;<br>    ));<br>    configuration.setAllowedMethods(List.of(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;, &quot;PATCH&quot;));<br>    configuration.setAllowedHeaders(List.of(&quot;Authorization&quot;, &quot;Content-Type&quot;));<br>    <br>    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();<br>    source.registerCorsConfiguration(&quot;/**&quot;, configuration);<br>    return source;<br>}</pre><p>Our application uses explicit CORS configuration, stateless session management, and clear security headers to minimize potential misconfiguration vulnerabilities.</p><p><strong>Impact if Unaddressed</strong>: Easy exploitation of other vulnerabilities, unauthorized access, and data leakage.</p><h4>5. Sensitive Data Exposure</h4><p><strong>Threat</strong>: Inadequate protection of sensitive data such as financial information, passwords, or personal details.</p><p><strong>Our Implementation</strong>:</p><pre>public void resetPasswordWithToken(String token, String newPassword) {<br>    PasswordResetToken resetToken = passwordResetTokenRepository.findByToken(token)<br>            .orElseThrow(() -&gt; new IllegalArgumentException(&quot;Token tidak valid&quot;));<br><br>    // Validate token and update password securely<br>    user.setPassword(passwordEncoder.encode(newPassword));<br>    userRepository.save(user);<br>}</pre><p>Our application encrypts passwords with BCrypt, implements secure password reset flows, and uses HTTPS (implied by proper deployment) for data in transit.</p><p><strong>Impact if Unaddressed</strong>: Data breaches exposing user credentials and personal information, potentially leading to financial loss or identity theft.</p><h4>6. Cross-Site Scripting (XSS)</h4><p><strong>Threat</strong>: Attackers inject client-side scripts into web pages viewed by other users.</p><p><strong>Our Implementation</strong>: While primarily a frontend concern, our backend helps mitigate XSS by:</p><ul><li>Returning data in safe formats (JSON)</li><li>Separating data from code</li><li>Using Content-Type headers appropriately</li></ul><p><strong>Impact if Unaddressed</strong>: Session hijacking, credential theft, and malicious actions performed on behalf of users.</p><h4>7. Insufficient Logging &amp; Monitoring</h4><p><strong>Threat</strong>: Lack of logging, monitoring, and incident response capability.</p><p><strong>Our Implementation</strong>:</p><pre>@Override<br>public void sendResetPasswordEmail(String to, String resetLink) {<br>    System.out.println(&quot;Sending reset password email to &quot; + to);<br>    // Email sending logic<br>}</pre><p><strong>Impact if Unaddressed</strong>: Breaches may remain undetected, allowing attackers more time to pivot, extract data, or cause damage.</p><h3>Analyzing Security Issues Across the SDLC</h3><p>Software security shouldn’t be an afterthought but rather an integrated part of the entire development lifecycle. Looking at the project structure and code implementation of our talent pool platform, several potential security vulnerabilities require attention. Let’s analyze these issues according to each SDLC phase and discuss effective mitigation strategies.</p><p><strong>Potential Issues:</strong></p><ul><li>Inadequate security requirements definition</li><li>Missing compliance considerations (GDPR, CCPA for user data)</li><li>Undefined security acceptance criteria</li></ul><p><strong>What’s Missing:</strong> The codebase doesn’t show evidence of security requirements or compliance considerations, especially concerning the sensitive personal data being stored (NIK, NPWP, photos of identity documents).</p><p><strong>Impact If Not Addressed:</strong> Without proper security requirements, the application might violate data protection regulations, potentially resulting in significant fines and reputational damage, especially considering the sensitive personal data stored.</p><p><strong>Mitigation Strategies:</strong></p><ul><li>Implement security requirements gathering through threat modeling</li><li>Define security-focused user stories and acceptance criteria</li><li>Include compliance requirements in initial planning</li></ul><p><strong>Potential Issues:</strong></p><ol><li>The current JWT implementation lacks token revocation mechanisms</li></ol><pre>@PostMapping(&quot;/login&quot;)<br>public ResponseEntity&lt;WebResponse&lt;LoginResponseDTO&gt;&gt; authenticate(@RequestBody LoginRequestDTO loginUserDto) {<br>    User authenticatedUser = authenticationService.authenticate(loginUserDto);<br>    String jwtToken = jwtService.generateToken(authenticatedUser);<br><br>    LoginResponseDTO loginResponse = new LoginResponseDTO();<br>    loginResponse.setToken(jwtToken);<br>    loginResponse.setExpiresIn(jwtService.getExpirationTime());<br><br>    WebResponse&lt;LoginResponseDTO&gt; response = WebResponse.&lt;LoginResponseDTO&gt;builder()<br>            .data(loginResponse)<br>            .errors(null)<br>            .build();<br><br>    return ResponseEntity.ok(response);<br>}</pre><p><strong>What’s Missing:</strong> Once a JWT token is issued, it remains valid until it expires, even if a user logs out or their account is compromised. There’s no mechanism to invalidate tokens before their expiration.</p><p><strong>Impact If Not Addressed:</strong> If a token is stolen, the attacker will have access until the token naturally expires (typically hours or days). This presents a significant security risk as even if a user changes their password after suspecting compromise, the old token would still grant access.</p><p><strong>Mitigation Code Solutions:</strong> Add implementation for token revocation and tracking:</p><pre>package rencanakan.id.talentpool.model;<br><br>import jakarta.persistence.*;<br>import lombok.*;<br><br>import java.time.Instant;<br><br>@Entity<br>@Getter<br>@Setter<br>@Builder<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class InvalidatedToken {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    <br>    @Column(nullable = false, unique = true)<br>    private String token;<br>    <br>    @Column(nullable = false)<br>    private Instant expiryDate;<br>    <br>    @Column(nullable = false)<br>    private String userId;<br>}</pre><p>And modify the JWT service to check for invalidated tokens:</p><pre>// Add this method to JwtService<br>public void invalidateToken(String token, User user) {<br>    Claims claims = extractAllClaims(token);<br>    Instant expiryDate = claims.getExpiration().toInstant();<br>    <br>    InvalidatedToken invalidatedToken = InvalidatedToken.builder()<br>        .token(token)<br>        .userId(user.getId())<br>        .expiryDate(expiryDate)<br>        .build();<br>        <br>    invalidatedTokenRepository.save(invalidatedToken);<br>}<br><br>// Modify isTokenValid to check for invalidated tokens<br>public boolean isTokenValid(String token, UserDetails userDetails) {<br>    final String username = extractUsername(token);<br>    Optional&lt;InvalidatedToken&gt; invalidatedToken = invalidatedTokenRepository.findByToken(token);<br>    <br>    return (username.equals(userDetails.getUsername())) <br>            &amp;&amp; !isTokenExpired(token) <br>            &amp;&amp; invalidatedToken.isEmpty();<br>}</pre><p>2. For rate limiting to prevent brute force attacks:</p><pre>package rencanakan.id.talentpool.configs;<br><br>import io.github.bucket4j.Bandwidth;<br>import io.github.bucket4j.Bucket;<br>import io.github.bucket4j.Bucket4j;<br>import io.github.bucket4j.Refill;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>import java.time.Duration;<br>import java.util.Map;<br>import java.util.concurrent.ConcurrentHashMap;<br><br>@Configuration<br>public class RateLimitingConfig {<br>    <br>    private final Map&lt;String, Bucket&gt; ipToBucket = new ConcurrentHashMap&lt;&gt;();<br>    <br>    @Bean<br>    public Map&lt;String, Bucket&gt; buckets() {<br>        return ipToBucket;<br>    }<br>    <br>    public Bucket resolveBucket(String ipAddress) {<br>        return ipToBucket.computeIfAbsent(ipAddress, this::createNewBucket);<br>    }<br>    <br>    private Bucket createNewBucket(String ipAddress) {<br>        // Allow 5 login attempts per minute<br>        Bandwidth limit = Bandwidth.classic(5, Refill.greedy(5, Duration.ofMinutes(1)));<br>        return Bucket4j.builder().addLimit(limit).build();<br>    }<br>}</pre><p><strong>3. Debug Statement Issues:</strong></p><p><strong>What’s Missing:</strong> The code contains several debug print statements in production code, which is a poor security practice:</p><pre>@Override<br>public void sendResetPasswordEmail(String to, String resetLink) {<br>    System.out.println(&quot;Sending reset password email to &quot; + to);  // Debug statement in production<br>    SimpleMailMessage message = new SimpleMailMessage();<br>    // rest of the code<br>}</pre><p><strong>Impact If Not Addressed:</strong> Debug statements can leak sensitive information to logs, which might be accessible to unauthorized personnel. They can also impact performance and make logs harder to analyze for actual issues.</p><p><strong>Mitigation Code Solutions</strong></p><pre>// Replace direct print statements with proper logging<br>private static final Logger log = LoggerFactory.getLogger(EmailServiceImpl.class);<br><br>@Override<br>public void sendResetPasswordEmail(String to, String resetLink) {<br>    log.debug(&quot;Sending reset password email to {}&quot;, to);  // Proper logging<br>    SimpleMailMessage message = new SimpleMailMessage();<br>    // rest of the code<br>}</pre><blockquote>Leaving debug statements like System.out.println() or excessive logging in your code can have serious consequences. Not only can they accidentally expose sensitive information to logs — which might be accessed by unauthorized users — but they also clutter log files, making it harder to trace real issues. Over time, this noise can degrade performance and reduce the effectiveness of your monitoring tools. That’s why it&#39;s critical to use proper logging levels (like DEBUG or INFO) and ensure debug logs are disabled or filtered in production environments. Clean logs are not just a best practice — they’re a security and performance necessity.</blockquote><h3>Summary</h3><p>Securing your application is a multi-layered process that involves both frontend and backend measures. By leveraging Spring Security for your backend and implementing React Context and Protected Routes on the frontend, you can build a robust security framework. Additionally, integrating OWASP recommendations and addressing potential security issues throughout the SDLC ensures your application remains resilient against threats.</p><p>Remember, security is an ongoing effort. Regular audits, updates, and monitoring are key to keeping your app safe. With Spring Security as your app’s bodyguard, you can stop OWASP threats at the door and protect your users from harm.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32431af91271" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Personalize Your Observability Stack with Prometheus & Grafana]]></title>
            <link>https://medium.com/@sunsetheus/spring-security-as-your-apps-bodyguard-stopping-owasp-threats-at-the-door-8bd92a96dd43?source=rss-63e584266b01------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bd92a96dd43</guid>
            <dc:creator><![CDATA[William]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 04:37:17 GMT</pubDate>
            <atom:updated>2025-05-08T07:51:43.367Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s fast-paced development environment, monitoring your applications and infrastructure is crucial for maintaining performance, detecting issues early, and ensuring a smooth user experience. While many platforms offer built-in monitoring tools (e.g., Firebase Monitoring, AWS CloudWatch, GCP Monitoring), custom solutions like Prometheus and Grafana provide unparalleled flexibility and control over how you observe your systems.</p><p>In this guide, we’ll walk you through what platform monitoring is, compare built-in monitoring tools with custom setups, and show you how to set up Prometheus and Grafana from scratch. We’ll also cover how to customize your monitoring stack to track specific metrics, such as API calls to /api/auth/login.</p><h3>What is Platform Monitoring?</h3><p>Platform monitoring involves collecting, analyzing, and visualizing data about the performance, health, and usage of your applications and infrastructure. It helps developers and DevOps teams identify bottlenecks, errors, and anomalies in real-time.</p><h3>Built-in Monitoring Tools</h3><p>Many development platforms come with their own monitoring solutions:</p><ul><li><strong>Firebase Monitoring </strong>: Tracks app performance, crash reports, and user analytics. Great for mobile apps but limited to Firebase ecosystems.</li><li><strong>AWS CloudWatch </strong>: Monitors AWS resources and applications running on AWS. Offers deep integration with AWS services but can be expensive for large-scale use.</li><li><strong>GCP Monitoring </strong>: Provides insights into Google Cloud resources and applications. Easy to set up but tightly coupled with GCP.</li></ul><h4>Pros of Built-in Monitoring Tools :</h4><ul><li>Quick setup with minimal configuration.</li><li>Tight integration with the platform’s ecosystem.</li><li>Often includes pre-built dashboards and alerts.</li></ul><h4>Cons of Built-in Monitoring Tools :</h4><ul><li>Limited flexibility for custom metrics.</li><li>Vendor lock-in (e.g., tied to Firebase, AWS, or GCP).</li><li>Can become costly at scale.</li></ul><h3>Prometheus and Grafana</h3><h4>Prometheus</h4><p>Prometheus is an open-source monitoring and alerting toolkit designed for reliability and scalability. It scrapes metrics from configured targets at given intervals, evaluates rule expressions, and triggers alerts if necessary.</p><h4>Key Features :</h4><ul><li>Pull-based metric collection.</li><li>Powerful query language (PromQL) for analyzing data.</li><li>Highly customizable and extensible.</li></ul><h4>Grafana</h4><p>Grafana is an open-source visualization tool that works seamlessly with Prometheus. It allows you to create interactive dashboards to visualize your metrics in real-time.</p><h4>Key Features :</h4><ul><li>Rich library of visualization options (graphs, gauges, heatmaps, etc.).</li><li>Supports multiple data sources (Prometheus, Elasticsearch, MySQL, etc.).</li><li>Customizable dashboards and alerting rules.</li></ul><h3>Setting Up Prometheus and Grafana</h3><h4>Folder Structure</h4><p>To keep things organized, follow this folder structure:</p><pre>monitoring/<br>├── docker-compose.yml<br>├── grafana/<br>│   └── provisioning/<br>│       └── datasource.yml<br>└── prometheus/<br>    └── prometheus.yml</pre><h4>File Descriptions :</h4><ol><li>docker-compose.yml : Defines the services for Prometheus and Grafana.</li><li>grafana/provisioning/datasource.yml : Configures Grafana to connect to Prometheus automatically.</li><li>prometheus/prometheus.yml : Configures Prometheus scraping jobs.</li></ol><pre>// docker-compose.yml<br>version: &#39;3.7&#39;<br><br>services:<br>  prometheus:<br>    image: prom/prometheus:v2.44.0<br>    container_name: prometheus<br>    ports:<br>      - &quot;9090:9090&quot;<br>    volumes:<br>      - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml<br><br>  grafana:<br>    image: grafana/grafana:9.5.2<br>    container_name: grafana<br>    ports:<br>      - &quot;3000:3000&quot;<br>    restart: unless-stopped<br>    volumes:<br>      - ./grafana/datasources:/etc/grafana/provisioning/datasources</pre><pre>// datasource.yml<br>apiVersion: 1<br>datasources:<br>  - name: Prometheus<br>    type: prometheus<br>    access: proxy<br>    url: http://prometheus:9090<br>    isDefault: true</pre><pre>// prometheus.yml<br>scrape_configs:<br>  - job_name: &#39;TalentPoolMicroserviceMetrics&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    scrape_interval: 3s<br>    static_configs:<br>      - targets: [&#39;host.docker.internal:8080&#39;]<br>        labels:<br>          application: &#39;My Spring Boot Application&#39;</pre><h3>Running the Setup</h3><ol><li>Navigate to the monitoring Directory :</li></ol><pre>cd monitoring</pre><p>2. Start the Services : Run the following command to start Prometheus and Grafana:</p><pre>docker-compose up -d</pre><p>3. Access the Tools :</p><ul><li>Open Grafana at: <a href="http://localhost:3000/">http://localhost:3000</a></li><li>Open Prometheus at: <a href="http://localhost:9090/">http://localhost:9090</a></li></ul><h3>Integrating Prometheus with Grafana</h3><h4>Steps to Add Prometheus as a Data Source</h4><ol><li>Open Grafana at <a href="http://localhost:3000/">http://localhost:3000 </a>.</li><li>Navigate to Configuration &gt; Data Sources .</li><li>Click Add data source and select Prometheus .</li><li>Enter the URL for Prometheus: <a href="http://prometheus:9090.">http://prometheus:9090.</a></li><li>Click Save &amp; Test to verify the connection.</li></ol><h4>Create a Custom Dashboard</h4><ol><li>In Grafana, go to Dashboards &gt; New &gt; New Panel .</li><li>Configure the query using PromQL to display the desired metrics.</li><li>Save the dashboard once you’re satisfied with the visualization.</li></ol><h3>Setup Sentry: Monitoring Specific Functions like Login</h3><ol><li>Open <a href="https://sentry.io/">https://sentry.io/</a>, create new account if you don’t have one, follow their instruction (auth option, your name, etc.). After that you’ll be redirected to your own sentry dashboard. Click “+ Create Project”</li></ol><p>2. Choose your platform</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZAVt7mUe8fxPl-F-MNpfuA.png" /></figure><p>3. Set your alert frequency</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QIgjUpCRBa3wfzuovaBCg.png" /></figure><p>4. Name your project and assign it a team</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nV2BAocxusU1KwPGq6qTNw.png" /></figure><p>5. Generate your token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*2ZOmEFKfGkAAIWLeJ73p6A.png" /></figure><p>6. Copy grade plugin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vh1Z3fb1Y-p3QquDWlgReQ.png" /></figure><p>7. Add your sentry configurations to app.properties</p><pre>sentry.dsn=<br>sentry.send-default-pii=true</pre><p>8. Verify</p><pre>import java.lang.Exception;<br>import io.sentry.Sentry;<br><br>try {<br>  throw new Exception(&quot;This is a test.&quot;);<br>} catch (Exception e) {<br>  Sentry.captureException(e);<br>}</pre><h4>Java Code Example: Capturing Login Success and Failure in Sentry</h4><pre>public User authenticate(LoginRequestDTO input) {<br>    try {<br>        authenticationManager.authenticate(<br>                new UsernamePasswordAuthenticationToken(<br>                        input.getEmail(),<br>                        input.getPassword()<br>                )<br>        );<br>        User user = userRepository.findByEmail(input.getEmail()).orElse(null);<br><br>        // Log successful login to Sentry<br>        Sentry.configureScope(scope -&gt; {<br>            scope.setTag(&quot;action&quot;, &quot;login&quot;);<br>            scope.setTag(&quot;status&quot;, &quot;success&quot;);<br>        });<br>        Sentry.captureMessage(&quot;Login successful for user: &quot; + input.getEmail(), SentryLevel.INFO);<br>        return user;<br><br>    } catch (BadCredentialsException e) {<br>        // Log failed login attempt to Sentry<br>        Sentry.configureScope(scope -&gt; {<br>            scope.setTag(&quot;action&quot;, &quot;login&quot;);<br>            scope.setTag(&quot;status&quot;, &quot;failed&quot;);<br>        });<br>        Sentry.captureMessage(&quot;Login failed for user: &quot; + input.getEmail(), SentryLevel.ERROR);<br>        Sentry.captureException(e);<br><br>        throw e;<br>    }<br>}</pre><p>This code will log both successful and failed login attempts. For failed login attempts, you can track which users are failing to log in, allowing you to take action — whether that’s manually handling password reset requests or tracking failed attempts for future improvements.</p><h3>Conclusion</h3><p>By combining Prometheus and Grafana , you can build a highly personalized observability stack tailored to your specific needs. Unlike built-in monitoring tools, this setup gives you full control over what metrics to collect, how to visualize them, and when to trigger alerts.</p><p>Adding Sentry into the mix helps you track specific application events, such as login attempts, and provides deeper insights into potential issues before they affect your users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bd92a96dd43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Anti-Patterns: When to Use Design Patterns Without Overengineering]]></title>
            <link>https://medium.com/@sunsetheus/spring-boot-anti-patterns-when-to-use-design-patterns-without-overengineering-361471d986f0?source=rss-63e584266b01------2</link>
            <guid isPermaLink="false">https://medium.com/p/361471d986f0</guid>
            <dc:creator><![CDATA[William]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 04:00:18 GMT</pubDate>
            <atom:updated>2025-04-29T05:26:42.530Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*j-eQS0GqSTdaThSZ" /></figure><h3>Introduction</h3><p>In software development, <strong><em>anti-patterns</em></strong> refer to common practices or solutions that seem effective at first glance but lead to problems in the long run. These issues often manifest as spaghetti code, hardcoding, or overly complex architectures that are difficult to maintain and scale.</p><p>For Spring Boot developers, anti-patterns frequently arise from three main challenges:</p><ol><li><strong>Legacy Code</strong> : Existing systems that have grown organically without proper structure.</li><li><strong>Overengineering</strong> : Applying design patterns unnecessarily, leading to bloated and convoluted codebases.</li><li><strong>Refactoring Only When Necessary</strong> : Developers tend to refactor only when the code becomes fragile or unsafe, which is often too late.</li></ol><blockquote>This article aims to address these challenges by exploring when and how to use design patterns effectively in Spring Boot applications without falling into the trap of overengineering. We’ll also demonstrate how to refactor your code using design patterns while being mindful of their trade-offs. Each design pattern has its pros and cons, and we’ll highlight these through practical code examples.</blockquote><h3>What Are Anti-Patterns and Their Impact?</h3><p>Anti-patterns are essentially “bad practices” that developers unintentionally adopt due to lack of experience, time constraints, or poor planning. In the context of Spring Boot, some common anti-patterns include:</p><ul><li><strong>Spaghetti Code</strong>: A tangled mess of interdependent classes and methods with no clear separation of concerns.</li><li><strong>Hardcoding</strong>: Embedding values directly into the code instead of using configuration files or constants.</li><li><strong>God Object</strong> : A single class that tries to do everything, violating the Single Responsibility Principle (SRP).</li></ul><h4>These anti-patterns lead to several issues:</h4><ul><li><strong>Legacy Code</strong>: Systems become rigid and resistant to change, making future updates costly and risky.</li><li><strong>Overengineering</strong>: Excessive complexity makes the codebase harder to understand and maintain.</li><li><strong>Poor Maintainability</strong>: Code becomes brittle, prone to bugs, and difficult for new team members to onboard.</li></ul><p>The good news? With careful application of design patterns, you can avoid these pitfalls and build robust, maintainable systems.</p><h3>When and How to Use Design Patterns in Spring Boot</h3><p>Design patterns are reusable solutions to common programming problems. They fall into three main categories:</p><ol><li><strong>Creational Patterns</strong>: Focus on object creation mechanisms (e.g., Singleton, Builder).</li><li><strong>Structural Patterns</strong>: Deal with class and object composition (e.g., Adapter, Facade).</li><li><strong>Behavioral Patterns</strong>: Concerned with communication between objects (e.g., Observer, State).</li></ol><h4><strong>Spring Boot’s Built-In Design Patterns</strong></h4><p>Spring Boot already incorporates many design patterns out of the box:</p><ul><li><strong>MVC Architecture</strong>: Separates concerns between controllers, services, and repositories.</li><li><strong>Repository Pattern</strong>: Abstracts data access logic.</li><li><strong>Dependency Injection</strong>: Promotes loose coupling and testability.</li></ul><h4>Avoiding Overengineering</h4><p>Not every problem requires a design pattern. For example, consider implementing a state pattern for handling message statuses like <strong>Pending </strong>and <strong>Accepted</strong>. If there are only two states, this approach might be overkill. You could end up with empty methods overridden for invalid actions, cluttering your code unnecessarily.</p><pre>public interface MessageState {<br>    void accept();<br>}<br><br>public class PendingState implements MessageState {<br>    @Override<br>    public void accept() {<br>        System.out.println(&quot;Processing accpeting message&quot;);<br>    }<br>}<br><br>public class AcceptedState implements MessageState {<br>    @Override<br>    public void accept() {<br>        // Nothing happens here because Accepted state doesn&#39;t support accepting<br>    }<br>}<br></pre><blockquote>While the <strong>State </strong>pattern works well for complex state transitions, it’s excessive for simple scenarios. Always evaluate whether the added complexity justifies the benefits.</blockquote><h3>Implementation: Practical Examples</h3><p>Let’s dive into three specific design patterns and see how they improve code quality in Spring Boot applications.</p><h4>1. Data Transfer Objects (DTO)</h4><p>DTOs help transfer data between layers, ensuring clean separation and reducing payload size.</p><pre>import jakarta.persistence.*;<br>import jakarta.validation.constraints.*;<br>import lombok.*;<br><br>@Entity<br>@Getter<br>@Setter<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class User {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @NotBlank(message = &quot;Name is required&quot;)<br>    @Size(max = 100, message = &quot;Name must not exceed 100 characters&quot;)<br>    private String name;<br><br>    @NotBlank(message = &quot;Email is required&quot;)<br>    @Email(message = &quot;Invalid email format&quot;)<br>    @Size(max = 150, message = &quot;Email must not exceed 150 characters&quot;)<br>    private String email;<br><br>    @NotBlank(message = &quot;Password is required&quot;)<br>    @Size(min = 8, max = 100, message = &quot;Password must be between 8 and 100 characters&quot;)<br>    private String password;<br><br>    @Size(max = 255, message = &quot;Address must not exceed 255 characters&quot;)<br>    private String address;<br><br>    @Size(max = 15, message = &quot;Phone number must not exceed 15 characters&quot;)<br>    private String phoneNumber;<br>}</pre><blockquote>Here, the entire <strong>User </strong>entity is exposed, including sensitive fields like passwords.</blockquote><h4>Without DTO</h4><pre>@RestController<br>@RequestMapping(&quot;/users&quot;)<br>public class UserController {<br><br>    @Autowired<br>    private UserService userService;<br><br>    @PatchMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;String&gt; updateUser(@PathVariable Long id, @RequestBody User user) {<br>        userService.updateUser(id, user);<br>        return ResponseEntity.ok(&quot;User updated successfully!&quot;);<br>    }<br>}</pre><blockquote>In this approach, we directly use the <em>User</em> entity to accept input from the client. However, this poses a security risk as all fields can be sent by the client, including sensitive fields like <em>password</em>.</blockquote><h4>With DTO</h4><pre>import jakarta.validation.constraints.Size;<br>import lombok.AllArgsConstructor;<br>import lombok.Data;<br>import lombok.NoArgsConstructor;<br><br>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class UserUpdateDto {<br><br>    @Size(max = 255, message = &quot;Address must not exceed 255 characters&quot;)<br>    private String address;<br><br>    @Size(max = 15, message = &quot;Phone number must not exceed 15 characters&quot;)<br>    private String phoneNumber;<br>}<br><br></pre><pre>@RestController<br>@RequestMapping(&quot;/users&quot;)<br>public class UserController {<br><br>    @Autowired<br>    private UserService userService;<br><br>    @PatchMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;String&gt; updateUser(@PathVariable Long id, @RequestBody UserUpdateDto userUpdateDto) {<br>        userService.updateUser(id, userUpdateDto);<br>        return ResponseEntity.ok(&quot;User updated successfully!&quot;);<br>    }<br>}</pre><blockquote>Using a DTO for updates offers several advantages. It enhances security by ensuring that sensitive fields like password cannot be accessed or modified by the client. Additionally, it improves efficiency by reducing payload size, as only the relevant fields are sent. Finally, it provides flexibility by allowing a clear separation of logic between the entity and its API representation, making the code easier to maintain and adapt to future changes.</blockquote><h4>Drawback of Using DTO</h4><ul><li>Requires additional code to create the DTO and handle mapping logic.</li></ul><h4>2. Builder Pattern for Models</h4><p>The Builder pattern simplifies object creation, especially for models with many fields.</p><h4>Without Builder</h4><p>When you don’t use the Builder pattern, you typically rely on constructors or setters to populate the object. However, as the number of attributes grows, managing constructors becomes cumbersome, especially when dealing with nullable fields.</p><pre>public Experience(<br>        Long id,<br>        String title,<br>        String company,<br>        EmploymentType employmentType,<br>        LocalDate startDate,<br>        LocalDate endDate, // Nullable<br>        String location,<br>        LocationType locationType,<br>        User user,<br>        String description // Other nullable field<br>) {<br>    this.id = id;<br>    this.title = title;<br>    this.company = company;<br>    this.employmentType = employmentType;<br>    this.startDate = startDate;<br>    this.endDate = endDate;<br>    this.location = location;<br>    this.locationType = locationType;<br>    this.user = user;<br>    this.description = description;<br>}<br></pre><p>Now, creating an Experience object requires passing all these parameters, even if some are null. This leads to verbose and error-prone code:</p><pre>Experience experience = new Experience(<br>    1,<br>    &quot;Software Engineer&quot;,<br>    &quot;TechCorp&quot;,<br>    EmploymentType.FULL_TIME,<br>    LocalDate.of(2026, 1, 1),<br>    null, // endDate (nullable)<br>    &quot;New York&quot;,<br>    LocationType.ON_SITE,<br>    user,<br>    null // description (nullable)<br>);</pre><blockquote>This approach is tedious and hard to maintain. If you add more nullable fields in the future, the constructor will grow even larger, making it harder to read and use.</blockquote><h4>With Builder</h4><pre>Experience experience = Experience.builder()<br>    .title(&quot;Software Engineer&quot;)<br>    .company(&quot;TechCorp&quot;)<br>    .employmentType(EmploymentType.FULL_TIME)<br>    .startDate(LocalDate.of(2020, 1, 1))<br>    .location(&quot;New York&quot;)<br>    .locationType(LocationType.ON_SITE)<br>    .user(user)<br>    .build(); // endDate and description is optional, so it&#39;s omitted here</pre><blockquote>This approach is clean, flexible, and scalable. Adding new nullable fields doesn’t require modifying constructors or creating multiple overloaded versions.</blockquote><h4>Drawbacks of the Builder Pattern</h4><p>While the Builder pattern is powerful, it’s not without trade-offs:</p><ol><li><strong>Boilerplate Code</strong>: Without tools like Lombok, implementing a builder manually can be verbose.</li><li><strong>Performance Overhead</strong>: In rare cases, creating builder instances might introduce slight overhead (though negligible for most applications).</li><li><strong>Learning Curve</strong>: Developers unfamiliar with builders might find them less intuitive initially.</li></ol><h4>3. Singleton Pattern for Logging</h4><p>A custom logger ensures centralized logging with minimal overhead.</p><h4>Without Singleton</h4><pre>Logger logger = LoggerFactory.getLogger(MyClass.class);<br>logger.info(&quot;Message logged&quot;);</pre><h4>With Singleton</h4><pre>public class Logger {<br>    private static CustomLogger instance;<br>    private static final String RED = &quot;\u001B[31m&quot;;<br>    private static final String YELLOW = &quot;\u001B[33m&quot;;<br>    private static final String GREEN = &quot;\u001B[32m&quot;;<br>    private static final String BLUE = &quot;\u001B[34m&quot;;<br><br>    private Logger() {}<br><br>    public static Logger getInstance() {<br>        if (instance == null) {<br>            synchronized (CustomLogger.class) {<br>                if (instance == null) {<br>                    instance = new CustomLogger();<br>                }<br>            }<br>        }<br>        return instance;<br>    }<br><br>    public void info(String message) {<br>        System.out.println(GREEN + &quot;[INFO] &quot; + message + RESET);<br>    }<br><br>    public void warn(String message) {<br>        System.out.println(YELLOW + &quot;[WARN] &quot; + message + RESET);<br>    }<br><br>    public void debug(String message) {<br>        System.out.println(BLUE + &quot;[DEBUG] &quot; + message + RESET);<br>    }<br><br>    public void error(String message) {<br>        System.out.println(RED + &quot;[ERROR] &quot; + message + RESET);<br>    }<br>}</pre><blockquote>This approach ensures centralized and consistent logging with minimal resource usage. It provides a single, unified instance for all logging needs, ensuring uniform behavior and reducing memory overhead. Additionally, proper synchronization makes it safe to use in multi-threaded environments.</blockquote><h4>Drawbacks of Singleton Logger</h4><ul><li><strong>Global State</strong>: The logger’s global accessibility can lead to tightly coupled code, making unit testing harder.</li><li><strong>Limited Flexibility</strong>: Adding new features (e.g., multiple loggers for different modules) requires significant refactoring.</li><li><strong>Potential Bottleneck</strong>: In high-concurrency scenarios, the synchronized block might introduce performance bottlenecks.</li></ul><h3>Refactoring with Design Patterns</h3><p>Refactoring isn’t just about fixing broken code; it’s about continuously improving your codebase. Start refactoring early — even before the code becomes problematic. For instance:</p><ul><li>Use DTOs to decouple layers.</li><li>Apply the Builder pattern for cleaner object creation.</li><li>Implement Singleton for shared resources like logging.</li></ul><h3>Non-Functional Impact</h3><h4>1. Payload Size and API Response Time</h4><ul><li>With DTOs : The payload size is significantly reduced because only the necessary fields are sent to the client. For example, sensitive fields like passwords or unnecessary fields like internal IDs are excluded. This results in faster API response times due to smaller data transfer over the network.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evmFuilTv12N-nPHEReHGA.png" /></figure><ul><li>Without DTOs : The payload includes all fields from the entity, leading to larger responses and slower API performance, especially when dealing with complex or large objects.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBLu9Y3tVbgcLZ4fAM2Pbw.png" /></figure><h4>2. Cyclomatic Complexity</h4><ul><li>With DTOs : Using DTOs simplifies controller logic by reducing branching and conditional checks (e.g., filtering sensitive data manually). Tools like Checkstyle show a lower cyclomatic complexity score, making the code easier to maintain and test.</li><li>Without DTOs : Controllers often include additional logic to handle sensitive data or filter unnecessary fields, increasing cyclomatic complexity and making the code harder to read and maintain.</li></ul><h4>3. Memory Usage</h4><ul><li>Singleton Logger : A single instance of the logger is shared across the application, consuming minimal memory. Tools like JProfiler confirm that memory usage remains constant regardless of the number of log calls.</li><li>Multiple Logger Instances : Creating multiple logger instances for different parts of the application increases memory overhead, which can become significant in large-scale applications.</li></ul><pre>package rencanakan.id.talentpool.util;<br><br>public class MemoryTest {<br>    public static void main(String[] args) {<br>        System.gc();<br><br>        printMemoryUsage(&quot;Baseline&quot;);<br><br>        System.out.println(&quot;\n=== TESTING NON-SINGLETON LOGGER ===&quot;);<br>        nonSingletonTest();<br><br>        System.out.println(&quot;\n=== TESTING SINGLETON LOGGER ===&quot;);<br>        singletonTest();<br>    }<br><br>    private static void nonSingletonTest() {<br>        System.gc();<br>        try {<br>            Thread.sleep(500);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br><br>        long startMemory = getUsedMemory();<br><br>        NonSingletonLogger[] loggers = new NonSingletonLogger[10_000];<br><br>        for (int i = 0; i &lt; 10_000; i++) {<br>            loggers[i] = new NonSingletonLogger(&quot;Logger-&quot; + i);<br>            loggers[i].log(&quot;Test &quot; + i);<br>        }<br><br>        System.out.println(&quot;&gt;&gt;&gt; All NonSingletonLogger instances created. Waiting for logs to finish...&quot;);<br>        try {<br>            Thread.sleep(2000);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br><br>        System.gc();<br>        try {<br>            Thread.sleep(500);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br><br>        long endMemory = getUsedMemory();<br>        System.out.println(&quot;[Non-Singleton Logger] Memory used: &quot; + endMemory + &quot; MB&quot;);<br>        System.out.println(&quot;[Non-Singleton Logger] Memory increase: &quot; + (endMemory - startMemory) + &quot; MB&quot;);<br>    }<br><br>    private static void singletonTest() {<br>        System.gc();<br>        try {<br>            Thread.sleep(500);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br><br>        long startMemory = getUsedMemory();<br><br>        SingletonLogger singletonLogger = SingletonLogger.getInstance();<br>        for (int i = 0; i &lt; 10_000; i++) {<br>            singletonLogger.log(&quot;Test &quot; + i);<br>        }<br><br>        System.out.println(&quot;&gt;&gt;&gt; All SingletonLogger calls completed. Waiting for logs to finish...&quot;);<br>        try {<br>            Thread.sleep(2000);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br><br>        System.gc();<br>        try {<br>            Thread.sleep(500);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br><br>        long endMemory = getUsedMemory();<br>        System.out.println(&quot;[Singleton Logger] Memory used: &quot; + endMemory + &quot; MB&quot;);<br>        System.out.println(&quot;[Singleton Logger] Memory increase: &quot; + (endMemory - startMemory) + &quot; MB&quot;);<br>    }<br><br>    private static void printMemoryUsage(String scenario) {<br>        long usedMemory = getUsedMemory();<br>        System.out.println(&quot;[&quot; + scenario + &quot;] Memory used: &quot; + usedMemory + &quot; MB&quot;);<br>    }<br><br>    private static long getUsedMemory() {<br>        Runtime runtime = Runtime.getRuntime();<br>        return (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024;<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*Hu685ej5_sxdDkiondwdew.png" /></figure><p>We’ve explored how to use design patterns effectively in Spring Boot without overengineering. Key takeaways:</p><ul><li>Understand anti-patterns and their impact.</li><li>Choose design patterns wisely based on actual needs.</li><li>Refactor proactively to keep your codebase healthy.</li><li>Be aware of trade-offs and measure non-functional impacts.</li></ul><p>For developers, my advice is simple: balance simplicity and scalability . Don’t shy away from design patterns, but <strong>don’t force</strong> them either. Your goal should always be clean, maintainable, and efficient code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=361471d986f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OOP Redefined: A Blueprint for Scalable Systems Using SOLID Principles]]></title>
            <link>https://medium.com/@sunsetheus/oop-redefined-a-blueprint-for-scalable-systems-using-solid-principles-5758bee0219c?source=rss-63e584266b01------2</link>
            <guid isPermaLink="false">https://medium.com/p/5758bee0219c</guid>
            <dc:creator><![CDATA[William]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 07:01:32 GMT</pubDate>
            <atom:updated>2025-05-08T07:25:02.249Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern software development, adhering to best practices is essential for creating maintainable, scalable, and robust applications. Among these practices, the SOLID Principles , Design Pattern, and other design principles play a critical role in ensuring code quality, especially in large-scale systems. In this article, we will explore these concepts, their importance, and how they can be applied effectively.</p><h3>1. SOLID Principles: The Foundation of Clean Code</h3><p>The SOLID Principles are a set of five design principles that guide developers in writing clean, maintainable, and scalable code. These principles are particularly useful in large projects where multiple developers collaborate. Below, we’ll explain each principle with before-and-after code examples to demonstrate their impact.</p><h4>1.1 Single Responsibility Principle (SRP)</h4><ul><li>Definition : A class should have only one reason to change.</li><li>Why It Matters : If a class has multiple responsibilities, changes in one area may inadvertently affect others, leading to bugs and maintenance challenges.</li></ul><p><strong>Without SRP</strong></p><pre>// Violating SRP - mixing HTTP handling, business logic, and data access<br>public class ExperienceMonolith {<br>    private JdbcTemplate jdbcTemplate;<br>    <br>    @PostMapping(&quot;/experiences&quot;)<br>    public Map&lt;String, Object&gt; createExperience(@RequestBody Map&lt;String, Object&gt; request, Principal principal) {<br>        // Extract data from request<br>        String title = (String) request.get(&quot;title&quot;);<br>        String company = (String) request.get(&quot;company&quot;);<br>        // More extraction...<br>        <br>        // Validate directly<br>        if (title == null || title.isEmpty()) {<br>            throw new IllegalArgumentException(&quot;Title is required&quot;);<br>        }<br>        <br>        // Business logic and DB operations mixed together<br>        String sql = &quot;INSERT INTO experience (title, company, employment_type, user_id) VALUES (?,?,?,?)&quot;;<br>        jdbcTemplate.update(sql, title, company, employmentType, principal.getName());<br>        <br>        // Construct response manually<br>        Map&lt;String, Object&gt; response = new HashMap&lt;&gt;();<br>        response.put(&quot;success&quot;, true);<br>        response.put(&quot;message&quot;, &quot;Experience created&quot;);<br>        return response;<br>    }<br>}</pre><p>This class violates SRP by blending HTTP, validation, and persistence logic. Changing any one of these concerns could require changes in the same class</p><p><strong>With SRP</strong></p><pre>// Controller handles HTTP request/response<br>@RestController<br>@RequestMapping(&quot;/experiences&quot;)<br>public class ExperienceController {<br>    private final ExperienceService experienceService;<br>    <br>    // Constructor injection<br>    public ExperienceController(ExperienceService experienceService) {<br>        this.experienceService = experienceService;<br>    }<br>    <br>    @PostMapping<br>    public ResponseEntity&lt;WebResponse&lt;ExperienceResponseDTO&gt;&gt; createExperience(<br>            @RequestBody @Valid ExperienceRequestDTO request,<br>            @AuthenticationPrincipal User user<br>    ) {<br>        ExperienceResponseDTO createdExperience = experienceService.createExperience(user.getId(), request);<br>        return ResponseEntity.status(HttpStatus.CREATED)<br>                .body(WebResponse.&lt;ExperienceResponseDTO&gt;builder()<br>                        .data(createdExperience)<br>                        .build());<br>    }<br>    // Other endpoints...<br>}<br><br>// Service implements business logic<br>@Service<br>public class ExperienceServiceImpl implements ExperienceService {<br>    private final ExperienceRepository experienceRepository;<br>    <br>    public ExperienceServiceImpl(ExperienceRepository experienceRepository) {<br>        this.experienceRepository = experienceRepository;<br>    }<br>    <br>    @Override<br>    public ExperienceResponseDTO createExperience(String userId, @Valid ExperienceRequestDTO request) {<br>        Experience newExperience = DTOMapper.map(request, Experience.class);<br>        newExperience.setUser(User.builder().id(userId).build());<br><br>        Experience savedExperience = experienceRepository.save(newExperience);<br>        return DTOMapper.map(savedExperience, ExperienceResponseDTO.class);<br>    }<br>    // Other methods...<br>}</pre><p>Responsibilities are clearly divided — the controller focuses on HTTP handling, while the service handles business logic. Changes in validation or database logic won’t affect controller code</p><h4>2.2 Open/Closed Principle (OCP)</h4><ul><li>Definition : Software entities should be open for extension but closed for modification.</li><li>Why It Matters : This allows you to add new functionality without altering existing code, reducing the risk of breaking existing features.</li></ul><pre>// Violating OCP - need to modify class directly to add new behavior<br>public class ExperienceManager {<br>    public ExperienceResponseDTO createExperience(String userId, ExperienceRequest request) {<br>        // Implementation...<br>    }<br>    <br>    // To add remote experience feature, we&#39;d need to modify this class<br>    // rather than extending through a new implementation<br>    public ExperienceResponseDTO createRemoteExperience(String userId, ExperienceRequest request) {<br>        // Special implementation for remote experiences<br>    }<br>}</pre><p>Violates OCP. Adding new experience types (like remote) means editing this class, increasing risk</p><p>With OCP</p><pre>// Service interface defines contract<br>public interface ExperienceService {<br>    ExperienceResponseDTO createExperience(String userId, ExperienceRequestDTO request);<br>    ExperienceResponseDTO editById(String userId, Long id, ExperienceRequestDTO dto);<br>    void deleteById(Long id);<br>    List&lt;ExperienceResponseDTO&gt; getByTalentId(String talentId);<br>}<br><br>// Implementation can be extended without changing interface<br>@Service<br>public class ExperienceServiceImpl implements ExperienceService {<br>    // Implementation details...<br>}</pre><p>New behaviors are added by implementing the interface, leaving existing code untouched</p><h4>2.3 Liskov Substitution Principle (LSP)</h4><ul><li>Definition : Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.</li><li>Why It Matters : Ensures that inheritance hierarchies are well-designed and predictable.</li></ul><p>Before LSP :</p><pre>// Violating LSP - implementation breaks contract expectations<br>public class BrokenExperienceServiceImpl implements ExperienceService {<br>    @Override<br>    public ExperienceResponseDTO createExperience(String userId, ExperienceRequestDTO request) {<br>        // Violates expected behavior by throwing exception in normal cases<br>        if (request.getEndDate() == null) {<br>            throw new IllegalArgumentException(&quot;End date is required&quot;); <br>            // This violates LSP since the base contract doesn&#39;t specify this constraint<br>        }<br>        <br>        // Another violation: returning null instead of a response object<br>        if (request.getTitle().length() &gt; 40) {<br>            return null; // Contract expects a valid response<br>        }<br>        <br>        // Rest of implementation...<br>    }<br>}</pre><p>New behaviors are added by implementing the interface, leaving existing code untouched.</p><h4>With LSP</h4><pre>// Interface defines the contract<br>public interface ExperienceService {<br>    ExperienceResponseDTO createExperience(String userId, ExperienceRequestDTO request);<br>    // Other methods...<br>}<br><br>// Implementation adheres to the contract<br>@Service<br>public class ExperienceServiceImpl implements ExperienceService {<br>    @Override<br>    public ExperienceResponseDTO createExperience(String userId, @Valid ExperienceRequestDTO request) {<br>        // Implementation that follows the contract...<br>    }<br>    // Other methods...<br>}<br><br>// Test class demonstrates substitutability<br>@ExtendWith(MockitoExtension.class)<br>class ExperienceServiceTest {<br>    @Mock<br>    private ExperienceRepository experienceRepository;<br>    <br>    @InjectMocks<br>    private ExperienceServiceImpl experienceService; // Using concrete implementation<br>    <br>    @Test<br>    void testCreateExperience_Success() {<br>        // Service behaves as expected<br>        // ...<br>    }<br>}</pre><p>This breaks client expectations. createExperience may throw or return null in scenarios not handled by other implementations.</p><h4>2.4 Interface Segregation Principle (ISP)</h4><ul><li>Definition : Clients should not be forced to depend on interfaces they do not use.</li><li>Why It Matters : Smaller, focused interfaces make the system more modular and easier to test.</li></ul><p>Before ISP :</p><pre>// Violating ISP - bloated interface forces clients to depend on methods they don&#39;t use<br>public interface TalentManagementService {<br>    // Experience methods<br>    ExperienceDTO createExperience(String userId, ExperienceDTO experience);<br>    ExperienceDTO updateExperience(Long id, ExperienceDTO experience);<br>    void deleteExperience(Long id);<br>    List&lt;ExperienceDTO&gt; getUserExperiences(String userId);<br>    <br>    // Education methods<br>    EducationDTO createEducation(String userId, EducationDTO education);<br>    EducationDTO updateEducation(Long id, EducationDTO education);<br>    void deleteEducation(Long id);<br>    List&lt;EducationDTO&gt; getUserEducations(String userId);<br>    <br>    // Skill methods<br>    SkillDTO addSkill(String userId, SkillDTO skill);<br>    void removeSkill(String userId, Long skillId);<br>    List&lt;SkillDTO&gt; getUserSkills(String userId);<br>    <br>    // Many more methods...<br>}</pre><p>A class implementing this interface may be forced to implement methods it doesn’t need</p><p><strong>With ISP</strong>:</p><pre>// Service interface exposes only relevant methods for experience management<br>public interface ExperienceService {<br>    ExperienceResponseDTO createExperience(String userId, ExperienceRequestDTO request);<br>    ExperienceResponseDTO editById(String userId, Long id, ExperienceRequestDTO dto);<br>    void deleteById(Long id);<br>    List&lt;ExperienceResponseDTO&gt; getByTalentId(String talentId);<br>}<br><br>// Repository interface focused on data access for experiences<br>public interface ExperienceRepository extends JpaRepository&lt;Experience, Long&gt; {<br>    List&lt;Experience&gt; findByUserId(String userId);<br>}</pre><p>Each service handles only one domain, making implementation and testing easier</p><h4>2.5 Dependency Inversion Principle (DIP)</h4><ul><li>Definition : High-level modules should not depend on low-level modules; both should depend on abstractions.</li><li>Why It Matters : Promotes loose coupling, making the system more flexible and testable.</li></ul><p>Before DIP :</p><pre>// Violating DIP - depending on concrete implementations<br>@RestController<br>@RequestMapping(&quot;/experiences&quot;)<br>public class BadExperienceController {<br>    // Direct dependency on implementation<br>    private final ExperienceServiceImpl experienceService;<br>    <br>    // Direct instantiation rather than injection<br>    public BadExperienceController() {<br>        // Creating direct dependency on implementation and its dependencies<br>        ExperienceRepositoryImpl repository = new ExperienceRepositoryImpl();<br>        this.experienceService = new ExperienceServiceImpl(repository);<br>    }<br>    <br>    @PostMapping<br>    public ResponseEntity&lt;Map&lt;String, Object&gt;&gt; createExperience(@RequestBody Map&lt;String, Object&gt; request) {<br>        // Implementation details...<br>    }<br>}</pre><p>High-level code depends directly on low-level implementation. Hard to mock or test</p><p><strong>With DIP :</strong></p><pre>// Controller depends on ExperienceService interface, not implementation<br>@RestController<br>@RequestMapping(&quot;/experiences&quot;)<br>public class ExperienceController {<br>    private final ExperienceService experienceService; // Interface, not implementation<br>    <br>    public ExperienceController(ExperienceService experienceService) {<br>        this.experienceService = experienceService;<br>    }<br>    <br>    @PostMapping<br>    public ResponseEntity&lt;WebResponse&lt;ExperienceResponseDTO&gt;&gt; createExperience(<br>            @RequestBody @Valid ExperienceRequestDTO request,<br>            @AuthenticationPrincipal User user<br>    ) {<br>        ExperienceResponseDTO createdExperience = experienceService.createExperience(user.getId(), request);<br>        // Rest of method...<br>    }<br>}<br><br>// Service depends on Repository interface, not implementation<br>@Service<br>public class ExperienceServiceImpl implements ExperienceService {<br>    private final ExperienceRepository experienceRepository; // Interface, not implementation<br>    <br>    public ExperienceServiceImpl(ExperienceRepository experienceRepository) {<br>        this.experienceRepository = experienceRepository;<br>    }<br>    <br>    // Implementation details...<br>}</pre><p>This promotes loose coupling. We can inject mock implementations during testing or swap services without modifying this class.</p><h3>3. Combining OOP and SOLID Principles</h3><p>By combining OOP with SOLID principles , you can create systems that are:</p><ul><li>Modular : Each component has a clear responsibility.</li><li>Scalable : Adding new features doesn’t break existing ones.</li><li>Testable : Dependencies are decoupled, making unit testing easier.</li><li>Maintainable : Code is easier to understand and modify.</li></ul><h3>Builder Pattern: Simplifying Complex Object Creation</h3><p>The Builder Pattern is a creational design pattern that simplifies the construction of complex objects. It is particularly useful when an object has many attributes, some of which may be optional.</p><h4>Example Without Builder Pattern</h4><p>Without the Builder Pattern, you might use a constructor to initialize all attributes. However, this approach can become cumbersome and error-prone as the number of attributes grows.</p><pre>@Entity<br>@Getter<br>@Setter<br>@NoArgsConstructor<br>@Table(name = &quot;experience&quot;)<br>public class Experience {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String title;<br>    private String company;<br>    private EmploymentType employmentType;<br>    private LocalDate startDate;<br>    private LocalDate endDate;<br>    private String location;<br>    private LocationType locationType;<br>    private User user;<br><br>    public Experience(String title, String company, EmploymentType employmentType, LocalDate startDate, LocalDate endDate, String location, LocationType locationType, User user) {<br>        this.title = title;<br>        this.company = company;<br>        this.employmentType = employmentType;<br>        this.startDate = startDate;<br>        this.endDate = endDate;<br>        this.location = location;<br>        this.locationType = locationType;<br>        this.user = user;<br>    }<br>}<br><br>// Usage<br>Experience experience = new Experience(<br>    &quot;Software Engineer&quot;, <br>    &quot;TechCorp&quot;, <br>    EmploymentType.FULL_TIME, <br>    LocalDate.of(2020, 1, 1), <br>    LocalDate.of(2023, 12, 31), <br>    &quot;Remote&quot;, <br>    LocationType.REMOTE, <br>    user<br>);</pre><p>Challenges :</p><ul><li>Readability : The constructor call is long and difficult to read.</li><li>Maintainability : Adding or removing attributes requires modifying the constructor and all its usages.</li><li>Flexibility : Optional attributes (e.g., endDate) complicate the constructor logic.</li></ul><h4>Example With Builder Pattern</h4><p>Using the Builder Pattern simplifies object creation and improves readability.</p><pre>@Entity<br>@Getter<br>@Setter<br>@Builder<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Table(name = &quot;experience&quot;)<br>public class Experience {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String title;<br>    private String company;<br>    private EmploymentType employmentType;<br>    private LocalDate startDate;<br>    private LocalDate endDate;<br>    private String location;<br>    private LocationType locationType;<br>    private User user;<br>}<br><br>// Usage<br>Experience experience = Experience.builder()<br>    .title(&quot;Software Engineer&quot;)<br>    .company(&quot;TechCorp&quot;)<br>    .employmentType(EmploymentType.FULL_TIME)<br>    .startDate(LocalDate.of(2020, 1, 1))<br>    .endDate(LocalDate.of(2023, 12, 31))<br>    .location(&quot;Remote&quot;)<br>    .locationType(LocationType.REMOTE)<br>    .user(user)<br>    .build();</pre><p>Benefits :</p><ul><li><strong>Readability</strong>: Each attribute is set explicitly, making the code easier to understand.</li><li><strong>Flexibility</strong>: Optional attributes can be omitted without complicating the constructor.</li><li><strong>Maintainability</strong>: Adding new attributes does not require modifying existing constructors.</li></ul><h3>Comparison with Other Best Practices</h3><p>While the current codebase adheres to the <strong>SOLID principles</strong>, there are alternative best practices and methodologies that could have been considered. Below, we compare these alternatives and explain why they were not chosen for this implementation.</p><h4>Monolithic Architecture vs. Modular Design</h4><p>Some developers prefer a <strong>monolithic architecture</strong>, where all components are tightly integrated into a single codebase. This approach simplifies deployment and reduces the complexity of managing multiple modules.</p><p><strong>Why it wasn’t chosen:</strong></p><ul><li>Monolithic architectures can become difficult to scale and maintain as the application grows.</li><li>Modular design, as implemented in this codebase, aligns better with the SOLID principles by promoting separation of concerns and scalability.</li></ul><h4>Event-Driven Architecture</h4><p>An <strong>event-driven architecture</strong> could have been used, where components communicate through events rather than direct method calls. This decouples components and improves scalability.</p><p><strong>Why it wasn’t chosen:</strong></p><ul><li>Event-driven systems add complexity, such as managing event queues and ensuring eventual consistency.</li><li>The current implementation focuses on simplicity and direct communication between components, which is sufficient for the project’s scope.</li></ul><h4>Domain-Driven Design (DDD)</h4><p><strong>Domain-Driven Design</strong> emphasizes modeling the business domain closely and using concepts like aggregates, entities, and value objects.</p><p><strong>Why it wasn’t chosen:</strong></p><ul><li>DDD is ideal for large, complex systems with intricate business rules. However, it can introduce unnecessary overhead for smaller or less complex projects.</li><li>The current codebase uses a simpler approach, focusing on SOLID principles to maintain clarity and reduce complexity.</li></ul><h4>Functional Programming Paradigm</h4><p>A <strong>functional programming</strong> approach could have been adopted, emphasizing immutability, pure functions, and declarative code.</p><p><strong>Why it wasn’t chosen:</strong></p><ul><li>Functional programming can be harder to adopt in object-oriented languages or teams unfamiliar with the paradigm.</li><li>The current codebase uses object-oriented programming (OOP), which aligns well with SOLID principles and is more widely understood by developers.</li></ul><h4><strong>CONCLUSION</strong></h4><p>Adhering to best practices like the SOLID Principles , using patterns like the Builder Pattern , and carefully choosing between Repository Pattern and ORM can significantly improve the quality of your software. These principles and patterns ensure that your code is:</p><ul><li>Readable : Easy to understand and maintain.</li><li>Scalable : Capable of handling increased complexity.</li><li>Testable : Facilitates unit testing and debugging.</li></ul><p>By applying these practices, you can build robust, maintainable systems that stand the test of time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5758bee0219c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Pushing Broken Code: CI/CD with SonarQube and Netlify]]></title>
            <link>https://medium.com/@sunsetheus/stop-pushing-broken-code-ci-cd-with-sonarqube-and-netlify-67a678f4afb0?source=rss-63e584266b01------2</link>
            <guid isPermaLink="false">https://medium.com/p/67a678f4afb0</guid>
            <dc:creator><![CDATA[William]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 06:51:16 GMT</pubDate>
            <atom:updated>2025-03-20T06:51:16.376Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Overview</strong></h3><p>In the modern software development landscape, Continuous Integration (CI) and Continuous Deployment (CD) have become the backbone of efficient development processes. With CI/CD, development teams can ensure that their code is always in a deployable state, reduce the risk of bugs, and accelerate release cycles. In this article, we’ll explore how to build a robust CI/CD pipeline using SonarQube for testing and code quality analysis, as well as Netlify for deployment — even though Netlify already has an auto-deploy feature, we’ll delve into creating our own custom CD process.</p><h3>What is CI/CD?</h3><p>Before diving deeper, let’s break down what CI and CD are:</p><ul><li>Continuous Integration (CI): The process where new code is automatically integrated into the main branch and tested to ensure there are no conflicts or errors.</li><li>Continuous Deployment (CD): The process where code that has passed the CI stage is automatically deployed to production or staging environments.</li></ul><p>With a combination of CI/CD, development teams can ensure that every change made to the codebase is immediately tested and released without bottlenecks.</p><h3>Step 1: Setting Up the CI Pipeline with SonarQube</h3><p>The CI pipeline is responsible for building, testing, and analyzing your code. Below is the build.yml file you provided, which integrates SonarQube for code quality checks.</p><pre>name: Build<br><br>on:<br>  push:<br>    branches:<br>      - &#39;**&#39;<br>  pull_request:<br>    types: [opened, synchronize, reopened]<br><br>jobs:<br>  build:<br>    name: Build and analyze<br>    runs-on: windows-latest<br><br>    steps:<br>      - uses: actions/checkout@v4<br>        with:<br>          fetch-depth: 0<br><br>      - name: Set up Node.js<br>        uses: actions/setup-node@v4<br>        with:<br>          node-version: &#39;18&#39;<br>          cache: &#39;npm&#39;<br><br>      - name: Install dependencies<br>        run: npm ci<br><br>      - name: Build<br>        run: npm run build --if-present<br><br>      - name: Run tests with coverage<br>        run: npm test<br><br>      - name: Upload coverage report<br>        uses: actions/upload-artifact@v4<br>        with:<br>          name: coverage-report<br>          path: coverage/<br>          retention-days: 1<br><br>      - name: SonarQube Scan<br>        uses: SonarSource/sonarqube-scan-action@v4<br>        env:<br>          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}<br>          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}<br>        with:<br>          args: &gt;<br>            -Dsonar.projectKey=rencanakan-talent_pool-frontend<br>            -Dsonar.javascript.lcov.reportPaths=coverage/lcov.info<br></pre><h3>How It Works</h3><ol><li>Triggering the Workflow:</li></ol><ul><li>The workflow is triggered on every push to any branch (&#39;**&#39;) or when a pull request is opened, updated, or reopened.</li></ul><p>2. Setting Up the Environment:</p><ul><li>The actions/checkout@v4 step fetches the repository code.</li><li>The actions/setup-node@v4 step sets up Node.js version 18 and caches npm dependencies for faster builds.</li></ul><p>3. Building and Testing:</p><ul><li>Dependencies are installed using npm ci.</li><li>The project is built using npm run build.</li><li>Tests are executed with npm test, generating a coverage report.</li></ul><p>4. Uploading Coverage Reports:</p><ul><li>The coverage report is uploaded as an artifact, allowing you to review it later.</li></ul><p>5. Analyzing Code Quality with SonarQube:</p><ul><li>The SonarSource/sonarqube-scan-action@v4 step sends the code and test coverage data to SonarQube for analysis.</li><li>The SONAR_TOKEN and SONAR_HOST_URL secrets connect the workflow to your SonarQube instance.</li></ul><h3>Benefits of Using SonarQube</h3><ul><li>Identifies bugs, vulnerabilities, and code smells early in the development process.</li><li>Provides actionable insights to improve code quality.</li><li>Integrates seamlessly with GitHub Actions for automated analysis.</li></ul><h3>Step 2: Setting Up the CD Pipeline with Netlify</h3><p>Once the CI pipeline confirms that the code is ready, the next step is to deploy it to the appropriate environment. Here’s how you can configure a custom CD pipeline for Netlify with separate workflows for dev, staging, and main branches.</p><h3>Deployment to Development (dev)</h3><p>This workflow deploys changes from the dev branch to the development environment.</p><pre>name: Deploy to Dev<br><br>on:<br>  push:<br>    branches:<br>      - dev<br><br>jobs:<br>  deploy-dev:<br>    runs-on: ubuntu-22.04<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4<br><br>      - name: Install dependencies<br>        run: npm install<br><br>      - name: Build project<br>        run: npm run build<br><br>      - name: Deploy to Netlify Dev<br>        uses: nwtgck/actions-netlify@v3.0<br>        with:<br>          publish-dir: &#39;./dist&#39;<br>          production-branch: dev<br>          github-token: ${{ secrets.GITHUB_TOKEN }}<br>          deploy-message: &#39;Dev deploy from GitHub Actions&#39;<br>        env:<br>          NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN_DEV }}<br>          NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID_DEV }}<br>        timeout-minutes: 2</pre><h3>How It Works</h3><ul><li>Each workflow is triggered by pushes to its respective branch (dev, staging, or main).</li><li>The code is checked out, dependencies are installed, and the project is built.</li><li>The nwtgck/actions-netlify@v3.0 action deploys the built project to the corresponding Netlify site.</li></ul><h3>Benefits of Custom CD with Netlify</h3><ul><li>Full control over deployment triggers and processes.</li><li>Separate environments for development, testing, and production.</li><li>Easy integration with GitHub Actions for automated deployments.</li></ul><p>With this setup, your CI/CD pipeline works as follows:</p><ol><li>Code Changes: Developers push code to the dev, staging, or main branch.</li><li>CI Pipeline:</li></ol><ul><li>The build.yml workflow builds the project, runs tests, and analyzes code quality with SonarQube.</li><li>If the code passes all checks, it moves to the CD stage.</li></ul><p>3. CD Pipeline:</p><ul><li>Changes to the dev branch are deployed to the development environment.</li><li>Changes to the staging branch are deployed to the staging environment.</li><li>Changes to the main branch are deployed to the production environment.</li></ul><h3>Conclusion</h3><p>By combining SonarQube for code quality analysis and Netlify for automated deployments, you can create a powerful CI/CD pipeline that ensures your application is always reliable and ready for release. This setup not only improves code quality but also streamlines the deployment process, saving time and reducing errors.</p><p>Whether you’re working on a small personal project or a large-scale enterprise application, adopting CI/CD practices will help you stay ahead of the curve. So, start implementing these workflows today and take your development process to the next level!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67a678f4afb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>