<?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 Larissa Falcão on Medium]]></title>
        <description><![CDATA[Stories by Larissa Falcão on Medium]]></description>
        <link>https://medium.com/@larissafalcaodev?source=rss-2c61733adf8b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*q4G-jhMesibuQnpyWhz51A.jpeg</url>
            <title>Stories by Larissa Falcão on Medium</title>
            <link>https://medium.com/@larissafalcaodev?source=rss-2c61733adf8b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:45:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@larissafalcaodev/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[ Mastering Grouping in Java Streams: The Power of Collectors.groupingBy()]]></title>
            <link>https://medium.com/@larissafalcaodev/mastering-grouping-in-java-streams-the-power-of-collectors-groupingby-c80ca8dcba52?source=rss-2c61733adf8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c80ca8dcba52</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Larissa Falcão]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 01:55:51 GMT</pubDate>
            <atom:updated>2025-04-08T01:55:51.258Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiTlNzJENdb2ldJWN4fPhg.jpeg" /><figcaption>Photo by Max Duzij fron Unsplash</figcaption></figure><p>Grouping data is a common task in software development, whether you’re categorizing products, grouping employees by department, or aggregating sales data. Java Streams provide a powerful way to do this with Collectors.groupingBy()</p><p>🔍 What is groupingBy()?</p><p>It’s a method in Java’s Collectors class that helps partition and collect elements into a Map based on a classification function.</p><p>💡 Example: Grouping Employees by Department Imagine we have a list of employees, and we want to organize them by department:</p><pre>import java.util.List;<br>import java.util.Map;<br>import java.util.stream.Collectors;<br><br>class Employee {<br>    String name;<br>    String department;<br>}<br><br>public class GroupingExample {<br>    public static void main(String[] args) {<br>        List&lt;Employee&gt; employees = List.of(<br>            new Employee(&quot;Alice&quot;, &quot;IT&quot;),<br>            new Employee(&quot;Bob&quot;, &quot;HR&quot;),<br>            new Employee(&quot;Charlie&quot;, &quot;IT&quot;),<br>            new Employee(&quot;David&quot;, &quot;HR&quot;),<br>            new Employee(&quot;Eve&quot;, &quot;Finance&quot;)<br>        );<br><br>        // Group employees by department<br>        Map&lt;String, List&lt;Employee&gt;&gt; employeesByDepartment = employees.stream()<br>            .collect(Collectors.groupingBy(emp -&gt; emp.department));<br><br>        System.out.println(employeesByDepartment);<br>    }<br>}</pre><p>✅ Output:</p><pre>{IT=[Alice, Charlie], HR=[Bob, David], Finance=[Eve]}</pre><p>💡 Example: Grouping and Counting</p><p>Need to count the number of employees in each department? Just tweak groupingBy() with counting():</p><pre>Map&lt;String, Long&gt; departmentCounts = employees.stream()<br>    .collect(Collectors.groupingBy(emp -&gt; emp.department, Collectors.counting()));</pre><pre>System.out.println(departmentCounts);</pre><p>✅ Output:</p><pre>{IT=2, HR=2, Finance=1}</pre><p>💡 Example: Grouping with Custom Downstream Collectors</p><p>What if we want to group employees but store only their names instead of Employee objects?</p><pre>Map&lt;String, List&lt;String&gt;&gt; departmentEmployeeNames = employees.stream()<br>    .collect(Collectors.groupingBy(emp -&gt; emp.department, <br>               Collectors.mapping(emp -&gt; emp.name, Collectors.toList())));</pre><pre>System.out.println(departmentEmployeeNames);</pre><p>✅ Output:</p><pre>{IT=[Alice, Charlie], HR=[Bob, David], Finance=[Eve]}</pre><h3>When Should You Use groupingBy()?</h3><p>✔️ When you need to categorize a collection of objects into groups.</p><p>✔️ When you want to aggregate data, such as counting elements per category.</p><p>✔️ When transforming grouped values using downstream collectors (mapping(), counting(), etc.).</p><p>Have you used groupingBy() in your projects? Let’s discuss its use cases in the comments!👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c80ca8dcba52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Handle Errors Cleanly in Java: Principles for Scalable, Maintainable Code]]></title>
            <link>https://medium.com/@larissafalcaodev/how-to-handle-errors-cleanly-in-java-principles-for-scalable-maintainable-code-b0443a5f1bcb?source=rss-2c61733adf8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0443a5f1bcb</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Larissa Falcão]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 00:13:26 GMT</pubDate>
            <atom:updated>2024-11-13T00:13:26.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9m80-_DK1uvWTCEST04lQ.jpeg" /><figcaption>Designed by Freepik</figcaption></figure><p>Error handling is often overlooked but is vital to the stability of any software, especially in Java, where we have a host of tools and patterns to create resilient and scalable code. This article dives into practical strategies for clean, effective error handling in Java, geared toward maintaining readability, predictability, and fault tolerance in complex systems.</p><h3>1. Avoid Generic Catch-All Exceptions</h3><p>Catching Exception or Throwable may seem easy, but it can mask issues, leading to undetected errors and less maintainable code. Instead, be specific when catching exceptions. By isolating recoverable errors, you make it clear what issues the code expects to handle and how.</p><pre>try {<br>    // Business logic<br>} catch (IOException e) {<br>    // Handle IO-specific issue<br>} catch (SQLException e) {<br>    // Handle database-specific issue<br>}</pre><h3>2. Use Custom Exceptions to Add Meaning</h3><p>Custom exceptions allow you to express <em>why</em> something failed, not just <em>what</em> happened. They provide context and make error logs clearer, which is especially valuable in large applications where tracing issues can otherwise be cumbersome.</p><p><strong>Example</strong>:</p><pre>public class InvalidOrderException extends RuntimeException {<br>    public InvalidOrderException(String message) {<br>        super(message);<br>    }<br>}</pre><p>Using domain-specific exceptions like InvalidOrderException makes error handling more meaningful. You’re no longer just catching a generic RuntimeException; you’re signaling a specific problem that occurred in your business logic.</p><h3>3. Favor Checked Exceptions for Recoverable Errors</h3><p>In Java, checked exceptions are meant for issues your code is likely to recover from. They force calling code to handle potential problems, making it clear where the failure could happen and how it should be managed. Use checked exceptions for conditions that are unusual but recoverable, such as a network failure where you might want to retry the operation.</p><p><strong>Example</strong>:</p><pre>public void processOrder(Order order) throws InvalidOrderException {<br>    if (!order.isValid()) {<br>        throw new InvalidOrderException(&quot;Order validation failed.&quot;);<br>    }<br>}</pre><p>By throwing InvalidOrderException for validation issues, you keep the logic clean and force handling only where the error matters.</p><h3>4. Use Optional for Absence of Values</h3><p>One of the easiest ways to avoid NullPointerException is to use Optional. If a method might return null, using Optional instead enforces thoughtfulness about how to handle the absence of a value.</p><p><strong>Example</strong>:</p><pre>public Optional&lt;User&gt; findUserById(String id) {<br>    return userRepository.findById(id);<br>}<br><br>findUserById(id).ifPresentOrElse(<br>    user -&gt; System.out.println(&quot;Hello, &quot; + user.getName() + &quot;!&quot;),<br>    () -&gt; System.out.println(&quot;User not found.&quot;)<br>);</pre><p>Here, Optional keeps the code concise and forces you to handle the “absent” case explicitly, making the flow of your application more predictable and null-safe.</p><h3>5. Use Circuit Breakers and Retry Patterns for Fault Tolerance</h3><p>In distributed systems, network calls and third-party services might fail sporadically. Using patterns like <strong>Circuit Breaker</strong> and <strong>Retry</strong> can help your application gracefully handle these transient issues. A Circuit Breaker prevents repetitive, failing calls from overloading the system, while Retry can handle temporary network glitches.</p><p>The Resilience4j library provides a simple way to implement Circuit Breaker and Retry mechanisms:</p><p><strong>Example</strong>:</p><pre>CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults(&quot;myService&quot;);<br><br>Supplier&lt;String&gt; decoratedSupplier = CircuitBreaker<br>    .decorateSupplier(circuitBreaker, () -&gt; myService.call());<br><br>String result = Try.ofSupplier(decoratedSupplier)<br>    .recover(throwable -&gt; &quot;Fallback result&quot;)<br>    .get();</pre><p>In this example, if myService.call() fails multiple times, the Circuit Breaker “opens” and subsequent calls immediately fall back to a default result, preventing further load on the failing service.</p><h3>Final Thoughts: Error Handling for Resilient Java Code</h3><p>In Java, clean error handling goes beyond simply catching exceptions. It’s about crafting reliable software that’s easy to understand and troubleshoot. By using specific exceptions, creating meaningful custom exceptions, leveraging Optional for missing values, and employing fault-tolerant patterns like Circuit Breaker, you can create applications that are both robust and maintainable.</p><p><strong>Summary</strong>:</p><ul><li>Be specific when catching exceptions.</li><li>Use custom exceptions to clarify meaning.</li><li>Leverage checked exceptions for recoverable errors.</li><li>Use Optional to avoid null-related issues.</li><li>Apply Circuit Breakers and Retry patterns for distributed systems.</li></ul><p>How do you handle errors in your Java projects? Let’s discuss best practices and experiences in creating resilient Java applications!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0443a5f1bcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring Conditionals in Java: Why Guard Clauses and Helper Methods Improve Code Quality]]></title>
            <link>https://medium.com/@larissafalcaodev/refactoring-conditionals-in-java-why-guard-clauses-and-helper-methods-improve-code-quality-7cc74b3e62ca?source=rss-2c61733adf8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cc74b3e62ca</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Larissa Falcão]]></dc:creator>
            <pubDate>Wed, 06 Nov 2024 01:47:48 GMT</pubDate>
            <atom:updated>2024-11-06T01:47:48.989Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BMZr1T1sILwfW7vFeHbj8Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@jontyson?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Jon Tyson</a> on <a href="https://unsplash.com/pt-br/fotografias/uma-pessoa-parada-no-meio-de-uma-rua-PXB7yEM5LVs?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>As Java developers, we all encounter condition-heavy methods that can quickly turn into a tangled mess. Deeply nested if statements—often referred to as <em>inherited conditions</em>—are among the main culprits behind complex, hard-to-read, and hard-to-maintain code. But with techniques like <em>guard clauses</em> and <em>helper methods</em>, we can simplify our code, make it more readable, and reduce the chances of introducing bugs.</p><p>In this article, I’ll walk through how to refactor a condition-heavy Java method using guard clauses and helper methods, showing how these techniques can improve your code quality.</p><h3>👎 The Problem with Nested Conditionals</h3><p>Imagine a method where you validate a User and their Order with a series of checks. The goal is to process the order only if all conditions are met. Without guard clauses or helper methods, we might end up with a deeply nested structure:</p><pre>public void processOrder(User user, Order order) {<br>    if (user != null) {<br>        if (user.isActive()) {<br>            if (user.hasPermission(&quot;PROCESS_ORDER&quot;)) {<br>                if (order != null &amp;&amp; order.isValid()) {<br>                    System.out.println(&quot;Order processed for &quot; + user.getName());<br>                } else {<br>                    System.out.println(&quot;Invalid order.&quot;);<br>                }<br>            } else {<br>                System.out.println(&quot;User does not have permission.&quot;);<br>            }<br>        } else {<br>            System.out.println(&quot;Inactive user.&quot;);<br>        }<br>    } else {<br>        System.out.println(&quot;User is null.&quot;);<br>    }<br>}</pre><p>This code works, but the nesting makes it difficult to read, debug, and maintain. As more conditions are added, this structure becomes increasingly unwieldy. Inherited conditions also violate the <strong>Single Responsibility Principle (SRP)</strong> by mixing validation logic with the main process.</p><h3>✅ Solution 1: Use Guard Clauses to Simplify Logic</h3><p>A guard clause is an early return statement that “guards” the rest of the method from executing if a condition isn’t met. By using guard clauses, we can eliminate deep nesting, allowing the main logic to stay on a single level.</p><pre>public void processOrder(User user, Order order) {<br>    if (user == null) {<br>        System.out.println(&quot;User is null.&quot;);<br>        return;<br>    }<br><br>    if (!user.isActive()) {<br>        System.out.println(&quot;Inactive user.&quot;);<br>        return;<br>    }<br><br>    if (!user.hasPermission(&quot;PROCESS_ORDER&quot;)) {<br>        System.out.println(&quot;User does not have permission.&quot;);<br>        return;<br>    }<br><br>    if (order == null || !order.isValid()) {<br>        System.out.println(&quot;Invalid order.&quot;);<br>        return;<br>    }<br><br>    System.out.println(&quot;Order processed for &quot; + user.getName());<br>}</pre><p>Using guard clauses makes it clear which checks are required, and if any of them fail, we return immediately. Now, the main logic — processing the order — is no longer buried inside nested if statements. This makes the code easier to read and understand at a glance.</p><h3>✅ Solution 2: Use Helper Methods to Increase Modularity</h3><p>We can improve the readability and modularity even further by extracting each condition check into a helper method. This way, each validation is clearly defined, and the processOrder method becomes highly readable and self-documenting.</p><pre>public void processOrder(User user, Order order) {<br>    if (isInvalidUser(user) || isInactiveUser(user) || lacksPermission(user) || isInvalidOrder(order)) {<br>        return;  // Exits if any condition fails<br>    }<br><br>    System.out.println(&quot;Order processed for &quot; + user.getName());<br>}<br><br>private boolean isInvalidUser(User user) {<br>    if (user == null) {<br>        System.out.println(&quot;User is null.&quot;);<br>        return true;<br>    }<br>    return false;<br>}<br><br>private boolean isInactiveUser(User user) {<br>    if (!user.isActive()) {<br>        System.out.println(&quot;Inactive user.&quot;);<br>        return true;<br>    }<br>    return false;<br>}<br><br>private boolean lacksPermission(User user) {<br>    if (!user.hasPermission(&quot;PROCESS_ORDER&quot;)) {<br>        System.out.println(&quot;User does not have permission.&quot;);<br>        return true;<br>    }<br>    return false;<br>}<br><br>private boolean isInvalidOrder(Order order) {<br>    if (order == null || !order.isValid()) {<br>        System.out.println(&quot;Invalid order.&quot;);<br>        return true;<br>    }<br>    return false;<br>}</pre><h3>Why This Approach Works Better</h3><ol><li><strong>Modularity</strong>: Each helper method encapsulates a single responsibility, which aligns with the <strong>Single Responsibility Principle</strong>. Each check is now self-contained, descriptive, and easier to update independently.</li><li><strong>Improved Readability</strong>: The main processOrder method reads almost like plain English. You can easily see that it checks for user validity, activity status, permission, and order validity before proceeding.</li><li><strong>Reusability</strong>: Helper methods can be reused throughout the application if similar checks are needed elsewhere. This ensures consistency and reduces code duplication.</li><li><strong>Easier Testing</strong>: Each helper method can be individually tested, making unit testing simpler and allowing you to verify each condition separately.</li></ol><h3>Final Thoughts: Clean, Maintainable Code Starts with Small Improvements</h3><p>Avoiding inherited conditions by using guard clauses and helper methods may seem like a small change, but it has a big impact on code quality. By keeping our code flat and modular, we make it easier to read, maintain, and extend. This approach also aligns with <strong>SOLID principles</strong> and the best practices of clean code, making your codebase robust and easier to work with over time.</p><p>Try incorporating guard clauses and helper methods in your Java projects, especially when handling complex conditionals. These techniques can help reduce cognitive load, improve readability, and make your code more future-proof.</p><p>Let me know your thoughts in the comments! Have you found other techniques that help manage complex conditionals in Java?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cc74b3e62ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Java Streams: Why Streams Are Better Than Conventional Loops]]></title>
            <link>https://medium.com/@larissafalcaodev/the-power-of-java-streams-why-streams-are-better-than-conventional-loops-0132a7d0e71a?source=rss-2c61733adf8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0132a7d0e71a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Larissa Falcão]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 01:08:38 GMT</pubDate>
            <atom:updated>2024-11-01T01:08:38.608Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3JhAjuFzDJX-XnnGkehpg.jpeg" /><figcaption>Designed by Freepik</figcaption></figure><p>When it comes to iterating over data in Java, we’re accustomed to using for or for-each loop. While loops are effective and straightforward, Java 8 introduced the <strong>Stream API</strong>, which offers a more flexible and expressive way to process data collections. With Streams, you can often write <strong>more readable, concise</strong>, and <strong>efficient</strong> code that enhances performance and maintainability. In this article, we’ll explore the benefits of using Java Streams over traditional loops and look at examples where streams shine.</p><h3>1. Readability and Conciseness</h3><p>One of the primary benefits of using streams is the improvement in <strong>code readability</strong>. Stream operations are <strong>declarative</strong>, meaning you focus on <em>what</em> you want to achieve rather than <em>how</em> to achieve it. This contrasts with the <strong>imperative</strong> nature of loops, where you have to manage the flow and control variables explicitly.</p><h4>Example: Filtering and Transforming a List</h4><p><strong>Using a conventional </strong><strong>for loop:</strong></p><pre>List&lt;String&gt; names = Arrays.asList(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;David&quot;);<br>List&lt;String&gt; filteredNames = new ArrayList&lt;&gt;();<br><br>for (String name : names) {<br>    if (name.startsWith(&quot;A&quot;)) {<br>        filteredNames.add(name.toUpperCase());<br>    }<br>}</pre><p>Using Streams:</p><pre>List&lt;String&gt; filteredNames = names.stream()<br>                                  .filter(name -&gt; name.startsWith(&quot;A&quot;))<br>                                  .map(String::toUpperCase)<br>                                  .collect(Collectors.toList());</pre><p>With streams, the logic for filtering (filter) and transforming (map) is explicitly chained, making the code easier to read. The stream version communicates the <strong>intention</strong> of the code—filter names that start with &quot;A&quot; and convert them to uppercase—without the boilerplate of a loop.</p><h3>2. Reduced Boilerplate Code</h3><p>Streams reduce the amount of <strong>boilerplate code</strong> in your application. In conventional loops, you often have to initialize collections, handle counters, and manage indexes or iterators. With streams, you skip these details and focus on the actual operation you want to perform, which results in <strong>shorter, cleaner code</strong>.</p><p>Consider calculating the sum of even numbers in a list:</p><p><strong>Using a conventional </strong><strong>for loop:</strong></p><pre>int sum = 0;<br>for (int num : numbers) {<br>    if (num % 2 == 0) {<br>        sum += num;<br>    }<br>}</pre><p><strong>Using Streams:</strong></p><pre>int sum = numbers.stream()<br>                 .filter(num -&gt; num % 2 == 0)<br>                 .mapToInt(Integer::intValue)<br>                 .sum();</pre><p>The stream version is not only shorter but also conveys the <strong>functional flow</strong> clearly, reducing the likelihood of errors due to indexing or loop counter mistakes.</p><h3>3. Built-in Parallel Processing</h3><p>The Stream API provides a <strong>parallelStream()</strong> method, which allows for easy parallelization of tasks. This can significantly improve performance in scenarios where you need to process large datasets by leveraging <strong>multithreading</strong> without extra code complexity.</p><h4>Example: Summing a Large List of Numbers</h4><p><strong>Using a parallel stream:</strong></p><pre>int sum = numbers.parallelStream()<br>                 .filter(num -&gt; num % 2 == 0)<br>                 .mapToInt(Integer::intValue)<br>                 .sum();</pre><p>Using parallelStream() lets the Java runtime handle parallelization for you, without needing to manage threads or synchronization explicitly. This is a significant advantage over a conventional loop, where you would need to set up multithreading manually.</p><h3>4. Enhanced Maintainability</h3><p>Streams promote <strong>immutable, side-effect-free operations</strong>, making the code easier to maintain. Since stream operations usually don’t modify the original collection, they eliminate many potential bugs that can arise from mutable states in loops.</p><h3>5. Improved Testability</h3><p>Since streams encourage a <strong>functional approach</strong>, where operations are often expressed as <strong>pure functions</strong> (i.e., functions with no side effects), testing becomes easier. Each step in the stream can be tested individually, and there is less risk of unintended changes to variables that might happen in a loop.</p><h3>6. Built-in Functional Methods</h3><p>Streams come with <strong>many built-in functional operations</strong> like filter, map, reduce, collect, sorted, and distinct, making complex operations straightforward to implement.</p><h4>Example: Complex Operation in a List</h4><p>Suppose you need to:</p><ol><li>Filter numbers greater than 10.</li><li>Square each number.</li><li>Sort the results in descending order.</li><li>Collect the first five results.</li></ol><p><strong>Using Streams:</strong></p><pre>List&lt;Integer&gt; result = numbers.stream()<br>                              .filter(num -&gt; num &gt; 10)<br>                              .map(num -&gt; num * num)<br>                              .sorted(Comparator.reverseOrder())<br>                              .limit(5)<br>                              .collect(Collectors.toList());</pre><p>The stream’s method of chaining lets you perform all these actions in one <strong>declarative, concise statement</strong>. With a traditional loop, implementing the same operation would require multiple lines of code and more careful handling of intermediate states.</p><h3>Key Takeaways</h3><ul><li><strong>Readability</strong>: Streams allow you to focus on <em>what</em> to do, not <em>how</em> to do it, improving code readability.</li><li><strong>Conciseness</strong>: Less boilerplate code means fewer lines of code and reduced potential for errors.</li><li><strong>Parallel Processing</strong>: Stream’s parallel support can easily improve performance for large datasets.</li><li><strong>Maintainability</strong>: Functional, immutable code reduces errors from mutable states.</li><li><strong>Testability</strong>: Stream-based code is easier to isolate and test.</li></ul><h3>When to Use Streams vs. Conventional Loops</h3><p>Streams are ideal for <strong>data processing</strong> tasks like filtering, mapping, and aggregating. However, a traditional for loop may sometimes be more appropriate if your loop contains complex business logic with multiple steps or side effects. Use streams where they enhance readability and make the code more intuitive, and stick to loops where they provide clearer logic or better control flow.</p><p>Embrace Java’s Stream API to write code that’s more readable, maintainable, and aligned with modern Java practices!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0132a7d0e71a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JPA with PostgreSQL: How to Tame Uppercase Tables and Columns]]></title>
            <link>https://medium.com/@larissafalcaodev/mastering-jpa-with-postgresql-how-to-tame-uppercase-tables-and-columns-9eb933929710?source=rss-2c61733adf8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eb933929710</guid>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Larissa Falcão]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 21:18:57 GMT</pubDate>
            <atom:updated>2024-10-25T21:18:57.355Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLpkDmIuVlfJDMeZS7bMnw.jpeg" /><figcaption>Designed by Freepik</figcaption></figure><p>I recently came across a situation where I needed JPA to consider the names of tables and columns as case-sensitive, that is, if the name has uppercase letters, JPA could not automatically convert it to lowercase.</p><p>When using PostgreSQL, which is case-sensitive by default for identifiers (tables, columns, etc.), you must ensure JPA maps uppercase names correctly. PostgreSQL treats unquoted identifiers as lowercase, so if you have uppercase names in your database schema, this can lead to errors if JPA doesn’t map them precisely. Here’s how to configure JPA with PostgreSQL to recognize uppercase names.</p><h3>1. Explicitly Specify Table and Column Names with @Table and @Column</h3><p>Since PostgreSQL requires identifiers to be quoted to maintain their case sensitivity, use the @Table and @Column annotations in each entity. This way, JPA will map the entity fields to the exact uppercase names in PostgreSQL, preserving the case sensitivity. But only doing this is not sufficient, you need to put a crasis around each name.</p><p>Example of entity:</p><pre>@Entity<br>@Table(name = &quot;`MY_TABLE`&quot;) // crasis to keep uppercase in PostgreSQL<br>public class MyEntity {<br><br>    @Id<br>    @Column(name = &quot;`ID`&quot;)<br>    private Long id;<br><br>    @Column(name = &quot;`FIRST_NAME`&quot;)<br>    private String firstName;<br><br>    @Column(name = &quot;`LAST_NAME`&quot;)<br>    private String lastName;<br><br>    // getters and setters<br>}</pre><p>By using crasis around the table and column names in the @Table and @Column annotations, you tell PostgreSQL to treat these names as case-sensitive, so it won’t auto-lowercase them.</p><h3>2. Use a Physical Naming Strategy to Enforce Case</h3><p>Additionally, it is necessary to include it in the project configuration. For Spring Boot and Hibernate, setting spring.jpa.hibernate.naming.physical-strategy to PhysicalNamingStrategyStandardImpl preserves the names as written in annotations without modifying their case. This prevents JPA from changing uppercase names to lowercase, ensuring accurate mapping.</p><p>So, add this to application.yml:</p><pre>spring:<br>  jpa:<br>    hibernate:<br>      naming:<br>        physical-strategy:org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl</pre><h3>3. Migrations</h3><p>To handle uppercase table and column names with PostgreSQL, let’s look at an example of a migration using Flyway, a popular migration tool. In this example, we’ll create an uppercase-named table and columns, then adjust JPA to recognize and work with them.</p><p>In Flyway, migration files are typically named with a version prefix like V1__Migration_Description.sql. Create a V1__Create_Uppercase_Table.sql file in your Flyway migrations folder (e.g., src/main/resources/db/migration for a standard Spring Boot project).</p><p>Inside V1__Create_Uppercase_Table.sql, define the table and column names in uppercase, ensuring they’re <strong>wrapped in double quotes</strong> to preserve case sensitivity (do not forget this).</p><pre>-- V1__Create_Uppercase_Table.sql<br>CREATE TABLE &quot;MY_TABLE&quot; (<br>    &quot;ID&quot; SERIAL PRIMARY KEY,<br>    &quot;FIRST_NAME&quot; VARCHAR(50),<br>    &quot;LAST_NAME&quot; VARCHAR(50),<br>    &quot;CREATED_AT&quot; TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eb933929710" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Use of Streams in Java]]></title>
            <link>https://medium.com/@larissafalcaodev/the-use-of-streams-in-java-169c49c2c02c?source=rss-2c61733adf8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/169c49c2c02c</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Larissa Falcão]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 02:17:22 GMT</pubDate>
            <atom:updated>2024-10-25T02:17:22.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fiUwUCbeAUFFnwncFv7hQ.jpeg" /><figcaption>Designed by Freepik</figcaption></figure><p>Java introduced the Stream API in Java 8 as part of the <a href="http://java.util.stream/">java.util.stream</a> package, revolutionizing how developers work with collections and other data sources. Streams provide a high-level, declarative approach to processing data by leveraging functional programming concepts.</p><h3>What is a Stream?</h3><p>A stream is a sequence of elements that supports various operations to produce a result. Unlike collections, streams do not store elements. Instead, they allow processing elements in a pipeline where data flows from one operation to another. This approach encourages a more readable and maintainable code structure.</p><h3>Core Concepts</h3><p>Streams operate primarily in three phases:</p><ol><li>Source: A stream is created from a data source, such as collections (List, Set, etc.).</li><li>Intermediate Operations: These are transformations applied to the stream. They are lazy, meaning they are not executed until a terminal operation is invoked. Examples include filter(), map(), and sorted().</li><li>Terminal Operations: These operations produce a result, such as a list, a sum, or a print statement. Common terminal operations include collect(), forEach(), and reduce().</li></ol><p>Example of Stream Usage</p><pre>List&lt;String&gt; names = Arrays.asList(&quot;Anna&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;David&quot;);<br><br>List&lt;String&gt; filteredNames = names.stream()<br>                                  .filter(name -&gt; name.startsWith(&quot;A&quot;))<br>                                  .sorted()<br>                                  .collect(Collectors.toList());<br><br>System.out.println(filteredNames);  // Output: [Anna]</pre><p>In the above example, the stream() method is called on a list of names. The filter() operation is applied to select only names starting with “A,” and the sorted() method orders them alphabetically. Finally, the collect() method is used to gather the results into a list.</p><h3>Benefits of Streams</h3><ul><li>Concise Code: Streams reduce boilerplate code and provide a clear and concise syntax for data manipulation.</li><li>Parallel Processing: By simply calling parallelStream(), streams can leverage multi-core processors to perform operations in parallel, enhancing performance in large data sets.</li><li>Immutability: Stream operations do not modify the underlying data source, promoting immutability and reducing potential side effects.</li></ul><h3>Conclusion</h3><p>Java Streams provide a powerful, flexible, and expressive way to process data. By shifting away from imperative loops and towards functional, declarative programming, developers can write more efficient, maintainable, and parallel-ready code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=169c49c2c02c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DTO Pattern vs Record in Java: A Comparison]]></title>
            <link>https://medium.com/@larissafalcaodev/dto-pattern-vs-record-in-java-a-comparison-85947768ccba?source=rss-2c61733adf8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/85947768ccba</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Larissa Falcão]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 01:23:39 GMT</pubDate>
            <atom:updated>2024-10-21T01:23:39.631Z</atom:updated>
            <content:encoded><![CDATA[<p>In Java, data transfer is a crucial aspect of building scalable applications. Two popular approaches for transferring data between layers in an application are the DTO (Data Transfer Object) pattern and Java Records, introduced in Java 14 as a preview feature and finalized in Java 16. Both serve the purpose of encapsulating data but have different design philosophies and use cases. Here’s a short comparison between them.</p><h3>DTO Pattern (Data Transfer Object)</h3><p>The DTO pattern is a well-established design pattern used for carrying data across different layers in an application, particularly between the service and presentation layers. Traditionally, a DTO is a POJO (Plain Old Java Object) containing private fields, public getters and setters, and sometimes utility methods like equals(), hashCode(), and toString().</p><h3>Benefits:</h3><ol><li>Customization: DTOs allow a high degree of flexibility in terms of behavior and logic. You can include business logic, custom validation, or transformation methods.</li><li>Backward Compatibility: DTOs are well-suited for projects that require backward compatibility with older Java versions or frameworks.</li><li>Granular Control: With DTOs, developers have complete control over the structure, serialization, and deserialization processes.</li></ol><h3>Drawbacks:</h3><ul><li>Boilerplate Code: DTOs often require writing a lot of repetitive code (constructors, getters, setters, etc.), especially when dealing with multiple fields.</li><li>Verbose: Even with tools like Lombok, DTOs can become bloated and harder to maintain as the number of attributes grows.</li></ul><h3>Example:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXnJyGbRFVRlMkFJGKYYLA.png" /></figure><h3>Java Records</h3><p>Introduced to reduce boilerplate code, Java Records provide a compact syntax for modeling immutable data. A record is a special type of class designed to hold immutable data, automatically generating implementations of methods such as equals(), hashCode(), and toString(). By default, records are used to store “data as data” rather than objects with behavior.</p><h3>Benefits:</h3><ol><li>Simplicity: Records significantly reduce the amount of boilerplate code. With a single line, you define a record that generates getters, constructors, and utility methods.</li><li>Immutability: Records are inherently immutable, making them ideal for scenarios where data integrity and consistency are critical.</li><li>Cleaner Code: For simple data containers, records enhance code readability and maintainability by reducing verbosity.</li><li>Thread Safety: Due to their immutability, records are inherently thread-safe and can be used in concurrent applications without requiring additional synchronization.</li></ol><h3>Drawbacks:</h3><ul><li>Limited Flexibility: Records are not suitable if you need to mutate data after initialization or if you require complex business logic within the data object.</li><li>Immutability Constraint: If mutable data is required, records are not the right tool, as they focus on immutability by design.</li><li>Customization: Records offer less flexibility when it comes to customization, such as overriding methods or adding behavior beyond the basic data container structure.</li></ul><h3>Example:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZ4tTL6lEAJ1EqHDbhZmPA.png" /></figure><h3>When to Use DTOs vs Records</h3><ul><li>Use DTOs: When you need rich, mutable data objects that can carry logic or validation and when your application architecture requires backward compatibility or fine-grained control over data.</li><li>Use Records: When you need simple, immutable data containers for transferring data between layers without the overhead of boilerplate code, especially when working with newer Java versions.</li></ul><h3>Conclusion</h3><p>Both DTOs and Records have their place in Java development. While DTOs offer flexibility and control, they come with added complexity and verbosity. Records, on the other hand, provide a concise and immutable alternative, perfect for cases where simplicity and thread safety are essential. The choice between them depends on the specific requirements of the project, including whether mutability or simplicity is the priority.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85947768ccba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>