<?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 Mahdi Farrokh on Medium]]></title>
        <description><![CDATA[Stories by Mahdi Farrokh on Medium]]></description>
        <link>https://medium.com/@farrokhpey?source=rss-bbadaa81eb40------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KRHV9HrGjPkdlZFhHhVtuQ.jpeg</url>
            <title>Stories by Mahdi Farrokh on Medium</title>
            <link>https://medium.com/@farrokhpey?source=rss-bbadaa81eb40------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:17:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@farrokhpey/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[In Java, what is the distinction between RuntimeException and Exception, and when should each be…]]></title>
            <link>https://medium.com/@farrokhpey/in-java-what-is-the-distinction-between-runtimeexception-and-exception-and-when-should-each-be-49cb8fe23e46?source=rss-bbadaa81eb40------2</link>
            <guid isPermaLink="false">https://medium.com/p/49cb8fe23e46</guid>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[softare-development]]></category>
            <category><![CDATA[java-development]]></category>
            <dc:creator><![CDATA[Mahdi Farrokh]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 08:29:24 GMT</pubDate>
            <atom:updated>2024-09-22T08:29:24.434Z</atom:updated>
            <content:encoded><![CDATA[<h3>In Java, what is the distinction between RuntimeException and Exception, and when should each be used?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zS3ByJ_IFs7W0y7Pd6bp3Q.jpeg" /></figure><p>Java exceptions are events that disrupt the normal flow of a program. They are used to handle unexpected conditions that occur during runtime. There are two main categories of exceptions in Java: checked exceptions and unchecked exceptions.</p><p>Java exceptions are events that disrupt the normal flow of a program. They are used to handle unexpected conditions that occur during runtime. There are two main categories of exceptions in Java: checked exceptions and unchecked exceptions.</p><p><strong>Checked Exceptions</strong></p><p>Checked exceptions are exceptions that must be declared in the throws clause of a method or constructor. This means that the compiler will force the programmer to handle the exception or propagate it to the calling method. Common examples of checked exceptions include IOException, SQLException, and ClassNotFoundException.</p><p><strong>Unchecked Exceptions</strong></p><p>Unchecked exceptions are exceptions that do not need to be declared in the throws clause of a method or constructor. This means that the compiler will not force the programmer to handle the exception. Unchecked exceptions are typically caused by programming errors, such as NullPointerException, ArrayIndexOutOfBoundsException, and ClassCastException.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49cb8fe23e46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Level Up Your Java Code: Mastering Switch Expressions and Patterns]]></title>
            <link>https://medium.com/@farrokhpey/level-up-your-java-code-mastering-switch-expressions-and-patterns-8fc94809ba98?source=rss-bbadaa81eb40------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fc94809ba98</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Mahdi Farrokh]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 06:19:18 GMT</pubDate>
            <atom:updated>2024-09-10T06:19:18.111Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*2AJqh943dn27zye-2ARc2g.png" /><figcaption>migrate to the light</figcaption></figure><p><strong>Introduction:</strong></p><p>For years, Java developers have relied on the classic switch statement for conditional branching based on specific values. While it excels in simplicity, it comes with limitations. However, Java 12 and subsequent updates introduced revolutionary features: switch expressions and switch patterns. These enhancements empower you to write more concise, expressive, and type-safe code for handling various scenarios.</p><p><strong>Understanding Switch Expressions:</strong></p><p>Switch expressions, introduced in Java 12, provide a way to use a switch statement as an expression that evaluates to a value. This allows you to assign the result of the switch directly to a variable or use it within a larger expression.</p><p>Here’s a basic example:</p><pre>int day = 2;<br>String dayName = switch (day) {<br>  case 1 -&gt; &quot;Monday&quot;;<br>  case 2 -&gt; &quot;Tuesday&quot;;<br>  default -&gt; &quot;Unknown Day&quot;;<br>};</pre><pre>System.out.println(dayName); // Output: Tuesday</pre><p><strong>Switch Expressions with Enhanced Readability:</strong></p><p>Switch expressions offer improved readability with features like:</p><ul><li><strong>Arrow Notation (-&gt;):</strong> Replaces the colon (:) used in traditional statements, making the code more concise.</li><li><strong>No Implicit Fall Through:</strong> Unlike traditional statements, each case ends with a value, preventing accidental fall-through behavior.</li><li><strong>Yield Statement (Java 13+):</strong> Enables returning a value from a case, further enhancing code clarity.</li></ul><p><strong>The Power of Switch Patterns (Java 17+):</strong></p><p>Introduced in Java 17, switch patterns take switch expressions to a whole new level. They allow you to match against complex data structures using pattern-matching syntax.</p><p>Here’s an example with pattern matching:</p><pre>String message = switch (orderStatus) {<br>  case PAID -&gt; &quot;Order is Paid&quot;;<br>  case SHIPPED -&gt; &quot;Order is Shipped&quot;;<br>  case CANCELLED cancelledReason -&gt; &quot;Order Cancelled: &quot; + cancelledReason;<br>  default -&gt; &quot;Unknown Order Status&quot;;<br>};</pre><p>This example utilizes the cancelledReason variable when the case CANCELLED matches, demonstrating pattern matching for extracting information.</p><p><strong>Benefits of Switch Expressions and Patterns:</strong></p><ul><li><strong>Improved Readability:</strong> Cleaner syntax and explicit case handling make code easier to understand.</li><li><strong>Enhanced Expressiveness:</strong> Switch expressions can be used within nested structures and larger expressions for greater flexibility.</li><li><strong>Type Safety:</strong> Pattern matching allows for stricter type checks, leading to fewer runtime errors.</li><li><strong>Reduced Boilerplate:</strong> Less code is needed for conditional branching compared to traditional if-else statements.</li></ul><p><strong>Conclusion:</strong></p><p>Switch expressions and patterns are powerful additions to the Java language. By incorporating them into your codebase, you can improve code readability, maintainability, and type safety. Embrace these features and experience a whole new level of control when working with conditional branching in your Java projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fc94809ba98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Not-So-Shiny Side of Microservices: Disadvantages for Java Developers]]></title>
            <link>https://medium.com/@farrokhpey/the-not-so-shiny-side-of-microservices-disadvantages-for-java-developers-4f934dca43e6?source=rss-bbadaa81eb40------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f934dca43e6</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[seniors]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Mahdi Farrokh]]></dc:creator>
            <pubDate>Thu, 09 May 2024 06:20:52 GMT</pubDate>
            <atom:updated>2024-05-09T06:20:52.622Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjzZPoGpjbl4T4kyKsSs8Q.jpeg" /><figcaption>complexity of microservices</figcaption></figure><p>Microservices have become a popular architectural style for building modern applications. By breaking down monolithic applications into smaller, independent services, they offer advantages like scalability, agility, and independent deployment. However, for Java developers, the microservice approach also comes with its own set of challenges.</p><p><strong>The Dark Side of the Force (Microservices):</strong></p><p>Let’s delve into some of the key disadvantages Java developers should consider before diving headfirst into microservices:</p><ul><li><strong>Increased Complexity:</strong> Microservices introduce a distributed system, leading to intricate service communication, API management, and potential network latency issues. This complexity can be overwhelming for development teams, especially those without prior experience with distributed systems.</li><li><strong>Operational Overhead:</strong> Managing multiple independent services requires significant operational overhead. Tasks like deployment, monitoring, logging, and debugging become more intricate, requiring additional tooling and processes.</li><li><strong>Testing Challenges:</strong> Unit testing individual microservices might be straightforward, but integration testing across services becomes a complex beast. Simulating different service interactions and failure scenarios can be a time-consuming and resource-intensive endeavor.</li><li><strong>Data Consistency:</strong> Maintaining data consistency across multiple services can be a challenge. Implementing robust data access patterns and eventual consistency models requires careful planning and development effort.</li><li><strong>Distributed System Skills Gap:</strong> Not all Java developers are well-versed in distributed system concepts. Adopting microservices might necessitate additional training or hiring developers with expertise in this area.</li></ul><p><strong>Conclusion</strong></p><p>Microservices offer numerous benefits, but they’re not a silver bullet. For Java developers, carefully evaluating the trade-offs between agility and complexity is crucial. Understanding the potential downsides allows teams to make informed decisions and adopt a pragmatic approach to microservice adoption. In some cases, a well-designed monolithic application might be the better choice.</p><p><strong>Remember:</strong> Microservices are a powerful tool, but like any tool, they require the right project and the right team to wield them effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f934dca43e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the Art of Storage: A Guide to Java Collections]]></title>
            <link>https://medium.com/@farrokhpey/mastering-the-art-of-storage-a-guide-to-java-collections-480584aa19ac?source=rss-bbadaa81eb40------2</link>
            <guid isPermaLink="false">https://medium.com/p/480584aa19ac</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mahdi Farrokh]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 05:12:59 GMT</pubDate>
            <atom:updated>2024-04-07T05:12:59.502Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KTjFAbbu9NstmCkqvlQMxw.jpeg" /><figcaption>A Guide to Java Collections</figcaption></figure><p>Java Collections Framework offers a powerful toolbox for storing and manipulating groups of objects. But with a variety of interfaces and classes, choosing the right collection can feel overwhelming. This article equips you with the knowledge to conquer this challenge!</p><p><strong>Understanding the Hierarchy:</strong></p><p>The framework revolves around interfaces that define collection behavior, with concrete classes implementing these interfaces. Here’s a breakdown of the key players:</p><ol><li><strong>Collection Interface:</strong> The grandparent of them all, Collection defines fundamental operations like adding, removing, and iterating over elements.</li><li><strong>Set Interface:</strong> Guarantees unique elements, preventing duplicates. Use cases include storing unique user IDs or non-repeating lottery numbers.</li><li><strong>HashSet:</strong> Employs hashing for fast insertion and removal, but maintains no order.</li></ol><pre>Set&lt;String&gt; fruits = new HashSet&lt;&gt;();<br>fruits.add(&quot;Apple&quot;);<br>fruits.add(&quot;Banana&quot;);<br>fruits.add(&quot;Apple&quot;); // Duplicate ignored<br>for (String fruit : fruits) {<br>  System.out.println(fruit); // Order not guaranteed<br>}</pre><pre>Set&lt;Integer&gt; numbers = new TreeSet&lt;&gt;();<br>numbers.add(3);<br>numbers.add(1);<br>numbers.add(4);<br>for (int number : numbers) {<br>  System.out.println(number); // Output: 1, 3, 4<br>}</pre><p><strong>3. List Interface:</strong> Represents an ordered collection of elements. You can access elements by their position (index).</p><ul><li><strong>ArrayList:</strong> A resizable array-based list, offering fast random access but slower insertions in the middle.</li></ul><pre>List&lt;String&gt; colors = new ArrayList&lt;&gt;();<br>colors.add(&quot;Red&quot;);<br>colors.add(&quot;Green&quot;);<br>colors.add(1, &quot;Blue&quot;); // Insert at index 1<br>System.out.println(colors.get(0)); // Access by index</pre><pre>List&lt;Integer&gt; ages = new LinkedList&lt;&gt;();<br>ages.add(25);<br>ages.addFirst(30); // Insert at the beginning<br>System.out.println(ages.remove(0)); // Remove by index</pre><p><strong>4. Queue Interface:</strong> Elements are processed in a First-In-First-Out (FIFO) manner, like a waiting line.</p><ul><li><strong>PriorityQueue:</strong> Orders elements based on a natural order or comparator, prioritizing higher values.</li></ul><pre>PriorityQueue&lt;String&gt; tasks = new PriorityQueue&lt;&gt;();<br>tasks.add(&quot;Urgent&quot;);<br>tasks.add(&quot;Normal&quot;);<br>tasks.add(&quot;Critical&quot;); // Critical will be processed first<br>System.out.println(tasks.poll()); // Retrieves and removes the highest priority element</pre><p><strong>5. Deque Interface:</strong> A more versatile queue, allowing insertion and removal from both ends.</p><ul><li><strong>ArrayDeque:</strong> Efficient for both queue and stack (Last-In-First-Out) operations.</li></ul><pre>Deque&lt;Character&gt; stack = new ArrayDeque&lt;&gt;();<br>stack.push(&#39;A&#39;); // Push to the end (stack operation)<br>stack.addFirst(&#39;B&#39;); // Add to the beginning (queue operation)<br>System.out.println(stack.pop()); // Remove from the end (stack operation)</pre><p><strong>6. Map Interface:</strong> Stores key-value pairs, similar to a dictionary. Keys must be unique, and values can be duplicated.</p><ul><li><strong>HashMap:</strong> Uses hashing for fast access by key, but maintains no order for key-value pairs.</li></ul><pre>Map&lt;String, Integer&gt; studentGrades = new HashMap&lt;&gt;();<br>studentGrades.put(&quot;Alice&quot;, 90);<br>studentGrades.put(&quot;Bob&quot;, 85);<br>System.out.println(studentGrades.get(&quot;Alice&quot;)); // Access by key</pre><p><strong>Choosing the Right Collection:</strong></p><p>Consider these factors when selecting a collection:</p><ul><li><strong>Uniqueness:</strong> Do you need to avoid duplicates (Set)?</li><li><strong>Order:</strong> Is order of elements important (List, Deque)?</li><li><strong>Access Pattern:</strong> Do you need frequent random access (List, HashMap) or FIFO/LIFO processing (Queue, Deque)?</li></ul><p><strong>Beyond the Basics:</strong></p><p>The Collections Framework offers a rich set of utility classes like Collections.sort() to sort elements and Collections.frequency() to count element occurrences. Additionally, Java 8 introduced features like Streams for more powerful collection processing.</p><p>By understanding the different collection types and their functionalities, you’ll be well-equipped to tackle various data storage and manipulation tasks in your Java programs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=480584aa19ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradle vs. Maven: Building a Better Java Project?]]></title>
            <link>https://medium.com/@farrokhpey/gradle-vs-maven-building-a-better-java-project-4455b1a54441?source=rss-bbadaa81eb40------2</link>
            <guid isPermaLink="false">https://medium.com/p/4455b1a54441</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Mahdi Farrokh]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 06:23:00 GMT</pubDate>
            <atom:updated>2024-02-14T06:23:00.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNzdDtuYDW58iOxK-vRarA.jpeg" /><figcaption>do you prefer Gradle or Maven?</figcaption></figure><p>When it comes to Java project management, two titans stand tall: Maven and Gradle. Both excel in automating builds, dependencies, and deployments, but each boasts unique strengths and weaknesses. Choosing the right tool can significantly impact your development workflow. So, let’s delve into the heart of Gradle vs. Maven, comparing their features, pros and cons, and ultimately, suggest the best practice for navigating this crucial decision.</p><p><strong>Foundations and Philosophy:</strong></p><ul><li><strong>Maven:</strong> Built on a pre-defined lifecycle with phases and goals, offering stability and consistency. XML files serve as project configuration, adhering to established conventions.</li><li><strong>Gradle:</strong> Utilizes a flexible, domain-specific language (DSL) for more granular control and customization. Groovy scripts enable complex builds and dynamic logic.</li></ul><p><strong>Dependency Management:</strong></p><ul><li><strong>Maven:</strong> Employs a centralized repository (Maven Central) with a hierarchical dependency structure. Version conflicts are resolved based on shortest path, sometimes leading to unexpected outcomes.</li><li><strong>Gradle:</strong> Offers advanced dependency management with customizable rules and conflict resolution strategies. This empowers developers to tailor the build process to their specific needs.</li></ul><p><strong>Performance and Flexibility:</strong></p><ul><li><strong>Maven:</strong> Generally considered slower, especially during incremental builds due to its reliance on XML parsing.</li><li><strong>Gradle:</strong> Leverages caching mechanisms and incremental builds, often resulting in faster execution times. Its flexible DSL allows for complex project structures and intricate build logic.</li></ul><p><strong>Community and Ecosystem:</strong></p><ul><li><strong>Maven:</strong> A mature platform with a vast community and a wealth of plugins and integrations. This extensive ecosystem simplifies integration with various tools and services.</li><li><strong>Gradle:</strong> Growing rapidly with a passionate community developing a wide range of plugins. While not as expansive as Maven’s, its plugin ecosystem is steadily catching up.</li></ul><p><strong>Pros and Cons:</strong></p><p><strong>Maven:</strong></p><p><strong>Pros:</strong></p><ul><li><strong>Mature and stable:</strong> Established conventions and large community lead to predictable outcomes.</li><li><strong>Easy to learn:</strong> Well-defined lifecycle simplifies initial setup and understanding.</li><li><strong>Rich ecosystem:</strong> Integrates seamlessly with various tools and services.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Limited flexibility:</strong> Less customizable than Gradle, potentially hindering complex build needs.</li><li><strong>Performance:</strong> Can be slower than Gradle, especially for large projects or frequent changes.</li><li><strong>Version conflicts:</strong> Dependency resolution based on shortest path can lead to unexpected results.</li></ul><p><strong>Gradle:</strong></p><p><strong>Pros:</strong></p><ul><li><strong>Highly flexible:</strong> Offers granular control over the build process with custom DSL.</li><li><strong>Faster:</strong> Often outperforms Maven in incremental builds due to caching and efficiency.</li><li><strong>Advanced features:</strong> Supports complex project structures, dependency management, and intricate build logic.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Steeper learning curve:</strong> DSL requires more coding knowledge compared to Maven’s XML.</li><li><strong>Smaller ecosystem:</strong> Plugin availability might be limited compared to Maven’s extensive repository.</li><li><strong>Potential complexity:</strong> Advanced features can lead to over-engineered builds if not used judiciously.</li></ul><p><strong>Choosing the Right Tool:</strong></p><p>So, which is the champion? Unfortunately, there’s no definitive answer. It depends on your specific project requirements and preferences. Here are some guiding principles:</p><ul><li><strong>For smaller projects or those valuing simplicity and stability, Maven might be a good starting point.</strong></li><li><strong>For larger projects, frequent changes, or requiring intricate build logic, Gradle’s flexibility and performance shine.</strong></li><li><strong>Consider team familiarity and existing infrastructure.</strong> Switching tools can involve effort and potential disruption.</li><li><strong>Evaluate the available plugins and integrations critical to your workflow.</strong> Both platforms offer robust ecosystems, but specific needs might influence your choice.</li></ul><p>Ultimately, experimentation is key. Explore both Maven and Gradle through sample projects or personal preference to determine which empowers you to build Java projects more efficiently and effectively. Remember, the best tool is the one that aligns seamlessly with your workflow and enables you to focus on what matters most — creating exceptional software.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4455b1a54441" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoded: The Immutability of Strings in Java — A Lesson Learned from the Interview Chair]]></title>
            <link>https://medium.com/@farrokhpey/decoded-the-immutability-of-strings-in-java-a-lesson-learned-from-the-interview-chair-0ce25c066ad0?source=rss-bbadaa81eb40------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ce25c066ad0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[interview-tips]]></category>
            <dc:creator><![CDATA[Mahdi Farrokh]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 05:43:47 GMT</pubDate>
            <atom:updated>2024-01-24T05:43:47.943Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PoSYKWLSTwxr4aVZfskT7g.jpeg" /><figcaption>A Lesson Learned from the Interview Chair</figcaption></figure><p>Confession time: I hesitated. While I knew strings felt immutable in practice, I wasn’t entirely sure of the technical underpinnings. This little gap in my knowledge, though seemingly minor, served as a valuable wake-up call. It highlighted the importance of truly understanding fundamental Java concepts, not just using them intuitively.</p><p>So, I decided to delve deeper and write this article, not just to solidify my own understanding but also to shed light on immutability in Java, particularly for the String class.</p><p>**Mutable vs. Immutable: A Tale of Two Worlds**</p><p>In the realm of Java objects, mutability reigns supreme. Objects, by default, are mutable, meaning their state can be altered after creation. Imagine a mutable object as a block of clay — you can mold and reshape it at will.</p><p>Immutable objects, on the other hand, are like stone sculptures — their form is set in stone after creation. Any attempt to modify them results in a new object being created, leaving the original untouched.</p><p>**Why Strings are Immutable: A Matter of Efficiency and Thread Safety**</p><p>The String class in Java proudly stands on the side of immutability. But why this design choice? The reasons are compelling:</p><p>* **Efficiency:** String objects are frequently used in Java programs. Making them immutable allows the JVM to optimize them for memory usage and performance. Since the value remains constant, the JVM can reuse existing String objects, reducing memory overhead and improving performance.</p><p>* **Thread Safety:** In the multi-threaded world of Java, immutability shines. When multiple threads access a mutable String object, the potential for data corruption arises. Immutability eliminates this risk as each thread works with a fixed copy of the string, ensuring data integrity.</p><p>**Beyond Strings: The Immutable Advantage**</p><p>While the String class is the most prominent example, immutability has broader benefits in Java applications:</p><p>* **Simplified Reasoning:** Reasoning about immutable objects is easier, as their state remains predictable. This can lead to cleaner code and fewer bugs.</p><p>* **Concurrency:** Immutable objects are inherently thread-safe, making them ideal for concurrent programming scenarios.</p><p>**The Interview Revisited: Armed with Knowledge**</p><p>Fast forward to my interview. Armed with this newfound understanding of immutability and the reasons behind the String class’s design, I confidently explained the concept to the interviewer. The discussion that followed was enriching, and I left feeling not just relieved but also grateful for the learning experience.</p><p>**Key Takeaways:**</p><p>* Understanding immutability is crucial for writing efficient and robust Java applications.<br>* The String class is immutable for reasons of performance, thread safety, and simplified reasoning.<br>* Embrace the learning opportunities that arise from interview challenges — they can illuminate vital concepts and make you a better programmer.</p><p>So, the next time you encounter a String object in Java, remember: it’s immutable, and that’s a good thing! And if you ever find yourself on the interview hot seat, face the questions with confidence, knowing that even a seemingly simple concept can hold valuable lessons.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ce25c066ad0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yes, No, Maybe So: Demystifying DTOs, Mappers, and DAOs in Spring]]></title>
            <link>https://medium.com/@farrokhpey/yes-no-maybe-so-demystifying-dtos-mappers-and-daos-in-spring-922f2c5b07cb?source=rss-bbadaa81eb40------2</link>
            <guid isPermaLink="false">https://medium.com/p/922f2c5b07cb</guid>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mahdi Farrokh]]></dc:creator>
            <pubDate>Wed, 03 Jan 2024 15:32:10 GMT</pubDate>
            <atom:updated>2024-01-03T15:32:10.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2c-FUs9riIGwqg_p4h_zg.jpeg" /><figcaption>Yes, No, Maybe So</figcaption></figure><p><strong>Understanding the Trio:</strong></p><ul><li><strong>DTOs (Data Transfer Objects):</strong> DTOs act as lightweight data carriers, shuttling information between layers without the baggage of complete entity models. They focus on specific data needs, promoting modularity and decoupling.</li><li><strong>Mappers:</strong> These magic wands handle the transformation between DTOs and entities. Whether using hand-written code, annotation-driven libraries, or dedicated mapper frameworks, they bridge the gap between presentation and persistence concerns.</li><li><strong>DAOs (Data Access Objects):</strong> DAOs encapsulate database interactions, hiding the gritty details of JDBC connections and SQL queries behind a clean API. They provide a unified interface for accessing and manipulating data, regardless of the underlying storage mechanism.</li></ul><p><strong>The “Yes” Case:</strong></p><ul><li><strong>Separation of Concerns:</strong> DTOs and DAOs keep presentation and persistence concerns segregated, making code cleaner, easier to maintain, and more testable.</li><li><strong>Performance Optimization:</strong> By transferring only the necessary data, DTOs reduce network traffic and database roundtrips, boosting application responsiveness.</li><li><strong>Flexibility and Customization:</strong> DTOs can be tailored to specific presentation needs, omitting irrelevant fields or transforming data for optimal consumption.</li></ul><p><strong>The “No” Case:</strong></p><ul><li><strong>Overkill for Simple Scenarios:</strong> For basic data interactions, directly using entities might be simpler and more efficient, avoiding the overhead of mapper overhead.</li><li><strong>Performance Cost of Mapping:</strong> Heavy object conversion with complex logic can introduce performance bottlenecks, requiring careful balancing with the benefits of decoupling.</li><li><strong>Maintenance Burden:</strong> Introducing more moving parts like mappers necessitates additional maintenance and testing, adding complexity to the project.</li></ul><p><strong>The “Maybe So” Case:</strong></p><ul><li><strong>Start Simple, Evolve Later:</strong> Begin with direct entity use for basic projects, transitioning to DTOs and DAOs as data complexity and presentation needs grow.</li><li><strong>Consider Alternatives:</strong> Explore existing Spring features like Spring Data repositories and projections before implementing custom DAOs and mappers.</li><li><strong>Weigh the Trade-offs:</strong> Evaluate the specific context of your project, balancing the benefits of architecture against the cost of implementation and maintenance.</li></ul><p><strong>Examples in Action:</strong></p><ul><li><strong>Scenario:</strong> Building a REST API endpoint that returns user details.</li><li><strong>Without DTOs:</strong> The controller directly fetches entities and returns them, exposing unnecessary internal data and potentially revealing sensitive information.</li><li><strong>With DTOs:</strong> A dedicated UserDTO captures the specific data needed for the API response, improving security and presentation clarity. Mappers ensure smooth conversion between entities and DTOs.</li></ul><p><strong>Closing Thoughts:</strong></p><p>DTOs, mappers, and DAOs are powerful tools in the Spring developer’s arsenal. Understanding their strengths and limitations empowers you to make informed decisions, crafting architectures that are efficient, maintainable, and tailored to your specific needs. Remember, the answer to their usage isn’t always a resounding “yes” or “no,” but a nuanced “maybe so,” depending on the context and trade-offs involved. Choose wisely, and your Spring projects will shine with clarity and efficiency.</p><p><strong>Call to Action:</strong></p><p>Share your thoughts in the comments below! What are your experiences with DTOs, mappers, and DAOs in Spring? When do you find them most valuable, and when would you avoid them? Let’s keep the conversation flowing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=922f2c5b07cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conquering the Microservice Maze: Your Guide to Spring Cloud API Gateway]]></title>
            <link>https://medium.com/@farrokhpey/conquering-the-microservice-maze-your-guide-to-spring-cloud-api-gateway-07dcc073afe7?source=rss-bbadaa81eb40------2</link>
            <guid isPermaLink="false">https://medium.com/p/07dcc073afe7</guid>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <dc:creator><![CDATA[Mahdi Farrokh]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 05:01:11 GMT</pubDate>
            <atom:updated>2023-12-25T05:06:53.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*xHkOUswyXPBj0L8t.jpg" /><figcaption>a maze with a clear path leading to a central location</figcaption></figure><p>Microservices have taken the software world by storm, offering agility and scalability like never before. But with great power comes great complexity, and managing the API sprawl of a microservices architecture can quickly become a tangled mess. Enter the <strong>Spring Cloud API Gateway</strong>, your trusty compass in the microservice maze.</p><p><strong>What is it?</strong></p><p>Imagine a single entry point for all your microservices, a bouncer who directs requests to the right service based on pre-defined rules. That’s the Spring Cloud API Gateway in a nutshell. Built on top of Spring WebFlux and Spring Boot, it seamlessly routes traffic, applies security policies, and even adds functionalities like rate limiting and circuit breakers.</p><p><strong>Why use it?</strong></p><ul><li><strong>Simplicity:</strong> Manage all your APIs from one place, no more chasing down individual service endpoints.</li><li><strong>Security:</strong> Centralize authentication and authorization, keeping your microservices safe and sound.</li><li><strong>Resilience:</strong> Build in fault tolerance with features like circuit breakers, ensuring graceful degradation under pressure.</li><li><strong>Monitoring:</strong> Gain insights into API traffic and performance with built-in metrics and tracing capabilities.</li><li><strong>Scalability:</strong> Handle growing traffic load seamlessly by adding more gateway instances.</li></ul><p><strong>How to get started:</strong></p><p>Spring Cloud Gateway is incredibly easy to set up. You can get started with a simple Spring Boot application and configure routes using YAML or Java code. Need more complex logic? Custom filters and predicates let you tailor the gateway’s behavior to your specific needs.</p><p><strong>Pros and Cons:</strong></p><p><strong>Pros:</strong></p><ul><li><strong>Simple and efficient:</strong> Get up and running quickly with minimal configuration.</li><li><strong>Powerful features:</strong> Built-in security, resilience, and monitoring capabilities.</li><li><strong>Spring ecosystem integration:</strong> Seamlessly integrates with other Spring Cloud components.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Reactive mindset:</strong> Requires understanding of reactive programming for advanced customization.</li><li><strong>Limited customization:</strong> Not as flexible as building your own gateway from scratch.</li><li><strong>Single point of failure:</strong> Gateway downtime can impact all microservices.</li></ul><p><strong>Alternatives:</strong></p><p>While Spring Cloud Gateway is a robust solution, other options exist:</p><ul><li><strong>Kong:</strong> Open-source, highly customizable API gateway with a vibrant community.</li><li><strong>Zuul:</strong> Netflix’s API gateway, popular for its simplicity and Spring integration.</li><li><strong>Ambassador:</strong> Envoy-based API gateway offering advanced features and high performance.</li></ul><p><strong>Choosing the right tool depends on your specific needs and skillset.</strong></p><p>a complete and simple guide to configure your application: <a href="https://medium.com/%40AlexanderObregon/implementing-api-gateway-with-spring-cloud-gateway-40d65732ed51&amp;hl=en">https://medium.com/AlexanderObregon/implementing-api-gateway-with-spring-cloud-gateway</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07dcc073afe7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL: A Double-Edged Sword for Java and Spring Developers]]></title>
            <link>https://medium.com/@farrokhpey/graphql-a-double-edged-sword-for-java-and-spring-developers-8f55c5f86fc9?source=rss-bbadaa81eb40------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f55c5f86fc9</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Mahdi Farrokh]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 05:36:27 GMT</pubDate>
            <atom:updated>2023-12-18T05:36:27.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3OnBRlv7X6Q6HDjXWre0g.jpeg" /></figure><p>In the ever-evolving world of web development, GraphQL has emerged as a powerful alternative to RESTful APIs. But for Java and Spring developers, the question remains: is GraphQL a blessing or a curse? In this article, we’ll explore both sides of the coin, examining the <strong>pros and cons of using GraphQL with Java and Spring</strong>.</p><p><strong>Pros: A Glimpse into GraphQL’s Advantages</strong></p><p><strong>1. Precise Data Fetching:</strong> One of the biggest advantages of GraphQL is its ability to let clients request exactly the data they need. This eliminates the need for over-fetching or under-fetching data, leading to <strong>improved performance and reduced network traffic</strong>.</p><p><strong>2. Flexibility and Adaptability:</strong> With GraphQL, clients can describe the data they need in a single query, regardless of its location in the underlying data model. This flexibility allows for <strong>easier integration with complex data structures and evolving requirements</strong>.</p><p><strong>3. Strong Typing:</strong> GraphQL provides a strongly typed schema that defines the available data and its structure. This ensures <strong>data consistency, prevents errors, and simplifies development by enabling code completion and type checking</strong>.</p><p><strong>Cons: The Flip Side of the GraphQL Coin</strong></p><p><strong>1. Increased Server Complexity:</strong> Unlike RESTful APIs, GraphQL servers require additional logic to handle dynamic data requests. This can lead to increased server complexity and potential performance bottlenecks.</p><p><strong>2. Over-Fetching and Under-Fetching Data:</strong> While GraphQL allows precise data fetching, it can also lead to over-fetching or under-fetching if not implemented correctly. Over-fetching can negate the performance benefits, while under-fetching can require additional queries to retrieve missing data.</p><p><strong>3. Security Concerns:</strong> Since GraphQL allows clients to request any data they have access to, it’s crucial to implement a robust security system to prevent unauthorized access and data leaks.</p><p><strong>4. Limited Tooling and Ecosystem:</strong> While GraphQL’s popularity is growing, its tooling and ecosystem are still maturing compared to RESTful APIs. This can lead to challenges in finding suitable libraries and tools for specific needs.</p><p><strong>Should You Use GraphQL with Java and Spring?</strong></p><p>The decision to use GraphQL depends on your specific needs and priorities. If your API requires flexibility, precise data fetching, and strong typing, GraphQL can be a valuable asset. However, if simplicity, performance, and a mature ecosystem are your top concerns, a RESTful API might be a better choice.</p><p><strong>Java and Spring: Putting GraphQL to Work</strong></p><p>Fortunately, Java and Spring provide excellent support for GraphQL development. Libraries like <strong>Spring GraphQL</strong> and <strong>GraphQL Java</strong> offer a robust framework for building GraphQL servers.</p><p>Here are some additional factors to consider when deciding whether to use GraphQL:</p><ul><li><strong>Size and complexity of your API:</strong> GraphQL shines with complex data models and evolving requirements.</li><li><strong>Client-side development needs:</strong> GraphQL can simplify client-side development by providing a single source for all data needs.</li><li><strong>Team experience and skills:</strong> Implementing GraphQL effectively requires expertise in both Java and GraphQL principles.</li></ul><p><strong>Conclusion:</strong></p><p>GraphQL offers a powerful and flexible alternative to RESTful APIs, but it’s not a perfect solution for all scenarios. By carefully weighing the pros and cons and considering your specific needs, you can make an informed decision about whether GraphQL is the right choice for your Java and Spring project.</p><p>Remember, it’s not an either/or situation. You can also leverage the strengths of both GraphQL and RESTful APIs by having a hybrid approach where appropriate.</p><p><strong>Ultimately, the best approach is to experiment and find the solution that best suits your project’s needs.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f55c5f86fc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Dependency Injection in Java using Spring Boot]]></title>
            <link>https://medium.com/@farrokhpey/demystifying-dependency-injection-in-java-using-spring-boot-04df517dc58e?source=rss-bbadaa81eb40------2</link>
            <guid isPermaLink="false">https://medium.com/p/04df517dc58e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mahdi Farrokh]]></dc:creator>
            <pubDate>Mon, 11 Dec 2023 04:27:29 GMT</pubDate>
            <atom:updated>2023-12-11T04:27:29.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3EgYj988Dv67c7Dw9uoZog.png" /><figcaption>a circuit board with interconnected components, representing dependencies in a software system</figcaption></figure><p>As seasoned Java developers, we’ve all encountered the challenges of managing dependencies between different parts of our applications. Dependency Injection (DI) emerges as a powerful design pattern that helps us overcome these hurdles and build robust, maintainable software.</p><p>But what exactly is DI? And how can we leverage its strengths in Java using Spring Boot, a popular framework for building modern microservices? In this article, we’ll delve into the concepts of DI, explore its benefits, and guide you through implementing it in your Spring Boot applications.</p><p><strong>The Essence of Dependency Injection</strong></p><p>Imagine a kitchen where various ingredients need to be assembled to cook a delicious meal. Instead of each ingredient finding and preparing its partners, a chef plays a central role in gathering and organizing them. Similarly, DI acts as the chef in our software development world.</p><p><strong>In simpler terms, DI involves providing a class with the objects it needs to function, rather than having it create or manage them itself.</strong> This shift in responsibility offers several key benefits:</p><ul><li><strong>Loose Coupling:</strong> By decoupling classes from their dependencies, we make them more independent and adaptable. This allows us to easily swap out implementations without affecting other parts of the system.</li><li><strong>Improved Testability:</strong> When dependencies are injected, we can easily mock or stub them for unit testing purposes, leading to more robust and reliable tests.</li><li><strong>Increased Maintainability:</strong> By centralizing dependency management, we simplify our codebase and make it easier to understand and modify.</li></ul><p><strong>Spring Boot: The Perfect Partner for DI</strong></p><p>Spring Boot simplifies DI implementation by offering various annotations and configurations. Here are three common approaches:</p><ol><li><strong>Constructor Injection:</strong> Dependencies are passed as constructor arguments, ensuring they are initialized at object creation.</li></ol><pre>@Component<br>public class MyService {<br>private final MyRepository repository;<br>public MyService(MyRepository repository) {<br> this.repository = repository;<br> }<br>// …<br>}</pre><p>2. <strong>Setter Injection:</strong> Dependencies are injected through setter methods.</p><pre>@Component<br>public class MyController {<br>private MyService service;<br>@Autowired<br> public void setService(MyService service) {<br> this.service = service;<br> }<br>// …<br>}</pre><p>3. <strong>Field Injection:</strong> Dependencies are directly injected into fields annotated with `<a href="http://twitter.com/Autowired">@Autowired</a>`.</p><pre>@Component<br>public class MyComponent {<br>@Autowired<br> private MyDependency dependency;<br>// …<br>}</pre><p>Spring Boot also offers powerful configuration options through @Beanannotations and BeanFactoryPostProcessor implementations, allowing fine-grained control over your dependencies.</p><p><strong>Beyond the Basics: Advanced DI Techniques</strong></p><p>As your applications grow, you might explore more advanced DI techniques:</p><ul><li><strong>Method Injection:</strong> Inject dependencies into specific methods for dynamic behavior.</li><li><strong>Qualifier Injection:</strong> Specify specific implementations for dependencies with multiple options.</li><li><strong>Lazy Injection:</strong> Delay the creation of dependencies until they are actually needed.</li></ul><p>These techniques offer greater flexibility and control over your dependencies, allowing you to create even more complex and efficient applications.</p><h3><strong>Conclusion</strong></h3><p>By embracing DI in your Spring Boot applications, you can unlock several benefits, including improved testability, maintainability, and loose coupling. By understanding the different injection methods and exploring advanced techniques, you can become a master of dependency management and contribute to your team’s success.</p><p>Remember, DI is not just a technique; it’s a philosophy that encourages clean design and promotes better software development practices. So, go ahead, embrace DI, and watch your code flourish!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04df517dc58e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>