<?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 Snigdhaa Katthula on Medium]]></title>
        <description><![CDATA[Stories by Snigdhaa Katthula on Medium]]></description>
        <link>https://medium.com/@kathulasnigdha2k?source=rss-a19c259eb288------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y3-3DurLsYx0-9OOAc4d9Q.jpeg</url>
            <title>Stories by Snigdhaa Katthula on Medium</title>
            <link>https://medium.com/@kathulasnigdha2k?source=rss-a19c259eb288------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:46:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kathulasnigdha2k/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[Chain of Responsibility Design Pattern]]></title>
            <link>https://medium.com/@kathulasnigdha2k/chain-of-responsibility-design-pattern-5cd9c051a5c9?source=rss-a19c259eb288------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cd9c051a5c9</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[chain-of-responsibility]]></category>
            <category><![CDATA[design-patterns-in-java]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Snigdhaa Katthula]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 05:42:36 GMT</pubDate>
            <atom:updated>2026-01-21T05:42:36.562Z</atom:updated>
            <content:encoded><![CDATA[<h3>The “Giant If-Else” Monster 👹</h3><p>Imagine you are building a <strong>Payment Authorization System</strong>. When a request comes in:</p><ol><li>It must be checked for <strong>Authentication</strong> (Is the user logged in?).</li><li>It must be checked for <strong>Authorization</strong> (Does the user have permission?).</li><li>It must be checked for <strong>Validation</strong> (Is the amount positive?).</li><li>It must be checked for <strong>Fraud</strong> (Is this a suspicious transaction?).</li></ol><p><strong>Without the Pattern:</strong> You end up with a massive class where one method has a giant block of nested if-else statements. If you want to add a 5th check (e.g., &quot;Currency Conversion&quot;), you have to break open that messy method again.</p><h3>2. The Solution: The Chain of Responsibility</h3><p>Instead of one big method, you create separate “Handler” objects. You link them together like a chain.</p><ul><li>The request enters the first link.</li><li>The link either <strong>handles it and stops</strong> OR <strong>handles it and passes it to the next link</strong>.</li><li>The client only needs to talk to the <em>first</em> link in the chain.</li></ul><h3>3. Java Implementation: Request Processing</h3><h4>Step 1: The Abstract Handler</h4><pre>public abstract class Handler {<br>    protected Handler next;<br>    public void setNext(Handler next) {<br>        this.next = next;<br>    }<br>    public abstract void handle(String request);<br>}</pre><h4>Step 2: Concrete Handlers</h4><pre>class AuthHandler extends Handler {<br>    public void handle(String request) {<br>        if (request.contains(&quot;Logged-In&quot;)) {<br>            System.out.println(&quot;Auth Passed.&quot;);<br>            if (next != null) next.handle(request);<br>        } else {<br>            System.out.println(&quot;Auth Failed! Stopping.&quot;);<br>        }<br>    }<br>}<br><br>class ValidationHandler extends Handler {<br>    public void handle(String request) {<br>        if (request.contains(&quot;Valid-Amount&quot;)) {<br>            System.out.println(&quot;Validation Passed.&quot;);<br>            if (next != null) next.handle(request);<br>        } else {<br>            System.out.println(&quot;Validation Failed!&quot;);<br>        }<br>    }<br>}</pre><h4>Step 3: How to call it (Building the Chain)</h4><pre>public class Main {<br>    public static void main(String[] args) {<br>        // 1. Create the links<br>        Handler auth = new AuthHandler();<br>        Handler validation = new ValidationHandler();<br>        // 2. Build the chain<br>        auth.setNext(validation);<br>        // 3. Start the process<br>        System.out.println(&quot;--- Test 1 ---&quot;);<br>        auth.handle(&quot;Logged-In, Valid-Amount&quot;);<br>        System.out.println(&quot;\n--- Test 2 ---&quot;);<br>        auth.handle(&quot;Guest-User&quot;);<br>    }<br>}</pre><h3>4. When to use it?</h3><ul><li><strong>When multiple objects can handle a request</strong>, and the handler isn’t known a priori.</li><li><strong>When you want to issue a request to one of several objects</strong> without specifying the receiver explicitly.</li><li><strong>When the set of objects that can handle a request should be specified dynamically.</strong></li></ul><h3>5. Identifying it in the Wild</h3><ul><li><strong>Middleware in Web Frameworks:</strong> If you use Express.js (Node) or Spring Security (Java), the “Filters” are a Chain of Responsibility.</li><li><strong>Logging:</strong> Logger levels (INFO -&gt; DEBUG -&gt; ERROR). If the error is severe, it gets handled by the “Error Logger”; otherwise, it passes through.</li><li><strong>UI Event Bubbling:</strong> In JavaScript, when you click a button, the click event travels up through the div, then the body, then the window until something handles it.</li></ul><h3>6. Why is this better?</h3><ul><li><strong>Single Responsibility:</strong> Each class does exactly one check.</li><li><strong>Open/Closed Principle:</strong> You can add a “FraudHandler” to the chain without touching the “AuthHandler” code.</li><li><strong>Flexibility:</strong> You can reorder the chain at runtime (e.g., check for Fraud <em>before</em> Validation).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cd9c051a5c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decorator Pattern]]></title>
            <link>https://medium.com/@kathulasnigdha2k/decorator-pattern-9ef3bb40031a?source=rss-a19c259eb288------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ef3bb40031a</guid>
            <category><![CDATA[design-patterns-in-java]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[decorator-design-pattern]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Snigdhaa Katthula]]></dc:creator>
            <pubDate>Mon, 19 Jan 2026 05:41:59 GMT</pubDate>
            <atom:updated>2026-01-19T05:41:59.501Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve all been there. You start with a simple Coffee class. Then you need CoffeeWithMilk. Then CoffeeWithSugar. Before you know it, you have a &quot;Class Explosion&quot; with 20 different subclasses for every possible combination of toppings.</p><p>This is the <strong>Inheritance Trap</strong>. It’s rigid, it’s messy, and it’s a nightmare to maintain.</p><p>Today, let’s look at the <strong>Decorator Pattern</strong> — the “Structural” way to add features to your objects at runtime without breaking your code.</p><h3>1. What is the Decorator Pattern?</h3><p>The Decorator is a design pattern that allows you to <strong>wrap</strong> an object inside another object to add new behavior.</p><p>Think of it like a <strong>Pizza</strong>.</p><ul><li>You start with a PlainPizza.</li><li>You wrap it in a CheeseDecorator.</li><li>You wrap <em>that</em> in a PepperoniDecorator.</li></ul><p>The final object still looks and acts like a Pizza, but it has a different price and description.</p><h3>2. The Real-World Problem: The “Subclass Nightmare”</h3><p>Imagine you are building a <strong>File Stream</strong> library.</p><ul><li>You have a SimpleFileStream.</li><li>You want it to be <strong>Encrypted</strong>. (Subclass: EncryptedFileStream)</li><li>You want it to be <strong>Compressed</strong>. (Subclass: CompressedFileStream)</li><li>Now… what if you want it to be <strong>BOTH</strong> Encrypted and Compressed?</li></ul><p>With inheritance, you’d need a new class: EncryptedCompressedFileStream. If you add a third feature like &quot;Buffered,&quot; you&#39;ll end up with a dozen classes.</p><p><strong>The Solution:</strong> Decorators allow you to “stack” these features at runtime like LEGO blocks.</p><h3>3. Java Implementation: The Coffee Shop</h3><p>Let’s look at the most famous example: building a coffee order.</p><h4>Step 1: The Base Interface</h4><pre>public interface Coffee {<br>    String getDescription();<br>    double getCost();<br>}</pre><h4>Step 2: The Concrete Product</h4><pre>public class SimpleCoffee implements Coffee {<br>    public String getDescription() { return &quot;Coffee&quot;; }<br>    public double getCost() { return 5.0; }<br>}</pre><h4>Step 3: The Abstract Decorator</h4><p>This is the secret sauce. The Decorator <strong>implements</strong> the interface AND <strong>contains</strong> an instance of the interface.</p><pre>public abstract class CoffeeDecorator implements Coffee {<br>    protected Coffee decoratedCoffee; // The &quot;Wrapped&quot; object<br>    public CoffeeDecorator(Coffee coffee) {<br>        this.decoratedCoffee = coffee;<br>    }<br>    public String getDescription() { return decoratedCoffee.getDescription(); }<br>    public double getCost() { return decoratedCoffee.getCost(); }<br>}</pre><h4>Step 4: Concrete Decorators (The Toppings)</h4><pre>public class MilkDecorator extends CoffeeDecorator {<br>    public MilkDecorator(Coffee coffee) { super(coffee); }<br>    public String getDescription() { <br>        return decoratedCoffee.getDescription() + &quot;, Milk&quot;; <br>    }<br>    public double getCost() { <br>        return decoratedCoffee.getCost() + 1.50; <br>    }<br>}</pre><h3>4. How to Call it (The Power of Wrapping)</h3><p>Instead of calling new MilkSugarCoffee(), you wrap them dynamically:</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        // 1. Start with basic coffee<br>        Coffee myOrder = new SimpleCoffee();<br>        // 2. Add Milk<br>        myOrder = new MilkDecorator(myOrder);<br>        // 3. Add Sugar (Assuming you built a SugarDecorator)<br>        myOrder = new SugarDecorator(myOrder);<br>        System.out.println(&quot;Order: &quot; + myOrder.getDescription());<br>        System.out.println(&quot;Total: $&quot; + myOrder.getCost());<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ef3bb40031a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bridge Design Pattern]]></title>
            <link>https://medium.com/@kathulasnigdha2k/bridge-design-pattern-cf2194e81d41?source=rss-a19c259eb288------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf2194e81d41</guid>
            <category><![CDATA[design-patterns-in-java]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[bridge-design-pattern]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Snigdhaa Katthula]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 05:42:50 GMT</pubDate>
            <atom:updated>2026-01-16T05:42:50.111Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Are your classes exploding? Use the Bridge Pattern to save your architecture. 🌉</strong></p><p>“Inheritance is great until it isn’t. When you find yourself creating classes like RedSquare, BlueSquare, and GreenSquare, you aren&#39;t coding—you&#39;re creating a maintenance graveyard.&quot;</p><p><strong>The fix?</strong> Stop using “Is-A” and start using “Has-A”. By bridging your hierarchies, you keep your shapes independent of your colors (or your Remotes independent of your TVs).</p><p>The <strong>Bridge Pattern</strong> is the “Structural” answer to the “Abstract Factory.” While the Abstract Factory handles how objects are created, the Bridge handles how they are <strong>structured</strong> so that they don’t become a nightmare to maintain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*ggRj-Mmh-ToGCP6B" /></figure><h3>1. The Problem: Class Explosion 💥</h3><p>Imagine you’re building a Graphics App. You have different <strong>Shapes</strong> (Square, Circle) and you want them to support different <strong>Colors</strong> (Red, Blue).</p><p>If you use normal inheritance, your class tree looks like this:</p><p>Shape</p><ul><li>RedSquare</li><li>BlueSquare</li><li>RedCircle</li><li>BlueCircle</li></ul><p>Now, imagine you add a Green color. You have to create GreenSquare and GreenCircle. Now add a Triangle shape... you see the problem? Every new feature multiplies the number of classes. This is <strong>Class Explosion</strong>.</p><h3>2. The Solution: The Bridge</h3><p>Instead of saying “A Red Square is a type of Square,” we say “A Square <strong>has</strong> a Color.” We pull the “Color” logic out into its own interface and “bridge” it back to the Shape.</p><h3>3. Java Implementation</h3><h4>Step 1: The Implementation Interface (The “Color”)</h4><pre>interface Color {<br>    void applyColor();<br>}<br><br>class Red implements Color {<br>    public void applyColor() { System.out.println(&quot;Applying Red color.&quot;); }<br>}<br><br>class Blue implements Color {<br>    public void applyColor() { System.out.println(&quot;Applying Blue color.&quot;); }<br>}</pre><h4>Step 2: The Abstraction (The “Shape”)1</h4><p>The Shape “holds” a reference to a Color. This is the <strong>Bridge</strong>.</p><pre>abstract class Shape {<br>    // This protected field is the &quot;Bridge&quot;<br>    protected Color color;<br>    public Shape(Color color) {<br>        this.color = color;<br>    }<br>    abstract void draw();<br>}</pre><h4>Step 3: Refined Abstractions</h4><pre>class Circle extends Shape {<br>    public Circle(Color color) { super(color); }<br>    public void draw() {<br>        System.out.print(&quot;Drawing Circle. &quot;);<br>        color.applyColor();<br>    }<br>}<br>class Square extends Shape {<br>    public Square(Color color) { super(color); }<br>    public void draw() {<br>        System.out.print(&quot;Drawing Square. &quot;);<br>        color.applyColor();<br>    }<br>}</pre><h4>Step 4: The Client Code</h4><pre>public class Main {<br>    public static void main(String[] args) {<br>        // We can mix and match any Shape with any Color at runtime!<br>        Shape redCircle = new Circle(new Red());<br>        Shape blueSquare = new Square(new Blue());<br>        redCircle.draw();<br>        blueSquare.draw();<br>    }<br>}</pre><h3>4. Why is this better?</h3><ul><li><strong>Independence:</strong> You can add 10 new colors without touching the Shape classes.</li><li><strong>Cleaner Code:</strong> You went from $N \times M$ classes to $N + M$ classes. (For 5 shapes and 5 colors, you go from 25 classes down to 10).</li><li><strong>Runtime Flexibility:</strong> You can change the color of a shape dynamically while the program is running.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf2194e81d41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adapter Design Pattern]]></title>
            <link>https://medium.com/@kathulasnigdha2k/adapter-design-pattern-d51f376c646f?source=rss-a19c259eb288------2</link>
            <guid isPermaLink="false">https://medium.com/p/d51f376c646f</guid>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[adapter-design-pattern]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <dc:creator><![CDATA[Snigdhaa Katthula]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 05:42:48 GMT</pubDate>
            <atom:updated>2026-01-14T05:42:48.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZRz4bhiELkSh0tfC" /><figcaption>Adapter</figcaption></figure><h3>1. The Problem: The “Incompatible Plug”</h3><p>Imagine you are building a <strong>Weather Monitoring App</strong>. Your app is modern and works with <strong>Celsius</strong>.</p><p>However, you’ve just bought a high-end <strong>Legacy Weather Sensor</strong> library that provides very accurate data, but it only returns temperature in <strong>Fahrenheit</strong>.</p><p><strong>The Conflict:</strong></p><ul><li>Your WeatherDisplay interface expects a getTemperatureInCelsius() method.</li><li>The LegacySensor class only has a getFahrenheitTemp() method.</li></ul><p>If you try to plug the LegacySensor directly into your WeatherDisplay, the code won&#39;t compile.</p><h3>2. The Solution: The Adapter</h3><p>Instead of rewriting your whole app to use Fahrenheit, or trying to hack the 3rd-party library (which you probably can’t edit), you create an <strong>Adapter</strong>.</p><h3>3. Java Implementation</h3><h4>The Target (What our app expects)</h4><pre>interface CelsiusSensor {<br>    double getTemperature();<br>}</pre><p><strong>The Adaptee (The “Incompatible” Legacy code)</strong></p><pre>class LegacyFahrenheitSensor {<br>    public double getFahrenheitTemp() {<br>        return 98.6; // High accuracy, but wrong units!<br>    }<br>}</pre><h4>The Adapter (The Translator)</h4><p>The Adapter implements the modern interface but talks to the legacy object inside.</p><pre>class TemperatureAdapter implements CelsiusSensor {<br>    private LegacyFahrenheitSensor legacySensor;<br>    public TemperatureAdapter(LegacyFahrenheitSensor sensor) {<br>        this.legacySensor = sensor;<br>    }<br>    @Override<br>    public double getTemperature() {<br>        double fahrenheit = legacySensor.getFahrenheitTemp();<br>        // Convert F to C<br>        return (fahrenheit - 32) * 5 / 9;<br>    }<br>}</pre><h4>The Client Code</h4><pre>public class WeatherApp {<br>    public static void main(String[] args) {<br>        // 1. We have the legacy hardware<br>        LegacyFahrenheitSensor oldSensor = new LegacyFahrenheitSensor();<br>        <br>        // 2. We wrap it in our Adapter<br>        CelsiusSensor adapter = new TemperatureAdapter(oldSensor);<br>        <br>        // 3. Our app is happy! It thinks it&#39;s talking to a Celsius sensor.<br>        System.out.println(&quot;Temperature in Celsius: &quot; + adapter.getTemperature());<br>    }<br>}</pre><h3>4. When to use the Adapter?</h3><ul><li><strong>Legacy Integration:</strong> When you have a new system but need to use an old class that has a different interface.</li><li><strong>Third-Party Libraries:</strong> When a library provides functionality you need, but its “method signatures” don’t match your project’s standards.</li><li><strong>Data Conversion:</strong> When you need to transform data formats (like XML to JSON) on the fly for a specific component.</li></ul><h3>5. Identification in the Wild</h3><p>You can spot an Adapter when:</p><ul><li>You see a class that <strong>implements one interface</strong> but holds an <strong>instance of another class</strong> (Composition).</li><li>The method in the class simply converts parameters/results and calls the internal object.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d51f376c646f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Abstract Factory Pattern]]></title>
            <link>https://medium.com/@kathulasnigdha2k/the-abstract-factory-pattern-768e6655a8f9?source=rss-a19c259eb288------2</link>
            <guid isPermaLink="false">https://medium.com/p/768e6655a8f9</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[abstract-design-pattern]]></category>
            <dc:creator><![CDATA[Snigdhaa Katthula]]></dc:creator>
            <pubDate>Mon, 12 Jan 2026 05:41:31 GMT</pubDate>
            <atom:updated>2026-01-12T05:41:31.883Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>When you need a whole matching set: Master the Abstract Factory Pattern 🧩</strong></p><p>So, you’ve mastered the Factory Method Pattern, deftly avoiding the perils of hardcoded new statements. But what if your application doesn&#39;t just need <em>one</em> specialized object, but an entire <strong>family of related objects</strong> that must always work together?</p><p>Enter the <strong>Abstract Factory Pattern</strong> the “factory of factories.”</p><h3>1. What is the Abstract Factory Pattern?</h3><p>The Abstract Factory is a <strong>Creational Design Pattern</strong> that provides an interface for creating <strong>families of related or dependent objects</strong> without specifying their concrete classes.</p><p>Think of it like a car manufacturing plant. When you choose to build a “Luxury Car,” you don’t just get a luxury engine. you get a luxury chassis, luxury interior, and luxury tires all from the same “Luxury Car Factory.” You don’t accidentally get a luxury engine with a budget chassis.</p><h3>2. The Problem: Why a single Factory isn’t enough</h3><p>Let’s go back to our <strong>GUI Application</strong> example. You want your app to look native on different operating systems (Windows, Mac, Linux).</p><ul><li><strong>The Products:</strong> Buttons, Checkboxes, TextFields (your UI components).</li><li><strong>The Families/Styles:</strong> Windows-style components, Mac-style components, Linux-style components.</li></ul><p><strong>The Mess Without Abstract Factory:</strong> If you used a simple Factory Method for each component, your code would be littered with if/else to ensure consistency</p><pre>// ❌ This is a mess: You have to manually ensure consistency everywhere<br>Button myButton;<br>Checkbox myCheckbox;<br>if (os.equals(&quot;Windows&quot;)) {<br>    myButton = new WinButton();<br>    myCheckbox = new WinCheckbox();<br>} else if (os.equals(&quot;Mac&quot;)) {<br>    myButton = new MacButton();<br>    myCheckbox = new MacCheckbox();<br>}<br>// What if you forget to add the &#39;else if&#39; for a new component type?<br>// You could end up with a Windows Button and a Mac Checkbox!</pre><p>This is fragile. If you add a new component (e.g., a “Slider”), you have to revisit all these if/else blocks to add the new component type for <em>every</em> OS.</p><h3>3. The Solution: The Abstract Factory Pattern</h3><p>The Abstract Factory centralizes the creation of <em>entire families</em> of products. It guarantees that all components you get from a specific factory belong to the same style.</p><h4>Step 1: Define Product Interfaces (The individual items)</h4><pre>// Common interfaces for our UI components<br>interface Button { void render(); }<br>interface Checkbox { void render(); }</pre><h4>Step 2: Create Concrete Products (The specific types, by family)</h4><pre>// Windows family components<br>class WinButton implements Button { @Override public void render() { System.out.println(&quot;Win Button&quot;); } }<br>class WinCheckbox implements Checkbox { @Override public void render() { System.out.println(&quot;Win Checkbox&quot;); } }<br>// Mac family components<br>class MacButton implements Button { @Override public void render() { System.out.println(&quot;Mac Button&quot;); } }<br>class MacCheckbox implements Checkbox { @Override public void render() { System.out.println(&quot;Mac Checkbox&quot;); } }</pre><h4>Step 3: Define the Abstract Factory (The Contract for the families)</h4><p>This is the “factory of factories” interface. It declares a set of methods for creating a <em>family</em> of products.</p><pre>interface GUIFactory {<br>    Button createButton();    // Factory Method for Buttons<br>    Checkbox createCheckbox(); // Factory Method for Checkboxes<br>}</pre><h4>Step 4: Create Concrete Factories (The specific families)</h4><p>Each concrete factory implements the GUIFactory interface to produce a consistent set of products.</p><pre>// Windows Factory: Creates only Windows-style components<br>class WinFactory implements GUIFactory {<br>    @Override public Button createButton() { return new WinButton(); }<br>    @Override public Checkbox createCheckbox() { return new WinCheckbox(); }<br>}<br><br>// Mac Factory: Creates only Mac-style components<br>class MacFactory implements GUIFactory {<br>    @Override public Button createButton() { return new MacButton(); }<br>    @Override public Checkbox createCheckbox() { return new MacCheckbox(); }<br>}</pre><h4>Step 5: The Client Code (Decoupled and Consistent)</h4><p>The client code now depends only on the <em>abstract</em> factory and product interfaces. It doesn’t care about “Windows” or “Mac” specifics.</p><pre>public class Application {<br>    private Button button;<br>    private Checkbox checkbox;<br>    // ✅ The client only knows about the GUIFactory interface.<br>    // It is completely decoupled from concrete OS styles.<br>    public Application(GUIFactory factory) {<br>        this.button = factory.createButton();<br>        this.checkbox = factory.createCheckbox();<br>    }<br>    public void displayUI() {<br>        button.render();<br>        checkbox.render();<br>    }<br>}</pre><h4>Step 6: Assembling the Application (Configuration Layer)</h4><p>This is the <em>only</em> place where you decide which concrete factory to use, usually based on runtime conditions (like the OS).</p><pre>public class Demo {<br>    public static void main(String[] args) {<br>        GUIFactory factory;<br>        String osName = System.getProperty(&quot;os.name&quot;).toLowerCase(); // Detect OS<br>        if (osName.contains(&quot;win&quot;)) {<br>            factory = new WinFactory(); // Get the Windows components family<br>        } else {<br>            factory = new MacFactory(); // Get the Mac components family<br>        }<br>        Application app = new Application(factory); // Inject the chosen factory<br>        app.displayUI(); // Render the consistent UI<br>    }<br>}</pre><h3>4. When to Use the Abstract Factory Pattern?</h3><ul><li><strong>When your system must be independent of how its products are created, composed, and represented.</strong></li><li><strong>When your system needs to be configured with one of multiple families of products.</strong> (e.g., you need to switch entire GUI toolkits, database connectors, or report generators).</li><li><strong>When you want to enforce a consistent set of products</strong> (i.e., you need to guarantee that all products used together are from the same family/style).</li></ul><h3>5. Identifying the Pattern in the Wild</h3><p>Look for:</p><ul><li>Multiple interfaces (e.g., Button, Checkbox) defining a family of products.</li><li>An abstract factory interface (GUIFactory) with methods for creating each product in the family.</li><li>Multiple concrete factories (WinFactory, MacFactory), each implementing the abstract factory to produce a specific style of products.</li><li>Client code that receives a concrete factory (often via Dependency Injection) and uses it to create entire sets of matching objects.</li></ul><p><strong>Final Thought:</strong> The Abstract Factory is your go-to pattern when consistency across a family of objects is paramount. It allows for highly configurable and scalable systems by centralizing the creation of related components.</p><p><strong>What’s the most complex “family of objects” you’ve ever had to manage in a project? Share your stories! 👇</strong></p><p>#Java #DesignPatterns #AbstractFactory #CreationalPatterns #SoftwareArchitecture #GUIToolkit</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=768e6655a8f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Factory Method Pattern]]></title>
            <link>https://medium.com/@kathulasnigdha2k/the-factory-method-pattern-cdd40952890b?source=rss-a19c259eb288------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdd40952890b</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[factory-design-pattern]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <dc:creator><![CDATA[Snigdhaa Katthula]]></dc:creator>
            <pubDate>Fri, 09 Jan 2026 05:42:44 GMT</pubDate>
            <atom:updated>2026-01-09T05:42:44.941Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Stop hardcoding </strong><strong>new! Unlock flexible object creation with the Factory Method Pattern 🏭</strong></p><p>Ever felt the frustration of adding a new feature and having to edit your code in a dozen different places? That’s the pain of <strong>tight coupling</strong>, often caused by directly using the new keyword throughout your business logic. When you write new SomeSpecificObject(), you&#39;re essentially gluing your code to that particular implementation.</p><p>This is where the <strong>Factory Method Pattern</strong> comes to the rescue.</p><h3>1. What is the Factory Method Pattern?</h3><p>The Factory Method is a <strong>Creational Design Pattern</strong> that provides an interface for creating objects, but allows subclasses to alter the type of objects that will actually be created.</p><p>Think of it this way: instead of you, the client, directly constructing a specific Car model, you go to a CarFactory and just say, &quot;Give me a car.&quot; The factory then decides which specific type of car (e.g., Sedan, SUV, SportsCar) to hand you. You don&#39;t care how it was built; you just get a car.</p><h3>2. The Problem: Life Without a Factory</h3><p>Let’s imagine you’re building a <strong>Notification System</strong>. Initially, your app only sends <strong>Email Notifications</strong>. Your code is simple, but inflexible:</p><pre>// Scattered throughout your UserRegistrationService, OrderConfirmation, etc.<br>EmailNotification emailSender = new EmailNotification();<br>emailSender.send(&quot;Welcome!&quot;);</pre><p><strong>The Mess Begins:</strong> When your boss says, “Great! Now we need to add <strong>SMS Notifications</strong> and <strong>Push Notifications</strong>.” Suddenly, you have to find every single place where you wrote new EmailNotification() and add complex if/else logic:</p><pre>// ❌ This is &#39;Constructor Chaos&#39; leading to Tight Coupling!<br>if (notificationType.equals(&quot;EMAIL&quot;)) {<br>    new EmailNotification().send(&quot;Hello!&quot;);<br>} else if (notificationType.equals(&quot;SMS&quot;)) {<br>    new SMSNotification().send(&quot;Hey!&quot;);<br>} else if (notificationType.equals(&quot;PUSH&quot;)) {<br>    new PushNotification().send(&quot;What&#39;s up!&quot;);<br>}<br>// Imagine adding 10 more notification types here...</pre><p>This violates the <strong>Open/Closed Principle</strong> (OCP) — you have to <strong>open</strong> your existing code to <strong>modify</strong> it every time you add a new notification type.</p><h3>3. The Solution: The Factory Method Pattern</h3><p>The Factory Method Pattern centralizes the object creation logic. It acts as a shield, preventing your client code from being directly dependent on concrete product classes.</p><h4>Step 1: Define the Product Interface (What are we making?)</h4><pre>// All notifications share a common contract<br>interface Notification {<br>    void send(String message);<br>}</pre><h4>Step 2: Create Concrete Products (The specific types)</h4><pre>class PushNotification implements Notification {<br>    @Override public void send(String message) { System.out.println(&quot;Push: &quot; + message); }<br>}</pre><pre>class EmailNotification implements Notification {<br>    @Override public void send(String message) { System.out.println(&quot;Email: &quot; + message); }<br>}</pre><pre>class SMSNotification implements Notification {<br>    @Override public void send(String message) { System.out.println(&quot;SMS: &quot; + message); }<br>}</pre><h4>Step 3: Implement the Factory Method (The Creator)</h4><p>This is where the magic of delegation happens. We define an abstract creator and let subclasses handle the actual new calls.</p><pre>// Abstract Creator: Defines the factory method<br>abstract class NotificationCreator {<br>    // This is the &quot;Factory Method&quot;<br>    public abstract Notification createNotification();<br>    // Any generic business logic that uses the product<br>    public void notifyUsers(String message) {<br>        Notification note = createNotification(); // &lt;-- The method call<br>        note.send(message);<br>    }<br>}<br><br><br>// Concrete Creators: Implement the factory method to return a specific product<br>class EmailNotificationCreator extends NotificationCreator {<br>    @Override<br>    public Notification createNotification() {<br>        return new EmailNotification(); // Creates an Email<br>    }<br>}<br><br><br>class SMSNotificationCreator extends NotificationCreator {<br>    @Override<br>    public Notification createNotification() {<br>        return new SMSNotification(); // Creates an SMS<br>    }<br>}</pre><h4>Step 4: The Client Code (Clean &amp; Decoupled)</h4><p>Now, your application logic doesn’t care <em>how</em> the notification is created. It just asks a Creator to do its job.</p><pre>public class Client {<br>    public static void main(String[] args) {<br>        NotificationCreator creator;<br>       // At runtime, decide which creator to use (e.g., from config, user choice)<br>        String notificationChoice = &quot;EMAIL&quot;; // Could come from UI or config<br>        if (notificationChoice.equals(&quot;EMAIL&quot;)) {<br>            creator = new EmailNotificationCreator();<br>        } else if (notificationChoice.equals(&quot;SMS&quot;)) {<br>            creator = new SMSNotificationCreator();<br>        } else {<br>            System.out.println(&quot;Invalid notification type.&quot;);<br>            return;<br>        }<br>        // The client simply tells the creator to perform the action<br>        creator.notifyUsers(&quot;Your order has been shipped!&quot;);<br>    }<br>}</pre><p>Notice the key difference: <strong>The </strong><strong>new keyword is now hidden inside the </strong><strong>createNotification() method of the <em>subclasses</em></strong>.</p><h3>4. When to use the Factory Method Pattern?</h3><ul><li><strong>When you don’t know the exact types of objects your code should create beforehand.</strong> (e.g., depending on OS, database type, user preferences).</li><li><strong>When you want to provide a way for subclasses to customize which objects are created.</strong> (e.g., a logging framework that lets users create their own file or database loggers).</li><li><strong>When you want to centralize object creation logic</strong> to maintain the Open/Closed Principle (OCP) — allowing you to add new product types without modifying existing code.</li></ul><h3>5. Identifying the Pattern in the Wild</h3><p>Look for:</p><ul><li>An abstract class or interface that declares a method (the &quot;factory method&quot;) that returns an object.</li><li>Multiple concrete subclasses that implement this method to return different types of products.</li><li>Client code that interacts with the abstract creator, not directly with the concrete products.</li></ul><h3>6. Factory Method in Python and TypeScript</h3><p>The Factory Method pattern is very common in dynamic languages too.</p><ul><li><strong>Python:</strong> You might use a function that returns different class instances based on arguments, or a registry of functions.</li><li><strong>TypeScript/JavaScript:</strong> Often used in UI frameworks to create different components or in API clients to instantiate different API handlers based on a type string.</li></ul><p>The core principle remains: <strong>delegate the </strong><strong>new keyword to a specialized creator.</strong></p><p><strong>Final Thought:</strong> By embracing the Factory Method, you write more flexible, maintainable, and robust code. It’s a fundamental step towards building scalable applications.</p><p><strong>What’s your favorite use case for the Factory Method? Share in the comments! 👇</strong></p><p>#Java #DesignPatterns #FactoryMethod #CreationalPatterns #CleanCode #SoftwareEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdd40952890b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master the Prototype Pattern in Java]]></title>
            <link>https://medium.com/@kathulasnigdha2k/master-the-prototype-pattern-in-java-8dd8b5e25386?source=rss-a19c259eb288------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dd8b5e25386</guid>
            <category><![CDATA[prototype-design-pattern]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <dc:creator><![CDATA[Snigdhaa Katthula]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 05:42:26 GMT</pubDate>
            <atom:updated>2026-01-07T05:42:26.361Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever had an object that was expensive to create? Maybe it required a heavy database call, or maybe it just has 50 fields that are exactly the same for 90% of your users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kKglRJEwM_nkGS9h.png" /></figure><p>In Java, we often default to using new. But there’s a faster, cleaner way: <strong>The Prototype Design Pattern.</strong></p><h3>1. What is the Prototype Pattern?</h3><p>The Prototype pattern is a creational design pattern that allows you to <strong>copy existing objects</strong> without making your code dependent on their classes. Instead of building from scratch, you “clone” a pre-configured version.</p><h3>2. What Real-World Problem does it solve?</h3><p>Imagine you are managing a School Registry.</p><ul><li><strong>The Problem:</strong> Every student in “9th Grade” at “Model School” shares the same school name, address, and class standard.</li><li><strong>The Mess:</strong> If you have 1,000 students, you don’t want to manually set schoolName and classStandard 1,000 times.</li><li><strong>The Solution:</strong> Create one “Prototype” student for 9th Grade. When a new student joins, <strong>clone</strong> that prototype and just fill in their name and email.</li></ul><h3>3. Java Implementation: The Registry Approach</h3><p>The best way to handle this in production is by using a <strong>Registry</strong> (a warehouse for your prototypes) and a <strong>Copy Constructor</strong>.</p><h4>Step 1: Create the Prototype Interface</h4><pre>public interface Prototype {<br>    Prototype clone();<br>}</pre><h4>Step 2: Implement the Copy Constructor</h4><p>Using a Copy Constructor is safer than Java’s default clone() because it avoids issues with final fields and CloneNotSupportedException.</p><pre>public class Student implements Prototype {<br>    private String name, schoolName, classStandard;<br>    // The Copy Constructor<br>    public Student(Student student) {<br>        this.schoolName = student.schoolName;<br>        this.classStandard = student.classStandard;<br>    }<br>    @Override<br>    public Student clone() {<br>        return new Student(this);<br>    }<br>}</pre><h4>Step 3: The Registry</h4><p>The Registry stores our “Templates” so the client doesn’t have to create them.</p><pre>public class Registry {<br>    private Map&lt;String, Student&gt; prototypes = new HashMap&lt;&gt;();<br>    public void addPrototype(String key, Student s) { prototypes.put(key, s); }<br>    public Student getPrototype(String key) { return prototypes.get(key).clone(); }<br>}</pre><h3>4. Why use this over a simple Constructor?</h3><ul><li><strong>Performance:</strong> Cloning memory is faster than running complex logic inside a constructor.</li><li><strong>Simplified Client Code:</strong> The client doesn’t need to know <em>how</em> to set up a “9th Grade Model School Student.” They just ask the Registry for one.</li><li><strong>Reduced Subclassing:</strong> You don’t need a ModelSchoolStudent class and a PublicSchoolStudent class. You just need different objects in your Registry.</li></ul><h3>5. Prototype in Python and TypeScript</h3><p>In modern languages, this pattern is even easier:</p><ul><li><strong>Python:</strong> Uses the copy module (copy.deepcopy(obj)).</li><li><strong>TypeScript:</strong> Uses object spreading {...prototypeObject} or Object.create(). Because these languages are more dynamic, the formal &quot;Prototype Class&quot; structure is often built into the language itself!</li></ul><h3>Final Thoughts</h3><p>The Prototype pattern is about efficiency. If you find yourself repeatedly setting the same fields on new objects, it’s time to stop using new and start using .clone().</p><p>“<strong>In Java, if your class only contains Primitives (</strong><strong>int) and Strings, a Shallow Copy is fine because Strings are immutable. But the moment you add a </strong><strong>List, </strong><strong>Map, or another </strong><strong>Object, you must implement a Deep Copy to keep your prototypes independent.</strong>&quot;</p><pre>// Inside Student Copy Constructor<br>this.subjects = new ArrayList&lt;&gt;(student.subjects); // New memory allocated!</pre><p><strong>Have you used the Registry pattern in your projects? Let’s talk about it in the comments!</strong></p><p>#Java #DesignPatterns #SoftwareArchitecture #CodingTips #Cloning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dd8b5e25386" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Builder Design Pattern: From “Constructor Chaos” to Clean Code ️]]></title>
            <link>https://medium.com/@kathulasnigdha2k/the-builder-design-pattern-from-constructor-chaos-to-clean-code-%EF%B8%8F-c7a469437bf1?source=rss-a19c259eb288------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7a469437bf1</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[builder-design-pattern]]></category>
            <dc:creator><![CDATA[Snigdhaa Katthula]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 06:12:53 GMT</pubDate>
            <atom:updated>2026-01-05T06:12:53.383Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Builder Design Pattern 🏗️</h3><p>If you’ve ever looked at a line of Java code and seen new User(&quot;John&quot;, &quot;Doe&quot;, &quot;Email&quot;, true, false, true, 25, null), you know the feeling of <strong>Constructor Chaos</strong>. Which true is for the newsletter? Is 25 the age or the street number?</p><p>In this post, we’re breaking down the <strong>Builder Design Pattern</strong> — the ultimate solution for creating complex objects without losing your sanity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ds-scCm_EQPJCjVg3vIzAA.png" /><figcaption><em>The constructor with lots of parameters has its downside: not all the parameters are needed at all times.</em></figcaption></figure><h3>1. What is the Builder Design Pattern?</h3><p>The Builder is a <strong>Creational Pattern</strong> that lets you construct complex objects step-by-step. Think of it like a custom sandwich shop: instead of choosing from 50 pre-made sandwiches, you tell the builder exactly what bread, meat, and toppings you want, and only then is the sandwich “built.”</p><h3>2. What Real-World Problem does it solve?</h3><p>It solves the <strong>“Telescoping Constructor”</strong> problem. This happens when a class has many optional parameters, forcing you to create multiple constructors:</p><ul><li>User(name, email)</li><li>User(name, email, age)</li><li>User(name, email, age, phone)</li></ul><p>This is a maintenance nightmare. The Builder pattern replaces this with a readable, fluent interface where you only set what you need.</p><h3>3. Implementing the Builder in Java</h3><p>Let’s look at a <strong>Laptop</strong> configuration example. A Laptop <em>must</em> have a CPU and RAM, but things like a Graphics Card or Bluetooth are optional.</p><h4>The Implementation</h4><p>We use a <strong>Static Inner Class</strong> for the Builder. This keeps the construction logic tightly coupled with the class it’s building.</p><pre>package builder;<br><br>public class Laptop {<br>    private String ram;<br>    private String cpu;<br>    private boolean isGraphicEnabled;<br>    private boolean isBluetoothEnabled;<br>    <br>    private Laptop(LaptopBuilder builder)<br>    {<br>        this.ram = builder.ram;<br>        this.cpu = builder.cpu;<br>    }<br>    // THIS IS USED, WHEN THERE ARE REQUIRED PARAMETERS<br>    private static LaptopBuilder getLaptopInstance(String ram, String cpu)<br>    {<br>        return new LaptopBuilder(ram, cpu);<br>    }<br>    // THIS IS USED, WHEN THERE IS NO REQUIRED PARAMETERS<br>    private static LaptopBuilder getLaptopInstance()<br>    {<br>        return new LaptopBuilder();<br>    }<br>    private static class LaptopBuilder<br>    {<br>        private String ram;<br>        private String cpu;<br>        private boolean isGraphicEnabled;<br>        private boolean isBluetoothEnabled;<br>        private LaptopBuilder()<br>        {<br>        }<br><br>        private LaptopBuilder(String ram, String cpu)<br>        {<br>            this.ram = ram;<br>            this.cpu = cpu;<br>        }<br>        private LaptopBuilder isGraphicEnabled(boolean enabled)<br>        {<br>            this.isGraphicEnabled = enabled;<br>            return this;<br><br>        }<br>        private LaptopBuilder isBluetoothEnabled(boolean enabled)<br>        {<br>            this.isBluetoothEnabled = enabled;<br>            return this;<br>        }<br>        private Laptop build(){<br>            // if there are any validations. validate it here<br>            return new Laptop(this);<br>        }<br>    }<br><br>    public String getRam() {<br>        return ram;<br>    }<br><br>    public String getCpu() {<br>        return cpu;<br>    }<br><br>    public boolean isGraphicEnabled() {<br>        return isGraphicEnabled;<br>    }<br><br>    public boolean isBluetoothEnabled() {<br>        return isBluetoothEnabled;<br>    }<br><br>    static void main() {<br>        // THIS IS HOW IT WILL BE, WHEN THERE IS REQUIRED PARAMETERS<br>        Laptop laptop = Laptop.getLaptopInstance(&quot;16GB&quot;, &quot;i3&quot;).isGraphicEnabled(true).isBluetoothEnabled(true).build();<br>        // THIS IS HOW IT WILL BE, WHEN THERE IS NO REQUIRED PARAMETERS<br>        Laptop laptop1 = Laptop.getLaptopInstance().isGraphicEnabled(true).isBluetoothEnabled(true).build();<br>    }<br>}</pre><h4>The Result: Fluent and Readable</h4><pre>public class Main {<br>    public static void main(String[] args) {<br>    <br>        // THIS IS HOW IT WILL BE, WHEN THERE IS REQUIRED PARAMETERS<br>        Laptop laptop = Laptop.getLaptopInstance(&quot;16GB&quot;, &quot;i3&quot;).isGraphicEnabled(true).isBluetoothEnabled(true).build();<br>        // THIS IS HOW IT WILL BE, WHEN THERE IS NO REQUIRED PARAMETERS<br>        Laptop laptop1 = Laptop.getLaptopInstance().isGraphicEnabled(true).isBluetoothEnabled(true).build();<br>    }<br>}</pre><h3>4. When should you use it?</h3><ul><li><strong>When there are many parameters:</strong> If your constructor has more than 3 or 4 arguments.</li><li><strong>When you want Immutability:</strong> Notice our Laptop class has no setters. Once it&#39;s built, it&#39;s &quot;frozen,&quot; which is great for thread safety.</li><li><strong>When you need Validation:</strong> You can ensure the object is “legal” (e.g., has a CPU) before it is ever instantiated.</li></ul><h3>5. Do we need this in Python or TypeScript?</h3><p>Short answer: <strong>Usually, no.</strong></p><p>Modern languages like Python and TypeScript have built-in features that solve the same problem more simply.</p><ul><li><strong>Python</strong> uses <strong>Named Arguments</strong>: Laptop(cpu=&quot;i9&quot;, ram=&quot;32GB&quot;, gpu=True)</li><li><strong>TypeScript</strong> uses <strong>Object Destructuring</strong>: new Laptop({ cpu: &quot;i9&quot;, ram: &quot;32GB&quot;, gpu: true })</li></ul><p>In these languages, a formal “Builder Class” is often considered over-engineering unless the construction logic is incredibly complex (e.g., involving network calls or multi-step calculations).</p><h3>Final Thoughts</h3><p>The Builder pattern turns messy, unreadable constructors into a clean, “fluent” API. It’s a staple in Java frameworks like <strong>Lombok</strong> (via @Builder) and is a skill every senior dev should have in their toolkit.</p><p><strong>Have you ever been bitten by a “Telescoping Constructor”? Let’s chat in the comments!</strong></p><p>#Java #SoftwareEngineering #DesignPatterns #CleanCode #Programming</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7a469437bf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop writing broken Singletons. (Yes, yours might be broken too.) ☕️]]></title>
            <link>https://medium.com/@kathulasnigdha2k/stop-writing-broken-singletons-yes-yours-might-be-broken-too-%EF%B8%8F-77fba23e6604?source=rss-a19c259eb288------2</link>
            <guid isPermaLink="false">https://medium.com/p/77fba23e6604</guid>
            <category><![CDATA[volatile]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[singleton-design-pattern]]></category>
            <dc:creator><![CDATA[Snigdhaa Katthula]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 09:40:08 GMT</pubDate>
            <atom:updated>2026-01-02T09:40:08.067Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve all written the “Double-Checked Locking” Singleton. It’s a classic interview question. But there’s a massive hidden trap that most devs miss: <strong>The missing </strong><strong>volatile keyword.</strong></p><p>Without it, your “<strong>thread-safe</strong>” code is actually a ticking time bomb.</p><h4>❌ The “I forgot volatile” version</h4><pre>public class Database {<br>    private static Database instance = null; // ❌ The bug is right here.<br>    public static Database getInstance() {<br>            if (instance == null) {<br>                synchronized (Database.class) {<br>                    if (instance == null) {<br>                        instance = new Database(); <br>                    }<br>                }<br>            }<br>            return instance;<br>        }<br>}</pre><p><strong>Why this fails:</strong> Because of CPU “Instruction Reordering,” Thread A can assign a memory address to instance <em>before</em> the constructor actually finishes. If Thread B walks in at that exact microsecond, it sees a non-null object, tries to use it, and—<strong>BOOM</strong>—NullPointerException or corrupted data.</p><h4>✅ The “Production-Ready” Class</h4><pre>public class Database {<br>    private static volatile Database instance = null; // ✅ Volatile is the fix.<br>    public static Database getInstance() {<br>            if (instance == null) {<br>                synchronized (Database.class) {<br>                    if (instance == null) {<br>                        instance = new Database();<br>                    }<br>                }<br>            }<br>            return instance;<br>        }<br>}</pre><p><strong>The fix:</strong> volatile creates a &quot;memory barrier.&quot; It forces the JVM to finish the constructor completely before letting any other thread touch that variable.</p><h4>🏆 The Real Winner: The Enum Singleton</h4><p>If you don’t need to extend a parent class, <strong>just use an Enum.</strong> It’s cleaner, safer, and basically “hacker-proof.”</p><pre>public enum Database {<br>    INSTANCE;<br>    public void connect() {<br>        System.out.println(&quot;Zero boilerplate. 100% thread-safe.&quot;);<br>    }<br>}</pre><p><strong>Why I prefer this:</strong> * No synchronized blocks to mess up.</p><ul><li>It’s naturally protected against Reflection attacks.</li><li>The JVM handles all the complex threading logic for you.</li></ul><h4>💡 Quick Summary:</h4><ul><li><strong>Use the Class version</strong> ONLY if you need inheritance (extending another class).</li><li><strong>Use the Enum version</strong> for everything else. It’s the industry standard for a reason.</li></ul><p>Ever had a Singleton fail on you in production? Drop a comment below. 👇</p><p>#Java #Backend #SoftwareEngineering #Concurrency</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77fba23e6604" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>