<?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 Thalzihthelu on Medium]]></title>
        <description><![CDATA[Stories by Thalzihthelu on Medium]]></description>
        <link>https://medium.com/@thalzihthelu?source=rss-840c627b2d96------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mmy3u663yBz1vQX3</url>
            <title>Stories by Thalzihthelu on Medium</title>
            <link>https://medium.com/@thalzihthelu?source=rss-840c627b2d96------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:39:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thalzihthelu/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[What is the auto Keyword in C++? A Beginner's Guide]]></title>
            <link>https://medium.com/@thalzihthelu/what-is-the-auto-keyword-in-c-a-beginners-guide-d6f424188e34?source=rss-840c627b2d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6f424188e34</guid>
            <dc:creator><![CDATA[Thalzihthelu]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 13:14:02 GMT</pubDate>
            <atom:updated>2026-07-17T13:14:02.721Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever stared at a C++ variable declaration and thought <em>“do I really need to spell out the full type every single time?”</em> — good news. The auto keyword was made for exactly that feeling.</p><p>Let’s break it down using a simple, real example.</p><h3>The Code We’re Working With</h3><pre>#include &lt;iostream&gt;<br>#include &lt;typeinfo&gt;<br>using namespace std;</pre><pre>class Base {};</pre><pre>int main()<br>{<br>    auto x = 20;<br>    auto y = 20.5;<br>    auto b = new Base();</pre><pre>    cout &lt;&lt; typeid(x).name() &lt;&lt; endl;<br>    cout &lt;&lt; typeid(y).name() &lt;&lt; endl;<br>    cout &lt;&lt; typeid(b).name() &lt;&lt; endl;</pre><pre>    return 0;<br>}</pre><p>Three variables. Three uses of auto. And three different types — all figured out by the compiler, not by you.</p><p>Let’s walk through each one.</p><h3>Line 1: auto x = 20;</h3><p>When you write 20 in C++, the compiler sees it as a plain integer. So when you say auto x = 20;, the compiler thinks:</p><blockquote><em>“The right-hand side is an integer literal. So </em><em>x must be an </em><em>int.&quot;</em></blockquote><p>Simple as that. No guessing. No ambiguity.</p><pre>auto x = 20;   // same as: int x = 20;</pre><h3>Line 2: auto y = 20.5;</h3><p>Now we have a decimal number. In C++, a literal like 20.5 is treated as a double by default.</p><p>So the compiler deduces:</p><pre>auto y = 20.5;   // same as: double y = 20.5;</pre><p>If you had written 20.5f instead, it would have been a float. The suffix matters. But without it, you get double every time.</p><h3>Line 3: auto b = new Base();</h3><p>This one’s slightly different. new Base() allocates a Base object on the heap and returns a <strong>pointer</strong> to it.</p><p>So auto doesn&#39;t deduce Base — it deduces Base* (a pointer to Base):</p><pre>auto b = new Base();   // same as: Base* b = new Base();</pre><p>This is a handy reminder: auto always deduces exactly what the right-hand side produces. If the expression returns a pointer, you get a pointer.</p><h3>How Do We Verify This? Enter typeid</h3><p>The code uses typeid(x).name() to print the actual type the compiler assigned. Think of it as asking the compiler: <em>&quot;Hey, what did you actually make this variable?&quot;</em></p><pre>cout &lt;&lt; typeid(x).name() &lt;&lt; endl;   // i     → int<br>cout &lt;&lt; typeid(y).name() &lt;&lt; endl;   // d     → double<br>cout &lt;&lt; typeid(b).name() &lt;&lt; endl;   // P4Base → pointer to Base</pre><p>A quick heads up: the names you see are <strong>compiler-specific</strong>. On GCC/Clang:</p><ul><li>i = int</li><li>d = double</li><li>P4Base = pointer to a class named &quot;Base&quot; (4 characters long)</li></ul><p>It’s a little cryptic, but it confirms what the compiler deduced. Super useful for learning and debugging.</p><h3>So Why Use auto At All?</h3><p>The honest answer: it saves you from repetition, especially when types get long and ugly.</p><p>Compare these two:</p><pre>// Without auto<br>std::map&lt;std::string, std::vector&lt;int&gt;&gt;::iterator it = myMap.begin();</pre><pre>// With auto<br>auto it = myMap.begin();</pre><p>Same thing. Way less noise.</p><p>For simple types like int and double, the gain is smaller — but it&#39;s still a good habit, especially in modern C++ code.</p><h3>The One Thing to Remember</h3><p>auto doesn&#39;t mean &quot;no type.&quot; It means <strong>&quot;figure out the type for me.&quot;</strong> The type is still there — fixed at compile time — you just didn&#39;t have to write it yourself.</p><pre>auto x = 20;     // x is an int. Forever. You can&#39;t later assign &quot;hello&quot; to it.</pre><p>This is not Python or JavaScript. C++ is still strongly typed. auto just lets the compiler do the spelling for you.</p><h3>Wrapping Up</h3><p>Here’s the quick summary of what we learned from those three lines:</p><p>Variable Value Deduced Type x 20 int y 20.5 double b new Base() Base*</p><p>The auto keyword was introduced in C++11 and has been a staple of modern C++ ever since. Once you get comfortable with it, you&#39;ll wonder how you ever lived without it.</p><p><em>Got questions or ran into something unexpected with </em><em>auto? Drop it in the comments — let&#39;s figure it out together.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6f424188e34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can You Call a Constructor and Destructor Manually in C++?]]></title>
            <link>https://medium.com/@thalzihthelu/can-you-call-a-constructor-and-destructor-manually-in-c-5d104e6ab9b7?source=rss-840c627b2d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d104e6ab9b7</guid>
            <dc:creator><![CDATA[Thalzihthelu]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 14:41:40 GMT</pubDate>
            <atom:updated>2026-07-16T14:41:40.896Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One of those C++ interview questions that sounds absurd until you realize the answer reveals something deep about how object lifetime actually works.</em></p><p>A CppNuts video I was watching recently opened with this question:</p><blockquote><em>“Is it possible to call a constructor and destructor by yourself?”</em></blockquote><p>My first instinct was: <em>no, that’s the compiler’s job.</em> Then I thought about it for two more seconds and changed my answer. Then I actually ran the code and changed it again.</p><p>This is exactly the kind of question that separates people who’ve used C++ from people who understand it.</p><h3>The Setup</h3><p>Here’s the code from the video:</p><pre>#include &lt;iostream&gt;<br>using namespace std;</pre><pre>class Base {<br>    int _baseVariable;<br>public:<br>    Base()  { cout &lt;&lt; &quot;Base Constructor&quot;  &lt;&lt; endl; }<br>    ~Base() { cout &lt;&lt; &quot;Base Destructor&quot;   &lt;&lt; endl; }<br>};</pre><pre>int main() {<br>    Base obj;           // line 15 — normal construction</pre><pre>    Base().~Base();     // line 17 — what does this actually do?<br>}</pre><p>Before reading ahead — what do you think the output is?</p><h3>What Most People Say</h3><p>Most people say one of two things:</p><p><strong>“It won’t compile.”</strong> — Wrong. It compiles cleanly.</p><p><strong>“It’ll print Constructor and Destructor once each, then crash.”</strong> — Closer, but still wrong on the details.</p><h3>What Actually Happens</h3><p>Let’s trace through it:</p><p><strong>Line 15: </strong><strong>Base obj;</strong> Standard stack allocation. Constructor fires. obj lives until the closing } of main.</p><p><strong>Line 17: </strong><strong>Base().~Base();</strong></p><p>This is two operations chained together:</p><ol><li>Base() — creates a <strong>temporary</strong> Base object. The constructor fires.</li><li>.~Base() — explicitly calls the destructor <strong>on that temporary</strong>.</li></ol><p>The temporary then goes out of scope at the semicolon, and the compiler calls the destructor <em>again</em> — automatically, because that’s what it does for temporaries.</p><p>So the output is:</p><pre>Base Constructor    ← obj on line 15<br>Base Constructor    ← temporary on line 17<br>Base Destructor     ← explicit ~Base() call on the temporary<br>Base Destructor     ← compiler auto-destructs the temporary (again)<br>Base Destructor     ← compiler auto-destructs obj at end of main</pre><p>That’s <strong>two constructors and three destructor calls</strong> from five lines of code.</p><h3>So Yes, You Can Call the Destructor Explicitly</h3><pre>Base().~Base();</pre><p>This is legal C++. The explicit destructor call syntax obj.~ClassName() has been in the standard since C++98. Most developers never write it by hand — but it&#39;s there, and it has a real use case.</p><p>The more interesting question is: <strong>why would you ever need to do this?</strong></p><h3>The Real-World Case: Placement New</h3><p>The only legitimate reason to explicitly call a destructor is when you’re managing memory manually with <strong>placement new</strong> — where you construct an object into a pre-allocated buffer you own:</p><pre>alignas(Base) char buffer[sizeof(Base)];</pre><pre>Base* p = new (buffer) Base;   // construct into buffer — constructor fires</pre><pre>// ... use p ...</pre><pre>p-&gt;~Base();   // explicitly destroy — destructor fires, but memory not freed<br>              // because we own the buffer, not the heap</pre><p>Here the destructor call is <em>necessary</em> — there’s no other way to run cleanup on an object whose lifetime you’ve manually controlled. delete p would be wrong because buffer isn&#39;t heap memory. p-&gt;~Base() is exactly right.</p><p>This pattern shows up in:</p><ul><li>Custom allocators and memory pools</li><li>std::optional and std::variant internals (both manage object lifetime over raw storage)</li><li>Lock-free data structures</li><li>Embedded systems where heap allocation is forbidden</li></ul><h3>The Danger: Double Destruction</h3><p>The example from the video isn’t just a quirk — it’s a genuine footgun. When you explicitly call a destructor on an object that the compiler is <em>also</em> going to destroy automatically, you get <strong>undefined behavior</strong>:</p><pre>Base obj;<br>obj.~Base();    // explicit call<br>// end of scope — compiler calls ~Base() again<br>// UB: destructor called twice on the same object</pre><p>For a toy class that just prints a string, you won’t see a crash. For a class that manages heap memory or a file handle, you’ll free memory that’s already been freed, or close a file descriptor that’s already been closed, and the behavior from that point forward is undefined.</p><p>This is why the rule is strict: <strong>only call the destructor explicitly if you constructed the object with placement new, and you’re certain the compiler won’t also call it.</strong></p><h3>What This Question Is Actually Testing</h3><p>On the surface it’s testing obscure syntax. But the real thing being probed is whether you understand <strong>object lifetime as a separate concern from memory</strong>. Most C++ developers conflate the two — “destroying an object” and “freeing memory” feel like the same thing because new/delete do both at once. Placement new breaks that coupling deliberately, and explicit destructor calls are the direct consequence of that separation.</p><p>If you can explain that clearly in an interview — and connect it to where the pattern genuinely appears (std::optional, allocators, embedded systems) — you&#39;re telling the interviewer something they actually care about: that you&#39;ve thought about C++ at the level where memory and lifetime are distinct problems.</p><h3>The One-Line Summary</h3><p>Yes, you can call a destructor explicitly — obj.~ClassName() — and yes, Base() creates a temporary you can call it on. The pattern is legal but dangerous unless you&#39;re using placement new, where it&#39;s not just legal but necessary.</p><p>The constructor call, incidentally, is less interesting: Base() in line 17 creates a temporary, so you&#39;re not really &quot;calling the constructor manually&quot; — you&#39;re just constructing a new object the normal way, then destroying it in an unusual one.</p><p>That asymmetry is worth sitting with. Constructors are called by the compiler on your behalf every time an object comes into existence. Destructors can be called explicitly — but only in the narrow window where you’ve taken full ownership of the object’s lifetime away from the compiler. Once you hand that ownership back, you’d better have already cleaned up.</p><p><em>Spotted something I got wrong, or have a use case for explicit destructor calls I didn’t cover? Drop it in the comments — the edge cases here are where it gets genuinely interesting.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d104e6ab9b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Designed a Food Delivery App Wrong Three Times Before It Clicked]]></title>
            <link>https://medium.com/@thalzihthelu/i-designed-a-food-delivery-app-wrong-three-times-before-it-clicked-6ee56eb34c71?source=rss-840c627b2d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ee56eb34c71</guid>
            <dc:creator><![CDATA[Thalzihthelu]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 19:28:27 GMT</pubDate>
            <atom:updated>2026-07-15T19:28:27.073Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What building “Tomato” — a Zomato/Swiggy-style LLD — taught me about the difference between code that works and code that survives contact with a real feature request.</em></p><p>The prompt looks harmless the first time you read it:</p><blockquote><em>“Design a food delivery application. Users browse restaurants, add items to a cart, place an order, pay, get notified.”</em></blockquote><p>I sat down and wrote a version that compiled, ran, and technically did everything asked. Then I imagined a product manager walking in and asking for one more feature — and watched my own design fall apart in my head, three separate times, before I had something that could actually take a hit.</p><p>Here’s the trail of mistakes, because the mistakes are the actual lesson.</p><h3>Mistake #1: I hardcoded payment methods</h3><p>First pass, Order looked like this:</p><pre>class Order {<br>    int id;<br>    User user;<br>    Restaurant* rest;<br>    vector&lt;MenuItem&gt; items;</pre><pre>    void pay(string method) {<br>        if (method == &quot;CREDIT_CARD&quot;) { /* charge card */ }<br>        else if (method == &quot;UPI&quot;) { /* charge UPI */ }<br>        else if (method == &quot;NETBANKING&quot;) { /* charge netbanking */ }<br>    }<br>};</pre><p>It works. Then I imagined the actual follow-up every interviewer asks: <em>“Now add wallet payments.”</em></p><p>To do that, I’d have to open Order, find the pay() method, and add a fourth branch — inside a class that&#39;s already responsible for holding order data. Every future payment method means editing code that&#39;s already shipped and already working. That&#39;s not a hypothetical risk, that&#39;s a guaranteed regression waiting to happen, because the one thing you never want to touch casually is a function three other payment types depend on.</p><p><strong>The fix</strong> was to stop treating “how do I pay” as a string and start treating it as a <em>behavior</em> — pulled out into its own interface:</p><pre>class IPaymentStrategy {<br>public:<br>    virtual void pay() = 0;<br>};</pre><pre>class CreditCard : public IPaymentStrategy { void pay() override { /* ... */ } };<br>class NetBanking : public IPaymentStrategy { void pay() override { /* ... */ } };<br>class UPI        : public IPaymentStrategy { void pay() override { /* ... */ } };</pre><p>Order now just holds a reference to whichever strategy the user picked:</p><pre>class Order {<br>    PaymentStrategy strategy;<br>    // ...<br>};</pre><p>Adding Wallet payments later is one new class. Order never changes again. This is the <strong>Strategy pattern</strong>, and the tell that you need it isn&#39;t &quot;this looks like a design pattern I should use&quot; — it&#39;s &quot;I just imagined the next feature request and it made me nervous about a class that already works.&quot;</p><h3>Mistake #2: I made “placing an order” a single rigid path</h3><p>Second pass, I had one Order class and one way to create it — synchronously, right now, delivered to the user&#39;s saved address. Then I pictured a second real feature: <em>&quot;users want to schedule an order for 7 PM&quot;</em> and a third: <em>&quot;users want to pick up in person instead of delivery.&quot;</em></p><p>Suddenly “create an order” isn’t one operation, it’s a combination of <strong>two independent decisions</strong> — <em>when</em> (now vs. scheduled) and <em>how</em> (delivery vs. pickup) — and I’d built a class that assumed both were fixed. Bolting scheduling on top would have meant a bool isScheduled flag and a bool isPickup flag scattered through the same class, with conditional logic multiplying every time either dimension grew. That&#39;s the kind of code where nobody wants to be the one who touches it six months later.</p><p><strong>The fix</strong> was to split the two decisions into two separate hierarchies instead of cramming both into one class with flags.</p><p><em>When</em> is a factory’s job:</p><pre>class IOrderFactory {<br>public:<br>    virtual Order* createOrder(string type) = 0;<br>};</pre><pre>class NowOrderFactory : public IOrderFactory {<br>    Order* createOrder(string type) override { /* build immediately */ }<br>};</pre><pre>class ScheduleOrderFactory : public IOrderFactory {<br>    string scheduleTime;<br>    Order* createOrder(string type) override { /* build for later */ }<br>};</pre><p><em>How</em> is an inheritance hierarchy:</p><pre>class Order {<br>    int id;<br>    User user;<br>    Restaurant* rest;<br>    vector&lt;MenuItem&gt; items;<br>    PaymentStrategy strategy;</pre><pre>    virtual string getType() = 0;<br>};</pre><pre>class DeliveryOrder : public Order {<br>    string address;<br>    string getType() override { return &quot;DELIVERY&quot;; }<br>};</pre><pre>class PickupOrder : public Order {<br>    string resAddress;<br>    string getType() override { return &quot;PICKUP&quot;; }<br>};</pre><p>Now “add curbside pickup” or “add recurring weekly orders” are each one new class, in one hierarchy, with zero ripple effect into the other. The lesson wasn’t “use a Factory” — it was noticing that I’d quietly merged two unrelated decisions into one class, and the flags were the symptom, not the disease.</p><h3>Mistake #3: I let every part of the system reach into restaurant data directly</h3><p>Third pass — smaller, but it’s the one that would’ve hurt most in production. My Cart and my ordering logic were both pulling restaurant data from wherever they felt like: a raw list passed around, queried and filtered inline. It worked in a single-user test. Then I asked myself the question that actually matters for anything shared: <em>&quot;what happens the moment two parts of the app need a consistent view of the same restaurant list at the same time?&quot;</em></p><p>Nothing enforced that there was only <strong>one</strong> canonical list of restaurants, or one canonical list of orders. Two components could each hold slightly stale copies, and nothing would ever tell you they’d drifted apart.</p><p><strong>The fix</strong>: a single owned, controlled access point for each — a Singleton, not because “Singleton is a pattern I should use,” but because the actual requirement was <em>one source of truth, one enforced access path</em>:</p><pre>class RestaurantManager {<br>private:<br>    static RestaurantManager* instance;<br>    vector&lt;Restaurant&gt; restaurants;<br>    RestaurantManager() {}</pre><pre>public:<br>    static RestaurantManager* getInstance();<br>    void addRestaurant(Restaurant r);<br>    vector&lt;Restaurant&gt; searchByLoc(string loc);<br>};</pre><p>OrderManager mirrors it for the order list. That&#39;s the whole justification for the pattern here — not &quot;singletons are good practice,&quot; but &quot;this specific piece of state has exactly one legitimate owner, and I want that enforced in code, not by convention.&quot;</p><h3>What was left standing</h3><p>By the third rewrite, the shape that survived looked like this end to end:</p><ol><li>User adds MenuItems to a Cart scoped to one Restaurant.</li><li>A Tomato facade — the one class the outside world actually calls — takes an order type and payment method.</li><li>The right IOrderFactory builds the right Order subtype.</li><li>The chosen IPaymentStrategy executes pay().</li><li>OrderManager registers it in the one canonical order list.</li><li>NotificationService fires notifyUser().</li></ol><p>Every one of those six steps had, at some point, been the <em>thing that broke</em> in an earlier draft. The patterns aren’t decoration on top of a working design — they’re what’s left after you’ve been burned by the same mistake enough times to stop making it.</p><h3>The actual takeaway</h3><p>None of this started with “which pattern should I use.” It started with imagining the next feature request and noticing which class got nervous. Strategy showed up because a pay() method didn&#39;t want to be edited again. Factory showed up because one class was quietly making two decisions at once. Singleton showed up because two parts of the system had no agreed-upon source of truth.</p><p>That’s the same instinct that matters outside of interview prep, too — the same reason you don’t hardcode a transport layer into a driver, or let two code paths independently own a piece of shared hardware state. The domain changes; the question doesn’t: <em>what’s about to change, and what does my current design make expensive when it does?</em></p><p><em>If you’ve hit a fourth mistake I didn’t — concurrent cart updates, order cancellation mid-flight, partial refunds — I’d genuinely like to hear where your design broke. That’s usually where the better lesson is.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ee56eb34c71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Observer Pattern: The Design Choice That Quietly Runs Your Entire App]]></title>
            <link>https://medium.com/@thalzihthelu/the-observer-pattern-the-design-choice-that-quietly-runs-your-entire-app-d96e02f4bcb9?source=rss-840c627b2d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/d96e02f4bcb9</guid>
            <dc:creator><![CDATA[Thalzihthelu]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 14:03:51 GMT</pubDate>
            <atom:updated>2026-07-15T14:03:51.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHGoKcCdAwnrxXxWI72okg.jpeg" /></figure><p>Every time you click “like” and a notification fires, every time a stock ticker updates three widgets at once, every time your phone’s battery icon changes and five different parts of the UI react — you’re watching the Observer pattern at work.</p><p>It’s one of the most useful patterns you’ll ever learn. It’s also one of the most <em>quietly dangerous</em> if you don’t understand what you’re trading away.</p><p>Most tutorials show you the diagram, hand you a notify() method, and call it a day. This article is different. I&#39;ll show you how it works, and then I&#39;ll be honest about the costs — because the Observer pattern doesn&#39;t just have benefits. It has a bill, and it comes due later, usually when you&#39;re debugging something at 2 AM.</p><h3>The Problem It Solves</h3><p>Imagine you’re building a weather station. A sensor reads the temperature. When it changes, you need to update:</p><ul><li>A display on screen</li><li>A logging system</li><li>An alert system that texts you if it’s freezing</li><li>A graph that plots history</li></ul><p>The naive approach:</p><pre>class WeatherSensor {<br>    Display display;<br>    Logger logger;<br>    AlertSystem alerts;<br>    Graph graph;</pre><pre>    void temperatureChanged(double newTemp) {<br>        display.update(newTemp);<br>        logger.update(newTemp);<br>        alerts.update(newTemp);<br>        graph.update(newTemp);<br>    }<br>};</pre><p>This works. Until it doesn’t.</p><p>Now your product manager wants to add a fifth thing that reacts to temperature. You open WeatherSensor and add a line. Then a sixth. Then someone wants the alert system removed for a specific customer. You&#39;re now editing your sensor class every single time anything <em>downstream</em> changes.</p><p>Your sensor knows about displays, loggers, graphs, and alerts. That’s four things it shouldn’t have to care about. It’s a temperature sensor. Its job is to read temperature — not to maintain a phonebook of everyone who’s interested.</p><p><strong>This is tight coupling, and it’s the exact problem the Observer pattern was invented to kill.</strong></p><h3>The Solution: Flip the Dependency</h3><p>The core idea is simple and a little bit magical:</p><blockquote><em>Instead of the sensor knowing about everyone who cares, everyone who cares </em>subscribes<em> to the sensor. The sensor just shouts “something changed!” into the void, and whoever signed up gets the message.</em></blockquote><p>The sensor no longer knows <em>who</em> is listening or <em>what</em> they do. It just keeps a list of subscribers and notifies them.</p><p>Here’s the structure, matching the UML:</p><h3>The two interfaces</h3><pre>// The thing being watched<br>class IObservable {<br>public:<br>    virtual void add(IObserver* o) = 0;<br>    virtual void remove(IObserver* o) = 0;<br>    virtual void notify() = 0;<br>    virtual ~IObservable() = default;<br>};</pre><pre>// The thing doing the watching<br>class IObserver {<br>public:<br>    virtual void update() = 0;<br>    virtual ~IObserver() = default;<br>};</pre><h3>The concrete subject</h3><pre>class ConcreteObservable : public IObservable {<br>    std::vector&lt;IObserver*&gt; observers;   // the subscriber list<br>    double temperature;</pre><pre>public:<br>    void add(IObserver* o) override {<br>        observers.push_back(o);<br>    }</pre><pre>    void remove(IObserver* o) override {<br>        observers.erase(<br>            std::remove(observers.begin(), observers.end(), o),<br>            observers.end()<br>        );<br>    }</pre><pre>    void notify() override {<br>        for (IObserver* o : observers) {<br>            o-&gt;update();     // shout to everyone<br>        }<br>    }</pre><pre>    void setTemperature(double t) {<br>        temperature = t;<br>        notify();            // state changed → tell the world<br>    }</pre><pre>    double getTemperature() const { return temperature; }<br>};</pre><h3>A concrete observer</h3><pre>class Display : public IObserver {<br>    ConcreteObservable* subject;   // &quot;has a&quot; reference back</pre><pre>public:<br>    Display(ConcreteObservable* s) : subject(s) {<br>        subject-&gt;add(this);        // subscribe on construction<br>    }</pre><pre>    void update() override {<br>        std::cout &lt;&lt; &quot;Display: &quot; &lt;&lt; subject-&gt;getTemperature() &lt;&lt; &quot;\n&quot;;<br>    }<br>};</pre><p>Now look at what happened to the sensor: <strong>it has no idea </strong><strong>Display exists.</strong> You can add a Logger, an AlertSystem, a Graph — the sensor code never changes. That&#39;s the payoff.</p><p>Notice the two “has a” relationships from the diagram:</p><ul><li>The <strong>observable has a</strong> list of observers (1..* — one subject, many observers).</li><li>Each <strong>observer has a</strong> reference back to the subject, so it can pull the data it needs when notified.</li></ul><h3>Now the Honest Part: The Trade-offs</h3><p>Here’s where most articles stop. But the Observer pattern is a <em>deal you make</em>, and every deal has terms. Let me walk through what you’re actually signing up for.</p><h3>Trade-off 1: Loose Coupling vs. Losing the Thread</h3><p><strong>What you gain:</strong> The subject and observers are decoupled. You can add, remove, or change observers without ever touching the subject. This is genuinely powerful — it’s the whole reason the pattern exists.</p><p><strong>What you lose:</strong> You can no longer read your code top-to-bottom and understand what happens.</p><p>With the naive version, temperatureChanged() literally lists everything that happens. It&#39;s ugly, but it&#39;s <em>honest</em> — you can see the whole chain.</p><p>With Observer, you call notify() and... something happens. To know what, you have to find every class that subscribed, which could be scattered across twenty files. The control flow is now <em>invisible</em>.</p><pre>subject-&gt;setTemperature(25.0);<br>// What just happened? Depends entirely on who subscribed at runtime.<br>// Could be nothing. Could be 15 side effects. You can&#39;t tell from here.</pre><p><strong>The real cost:</strong> Debugging. When a bug appears “somewhere in the reaction to a temperature change,” you can’t set one breakpoint and trace it. You’re hunting through a runtime graph you can’t see in the source. Loose coupling and traceability are in direct tension — you bought one with the other.</p><h3>Trade-off 2: Flexibility vs. The Lapsed Listener (Memory Leaks)</h3><p>This is the one that bites hardest, and it’s especially brutal in C++ or any language without garbage collection.</p><p><strong>What you gain:</strong> Observers can come and go dynamically at runtime. Total flexibility.</p><p><strong>What you lose:</strong> The subject holds a raw pointer to every observer. If an observer is destroyed but <em>forgets to unsubscribe</em>, the subject still holds a dangling pointer. The next notify() calls update() on freed memory — undefined behavior, crashes, or worse, silent corruption.</p><pre>{<br>    Display d(&amp;subject);   // subscribes<br>}   // d destroyed here — but did it unsubscribe?<br>    // subject.observers STILL contains a pointer to dead memory</pre><pre>subject.setTemperature(30.0);   // 💥 calls update() on a corpse</pre><p>Even in garbage-collected languages (Java, C#, JavaScript), this shows up as the <strong>lapsed listener problem</strong>: the subject holds a reference to the observer, so the garbage collector <em>can’t</em> collect it. The observer lives forever, invisibly, because something is still “listening.” You get a slow memory leak that’s maddening to find.</p><p><strong>The real cost:</strong> Lifetime management becomes <em>your</em> problem, forever. Every observer must reliably unsubscribe in its destructor (or dispose, or useEffect cleanup). Miss one, and you&#39;ve got a leak or a dangling pointer. This is the single most common Observer bug in production.</p><p><em>Mitigation:</em> use weak_ptr in C++, weak references in Java/C#, or explicit cleanup hooks. But note — that&#39;s <em>more</em> code, which chips away at the &quot;elegant and simple&quot; pitch.</p><h3>Trade-off 3: Automatic Updates vs. Unpredictable Cascades</h3><p><strong>What you gain:</strong> When state changes, everyone updates automatically. No manual wiring.</p><p><strong>What you lose:</strong> Control over <em>how much</em> happens and <em>how often</em>.</p><p>Two nasty variants:</p><p><strong>Update storms.</strong> If notify() runs synchronously and you have 500 observers, one state change blocks until all 500 finish their update(). If one observer is slow (writes to disk, hits the network), it stalls everyone. In a UI thread or an interrupt handler, this is a freeze.</p><p><strong>Cascading notifications.</strong> What if an observer, inside its update(), changes another subject, which notifies <em>its</em> observers, which change something else? You can trigger a chain reaction — sometimes an infinite loop:</p><pre>void update() override {<br>    // reacting to A&#39;s change, I modify B...<br>    otherSubject-&gt;setValue(x);<br>    // ...whose observers modify A again... 🔁<br>}</pre><p><strong>The real cost:</strong> The pattern makes it trivially easy to build a system where one small change fans out into hundreds of updates you never intended. Performance degrades non-obviously, and infinite loops hide in plain sight. Nothing in the pattern protects you from this — the discipline is on you.</p><h3>Trade-off 4: The Notification Order You Can’t Rely On</h3><p><strong>What you gain:</strong> You don’t have to think about ordering. Just subscribe.</p><p><strong>What you lose:</strong> Any guarantee about <em>who gets notified first</em>.</p><p>The notify() loop walks the observer list in whatever order they subscribed — which is usually accidental. If observer B secretly depends on observer A having already updated, your app works today and breaks tomorrow when subscription order shifts by one line.</p><p><strong>The real cost:</strong> Hidden ordering dependencies. These are some of the worst bugs to diagnose because the code is “correct” — it just runs in the wrong order, intermittently. The pattern actively <em>encourages</em> you not to think about ordering, which is exactly why the bug is so easy to introduce.</p><h3>Trade-off 5: Push vs. Pull (A Trade-off Inside the Trade-off)</h3><p>When the subject notifies, how does the observer get the data? Two options, each with a cost.</p><p><strong>Push model</strong> — the subject sends the data in the call: update(newTemperature).</p><ul><li>✅ Observer gets exactly what it needs, immediately.</li><li>❌ The subject has to guess what every observer wants. Add an observer that needs humidity too, and now you’re changing update()&#39;s signature — which touches <em>every</em> observer. Coupling creeps back in.</li></ul><p><strong>Pull model</strong> — the subject just says update(), and the observer calls back to fetch what it needs (this is what the diagram shows — observers hold a reference to the subject).</p><ul><li>✅ The subject stays dumb and generic. Observers grab only what they care about.</li><li>❌ More back-and-forth calls, and the observer needs a reference to the subject (tighter coupling in the other direction). Also risks the observer reading <em>stale or half-updated</em> state if timing is off.</li></ul><p><strong>The real cost:</strong> There’s no free lunch here. Push keeps observers simple but makes the subject rigid. Pull keeps the subject flexible but leaks the subject’s interface into every observer. You have to pick your poison based on how often each side changes.</p><h3>Trade-off 6: Thread Safety Isn’t Free</h3><p><strong>What you gain (on paper):</strong> A clean, decoupled architecture.</p><p><strong>What you lose (in reality, under concurrency):</strong> Safety, unless you add it yourself.</p><p>Picture one thread iterating the observer list inside notify() while another thread calls add() or remove(). You&#39;re now modifying a vector while iterating it — a classic crash or corruption.</p><pre>// Thread A<br>void notify() {<br>    for (auto* o : observers)   // iterating...<br>        o-&gt;update();<br>}</pre><pre>// Thread B (simultaneously)<br>subject.remove(someObserver);   // ...mutating the same vector 💥</pre><p><strong>The real cost:</strong> In any multithreaded system — which is most real systems — you have to add locking, copy-the-list-before-notifying, or use concurrent data structures. All of that adds complexity and can introduce deadlocks (imagine an observer’s update() trying to remove() itself while you hold the lock). The clean diagram says nothing about any of this, but production will demand it.</p><h3>So When Should You Actually Use It?</h3><p>Use the Observer pattern when:</p><ul><li><strong>One-to-many</strong> is the natural shape: one source of truth, many things that react.</li><li>The set of listeners <strong>changes at runtime</strong>, or you don’t know them at compile time.</li><li>You want the subject to stay <strong>ignorant of its consumers</strong> (libraries, frameworks, event systems).</li></ul><p>Classic great fits: UI event systems, reactive state (React, Vue, RxJS all <em>are</em> Observer under the hood), pub/sub messaging, model-view architectures, and — for the embedded crowd — dispatching to multiple callback handlers off a single hardware event.</p><p><strong>Think twice when:</strong></p><ul><li>There’s only <strong>one</strong> observer that never changes. Then you’re paying all the indirection cost for none of the flexibility — just call the method directly.</li><li><strong>Ordering between observers matters.</strong> The pattern fights you here.</li><li>You’re in a <strong>hard-real-time or tight-latency path</strong> where a synchronous notification loop could blow your timing budget.</li><li>The <strong>notification chains are deep.</strong> Cascades will haunt you; consider an explicit event queue instead.</li></ul><h3>The Honest Summary</h3><p>The Observer pattern trades <strong>explicit, traceable, tightly-coupled code</strong> for <strong>flexible, decoupled, but invisible-at-runtime code.</strong></p><p>That’s the deal. In one sentence:</p><blockquote><em>You make it easy to </em>add<em> behavior and hard to </em>trace<em> behavior.</em></blockquote><p>For a system where things react and change constantly, that’s a fantastic trade. For a simple, fixed pipeline of three fixed steps, it’s overkill that buys you nothing but debugging pain.</p><p>The pattern isn’t good or bad. It’s a <em>loan</em>. It gives you flexibility up front, and you pay it back in lifetime management, debugging difficulty, ordering fragility, and concurrency headaches. Whether that loan is worth it depends entirely on how much your requirements are going to change.</p><p>The best engineers I know don’t reach for Observer because it’s clever. They reach for it because they’ve priced the loan, and for <em>this</em> problem, the terms are good.</p><p><em>If you’ve been bitten by an Observer-pattern memory leak or a notification cascade you didn’t see coming — I’d love to hear the war story in the comments. Those bugs teach more than any tutorial.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d96e02f4bcb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Payment System That Won’t Break]]></title>
            <link>https://medium.com/@thalzihthelu/how-to-build-a-payment-system-that-wont-break-4cd2a2c0486f?source=rss-840c627b2d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cd2a2c0486f</guid>
            <dc:creator><![CDATA[Thalzihthelu]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 11:03:28 GMT</pubDate>
            <atom:updated>2026-07-14T11:03:28.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mpm-pou33SbvHHmyvn2obw.avif" /></figure><p>Let me tell you a story.</p><p>You’re a startup founder with a hot new app. Users love it. The money starts flowing in. You integrate Razorpay for payments — it works great, easy setup, good documentation.</p><p>Then one day, Razorpay has an outage. For 4 hours, your app can’t process payments. Revenue stops. Customer emails flood in. Your team scrambles.</p><p>The next week, your investors ask: <em>“Why are we completely dependent on one payment provider?”</em></p><p>You start searching your codebase for Razorpay references. It’s everywhere. Controllers, services, database queries — the whole system is baked around Razorpay. Switching to PayTM or Stripe would take weeks of refactoring.</p><p><strong>This is the story that leads developers to design patterns.</strong></p><p>Today, I’ll show you how to build a payment system that’s flexible, resilient, and actually enjoyable to maintain. No more late-night panics when a provider has issues.</p><h3>The Root Problem: Why Direct Integration Is a Trap</h3><p>Let’s say you start with the simplest possible approach:</p><pre>public class CheckoutPage {<br>    public void processPayment(double amount, String userEmail) {<br>        RazorpayClient client = new RazorpayClient(&quot;api_key&quot;);<br>        String paymentUrl = client.createPaymentLink(amount);<br>        sendEmailWithLink(userEmail, paymentUrl);<br>    }<br>}</pre><p>It works. Your first 1,000 users are happy.</p><p>But now imagine your business grows:</p><p><strong>Scenario 1: A VIP client wants to pay through PayTM instead of Razorpay</strong></p><ul><li>You add an if-statement: “if customer prefers PayTM…”</li><li>Now you have Razorpay code AND PayTM code in the same method</li><li>This method is getting messy</li></ul><p><strong>Scenario 2: Your payment volume grows, Razorpay fees become expensive</strong></p><ul><li>You want to use Stripe for international transactions</li><li>You add another if-statement</li><li>Now you’re juggling three different payment APIs in one place</li></ul><p><strong>Scenario 3: You’re adding a new feature — payment plans and subscriptions</strong></p><ul><li>Different gateways handle subscriptions differently</li><li>Your code becomes a maze of gateway-specific logic</li><li>A simple bug fix in one gateway’s section might break another</li></ul><p><strong>Scenario 4: You want to write tests for your payment logic</strong></p><ul><li>Can’t test without hitting actual Razorpay API</li><li>Tests are slow, unreliable, and cost money</li><li>Your test suite becomes a nightmare</li></ul><p>Sound familiar? This is why we need a better approach.</p><h3>The Solution: Separating Payment Logic from Gateway Details</h3><p>Here’s the core insight: <strong>Your business cares about “process a payment,” not about the specific gateway.</strong></p><p>Think of it like this: When you go to a restaurant, you don’t care if they use UberEats or Swiggy for delivery. You care that your food arrives hot. The delivery mechanism is an implementation detail.</p><p>We’re going to build the same separation in our code.</p><h3>The Design: Factory Pattern + Strategy Pattern</h3><p>Let me explain these patterns, but first: <strong>What’s a design pattern?</strong></p><p>A design pattern is a proven solution to a common problem. It’s like a recipe — not the exact ingredients for YOUR dish, but the proven steps that work for similar problems.</p><h3>What We’re Building</h3><pre>User clicks &quot;Pay Now&quot;<br>    ↓<br>PaymentController (receives the request)<br>    ↓<br>PaymentService (decides what to do)<br>    ↓<br>GatewayFactory (chooses which payment provider)<br>    ↓<br>Concrete Gateway (Razorpay/PayTM/Stripe)<br>    ↓<br>Payment Provider&#39;s API</pre><p>Let’s build this step by step, and I’ll explain the trade-offs at each stage.</p><h3>Step 1: The Request Object</h3><pre>public class PaymentRequest {<br>    private String sender;        // Who&#39;s paying<br>    private String receiver;      // Who receives money<br>    private double amount;        // How much<br>    private String currency;      // What currency</pre><pre>    public PaymentRequest(String sender, String receiver, <br>                         double amount, String currency) {<br>        this.sender = sender;<br>        this.receiver = receiver;<br>        this.amount = amount;<br>        this.currency = currency;<br>    }</pre><pre>    public String getSender() { return sender; }<br>    public String getReceiver() { return receiver; }<br>    public double getAmount() { return amount; }<br>    public String getCurrency() { return currency; }<br>}</pre><p><strong>Why this object?</strong></p><p>Instead of passing random parameters (processPayment(String api, double amount, int userId, String...)), we group everything into one structured object.</p><p><strong>Trade-off: Slight overhead for huge clarity</strong></p><ul><li>❌ One more class to maintain</li><li>✅ Anyone reading the code instantly knows what data is needed</li><li>✅ Easy to add new payment details without changing method signatures</li><li>✅ Can validate all payment data in one place</li></ul><h3>Step 2: The Gateway Interface (The Strategy Pattern)</h3><p>This is the most important part. Here’s the contract that every payment gateway MUST follow:</p><pre>public interface PaymentGateway {<br>    <br>    // Can we process this payment?<br>    boolean validatePayment(PaymentRequest request);<br>    <br>    // Start the payment<br>    PaymentResponse initiatePayment(PaymentRequest request);<br>    <br>    // Verify payment is complete<br>    void confirmPayment(String paymentId);<br>    <br>    // Give money back<br>    boolean refundPayment(String paymentId);<br>}</pre><p><strong>What’s happening here?</strong></p><p>We’re saying: <em>“If you’re a payment gateway, you MUST implement these four methods.”</em></p><p>This is called the <strong>Strategy Pattern</strong>. Each payment provider is a different “strategy” for accomplishing the same goal: processing a payment.</p><p><strong>Trade-off: Standardization vs. Gateway Flexibility</strong></p><p>❌ <strong>What we lose:</strong></p><ul><li>Razorpay might have unique features we can’t use (like their subscription plans)</li><li>We’re forcing all gateways into the same box</li><li>Some gateway features might not fit this interface</li></ul><p>✅ <strong>What we gain:</strong></p><ul><li>Can swap gateways without touching business logic</li><li>Same code works for Razorpay, PayTM, or Stripe</li><li>Easy to test with fake gateways</li><li>New developers instantly understand what a gateway must do</li></ul><p><strong>Real-world example of this trade-off:</strong> Razorpay supports “Route” (send payments to sub-accounts). Our interface doesn’t mention it. So if we want to use Route, we either add it to the interface (affecting all gateways) OR we leave it out and use Razorpay directly for that feature.</p><p><strong>Decision: Leave it out.</strong> The 90% of payments that are normal are more important than the 10% that need special features.</p><h3>Step 3: The Response Object</h3><pre>public class PaymentResponse {<br>    private String paymentId;<br>    private PaymentStatus status;<br>    private String message;<br>    private long timestamp;</pre><pre>    public enum PaymentStatus {<br>        INITIATED,    // We started the process<br>        PENDING,      // Waiting for confirmation<br>        SUCCESS,      // Money transferred<br>        FAILED,       // Something went wrong<br>        CANCELLED     // User canceled<br>    }</pre><pre>    public PaymentResponse(String paymentId, PaymentStatus status, String message) {<br>        this.paymentId = paymentId;<br>        this.status = status;<br>        this.message = message;<br>        this.timestamp = System.currentTimeMillis();<br>    }<br>}</pre><p><strong>Why standardize the response?</strong></p><p>Different gateways return data in different formats. Razorpay returns JSON, a direct bank API might return XML. We’re translating everything into one common format.</p><p><strong>Trade-off: Losing Gateway-Specific Details</strong></p><p>❌ <strong>What we lose:</strong></p><ul><li>Razorpay returns a short_url for the payment link</li><li>Our PaymentResponse only has generic fields</li><li>We might lose fine-grained error codes</li></ul><p>✅ <strong>What we gain:</strong></p><ul><li>UI code works the same way for all gateways</li><li>Don’t need to write 3 different response handlers</li><li>Easy to log and track payments consistently</li></ul><p><strong>Real-world analogy:</strong> Your restaurant kitchen doesn’t care if the order came from Uber, Swiggy, or your phone. They all get standardized in the same order format. The delivery platform details are hidden.</p><h3>Step 4: Implementing Concrete Gateways</h3><p>Now here’s where each payment provider gets its own class:</p><h3>Razorpay Gateway</h3><pre>public class RazorPayGateway implements PaymentGateway {<br>    <br>    private static final String API_KEY = &quot;your_razorpay_key&quot;;</pre><pre>    @Override<br>    public boolean validatePayment(PaymentRequest request) {<br>        // Razorpay rules:<br>        // - Amount between 1 paise and 10 crore<br>        // - Only INR, USD, EUR<br>        <br>        if (request.getAmount() &lt;= 0 || request.getAmount() &gt; 10000000) {<br>            return false;<br>        }<br>        <br>        if (!request.getCurrency().matches(&quot;INR|USD|EUR&quot;)) {<br>            return false;<br>        }<br>        <br>        return true;<br>    }</pre><pre>    @Override<br>    public PaymentResponse initiatePayment(PaymentRequest request) {<br>        try {<br>            // Call Razorpay&#39;s actual API<br>            String paymentId = callRazorpayAPI(request);<br>            <br>            return new PaymentResponse(<br>                paymentId, <br>                PaymentResponse.PaymentStatus.INITIATED,<br>                &quot;Razorpay payment started&quot;<br>            );<br>        } catch (Exception e) {<br>            return new PaymentResponse(<br>                null, <br>                PaymentResponse.PaymentStatus.FAILED,<br>                &quot;Razorpay error: &quot; + e.getMessage()<br>            );<br>        }<br>    }</pre><pre>    @Override<br>    public void confirmPayment(String paymentId) {<br>        System.out.println(&quot;Confirming Razorpay payment: &quot; + paymentId);<br>    }</pre><pre>    @Override<br>    public boolean refundPayment(String paymentId) {<br>        try {<br>            callRazorpayRefundAPI(paymentId);<br>            return true;<br>        } catch (Exception e) {<br>            return false;<br>        }<br>    }</pre><pre>    // These are the gateway-specific API calls<br>    private String callRazorpayAPI(PaymentRequest request) {<br>        // In real code, this would use Razorpay SDK<br>        return &quot;razorpay_&quot; + System.currentTimeMillis();<br>    }</pre><pre>    private void callRazorpayRefundAPI(String paymentId) {<br>        // Real refund call here<br>        System.out.println(&quot;Razorpay refund for: &quot; + paymentId);<br>    }<br>}</pre><h3>PayTM Gateway (Different rules, same interface)</h3><pre>public class PayTMGateway implements PaymentGateway {<br>    <br>    @Override<br>    public boolean validatePayment(PaymentRequest request) {<br>        // PayTM has different rules:<br>        // - Minimum 100, maximum 50 lakh<br>        // - Only INR<br>        <br>        if (request.getAmount() &lt; 100 || request.getAmount() &gt; 5000000) {<br>            return false;<br>        }<br>        return &quot;INR&quot;.equals(request.getCurrency());<br>    }</pre><pre>    @Override<br>    public PaymentResponse initiatePayment(PaymentRequest request) {<br>        try {<br>            String paymentId = callPayTMAPI(request);<br>            return new PaymentResponse(<br>                paymentId,<br>                PaymentResponse.PaymentStatus.INITIATED,<br>                &quot;PayTM payment started&quot;<br>            );<br>        } catch (Exception e) {<br>            return new PaymentResponse(<br>                null,<br>                PaymentResponse.PaymentStatus.FAILED,<br>                &quot;PayTM error: &quot; + e.getMessage()<br>            );<br>        }<br>    }</pre><pre>    @Override<br>    public void confirmPayment(String paymentId) {<br>        System.out.println(&quot;Confirming PayTM payment: &quot; + paymentId);<br>    }</pre><pre>    @Override<br>    public boolean refundPayment(String paymentId) {<br>        try {<br>            callPayTMRefundAPI(paymentId);<br>            return true;<br>        } catch (Exception e) {<br>            return false;<br>        }<br>    }</pre><pre>    private String callPayTMAPI(PaymentRequest request) {<br>        return &quot;paytm_&quot; + System.currentTimeMillis();<br>    }</pre><pre>    private void callPayTMRefundAPI(String paymentId) {<br>        System.out.println(&quot;PayTM refund for: &quot; + paymentId);<br>    }<br>}</pre><p><strong>Notice what’s happening:</strong></p><p>Each gateway has its own validation rules. Razorpay allows up to 10 crore, PayTM only allows 50 lakh. Both implement the same interface, but their implementations are completely different.</p><p><strong>The beauty:</strong> The rest of your code doesn’t care. It just calls gateway.validatePayment().</p><p><strong>Trade-off: More classes to manage</strong></p><p>❌ <strong>What we lose:</strong></p><ul><li>More files to maintain</li><li>More boilerplate code</li><li>If you have 10 gateways, that’s 10 classes</li></ul><p>✅ <strong>What we gain:</strong></p><ul><li>Each gateway’s logic is isolated</li><li>Change PayTM rules without touching Razorpay</li><li>Each class is small and focused</li><li>Easy to test each gateway independently</li></ul><h3>Step 5: The Gateway Factory (The Factory Pattern)</h3><p>This is where the magic happens:</p><pre>public class GatewayFactory {<br>    <br>    public enum GatewayType {<br>        RAZORPAY, PAYTM, BANKING_SYSTEM<br>    }</pre><pre>    /**<br>     * Simple factory: Given a type, return the gateway<br>     */<br>    public static PaymentGateway getGateway(GatewayType type) {<br>        switch (type) {<br>            case RAZORPAY:<br>                return new RazorPayGateway();<br>            case PAYTM:<br>                return new PayTMGateway();<br>            case BANKING_SYSTEM:<br>                return new BankingSystemGateway();<br>            default:<br>                throw new IllegalArgumentException(&quot;Unknown gateway: &quot; + type);<br>        }<br>    }</pre><pre>    /**<br>     * Intelligent factory: Choose the BEST gateway based on payment details<br>     */<br>    public static PaymentGateway selectOptimalGateway(PaymentRequest request) {<br>        double amount = request.getAmount();<br>        <br>        // Rule 1: Very high-value payments go through banking system<br>        // (direct bank transfers are more secure for large amounts)<br>        if (amount &gt; 100000) {<br>            return getGateway(GatewayType.BANKING_SYSTEM);<br>        }<br>        <br>        // Rule 2: Normal-sized payments use Razorpay<br>        // (best fees, best features)<br>        if (amount &gt;= 100) {<br>            return getGateway(GatewayType.RAZORPAY);<br>        }<br>        <br>        // Rule 3: Very small payments use PayTM<br>        // (has the lowest minimum threshold)<br>        return getGateway(GatewayType.PAYTM);<br>    }<br>}</pre><p><strong>What’s the Factory Pattern?</strong></p><p>Instead of writing:</p><pre>if (userWantsRazorpay) {<br>    gateway = new RazorPayGateway();<br>} else if (userWantsPayTM) {<br>    gateway = new PayTMGateway();<br>}</pre><p>Throughout your code, you centralize it in ONE place (the factory).</p><p><strong>Trade-off: One more indirection</strong></p><p>❌ <strong>What we lose:</strong></p><ul><li>One more class to understand</li><li>Tiny performance hit (negligible)</li><li>Adding a gateway means editing the factory</li></ul><p>✅ <strong>What we gain:</strong></p><ul><li>Gateway creation is in ONE place</li><li>Can change selection logic globally</li><li>Easy to add intelligence (select based on amount, region, etc.)</li><li>Tests can inject mock gateways</li></ul><p><strong>Real-world analogy:</strong> Instead of every department in a company calling the supplier directly, they all go through procurement. Procurement decides which supplier, handles discounts, tracks orders centrally.</p><h3>Step 6: The Payment Service (Singleton Pattern)</h3><pre>public class PaymentService {<br>    <br>    // Singleton: Only ONE instance exists in the entire application<br>    private static PaymentService instance;<br>    <br>    private PaymentValidator validator;<br>    private PaymentLogger logger;</pre><pre>    private PaymentService() {<br>        this.validator = new PaymentValidator();<br>        this.logger = new PaymentLogger();<br>    }</pre><pre>    public static synchronized PaymentService getInstance() {<br>        if (instance == null) {<br>            instance = new PaymentService();<br>        }<br>        return instance;<br>    }</pre><pre>    /**<br>     * Main method: Process a payment<br>     * This is where all the business logic lives<br>     */<br>    public PaymentResponse processPayment(PaymentRequest request, <br>                                          GatewayFactory.GatewayType gatewayType) {<br>        <br>        logger.logInfo(&quot;Processing payment: &quot; + request.getAmount() + <br>                       &quot; &quot; + request.getCurrency());<br>        <br>        // Step 1: Validate the payment request<br>        if (!validator.validatePaymentRequest(request)) {<br>            logger.logError(&quot;Invalid payment request&quot;);<br>            return new PaymentResponse(null,<br>                PaymentResponse.PaymentStatus.FAILED,<br>                &quot;Invalid payment details&quot;);<br>        }</pre><pre>        // Step 2: Get the gateway<br>        PaymentGateway gateway = GatewayFactory.getGateway(gatewayType);<br>        logger.logInfo(&quot;Using gateway: &quot; + gatewayType);</pre><pre>        // Step 3: Let the gateway validate too<br>        if (!gateway.validatePayment(request)) {<br>            logger.logError(&quot;Gateway validation failed&quot;);<br>            return new PaymentResponse(null,<br>                PaymentResponse.PaymentStatus.FAILED,<br>                &quot;Payment not allowed by gateway&quot;);<br>        }</pre><pre>        // Step 4: Actually process the payment<br>        PaymentResponse response = gateway.initiatePayment(request);<br>        logger.logInfo(&quot;Payment initiated: &quot; + response.getPaymentId());</pre><pre>        return response;<br>    }</pre><pre>    /**<br>     * Auto-select the best gateway<br>     */<br>    public PaymentResponse processPaymentAuto(PaymentRequest request) {<br>        PaymentGateway gateway = GatewayFactory.selectOptimalGateway(request);<br>        <br>        if (!gateway.validatePayment(request)) {<br>            return new PaymentResponse(null,<br>                PaymentResponse.PaymentStatus.FAILED,<br>                &quot;Payment validation failed&quot;);<br>        }</pre><pre>        return gateway.initiatePayment(request);<br>    }</pre><pre>    /**<br>     * After the gateway redirects back, confirm the payment<br>     */<br>    public void confirmPayment(String paymentId, GatewayFactory.GatewayType gatewayType) {<br>        PaymentGateway gateway = GatewayFactory.getGateway(gatewayType);<br>        gateway.confirmPayment(paymentId);<br>        logger.logInfo(&quot;Payment confirmed: &quot; + paymentId);<br>    }</pre><pre>    /**<br>     * Refund a payment<br>     */<br>    public boolean refundPayment(String paymentId, GatewayFactory.GatewayType gatewayType) {<br>        PaymentGateway gateway = GatewayFactory.getGateway(gatewayType);<br>        boolean success = gateway.refundPayment(paymentId);<br>        <br>        if (success) {<br>            logger.logInfo(&quot;Refund processed: &quot; + paymentId);<br>        } else {<br>            logger.logError(&quot;Refund failed: &quot; + paymentId);<br>        }<br>        <br>        return success;<br>    }<br>}</pre><p><strong>Why Singleton?</strong></p><p>All payments in your app should go through this one service. This ensures:</p><ul><li>Consistent logging</li><li>Consistent validation</li><li>Single place to add security checks</li><li>Easy to track metrics</li></ul><p><strong>Trade-off: Global state</strong></p><p>❌ <strong>What we lose:</strong></p><ul><li>Singletons can be hard to test</li><li>Creates global state that can hide dependencies</li><li>Not easy to have multiple payment services with different rules</li></ul><p>✅ <strong>What we gain:</strong></p><ul><li>Single entry point for all payments</li><li>Consistent behavior across the app</li><li>Easy to add company-wide payment rules</li><li>One place to audit for security</li></ul><p><strong>Real-world analogy:</strong> A company has one CFO. All spending decisions go through the CFO. This ensures consistent financial policy, auditing, and reporting.</p><h3>Step 7: The Controller (How the API Looks)</h3><pre>public class PaymentController {<br>    <br>    private PaymentService paymentService = PaymentService.getInstance();</pre><pre>    /**<br>     * POST /api/payments/initiate<br>     * {<br>     *   &quot;sender&quot;: &quot;user123&quot;,<br>     *   &quot;receiver&quot;: &quot;merchant456&quot;,<br>     *   &quot;amount&quot;: 5000,<br>     *   &quot;currency&quot;: &quot;INR&quot;,<br>     *   &quot;gatewayPreference&quot;: &quot;auto&quot;  // or &quot;RAZORPAY&quot;, &quot;PAYTM&quot;<br>     * }<br>     */<br>    public PaymentResponse initiatePayment(PaymentRequest request, <br>                                           String gatewayPreference) {<br>        <br>        if (&quot;auto&quot;.equals(gatewayPreference)) {<br>            // Let the system choose<br>            return paymentService.processPaymentAuto(request);<br>        } else {<br>            // User specified a gateway<br>            GatewayFactory.GatewayType gatewayType = <br>                GatewayFactory.GatewayType.valueOf(gatewayPreference);<br>            return paymentService.processPayment(request, gatewayType);<br>        }<br>    }</pre><pre>    /**<br>     * POST /api/payments/confirm<br>     * Called when the payment gateway redirects back to your app<br>     */<br>    public void confirmPayment(String paymentId, String gateway) {<br>        GatewayFactory.GatewayType gatewayType = <br>            GatewayFactory.GatewayType.valueOf(gateway);<br>        paymentService.confirmPayment(paymentId, gatewayType);<br>    }</pre><pre>    /**<br>     * POST /api/payments/{paymentId}/refund<br>     * Get money back<br>     */<br>    public boolean refundPayment(String paymentId, String gateway) {<br>        GatewayFactory.GatewayType gatewayType = <br>            GatewayFactory.GatewayType.valueOf(gateway);<br>        return paymentService.refundPayment(paymentId, gatewayType);<br>    }<br>}</pre><p><strong>Notice how simple the controller is?</strong></p><p>All the complex logic is hidden in PaymentService and the gateway implementations. The controller just orchestrates.</p><h3>Why This Architecture Actually Works</h3><h3>✅ Easy to Add New Gateways</h3><p>Want to add Stripe? Takes 15 minutes:</p><pre>public class StripeGateway implements PaymentGateway {<br>    @Override<br>    public boolean validatePayment(PaymentRequest request) {<br>        // Stripe rules...<br>        return true;<br>    }</pre><pre>    @Override<br>    public PaymentResponse initiatePayment(PaymentRequest request) {<br>        // Call Stripe API...<br>        return new PaymentResponse(...);<br>    }</pre><pre>    // ... other methods<br>}</pre><p>Then add to factory:</p><pre>case STRIPE:<br>    return new StripeGateway();</pre><p>Done. No changes needed to the rest of your app.</p><p><strong>Trade-off: Code duplication for similar gateways</strong></p><ul><li>Each gateway re-implements the same interface</li><li>Some validation logic might be copy-pasted</li><li><strong>But:</strong> This isolation is worth the repetition</li></ul><h3>✅ Easy to Test</h3><p>Want to test payment logic without hitting real APIs?</p><pre>public class MockPaymentGateway implements PaymentGateway {<br>    @Override<br>    public PaymentResponse initiatePayment(PaymentRequest request) {<br>        // Always succeed<br>        return new PaymentResponse(&quot;test_123&quot;, <br>            PaymentResponse.PaymentStatus.SUCCESS,<br>            &quot;Test payment&quot;);<br>    }<br>}</pre><pre>// In your test:<br>PaymentRequest testPayment = new PaymentRequest(<br>    &quot;test_user&quot;, &quot;test_merchant&quot;, 1000, &quot;INR&quot;<br>);<br>PaymentGateway mockGateway = new MockPaymentGateway();<br>PaymentResponse response = mockGateway.initiatePayment(testPayment);<br>assert response.getStatus() == PaymentResponse.PaymentStatus.SUCCESS;</pre><p>Tests are instant, cheap, and don’t require API keys.</p><h3>✅ Easy to Handle Outages</h3><p>When Razorpay goes down, you can:</p><p><strong>Option 1: Manual failover</strong></p><pre>public PaymentResponse processWithFallback(PaymentRequest request) {<br>    try {<br>        return GatewayFactory.getGateway(GatewayType.RAZORPAY)<br>                             .initiatePayment(request);<br>    } catch (Exception e) {<br>        logger.logWarning(&quot;Razorpay failed, trying PayTM&quot;);<br>        return GatewayFactory.getGateway(GatewayType.PAYTM)<br>                             .initiatePayment(request);<br>    }<br>}</pre><p><strong>Option 2: Configuration-based failover</strong></p><pre>payment:<br>  primary: RAZORPAY<br>  fallback: PAYTM<br>  timeout_seconds: 10</pre><p><strong>Option 3: Region-based routing</strong></p><pre>public PaymentGateway selectByRegion(String userCountry) {<br>    if (&quot;IN&quot;.equals(userCountry)) return getGateway(GatewayType.PAYTM);<br>    if (&quot;US&quot;.equals(userCountry)) return getGateway(GatewayType.STRIPE);<br>    return getGateway(GatewayType.RAZORPAY);<br>}</pre><p>Your business didn’t change. You just changed where payments go.</p><h3>✅ Easy to Optimize Costs</h3><pre>public PaymentGateway selectCheapestGateway(PaymentRequest request) {<br>    // Razorpay: 2% + ₹5<br>    // PayTM: 2.5% (no fixed fee)<br>    // Stripe: 2% + $0.30<br>    <br>    // Calculate cost on each<br>    double razorpayCost = (request.getAmount() * 0.02) + 5;<br>    double paytmCost = request.getAmount() * 0.025;<br>    <br>    if (paytmCost &lt; razorpayCost) {<br>        return getGateway(GatewayType.PAYTM);<br>    }<br>    return getGateway(GatewayType.RAZORPAY);<br>}</pre><p>You literally save money by routing payments intelligently.</p><h3>The Trade-offs: What You Give Up</h3><p>Let me be honest about the costs of this architecture.</p><h3>Trade-off 1: Complexity</h3><p>❌ You now have:</p><ul><li>1 Interface (PaymentGateway)</li><li>3+ Concrete Gateways</li><li>1 Factory</li><li>1 Service</li><li>Request/Response objects</li></ul><p>For a simple app that only uses one gateway, this feels like overkill.</p><p>✅ But:</p><ul><li>When you add gateway 2, the complexity pays for itself</li><li>By gateway 3, you’re printing money in time saved</li><li>Code is easier to understand (each class does one thing)</li></ul><p><strong>My advice:</strong> If you’re SURE you’ll never change payment providers, skip this. But how sure are you really?</p><h3>Trade-off 2: Lost Gateway-Specific Features</h3><p>Razorpay has a feature called “Route” (split payments). Our interface doesn’t mention it.</p><p>❌ We can’t use Route easily</p><p>✅ But:</p><ul><li>95% of payments don’t need Route</li><li>For the rare case that does, you can call Razorpay directly</li><li>The 95% runs on clean, maintainable code</li></ul><p><strong>Real example from my work:</strong> At my last startup, we needed Razorpay’s Route feature. So we added it specifically:</p><pre>public class PaymentService {<br>    public void processPaymentWithRoute(PaymentRequest request, <br>                                        RoutingRules rules) {<br>        RazorPayGateway razorpay = new RazorPayGateway();<br>        razorpay.initiatePaymentWithRoute(request, rules);<br>    }<br>}</pre><p>We kept the normal flow generic, and added Razorpay-specific code for special cases. Best of both worlds.</p><h3>Trade-off 3: Performance Overhead</h3><p>You’re creating objects, calling methods through interfaces, logging. It’s not free.</p><p>❌ Tiny performance hit (milliseconds)</p><p>✅ But:</p><ul><li>Network latency to payment gateway is 100–500ms</li><li>Your code overhead is 1–5ms</li><li>Users won’t notice</li><li>For 99.9% of companies, this doesn’t matter</li></ul><p><strong>Exception:</strong> If you’re processing millions of payments per second, benchmark first. But if you’re at that scale, you have dedicated payment infrastructure anyway.</p><h3>Real-World Scenario: How This Saves Your Butt</h3><p>Let me walk through an actual situation:</p><p><strong>Scenario:</strong> Your app is processing ₹1 crore in monthly payments through Razorpay. Razorpay raises fees from 2% to 3%.</p><p><strong>Without this architecture:</strong></p><ul><li>Search code for all Razorpay references</li><li>Each one is different (some use direct API, some use their mobile SDK)</li><li>Refactor each location to add alternative gateway</li><li>Test everything again</li><li><strong>Timeline: 3 weeks</strong></li><li><strong>Cost: 2 developers × 3 weeks</strong></li></ul><p><strong>With this architecture:</strong></p><ul><li>Add StripeGateway class (1 day)</li><li>Add intelligent routing in factory (2 hours)</li><li>Test with mock gateways (4 hours)</li><li><strong>Timeline: 2 days</strong></li><li><strong>Cost: 1 developer × 2 days</strong></li><li><strong>Savings: 2.5 weeks, potentially thousands of dollars</strong></li></ul><p>And you keep 1% savings on fees going forward.</p><h3>How to Actually Build This</h3><h3>Phase 1: Start Simple (Week 1)</h3><ul><li>Build PaymentGateway interface</li><li>Implement for your current provider (Razorpay)</li><li>Refactor existing code to use it</li><li>Add tests with mock gateway</li></ul><h3>Phase 2: Add Second Gateway (Week 2–3)</h3><ul><li>Implement second gateway (PayTM)</li><li>Add factory with basic selection</li><li>Test both gateways</li><li>Monitor in production</li></ul><h3>Phase 3: Add Intelligence (Week 4+)</h3><ul><li>Region-based routing</li><li>Amount-based selection</li><li>Cost optimization</li><li>A/B testing different gateways</li></ul><p><strong>Don’t build the whole thing upfront.</strong> Build phase 1, use it, then add more.</p><h3>Common Mistakes to Avoid</h3><h3>❌ Mistake 1: Forcing All Gateways Into One Implementation</h3><pre>// DON&#39;T DO THIS:<br>public class PaymentGateway {<br>    private RazorpayConfig razorpayConfig;<br>    private PayTMConfig paytmConfig;<br>    private StripeConfig stripeConfig;<br>    <br>    public void pay(PaymentRequest request, String gateway) {<br>        if (&quot;razorpay&quot;.equals(gateway)) {<br>            // 50 lines of Razorpay code<br>        } else if (&quot;paytm&quot;.equals(gateway)) {<br>            // 50 lines of PayTM code<br>        }<br>    }<br>}</pre><p>This defeats the whole purpose. Each gateway should be its own class.</p><h3>❌ Mistake 2: Too Much Logic in the Factory</h3><pre>// DON&#39;T DO THIS:<br>public class GatewayFactory {<br>    public PaymentGateway getGateway(PaymentRequest request) {<br>        if (request.getAmount() &gt; 100000) {<br>            if (&quot;IN&quot;.equals(request.getCountry())) {<br>                if (isEvening()) {<br>                    // Some complex business logic<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Factory’s job: Create the gateway. Service’s job: Decide what to do.</p><p>Keep them separate.</p><h3>❌ Mistake 3: Forgetting to Handle Errors</h3><pre>// DON&#39;T DO THIS:<br>PaymentGateway gateway = GatewayFactory.getGateway(type);<br>PaymentResponse response = gateway.initiatePayment(request);<br>// What if gateway is null? What if API fails?</pre><p>Always assume things will fail:</p><pre>// DO THIS:<br>try {<br>    PaymentGateway gateway = GatewayFactory.getGateway(type);<br>    if (gateway == null) {<br>        throw new IllegalArgumentException(&quot;Unknown gateway: &quot; + type);<br>    }<br>    PaymentResponse response = gateway.initiatePayment(request);<br>    if (response == null) {<br>        // Handle null response<br>    }<br>    return response;<br>} catch (Exception e) {<br>    logger.logError(&quot;Payment failed: &quot; + e.getMessage());<br>    return new PaymentResponse(null, <br>        PaymentResponse.PaymentStatus.FAILED,<br>        &quot;Payment processing error&quot;);<br>}</pre><h3>How This Fits Into Your Bigger System</h3><p>Your payment system doesn’t exist in isolation. Here’s where it connects:</p><pre>User App<br>    ↓<br>Payment API (PaymentController)<br>    ↓<br>Payment Service (Business Logic)<br>    ↓<br>Payment Gateways (Razorpay, PayTM, Stripe)<br>    ↓<br>Payment Database (Store transaction records)<br>    ↓<br>Webhook Handler (Listen for confirmations)</pre><p>Your code in this article handles the “Payment Service” and “Payment Gateways” layers.</p><p>For the database: Store the PaymentResponse for every payment. Include paymentId, gateway, status, timestamp.</p><p>For webhooks: Different gateways send confirmations differently. Have a webhook handler that translates them:</p><pre>public class PaymentWebhookHandler {<br>    public void handleRazorpayWebhook(RazorpayWebhookBody body) {<br>        String paymentId = body.getPaymentId();<br>        paymentService.confirmPayment(paymentId, GatewayType.RAZORPAY);<br>    }<br>    <br>    public void handlePayTMWebhook(PayTMWebhookBody body) {<br>        String paymentId = body.getPaymentId();<br>        paymentService.confirmPayment(paymentId, GatewayType.PAYTM);<br>    }<br>}</pre><h3>The Bottom Line</h3><p>Building a payment system with design patterns might seem like extra work upfront.</p><p>But it’s insurance against the future.</p><p><strong>Without this architecture:</strong></p><ul><li>You’re locked into your payment provider</li><li>Adding a new gateway takes weeks</li><li>Code becomes a mess as you add more gateways</li><li>Testing is slow and expensive</li><li>Outages affect your entire service</li></ul><p><strong>With this architecture:</strong></p><ul><li>Adding a gateway takes days</li><li>Code remains clean and maintainable</li><li>Testing is fast and free</li><li>You can route around outages</li><li>Your business logic is independent of implementation details</li></ul><p><strong>The real magic:</strong> You don’t just handle payments differently. You handle ALL external services differently. This pattern works for email (SendGrid, Mailgun, AWS SES), SMS (Twilio, AWS SNS), storage (S3, Azure, GCP), etc.</p><p>Learn it once, use it everywhere.</p><h3>Your Next Steps</h3><ol><li><strong>Read this article again.</strong> Find the parts that confused you.</li><li><strong>Draw the architecture.</strong> Sketch it on paper or in Figma.</li><li><strong>Implement Phase 1.</strong> Create the interface for your current gateway.</li><li><strong>Write tests.</strong> Use a mock gateway.</li><li><strong>Refactor slowly.</strong> Don’t try to change everything at once.</li><li><strong>Add a second gateway.</strong> See how easy it becomes.</li><li><strong>Share what you learned.</strong> Teach your team.</li></ol><p>Payment processing isn’t exciting. But your system’s architecture should be.</p><p><strong>Have you built payment systems? What patterns have saved your sanity? Drop a comment — I’d love to learn from your experience.</strong></p><p><em>Thanks for reading. Now go build something resilient.</em>How to Build a Payment System That Won’t Break When Razorpay Goes Down</p><p>Let me tell you a story.</p><p>You’re a startup founder with a hot new app. Users love it. The money starts flowing in. You integrate Razorpay for payments — it works great, easy setup, good documentation.</p><p>Then one day, Razorpay has an outage. For 4 hours, your app can’t process payments. Revenue stops. Customer emails flood in. Your team scrambles.</p><p>The next week, your investors ask: <em>“Why are we completely dependent on one payment provider?”</em></p><p>You start searching your codebase for Razorpay references. It’s everywhere. Controllers, services, database queries — the whole system is baked around Razorpay. Switching to PayTM or Stripe would take weeks of refactoring.</p><p><strong>This is the story that leads developers to design patterns.</strong></p><p>Today, I’ll show you how to build a payment system that’s flexible, resilient, and actually enjoyable to maintain. No more late-night panics when a provider has issues.</p><h3>The Root Problem: Why Direct Integration Is a Trap</h3><p>Let’s say you start with the simplest possible approach:</p><pre>public class CheckoutPage {<br>    public void processPayment(double amount, String userEmail) {<br>        RazorpayClient client = new RazorpayClient(&quot;api_key&quot;);<br>        String paymentUrl = client.createPaymentLink(amount);<br>        sendEmailWithLink(userEmail, paymentUrl);<br>    }<br>}</pre><p>It works. Your first 1,000 users are happy.</p><p>But now imagine your business grows:</p><p><strong>Scenario 1: A VIP client wants to pay through PayTM instead of Razorpay</strong></p><ul><li>You add an if-statement: “if customer prefers PayTM…”</li><li>Now you have Razorpay code AND PayTM code in the same method</li><li>This method is getting messy</li></ul><p><strong>Scenario 2: Your payment volume grows, Razorpay fees become expensive</strong></p><ul><li>You want to use Stripe for international transactions</li><li>You add another if-statement</li><li>Now you’re juggling three different payment APIs in one place</li></ul><p><strong>Scenario 3: You’re adding a new feature — payment plans and subscriptions</strong></p><ul><li>Different gateways handle subscriptions differently</li><li>Your code becomes a maze of gateway-specific logic</li><li>A simple bug fix in one gateway’s section might break another</li></ul><p><strong>Scenario 4: You want to write tests for your payment logic</strong></p><ul><li>Can’t test without hitting actual Razorpay API</li><li>Tests are slow, unreliable, and cost money</li><li>Your test suite becomes a nightmare</li></ul><p>Sound familiar? This is why we need a better approach.</p><h3>The Solution: Separating Payment Logic from Gateway Details</h3><p>Here’s the core insight: <strong>Your business cares about “process a payment,” not about the specific gateway.</strong></p><p>Think of it like this: When you go to a restaurant, you don’t care if they use UberEats or Swiggy for delivery. You care that your food arrives hot. The delivery mechanism is an implementation detail.</p><p>We’re going to build the same separation in our code.</p><h3>The Design: Factory Pattern + Strategy Pattern</h3><p>Let me explain these patterns, but first: <strong>What’s a design pattern?</strong></p><p>A design pattern is a proven solution to a common problem. It’s like a recipe — not the exact ingredients for YOUR dish, but the proven steps that work for similar problems.</p><h3>What We’re Building</h3><pre>User clicks &quot;Pay Now&quot;<br>    ↓<br>PaymentController (receives the request)<br>    ↓<br>PaymentService (decides what to do)<br>    ↓<br>GatewayFactory (chooses which payment provider)<br>    ↓<br>Concrete Gateway (Razorpay/PayTM/Stripe)<br>    ↓<br>Payment Provider&#39;s API</pre><p>Let’s build this step by step, and I’ll explain the trade-offs at each stage.</p><h3>Step 1: The Request Object</h3><pre>public class PaymentRequest {<br>    private String sender;        // Who&#39;s paying<br>    private String receiver;      // Who receives money<br>    private double amount;        // How much<br>    private String currency;      // What currency</pre><pre>    public PaymentRequest(String sender, String receiver, <br>                         double amount, String currency) {<br>        this.sender = sender;<br>        this.receiver = receiver;<br>        this.amount = amount;<br>        this.currency = currency;<br>    }</pre><pre>    public String getSender() { return sender; }<br>    public String getReceiver() { return receiver; }<br>    public double getAmount() { return amount; }<br>    public String getCurrency() { return currency; }<br>}</pre><p><strong>Why this object?</strong></p><p>Instead of passing random parameters (processPayment(String api, double amount, int userId, String...)), we group everything into one structured object.</p><p><strong>Trade-off: Slight overhead for huge clarity</strong></p><ul><li>❌ One more class to maintain</li><li>✅ Anyone reading the code instantly knows what data is needed</li><li>✅ Easy to add new payment details without changing method signatures</li><li>✅ Can validate all payment data in one place</li></ul><h3>Step 2: The Gateway Interface (The Strategy Pattern)</h3><p>This is the most important part. Here’s the contract that every payment gateway MUST follow:</p><pre>public interface PaymentGateway {<br>    <br>    // Can we process this payment?<br>    boolean validatePayment(PaymentRequest request);<br>    <br>    // Start the payment<br>    PaymentResponse initiatePayment(PaymentRequest request);<br>    <br>    // Verify payment is complete<br>    void confirmPayment(String paymentId);<br>    <br>    // Give money back<br>    boolean refundPayment(String paymentId);<br>}</pre><p><strong>What’s happening here?</strong></p><p>We’re saying: <em>“If you’re a payment gateway, you MUST implement these four methods.”</em></p><p>This is called the <strong>Strategy Pattern</strong>. Each payment provider is a different “strategy” for accomplishing the same goal: processing a payment.</p><p><strong>Trade-off: Standardization vs. Gateway Flexibility</strong></p><p>❌ <strong>What we lose:</strong></p><ul><li>Razorpay might have unique features we can’t use (like their subscription plans)</li><li>We’re forcing all gateways into the same box</li><li>Some gateway features might not fit this interface</li></ul><p>✅ <strong>What we gain:</strong></p><ul><li>Can swap gateways without touching business logic</li><li>Same code works for Razorpay, PayTM, or Stripe</li><li>Easy to test with fake gateways</li><li>New developers instantly understand what a gateway must do</li></ul><p><strong>Real-world example of this trade-off:</strong> Razorpay supports “Route” (send payments to sub-accounts). Our interface doesn’t mention it. So if we want to use Route, we either add it to the interface (affecting all gateways) OR we leave it out and use Razorpay directly for that feature.</p><p><strong>Decision: Leave it out.</strong> The 90% of payments that are normal are more important than the 10% that need special features.</p><h3>Step 3: The Response Object</h3><pre>public class PaymentResponse {<br>    private String paymentId;<br>    private PaymentStatus status;<br>    private String message;<br>    private long timestamp;</pre><pre>    public enum PaymentStatus {<br>        INITIATED,    // We started the process<br>        PENDING,      // Waiting for confirmation<br>        SUCCESS,      // Money transferred<br>        FAILED,       // Something went wrong<br>        CANCELLED     // User canceled<br>    }</pre><pre>    public PaymentResponse(String paymentId, PaymentStatus status, String message) {<br>        this.paymentId = paymentId;<br>        this.status = status;<br>        this.message = message;<br>        this.timestamp = System.currentTimeMillis();<br>    }<br>}</pre><p><strong>Why standardize the response?</strong></p><p>Different gateways return data in different formats. Razorpay returns JSON, a direct bank API might return XML. We’re translating everything into one common format.</p><p><strong>Trade-off: Losing Gateway-Specific Details</strong></p><p>❌ <strong>What we lose:</strong></p><ul><li>Razorpay returns a short_url for the payment link</li><li>Our PaymentResponse only has generic fields</li><li>We might lose fine-grained error codes</li></ul><p>✅ <strong>What we gain:</strong></p><ul><li>UI code works the same way for all gateways</li><li>Don’t need to write 3 different response handlers</li><li>Easy to log and track payments consistently</li></ul><p><strong>Real-world analogy:</strong> Your restaurant kitchen doesn’t care if the order came from Uber, Swiggy, or your phone. They all get standardized in the same order format. The delivery platform details are hidden.</p><h3>Step 4: Implementing Concrete Gateways</h3><p>Now here’s where each payment provider gets its own class:</p><h3>Razorpay Gateway</h3><pre>public class RazorPayGateway implements PaymentGateway {<br>    <br>    private static final String API_KEY = &quot;your_razorpay_key&quot;;</pre><pre>    @Override<br>    public boolean validatePayment(PaymentRequest request) {<br>        // Razorpay rules:<br>        // - Amount between 1 paise and 10 crore<br>        // - Only INR, USD, EUR<br>        <br>        if (request.getAmount() &lt;= 0 || request.getAmount() &gt; 10000000) {<br>            return false;<br>        }<br>        <br>        if (!request.getCurrency().matches(&quot;INR|USD|EUR&quot;)) {<br>            return false;<br>        }<br>        <br>        return true;<br>    }</pre><pre>    @Override<br>    public PaymentResponse initiatePayment(PaymentRequest request) {<br>        try {<br>            // Call Razorpay&#39;s actual API<br>            String paymentId = callRazorpayAPI(request);<br>            <br>            return new PaymentResponse(<br>                paymentId, <br>                PaymentResponse.PaymentStatus.INITIATED,<br>                &quot;Razorpay payment started&quot;<br>            );<br>        } catch (Exception e) {<br>            return new PaymentResponse(<br>                null, <br>                PaymentResponse.PaymentStatus.FAILED,<br>                &quot;Razorpay error: &quot; + e.getMessage()<br>            );<br>        }<br>    }</pre><pre>    @Override<br>    public void confirmPayment(String paymentId) {<br>        System.out.println(&quot;Confirming Razorpay payment: &quot; + paymentId);<br>    }</pre><pre>    @Override<br>    public boolean refundPayment(String paymentId) {<br>        try {<br>            callRazorpayRefundAPI(paymentId);<br>            return true;<br>        } catch (Exception e) {<br>            return false;<br>        }<br>    }</pre><pre>    // These are the gateway-specific API calls<br>    private String callRazorpayAPI(PaymentRequest request) {<br>        // In real code, this would use Razorpay SDK<br>        return &quot;razorpay_&quot; + System.currentTimeMillis();<br>    }</pre><pre>    private void callRazorpayRefundAPI(String paymentId) {<br>        // Real refund call here<br>        System.out.println(&quot;Razorpay refund for: &quot; + paymentId);<br>    }<br>}</pre><h3>PayTM Gateway (Different rules, same interface)</h3><pre>public class PayTMGateway implements PaymentGateway {<br>    <br>    @Override<br>    public boolean validatePayment(PaymentRequest request) {<br>        // PayTM has different rules:<br>        // - Minimum 100, maximum 50 lakh<br>        // - Only INR<br>        <br>        if (request.getAmount() &lt; 100 || request.getAmount() &gt; 5000000) {<br>            return false;<br>        }<br>        return &quot;INR&quot;.equals(request.getCurrency());<br>    }</pre><pre>    @Override<br>    public PaymentResponse initiatePayment(PaymentRequest request) {<br>        try {<br>            String paymentId = callPayTMAPI(request);<br>            return new PaymentResponse(<br>                paymentId,<br>                PaymentResponse.PaymentStatus.INITIATED,<br>                &quot;PayTM payment started&quot;<br>            );<br>        } catch (Exception e) {<br>            return new PaymentResponse(<br>                null,<br>                PaymentResponse.PaymentStatus.FAILED,<br>                &quot;PayTM error: &quot; + e.getMessage()<br>            );<br>        }<br>    }</pre><pre>    @Override<br>    public void confirmPayment(String paymentId) {<br>        System.out.println(&quot;Confirming PayTM payment: &quot; + paymentId);<br>    }</pre><pre>    @Override<br>    public boolean refundPayment(String paymentId) {<br>        try {<br>            callPayTMRefundAPI(paymentId);<br>            return true;<br>        } catch (Exception e) {<br>            return false;<br>        }<br>    }</pre><pre>    private String callPayTMAPI(PaymentRequest request) {<br>        return &quot;paytm_&quot; + System.currentTimeMillis();<br>    }</pre><pre>    private void callPayTMRefundAPI(String paymentId) {<br>        System.out.println(&quot;PayTM refund for: &quot; + paymentId);<br>    }<br>}</pre><p><strong>Notice what’s happening:</strong></p><p>Each gateway has its own validation rules. Razorpay allows up to 10 crore, PayTM only allows 50 lakh. Both implement the same interface, but their implementations are completely different.</p><p><strong>The beauty:</strong> The rest of your code doesn’t care. It just calls gateway.validatePayment().</p><p><strong>Trade-off: More classes to manage</strong></p><p>❌ <strong>What we lose:</strong></p><ul><li>More files to maintain</li><li>More boilerplate code</li><li>If you have 10 gateways, that’s 10 classes</li></ul><p>✅ <strong>What we gain:</strong></p><ul><li>Each gateway’s logic is isolated</li><li>Change PayTM rules without touching Razorpay</li><li>Each class is small and focused</li><li>Easy to test each gateway independently</li></ul><h3>Step 5: The Gateway Factory (The Factory Pattern)</h3><p>This is where the magic happens:</p><pre>public class GatewayFactory {<br>    <br>    public enum GatewayType {<br>        RAZORPAY, PAYTM, BANKING_SYSTEM<br>    }</pre><pre>    /**<br>     * Simple factory: Given a type, return the gateway<br>     */<br>    public static PaymentGateway getGateway(GatewayType type) {<br>        switch (type) {<br>            case RAZORPAY:<br>                return new RazorPayGateway();<br>            case PAYTM:<br>                return new PayTMGateway();<br>            case BANKING_SYSTEM:<br>                return new BankingSystemGateway();<br>            default:<br>                throw new IllegalArgumentException(&quot;Unknown gateway: &quot; + type);<br>        }<br>    }</pre><pre>    /**<br>     * Intelligent factory: Choose the BEST gateway based on payment details<br>     */<br>    public static PaymentGateway selectOptimalGateway(PaymentRequest request) {<br>        double amount = request.getAmount();<br>        <br>        // Rule 1: Very high-value payments go through banking system<br>        // (direct bank transfers are more secure for large amounts)<br>        if (amount &gt; 100000) {<br>            return getGateway(GatewayType.BANKING_SYSTEM);<br>        }<br>        <br>        // Rule 2: Normal-sized payments use Razorpay<br>        // (best fees, best features)<br>        if (amount &gt;= 100) {<br>            return getGateway(GatewayType.RAZORPAY);<br>        }<br>        <br>        // Rule 3: Very small payments use PayTM<br>        // (has the lowest minimum threshold)<br>        return getGateway(GatewayType.PAYTM);<br>    }<br>}</pre><p><strong>What’s the Factory Pattern?</strong></p><p>Instead of writing:</p><pre>if (userWantsRazorpay) {<br>    gateway = new RazorPayGateway();<br>} else if (userWantsPayTM) {<br>    gateway = new PayTMGateway();<br>}</pre><p>Throughout your code, you centralize it in ONE place (the factory).</p><p><strong>Trade-off: One more indirection</strong></p><p>❌ <strong>What we lose:</strong></p><ul><li>One more class to understand</li><li>Tiny performance hit (negligible)</li><li>Adding a gateway means editing the factory</li></ul><p>✅ <strong>What we gain:</strong></p><ul><li>Gateway creation is in ONE place</li><li>Can change selection logic globally</li><li>Easy to add intelligence (select based on amount, region, etc.)</li><li>Tests can inject mock gateways</li></ul><p><strong>Real-world analogy:</strong> Instead of every department in a company calling the supplier directly, they all go through procurement. Procurement decides which supplier, handles discounts, tracks orders centrally.</p><h3>Step 6: The Payment Service (Singleton Pattern)</h3><pre>public class PaymentService {<br>    <br>    // Singleton: Only ONE instance exists in the entire application<br>    private static PaymentService instance;<br>    <br>    private PaymentValidator validator;<br>    private PaymentLogger logger;</pre><pre>    private PaymentService() {<br>        this.validator = new PaymentValidator();<br>        this.logger = new PaymentLogger();<br>    }</pre><pre>    public static synchronized PaymentService getInstance() {<br>        if (instance == null) {<br>            instance = new PaymentService();<br>        }<br>        return instance;<br>    }</pre><pre>    /**<br>     * Main method: Process a payment<br>     * This is where all the business logic lives<br>     */<br>    public PaymentResponse processPayment(PaymentRequest request, <br>                                          GatewayFactory.GatewayType gatewayType) {<br>        <br>        logger.logInfo(&quot;Processing payment: &quot; + request.getAmount() + <br>                       &quot; &quot; + request.getCurrency());<br>        <br>        // Step 1: Validate the payment request<br>        if (!validator.validatePaymentRequest(request)) {<br>            logger.logError(&quot;Invalid payment request&quot;);<br>            return new PaymentResponse(null,<br>                PaymentResponse.PaymentStatus.FAILED,<br>                &quot;Invalid payment details&quot;);<br>        }</pre><pre>        // Step 2: Get the gateway<br>        PaymentGateway gateway = GatewayFactory.getGateway(gatewayType);<br>        logger.logInfo(&quot;Using gateway: &quot; + gatewayType);</pre><pre>        // Step 3: Let the gateway validate too<br>        if (!gateway.validatePayment(request)) {<br>            logger.logError(&quot;Gateway validation failed&quot;);<br>            return new PaymentResponse(null,<br>                PaymentResponse.PaymentStatus.FAILED,<br>                &quot;Payment not allowed by gateway&quot;);<br>        }</pre><pre>        // Step 4: Actually process the payment<br>        PaymentResponse response = gateway.initiatePayment(request);<br>        logger.logInfo(&quot;Payment initiated: &quot; + response.getPaymentId());</pre><pre>        return response;<br>    }</pre><pre>    /**<br>     * Auto-select the best gateway<br>     */<br>    public PaymentResponse processPaymentAuto(PaymentRequest request) {<br>        PaymentGateway gateway = GatewayFactory.selectOptimalGateway(request);<br>        <br>        if (!gateway.validatePayment(request)) {<br>            return new PaymentResponse(null,<br>                PaymentResponse.PaymentStatus.FAILED,<br>                &quot;Payment validation failed&quot;);<br>        }</pre><pre>        return gateway.initiatePayment(request);<br>    }</pre><pre>    /**<br>     * After the gateway redirects back, confirm the payment<br>     */<br>    public void confirmPayment(String paymentId, GatewayFactory.GatewayType gatewayType) {<br>        PaymentGateway gateway = GatewayFactory.getGateway(gatewayType);<br>        gateway.confirmPayment(paymentId);<br>        logger.logInfo(&quot;Payment confirmed: &quot; + paymentId);<br>    }</pre><pre>    /**<br>     * Refund a payment<br>     */<br>    public boolean refundPayment(String paymentId, GatewayFactory.GatewayType gatewayType) {<br>        PaymentGateway gateway = GatewayFactory.getGateway(gatewayType);<br>        boolean success = gateway.refundPayment(paymentId);<br>        <br>        if (success) {<br>            logger.logInfo(&quot;Refund processed: &quot; + paymentId);<br>        } else {<br>            logger.logError(&quot;Refund failed: &quot; + paymentId);<br>        }<br>        <br>        return success;<br>    }<br>}</pre><p><strong>Why Singleton?</strong></p><p>All payments in your app should go through this one service. This ensures:</p><ul><li>Consistent logging</li><li>Consistent validation</li><li>Single place to add security checks</li><li>Easy to track metrics</li></ul><p><strong>Trade-off: Global state</strong></p><p>❌ <strong>What we lose:</strong></p><ul><li>Singletons can be hard to test</li><li>Creates global state that can hide dependencies</li><li>Not easy to have multiple payment services with different rules</li></ul><p>✅ <strong>What we gain:</strong></p><ul><li>Single entry point for all payments</li><li>Consistent behavior across the app</li><li>Easy to add company-wide payment rules</li><li>One place to audit for security</li></ul><p><strong>Real-world analogy:</strong> A company has one CFO. All spending decisions go through the CFO. This ensures consistent financial policy, auditing, and reporting.</p><h3>Step 7: The Controller (How the API Looks)</h3><pre>public class PaymentController {<br>    <br>    private PaymentService paymentService = PaymentService.getInstance();</pre><pre>    /**<br>     * POST /api/payments/initiate<br>     * {<br>     *   &quot;sender&quot;: &quot;user123&quot;,<br>     *   &quot;receiver&quot;: &quot;merchant456&quot;,<br>     *   &quot;amount&quot;: 5000,<br>     *   &quot;currency&quot;: &quot;INR&quot;,<br>     *   &quot;gatewayPreference&quot;: &quot;auto&quot;  // or &quot;RAZORPAY&quot;, &quot;PAYTM&quot;<br>     * }<br>     */<br>    public PaymentResponse initiatePayment(PaymentRequest request, <br>                                           String gatewayPreference) {<br>        <br>        if (&quot;auto&quot;.equals(gatewayPreference)) {<br>            // Let the system choose<br>            return paymentService.processPaymentAuto(request);<br>        } else {<br>            // User specified a gateway<br>            GatewayFactory.GatewayType gatewayType = <br>                GatewayFactory.GatewayType.valueOf(gatewayPreference);<br>            return paymentService.processPayment(request, gatewayType);<br>        }<br>    }</pre><pre>    /**<br>     * POST /api/payments/confirm<br>     * Called when the payment gateway redirects back to your app<br>     */<br>    public void confirmPayment(String paymentId, String gateway) {<br>        GatewayFactory.GatewayType gatewayType = <br>            GatewayFactory.GatewayType.valueOf(gateway);<br>        paymentService.confirmPayment(paymentId, gatewayType);<br>    }</pre><pre>    /**<br>     * POST /api/payments/{paymentId}/refund<br>     * Get money back<br>     */<br>    public boolean refundPayment(String paymentId, String gateway) {<br>        GatewayFactory.GatewayType gatewayType = <br>            GatewayFactory.GatewayType.valueOf(gateway);<br>        return paymentService.refundPayment(paymentId, gatewayType);<br>    }<br>}</pre><p><strong>Notice how simple the controller is?</strong></p><p>All the complex logic is hidden in PaymentService and the gateway implementations. The controller just orchestrates.</p><h3>Why This Architecture Actually Works</h3><h3>✅ Easy to Add New Gateways</h3><p>Want to add Stripe? Takes 15 minutes:</p><pre>public class StripeGateway implements PaymentGateway {<br>    @Override<br>    public boolean validatePayment(PaymentRequest request) {<br>        // Stripe rules...<br>        return true;<br>    }</pre><pre>    @Override<br>    public PaymentResponse initiatePayment(PaymentRequest request) {<br>        // Call Stripe API...<br>        return new PaymentResponse(...);<br>    }</pre><pre>    // ... other methods<br>}</pre><p>Then add to factory:</p><pre>case STRIPE:<br>    return new StripeGateway();</pre><p>Done. No changes needed to the rest of your app.</p><p><strong>Trade-off: Code duplication for similar gateways</strong></p><ul><li>Each gateway re-implements the same interface</li><li>Some validation logic might be copy-pasted</li><li><strong>But:</strong> This isolation is worth the repetition</li></ul><h3>✅ Easy to Test</h3><p>Want to test payment logic without hitting real APIs?</p><pre>public class MockPaymentGateway implements PaymentGateway {<br>    @Override<br>    public PaymentResponse initiatePayment(PaymentRequest request) {<br>        // Always succeed<br>        return new PaymentResponse(&quot;test_123&quot;, <br>            PaymentResponse.PaymentStatus.SUCCESS,<br>            &quot;Test payment&quot;);<br>    }<br>}</pre><pre>// In your test:<br>PaymentRequest testPayment = new PaymentRequest(<br>    &quot;test_user&quot;, &quot;test_merchant&quot;, 1000, &quot;INR&quot;<br>);<br>PaymentGateway mockGateway = new MockPaymentGateway();<br>PaymentResponse response = mockGateway.initiatePayment(testPayment);<br>assert response.getStatus() == PaymentResponse.PaymentStatus.SUCCESS;</pre><p>Tests are instant, cheap, and don’t require API keys.</p><h3>✅ Easy to Handle Outages</h3><p>When Razorpay goes down, you can:</p><p><strong>Option 1: Manual failover</strong></p><pre>public PaymentResponse processWithFallback(PaymentRequest request) {<br>    try {<br>        return GatewayFactory.getGateway(GatewayType.RAZORPAY)<br>                             .initiatePayment(request);<br>    } catch (Exception e) {<br>        logger.logWarning(&quot;Razorpay failed, trying PayTM&quot;);<br>        return GatewayFactory.getGateway(GatewayType.PAYTM)<br>                             .initiatePayment(request);<br>    }<br>}</pre><p><strong>Option 2: Configuration-based failover</strong></p><pre>payment:<br>  primary: RAZORPAY<br>  fallback: PAYTM<br>  timeout_seconds: 10</pre><p><strong>Option 3: Region-based routing</strong></p><pre>public PaymentGateway selectByRegion(String userCountry) {<br>    if (&quot;IN&quot;.equals(userCountry)) return getGateway(GatewayType.PAYTM);<br>    if (&quot;US&quot;.equals(userCountry)) return getGateway(GatewayType.STRIPE);<br>    return getGateway(GatewayType.RAZORPAY);<br>}</pre><p>Your business didn’t change. You just changed where payments go.</p><h3>✅ Easy to Optimize Costs</h3><pre>public PaymentGateway selectCheapestGateway(PaymentRequest request) {<br>    // Razorpay: 2% + ₹5<br>    // PayTM: 2.5% (no fixed fee)<br>    // Stripe: 2% + $0.30<br>    <br>    // Calculate cost on each<br>    double razorpayCost = (request.getAmount() * 0.02) + 5;<br>    double paytmCost = request.getAmount() * 0.025;<br>    <br>    if (paytmCost &lt; razorpayCost) {<br>        return getGateway(GatewayType.PAYTM);<br>    }<br>    return getGateway(GatewayType.RAZORPAY);<br>}</pre><p>You literally save money by routing payments intelligently.</p><h3>The Trade-offs: What You Give Up</h3><p>Let me be honest about the costs of this architecture.</p><h3>Trade-off 1: Complexity</h3><p>❌ You now have:</p><ul><li>1 Interface (PaymentGateway)</li><li>3+ Concrete Gateways</li><li>1 Factory</li><li>1 Service</li><li>Request/Response objects</li></ul><p>For a simple app that only uses one gateway, this feels like overkill.</p><p>✅ But:</p><ul><li>When you add gateway 2, the complexity pays for itself</li><li>By gateway 3, you’re printing money in time saved</li><li>Code is easier to understand (each class does one thing)</li></ul><p><strong>My advice:</strong> If you’re SURE you’ll never change payment providers, skip this. But how sure are you really?</p><h3>Trade-off 2: Lost Gateway-Specific Features</h3><p>Razorpay has a feature called “Route” (split payments). Our interface doesn’t mention it.</p><p>❌ We can’t use Route easily</p><p>✅ But:</p><ul><li>95% of payments don’t need Route</li><li>For the rare case that does, you can call Razorpay directly</li><li>The 95% runs on clean, maintainable code</li></ul><p><strong>Real example from my work:</strong> At my last startup, we needed Razorpay’s Route feature. So we added it specifically:</p><pre>public class PaymentService {<br>    public void processPaymentWithRoute(PaymentRequest request, <br>                                        RoutingRules rules) {<br>        RazorPayGateway razorpay = new RazorPayGateway();<br>        razorpay.initiatePaymentWithRoute(request, rules);<br>    }<br>}</pre><p>We kept the normal flow generic, and added Razorpay-specific code for special cases. Best of both worlds.</p><h3>Trade-off 3: Performance Overhead</h3><p>You’re creating objects, calling methods through interfaces, logging. It’s not free.</p><p>❌ Tiny performance hit (milliseconds)</p><p>✅ But:</p><ul><li>Network latency to payment gateway is 100–500ms</li><li>Your code overhead is 1–5ms</li><li>Users won’t notice</li><li>For 99.9% of companies, this doesn’t matter</li></ul><p><strong>Exception:</strong> If you’re processing millions of payments per second, benchmark first. But if you’re at that scale, you have dedicated payment infrastructure anyway.</p><h3>Real-World Scenario: How This Saves Your Butt</h3><p>Let me walk through an actual situation:</p><p><strong>Scenario:</strong> Your app is processing ₹1 crore in monthly payments through Razorpay. Razorpay raises fees from 2% to 3%.</p><p><strong>Without this architecture:</strong></p><ul><li>Search code for all Razorpay references</li><li>Each one is different (some use direct API, some use their mobile SDK)</li><li>Refactor each location to add alternative gateway</li><li>Test everything again</li><li><strong>Timeline: 3 weeks</strong></li><li><strong>Cost: 2 developers × 3 weeks</strong></li></ul><p><strong>With this architecture:</strong></p><ul><li>Add StripeGateway class (1 day)</li><li>Add intelligent routing in factory (2 hours)</li><li>Test with mock gateways (4 hours)</li><li><strong>Timeline: 2 days</strong></li><li><strong>Cost: 1 developer × 2 days</strong></li><li><strong>Savings: 2.5 weeks, potentially thousands of dollars</strong></li></ul><p>And you keep 1% savings on fees going forward.</p><h3>How to Actually Build This</h3><h3>Phase 1: Start Simple (Week 1)</h3><ul><li>Build PaymentGateway interface</li><li>Implement for your current provider (Razorpay)</li><li>Refactor existing code to use it</li><li>Add tests with mock gateway</li></ul><h3>Phase 2: Add Second Gateway (Week 2–3)</h3><ul><li>Implement second gateway (PayTM)</li><li>Add factory with basic selection</li><li>Test both gateways</li><li>Monitor in production</li></ul><h3>Phase 3: Add Intelligence (Week 4+)</h3><ul><li>Region-based routing</li><li>Amount-based selection</li><li>Cost optimization</li><li>A/B testing different gateways</li></ul><p><strong>Don’t build the whole thing upfront.</strong> Build phase 1, use it, then add more.</p><h3>Common Mistakes to Avoid</h3><h3>❌ Mistake 1: Forcing All Gateways Into One Implementation</h3><pre>// DON&#39;T DO THIS:<br>public class PaymentGateway {<br>    private RazorpayConfig razorpayConfig;<br>    private PayTMConfig paytmConfig;<br>    private StripeConfig stripeConfig;<br>    <br>    public void pay(PaymentRequest request, String gateway) {<br>        if (&quot;razorpay&quot;.equals(gateway)) {<br>            // 50 lines of Razorpay code<br>        } else if (&quot;paytm&quot;.equals(gateway)) {<br>            // 50 lines of PayTM code<br>        }<br>    }<br>}</pre><p>This defeats the whole purpose. Each gateway should be its own class.</p><h3>❌ Mistake 2: Too Much Logic in the Factory</h3><pre>// DON&#39;T DO THIS:<br>public class GatewayFactory {<br>    public PaymentGateway getGateway(PaymentRequest request) {<br>        if (request.getAmount() &gt; 100000) {<br>            if (&quot;IN&quot;.equals(request.getCountry())) {<br>                if (isEvening()) {<br>                    // Some complex business logic<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Factory’s job: Create the gateway. Service’s job: Decide what to do.</p><p>Keep them separate.</p><h3>❌ Mistake 3: Forgetting to Handle Errors</h3><pre>// DON&#39;T DO THIS:<br>PaymentGateway gateway = GatewayFactory.getGateway(type);<br>PaymentResponse response = gateway.initiatePayment(request);<br>// What if gateway is null? What if API fails?</pre><p>Always assume things will fail:</p><pre>// DO THIS:<br>try {<br>    PaymentGateway gateway = GatewayFactory.getGateway(type);<br>    if (gateway == null) {<br>        throw new IllegalArgumentException(&quot;Unknown gateway: &quot; + type);<br>    }<br>    PaymentResponse response = gateway.initiatePayment(request);<br>    if (response == null) {<br>        // Handle null response<br>    }<br>    return response;<br>} catch (Exception e) {<br>    logger.logError(&quot;Payment failed: &quot; + e.getMessage());<br>    return new PaymentResponse(null, <br>        PaymentResponse.PaymentStatus.FAILED,<br>        &quot;Payment processing error&quot;);<br>}</pre><h3>How This Fits Into Your Bigger System</h3><p>Your payment system doesn’t exist in isolation. Here’s where it connects:</p><pre>User App<br>    ↓<br>Payment API (PaymentController)<br>    ↓<br>Payment Service (Business Logic)<br>    ↓<br>Payment Gateways (Razorpay, PayTM, Stripe)<br>    ↓<br>Payment Database (Store transaction records)<br>    ↓<br>Webhook Handler (Listen for confirmations)</pre><p>Your code in this article handles the “Payment Service” and “Payment Gateways” layers.</p><p>For the database: Store the PaymentResponse for every payment. Include paymentId, gateway, status, timestamp.</p><p>For webhooks: Different gateways send confirmations differently. Have a webhook handler that translates them:</p><pre>public class PaymentWebhookHandler {<br>    public void handleRazorpayWebhook(RazorpayWebhookBody body) {<br>        String paymentId = body.getPaymentId();<br>        paymentService.confirmPayment(paymentId, GatewayType.RAZORPAY);<br>    }<br>    <br>    public void handlePayTMWebhook(PayTMWebhookBody body) {<br>        String paymentId = body.getPaymentId();<br>        paymentService.confirmPayment(paymentId, GatewayType.PAYTM);<br>    }<br>}</pre><h3>The Bottom Line</h3><p>Building a payment system with design patterns might seem like extra work upfront.</p><p>But it’s insurance against the future.</p><p><strong>Without this architecture:</strong></p><ul><li>You’re locked into your payment provider</li><li>Adding a new gateway takes weeks</li><li>Code becomes a mess as you add more gateways</li><li>Testing is slow and expensive</li><li>Outages affect your entire service</li></ul><p><strong>With this architecture:</strong></p><ul><li>Adding a gateway takes days</li><li>Code remains clean and maintainable</li><li>Testing is fast and free</li><li>You can route around outages</li><li>Your business logic is independent of implementation details</li></ul><p><strong>The real magic:</strong> You don’t just handle payments differently. You handle ALL external services differently. This pattern works for email (SendGrid, Mailgun, AWS SES), SMS (Twilio, AWS SNS), storage (S3, Azure, GCP), etc.</p><p>Learn it once, use it everywhere.</p><h3>Your Next Steps</h3><ol><li><strong>Read this article again.</strong> Find the parts that confused you.</li><li><strong>Draw the architecture.</strong> Sketch it on paper or in Figma.</li><li><strong>Implement Phase 1.</strong> Create the interface for your current gateway.</li><li><strong>Write tests.</strong> Use a mock gateway.</li><li><strong>Refactor slowly.</strong> Don’t try to change everything at once.</li><li><strong>Add a second gateway.</strong> See how easy it becomes.</li><li><strong>Share what you learned.</strong> Teach your team.</li></ol><p>Payment processing isn’t exciting. But your system’s architecture should be.</p><p><strong>Have you built payment systems? What patterns have saved your sanity? Drop a comment — I’d love to learn from your experience.</strong></p><p><em>Thanks for reading. Now go build something resilient.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cd2a2c0486f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>