<?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 Gouthamdaneti on Medium]]></title>
        <description><![CDATA[Stories by Gouthamdaneti on Medium]]></description>
        <link>https://medium.com/@gouthamdaneti?source=rss-1f810a1f24c3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*f41CSzHGjh06VJ00</url>
            <title>Stories by Gouthamdaneti on Medium</title>
            <link>https://medium.com/@gouthamdaneti?source=rss-1f810a1f24c3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 03:41:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gouthamdaneti/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[From Cluttered to Clean: The Strategy Pattern in Practice]]></title>
            <link>https://medium.com/@gouthamdaneti/from-cluttered-to-clean-the-strategy-pattern-in-practice-990e9a0d6503?source=rss-1f810a1f24c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/990e9a0d6503</guid>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Gouthamdaneti]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 18:01:47 GMT</pubDate>
            <atom:updated>2025-07-03T18:01:47.671Z</atom:updated>
            <content:encoded><![CDATA[<h4>Unlock the key to eliminating complex conditionals and future-proofing your applications with proven design principles</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZubegQQ1ilIprUkIaOeVQg.png" /><figcaption>Choose strategy based on criteria</figcaption></figure><p>The Strategy pattern is a <strong>behavioural design pattern that allows you to define a family of algorithms, encapsulate each one as an object, and make them interchangeable at runtime</strong>. This pattern lets the algorithm vary independently of the clients that use it.</p><h4>💭 Why I Chose Strategy Pattern</h4><p>🔍 The example used in this post is a <strong>simplified version</strong> of a real-world problem I solved in a production microservice. Due to company policies 🛡️, I can’t share the exact implementation — but the structure and intent remain the same.</p><p>⚙️ In my case, I had a common operation that needed to behave differently based on certain request parameters. Instead of using nested conditionals 🤯 throughout the codebase, I used the <strong>Strategy pattern</strong> to encapsulate each variation cleanly ✅. This made the system <strong>easier to maintain</strong>, <strong>test</strong>, and <strong>extend</strong> — especially when new behaviours needed to be added without touching existing logic 🚀.</p><h4>❌ Without Strategy Pattern (Not Ideal)</h4><pre>public class DataExportService {<br><br>    public void exportData(List&lt;String&gt; data, String fileType, String compressionType) {<br>        String exportedData;<br><br>        // Export logic<br>        if (&quot;csv&quot;.equalsIgnoreCase(fileType)) {<br>            exportedData = String.join(&quot;,&quot;, data);<br>        } else if (&quot;json&quot;.equalsIgnoreCase(fileType)) {<br>            exportedData = &quot;[&quot; + String.join(&quot;,&quot;, data.stream()<br>                                      .map(s -&gt; &quot;\&quot;&quot; + s + &quot;\&quot;&quot;)<br>                                      .toList()) + &quot;]&quot;;<br>        } else {<br>            throw new IllegalArgumentException(&quot;Unsupported file type&quot;);<br>        }<br><br>        // Compression logic<br>        if (&quot;zip&quot;.equalsIgnoreCase(compressionType)) {<br>            System.out.println(&quot;Exporting data as ZIP: &quot; + exportedData);<br>        } else if (&quot;gzip&quot;.equalsIgnoreCase(compressionType)) {<br>            System.out.println(&quot;Exporting data as GZIP: &quot; + exportedData);<br>        } else if (&quot;none&quot;.equalsIgnoreCase(compressionType)) {<br>            System.out.println(&quot;Exporting data without compression: &quot; + exportedData);<br>        } else {<br>            throw new IllegalArgumentException(&quot;Unsupported compression type&quot;);<br>        }<br>    }<br>}</pre><h4>🧨 Drawbacks:</h4><ul><li>Hard to read, extend, or test</li><li>Violates <strong>Open/Closed Principle</strong></li><li>You’ll end up editing this class every time a new format or compression method is added</li></ul><h4>✅ With Strategy Pattern (Clean &amp; Extensible)</h4><p><strong>Step 1: Define the interfaces</strong></p><pre>public interface DataExportStrategy {<br>    String export(List&lt;String&gt; data);<br>}<br><br>public interface CompressionStrategy {<br>    void compress(String data);<br>}</pre><p><strong>Step 2: Implement strategies</strong></p><pre>public class CsvExportStrategy implements DataExportStrategy {<br>    public String export(List&lt;String&gt; data) {<br>        return String.join(&quot;,&quot;, data);<br>    }<br>}<br><br>public class JsonExportStrategy implements DataExportStrategy {<br>    public String export(List&lt;String&gt; data) {<br>        return &quot;[&quot; + data.stream()<br>                         .map(s -&gt; &quot;\&quot;&quot; + s + &quot;\&quot;&quot;)<br>                         .collect(Collectors.joining(&quot;, &quot;)) + &quot;]&quot;;<br>    }<br>}<br><br>public class ZipCompressionStrategy implements CompressionStrategy {<br>    public void compress(String data) {<br>        System.out.println(&quot;Compressing with ZIP: &quot; + data);<br>    }<br>}<br><br>public class GzipCompressionStrategy implements CompressionStrategy {<br>    public void compress(String data) {<br>        System.out.println(&quot;Compressing with GZIP: &quot; + data);<br>    }<br>}<br><br>public class NoCompressionStrategy implements CompressionStrategy {<br>    public void compress(String data) {<br>        System.out.println(&quot;No compression: &quot; + data);<br>    }<br>}</pre><p><strong>Step 3: Use in your service</strong></p><pre>public class DataExportService {<br><br>    private final DataExportStrategy exportStrategy;<br>    private final CompressionStrategy compressionStrategy;<br><br>    public DataExportService(DataExportStrategy exportStrategy, CompressionStrategy compressionStrategy) {<br>        this.exportStrategy = exportStrategy;<br>        this.compressionStrategy = compressionStrategy;<br>    }<br><br>    public void exportData(List&lt;String&gt; data) {<br>        String exported = exportStrategy.export(data);<br>        compressionStrategy.compress(exported);<br>    }<br>}</pre><p><strong>Step 4: Client code</strong></p><pre>List&lt;String&gt; data = List.of(&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;);<br><br>DataExportStrategy exportStrategy = new JsonExportStrategy();<br>CompressionStrategy compressionStrategy = new GzipCompressionStrategy();<br><br>DataExportService service = new DataExportService(exportStrategy, compressionStrategy);<br>service.exportData(data);</pre><h3>Benefits of Using the Strategy Pattern</h3><p>The Strategy pattern offers several key advantages that contribute to a more robust and maintainable codebase:</p><h4>1. Cleaner Code: Say Goodbye to Complex Conditionals 🧹</h4><p>Consider a scenario where your logic branches out based on numerous conditions. This often leads to lengthy and difficult-to-read if-else or switch statements. The Strategy pattern elegantly replaces these bulky conditional blocks by encapsulating each algorithm within its own class. This separation of concerns makes your code significantly cleaner, more focused, and easier to understand. ✨</p><h4>2. Improved Maintainability: Adapting to Change with Ease 🔧</h4><p>As software requirements evolve, you may need to modify existing algorithms or introduce new ones. With traditional conditional logic, such changes can be risky and error-prone, potentially affecting other parts of the code. The Strategy pattern excels in this area. ✅ Because each algorithm is isolated, you can modify or add new strategies without altering the core logic that selects the appropriate strategy. This reduces the risk of introducing bugs and makes maintenance much easier. 🔄</p><h4>3. Adherence to the Open/Closed Principle: Open for Extension, Closed for Modification 🚪🔒</h4><p>The Open/Closed Principle — a fundamental concept in object-oriented design — states that software entities should be open for extension but closed for modification. The Strategy pattern naturally aligns with this principle. You can introduce new strategies (extending the functionality) without modifying the context class that uses them. This promotes a more stable and scalable design. 📈</p><p>By adopting the Strategy pattern, you enable your application to handle varying behaviours in a structured and flexible way, ultimately resulting in a more maintainable and adaptable system. 💡🛠️</p><h3>Conclusion</h3><p>The Strategy pattern isn’t just a neat trick — it’s all about writing code that’s flexible, easy to change, and way less messy. By breaking down behaviors into separate pieces, you keep things simple and ready to grow as your app evolves. This way, you spend less time untangling spaghetti code and more time building awesome features. 🚀</p><h4>Happy coding! ✨</h4><p>If you found this helpful, feel free to share it with your fellow developers! Let’s spread the love for clean, maintainable code. 💻✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=990e9a0d6503" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How HashSet Order Broke My API Tests — And How I Fixed It]]></title>
            <link>https://medium.com/@gouthamdaneti/how-hashset-order-broke-my-api-tests-and-how-i-fixed-it-99766aec3b03?source=rss-1f810a1f24c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/99766aec3b03</guid>
            <category><![CDATA[hashset]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[sort]]></category>
            <dc:creator><![CDATA[Gouthamdaneti]]></dc:creator>
            <pubDate>Mon, 05 May 2025 12:31:31 GMT</pubDate>
            <atom:updated>2025-05-05T12:31:31.265Z</atom:updated>
            <content:encoded><![CDATA[<h3>How HashSet Order Broke My API Tests — And How I Fixed It</h3><h4>And why you should never trust the iteration order of a HashSet in Java</h4><figure><img alt="Even sets can shuffle — beware of relying on order." src="https://cdn-images-1.medium.com/max/1024/1*jUtxeuMq1PDpM4Q2tt4O-A.jpeg" /><figcaption>Even sets can shuffle — beware of relying on order.</figcaption></figure><p>When working with collections in Java, we often reach for HashSet because of its <strong>uniqueness guarantees</strong> and <strong>fast operations</strong>. It’s easy to forget that HashSet does not guarantee <strong>any predictable iteration order</strong>. Most of the time, things “just work” — until they don&#39;t.</p><p>Let me show you how HashSet quietly broke our API tests after years of stability — and how a small change made our tests both <strong>cleaner</strong> and <strong>more robust</strong>.</p><h4>🚀 The Scenario: API Response with a HashSet</h4><p>We had an <strong>API endpoint</strong> that returned a response containing a collection of objects backed by a HashSet. When serialized to JSON, the HashSet naturally turned into a <strong>JSON array</strong>.</p><p>In our unit tests (UTs), we originally wrote assertions like below — <strong>assuming the iteration order of the HashSet would stay stable</strong>:</p><pre>Object defaultValue = responseBody.get(0);<br>Assertions.assertThat(defaultValue.isDefault()).isTrue();<br>Assertions.assertThat(defaultValue.isActive()).isTrue();<br>Assertions.assertThat(defaultValue.getName()).isEqualTo(“Default”);<br><br>Object customValue = responseBody.get(1);<br>Assertions.assertThat(customValue.isDefault()).isFalse();<br>Assertions.assertThat(customValue.isActive()).isFalse();<br>Assertions.assertThat(customValue.getName()).isEqualTo(&quot;Custom&quot;);</pre><blockquote><strong><em>These assertions worked reliably for years. <br></em></strong><em>Even though </em><em>HashSet does not promise order, in practice, the iteration order stayed stable because the objects&#39; </em><strong><em>hashCode() and </em></strong><strong><em>equals()</em></strong><em> didn’t change and their bucket distribution remained consistent.</em></blockquote><h4>🐛 The Breaking Change: How Our Tests Failed</h4><p>Later, we <strong>enhanced the response objects</strong>. We added new <strong>associations</strong> and <strong>fields</strong>, which (unintentionally) impacted their <strong>hashCode() </strong>implementations.</p><blockquote><em>When </em><em>hashCode() changes, objects can land in </em><strong><em>different buckets</em></strong><em> inside the </em><em>HashSet.<br> This </em><strong><em>reshuffles the iteration order</em></strong><em> of elements.</em></blockquote><p><strong>As a result:</strong></p><ul><li>The API response’s JSON array order <strong>shifted</strong>.</li><li>Our tests (which assumed index 0 and 1) <strong>started failing unexpectedly</strong>.</li></ul><h4>🔍 The Root Cause</h4><blockquote><strong><em>Never assume iteration order of a </em></strong><strong><em>HashSet — even if it seems stable.</em></strong><em><br> When the object&#39;s </em><em>hashCode() or </em><em>equals() changes, bucket assignments shift → iteration order shifts → assertions relying on order fail.</em></blockquote><h4>✅ The Clean Fix: Target Elements by Property, Not Position</h4><p>Instead of relying on <strong>fixed indices</strong>, we rewrote our assertions to <strong>explicitly fetch the object we care about</strong>, and then assert on it.</p><p>Here’s the <strong>refactored, resilient test pattern</strong>:</p><pre>Object defaultValue = responseBody.stream()<br> .filter(result -&gt; result.isDefault()) // Find the default object<br> .findFirst()<br> .orElseThrow(() -&gt; new IllegalStateException(“No default value found”));<br>Assertions.assertThat(defaultValue.isDefault()).isTrue();<br>Assertions.assertThat(defaultValue.isActive()).isTrue();<br>Assertions.assertThat(defaultValue.getName()).isEqualTo(&quot;Default&quot;);<br><br>Object customValue = responseBody.stream()<br> .filter(result -&gt; !result.isDefault()) // Find the custom object<br> .findFirst()<br> .orElseThrow(() -&gt; new IllegalStateException(&quot;No custom value found&quot;));<br>Assertions.assertThat(customValue.isDefault()).isFalse();<br>Assertions.assertThat(customValue.isActive()).isFalse();<br>Assertions.assertThat(customValue.getName()).isEqualTo(&quot;Custom&quot;);</pre><h4>📝 Why This Pattern Is Better</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmBHg4PfoF7kWF2MTKydsg.png" /></figure><h4>⚡ Alternative: anySatisfy() (Quick but Less Precise)</h4><p>Another option is using AssertJ’s <strong>anySatisfy()</strong>:</p><pre>Assertions.assertThat(responseBody)<br>    .anySatisfy(value -&gt; {<br>        Assertions.assertThat(value.isDefault()).isTrue();<br>        Assertions.assertThat(value.getName()).isEqualTo(&quot;Default&quot;);<br>    });</pre><p>This works well when you want to <strong>assert a few fields quickly</strong>,<br> but if you want to assert <strong>multiple fields on the same object</strong>,<br> the <strong>stream().filter()</strong> pattern makes intent <strong>clearer</strong>.</p><h4>🏆 Final Takeaways</h4><ul><li><strong>Never trust iteration order of </strong><strong>HashSet</strong>, even if it “worked fine for years.”</li><li>For <strong>API responses</strong>, write tests that are <strong>resilient to order changes</strong>:</li><li>Use .stream().filter(...).findFirst() to fetch objects by their property.</li><li>Use LinkedHashSet <strong>only</strong> if preserving insertion order is an actual business requirement.</li><li>Cleaner tests → Fewer flaky failures → Happier developers 😄</li></ul><h4>💡 TL;DR</h4><p>✅ Don’t assert get(0) on unordered collections<br>✅ Use .stream().filter(...).findFirst() to target objects explicitly<br>✅ Sleep better knowing your tests won’t randomly break after future enhancements</p><h4><strong>Happy coding!</strong> ✨</h4><p>If you found this helpful, consider sharing it with your team — <br> especially before that next big refactor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99766aec3b03" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>