<?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 Irfan on Medium]]></title>
        <description><![CDATA[Stories by Irfan on Medium]]></description>
        <link>https://medium.com/@neuron_sama?source=rss-b1b53ca4306e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pXIAE_wjmCMUZ6I78lRCsw.jpeg</url>
            <title>Stories by Irfan on Medium</title>
            <link>https://medium.com/@neuron_sama?source=rss-b1b53ca4306e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:47:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@neuron_sama/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[Singleton Design Pattern]]></title>
            <link>https://medium.com/@neuron_sama/singleton-design-pattern-3155d9821749?source=rss-b1b53ca4306e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3155d9821749</guid>
            <category><![CDATA[singleton-design-pattern]]></category>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Irfan]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 07:10:20 GMT</pubDate>
            <atom:updated>2026-02-28T07:10:20.568Z</atom:updated>
            <content:encoded><![CDATA[<p>Singleton means a class which can only be instantiate once. If we again try to instantiate the class it will just return us the earlier object.</p><p>Singleton design pattern is used to implement singleton class.</p><h3>Introduction</h3><p>Without implementing singleton pattern the code will look like this:</p><pre>class NoSingleton:<br>    def __init__(self):<br>        print(&quot;Singleton Constructor called. New Object created.&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    s1 = NoSingleton()<br>    s2 = NoSingleton()<br><br>    print(s1 is s2)</pre><h4>Output</h4><pre>Singleton Constructor called. New Object created.<br>Singleton Constructor called. New Object created.<br>False</pre><p>In the above example we can see 2 different objects being created. We can implement a simple singleton code by making the constructor private (note that is python there is no concept of a private constructor)</p><pre>class Singleton:<br>    _instance = None  # Initialize static member <br>    _initialized = False  # Guard to mimic private constructor<br><br>    # It is always public — we manually guard it with a flag<br>    def __init__(self):<br>        if not Singleton._initialized:<br>            raise RuntimeError(&quot;Constructor is private. Use get_instance() instead.&quot;)  # mimicking private constructor behavior<br>        print(&quot;Singleton Constructor called&quot;)<br><br>    # @classmethod + cls parameter : for static methods<br>    @classmethod<br>    def get_instance(cls):<br>        if cls._instance is None:<br>            cls._initialized = True<br>            cls._instance = Singleton()<br>            cls._initialized = False<br>        return cls._instance<br><br><br>if __name__ == &quot;__main__&quot;:<br>    s1 = Singleton.get_instance()<br>    s2 = Singleton.get_instance()<br><br>    print(s1 is s2)<br><br>    # Trying to create a new instance directly will raise an error<br>    # s3 = Singleton()  # RuntimeError: Constructor is private. Use get_instance() instead.</pre><h4>Output</h4><pre>Singleton Constructor called<br>True</pre><p>The problem is that the above code is not thread safe. To make it thread safe we make it like below code.</p><pre>import threading<br><br><br>class Singleton:<br>    _instance = None  <br>    _lock = threading.Lock()<br>    _initialized = False<br><br>    <br>    def __init__(self):<br>        if not Singleton._initialized:<br>            raise RuntimeError(&quot;Constructor is private. Use get_instance() instead.&quot;) <br>        print(&quot;Singleton Constructor Called!&quot;)<br><br>    <br>    @classmethod<br>    def get_instance(cls):<br>        with cls._lock: <br>            if cls._instance is None:<br>                cls._initialized = True<br>                cls._instance = Singleton()<br>                cls._initialized = False<br>        return cls._instance<br><br>if __name__ == &quot;__main__&quot;:<br>    s1 = Singleton.get_instance()<br>    s2 = Singleton.get_instance()<br><br>    print(s1 is s2)<br><br><br># This aproach is resource heavy because we have to hold the resource whenever the function is called </pre><h4>Output</h4><pre>Singleton Constructor Called!<br>True</pre><p><strong>Problem:</strong> <em>The above aproach is resource heavy because we have to hold the resource whenever the method is called.</em></p><p>To solve this problem we use locks.</p><pre>import threading<br><br><br>class Singleton:<br>    _instance = None  <br>    _lock = threading.Lock()<br>    _initialized = False<br><br>    def __init__(self):<br>        if not Singleton._initialized:<br>            raise RuntimeError(&quot;Constructor is private. Use get_instance() instead.&quot;)<br>        print(&quot;Singleton Constructor Called!&quot;)<br><br>    # Double check locking..<br>    @classmethod<br>    def get_instance(cls):<br>        if cls._instance is None:  # First check (no locking)<br>            with cls._lock:  # Lock only if needed<br>                if cls._instance is None:  # Second check (after acquiring lock)<br>                    cls._initialized = True<br>                    cls._instance = Singleton()<br>                    cls._initialized = False<br>        return cls._instance<br><br><br>if __name__ == &quot;__main__&quot;:<br>    s1 = Singleton.get_instance()<br>    s2 = Singleton.get_instance()<br><br>    print(s1 is s2) </pre><h4>Output</h4><pre>Singleton Constructor Called!<br>True</pre><p>Another way to solve the problem without using locks is to do eager initialisation.</p><pre>class Singleton:<br>    _initialized = False <br><br>    def __init__(self):<br>        if not Singleton._initialized:<br>            raise RuntimeError(&quot;Constructor is private. Use get_instance() instead.&quot;)<br>        print(&quot;Singleton Constructor Called!&quot;)<br><br>    @classmethod<br>    def get_instance(cls):<br>        return cls._instance<br><br><br># Initialize static members — eagerly create the instance at class load time<br>Singleton._initialized = True<br>Singleton._instance = Singleton()<br>Singleton._initialized = False<br><br><br>if __name__ == &quot;__main__&quot;:<br>    s1 = Singleton.get_instance()<br>    s2 = Singleton.get_instance()<br><br>    print(s1 is s2) <br><br><br># Pros: simple to implement<br># Cons: if the object initialisation is resource heavy and it is not used after initialization then it is waste of resource, so this approach can only be suitable for light weight objects</pre><h4>Output</h4><pre>Singleton Constructor Called!<br>True</pre><p><strong><em>Pros:</em></strong><em> simple to implement</em></p><p><strong><em>Cons:</em></strong><em> if the object initialisation is resource heavy and it is not used after initialization then it is waste of resource, so this approach can only be suitable for light weight objects.</em></p><h3>Practical Usecase</h3><ol><li>Logging system</li><li>Database connection</li><li>Configuration Manager</li></ol><p>In all these examples we only need one instance of the class.</p><p><em>Thank you for reading the blog. In our next blog we will be learning about build a LLD diagram of a food delivery app.</em></p><p><strong><em>Credits:</em></strong><em> </em><a href="https://www.youtube.com/playlist?list=PLQEaRBV9gAFvzp6XhcNFpk1WdOcyVo9qT"><strong><em>Aditya Tandon</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3155d9821749" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Design Pattern]]></title>
            <link>https://medium.com/@neuron_sama/factory-design-pattern-fbbe550c39a2?source=rss-b1b53ca4306e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbbe550c39a2</guid>
            <category><![CDATA[factory-design-pattern]]></category>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Irfan]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 06:51:24 GMT</pubDate>
            <atom:updated>2026-02-24T06:51:24.571Z</atom:updated>
            <content:encoded><![CDATA[<p>In our last blog we talked about strategy design pattern In today’s blog we will learning a new design pattern.</p><h3>Introduction</h3><p>In real world factory is something from which we get the products. In the same way in LLD, Factory is a class from which we get our objects.</p><p>Main goal of Factory Design pattern is to seperate business logic and object creation logic. <strong>There are 3 types of Factory Design:</strong></p><ol><li>Simple Factory. (not a design pattern by itself, it is more like a design principle)</li><li>Factory Method.</li><li>Abstract Factory Method.</li></ol><h3>Simple Factory</h3><p>It is a type of Factory class that descides which concrete class to instantiate. (creating it’s object)</p><p><strong>Ex: </strong>Let’s assume a Burger Shop scenario. It can prepare 3 types of burger: BasicBurger, StaandardBurger and PremiumBurger. This scenario can be depicted in the below UML diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VqGTRr8BOBp64iljpMjoFQ.png" /></figure><ul><li>Below is the implementation of this:</li></ul><pre>from abc import ABC, abstractmethod<br><br><br>class Burger(ABC):<br>    @abstractmethod<br>    def prepare(self):<br>        pass<br><br><br>class BasicBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Basic Burger with bun, patty, and ketchup!&quot;)<br><br><br>class StandardBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Standard Burger with bun, patty, cheese, and lettuce!&quot;)<br><br><br>class PremiumBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Premium Burger with gourmet bun, premium patty, cheese, lettuce, and secret sauce!&quot;)<br><br><br>class BurgerFactory:<br>    def create_burger(self, burger_type: str) -&gt; Burger | None:<br>        if burger_type == &quot;basic&quot;:<br>            return BasicBurger()<br>        elif burger_type == &quot;standard&quot;:<br>            return StandardBurger()<br>        elif burger_type == &quot;premium&quot;:<br>            return PremiumBurger()<br>        else:<br>            print(&quot;Invalid burger type!&quot;)<br>            return None<br><br><br>def main():<br>    burger_type = &quot;standard&quot;<br><br>    my_burger_factory = BurgerFactory()<br><br>    burger = my_burger_factory.create_burger(burger_type)<br><br>    burger.prepare()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>Output</h4><pre>Preparing Standard Burger with bun, patty, cheese, and lettuce!</pre><h4>Standard UML Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m4He-7fDAGwWXxViELQk_w.png" /></figure><h3>Factory Method</h3><p><strong>Defination: </strong>Definies an interface for creating objects but allows subclass to decide which class to instantiate.</p><p>Suppose in our earlier example we can have multiple shops. The new shop (KingBurger) can make BasicWheatBurger, StandardWheatBurger and PremiumWheatBurger and the old shop (SighBurger) can make BasicBurger, StandardBurger and PremiumBurger.</p><p>Polymorphically it will decide which burger to create. Just Like the abstraction in Product we can also create abstraction layer in Factory side also in Factory method.</p><p><strong>Ex:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIDkr49Pzeg6OAcW7t36hw.png" /></figure><ul><li>Below is the implementation of this:</li></ul><pre>from abc import ABC, abstractmethod<br><br><br># Product Class and subclasses<br>class Burger(ABC):<br>    @abstractmethod<br>    def prepare(self):  <br>        pass<br><br><br>class BasicBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Basic Burger with bun, patty, and ketchup!&quot;)<br><br><br>class StandardBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Standard Burger with bun, patty, cheese, and lettuce!&quot;)<br><br><br>class PremiumBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Premium Burger with gourmet bun, premium patty, cheese, lettuce, and secret sauce!&quot;)<br><br><br>class BasicWheatBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Basic Wheat Burger with bun, patty, and ketchup!&quot;)<br><br><br>class StandardWheatBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Standard Wheat Burger with bun, patty, cheese, and lettuce!&quot;)<br><br><br>class PremiumWheatBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Premium Wheat Burger with gourmet bun, premium patty, cheese, lettuce, and secret sauce!&quot;)<br><br><br># Factory and its concretions<br>class BurgerFactory(ABC):<br>    @abstractmethod<br>    def create_burger(self, burger_type: str) -&gt; Burger | None:<br>        pass<br><br><br>class SinghBurger(BurgerFactory):<br>    def create_burger(self, burger_type: str) -&gt; Burger | None:<br>        if burger_type == &quot;basic&quot;:<br>            return BasicBurger()<br>        elif burger_type == &quot;standard&quot;:<br>            return StandardBurger()<br>        elif burger_type == &quot;premium&quot;:<br>            return PremiumBurger()<br>        else:<br>            print(&quot;Invalid burger type!&quot;)<br>            return None<br><br><br>class KingBurger(BurgerFactory):<br>    def create_burger(self, burger_type: str) -&gt; Burger | None:<br>        if burger_type == &quot;basic&quot;:<br>            return BasicWheatBurger()<br>        elif burger_type == &quot;standard&quot;:<br>            return StandardWheatBurger()<br>        elif burger_type == &quot;premium&quot;:<br>            return PremiumWheatBurger()<br>        else:<br>            print(&quot;Invalid burger type!&quot;)<br>            return None<br><br><br>def main():<br>    burger_type = &quot;basic&quot;<br><br>    my_factory = SinghBurger()<br><br>    burger = my_factory.create_burger(burger_type)<br><br>    burger.prepare()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><pre>Preparing Basic Burger with bun, patty, and ketchup!</pre><h4>Standard UML</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73TOaoXPlhVi8a92xiXoCw.png" /></figure><h3>Abstarct Factory Method</h3><p>It provides an interface for creating families of relerated objects without specifying there specific concrete class.</p><p>Abstarct factory are those factory that are responsible for making more than one products.</p><p>Ex: Let’s say KingBurger can make a new product GarlicBread (BasicGarlicBread, StandardGarlicBread and PremiumGarlicBread)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXRpainle3JqjulE-5uESA.png" /></figure><ul><li>Below is the implementation of this:</li></ul><pre>from abc import ABC, abstractmethod<br><br><br># Product 1 --&gt; Burger<br>class Burger(ABC):<br>    @abstractmethod<br>    def prepare(self): <br>        pass<br><br><br>class BasicBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Basic Burger with bun, patty, and ketchup!&quot;)<br><br><br>class StandardBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Standard Burger with bun, patty, cheese, and lettuce!&quot;)<br><br><br>class PremiumBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Premium Burger with gourmet bun, premium patty, cheese, lettuce, and secret sauce!&quot;)<br><br><br>class BasicWheatBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Basic Wheat Burger with bun, patty, and ketchup!&quot;)<br><br><br>class StandardWheatBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Standard Wheat Burger with bun, patty, cheese, and lettuce!&quot;)<br><br><br>class PremiumWheatBurger(Burger):<br>    def prepare(self):<br>        print(&quot;Preparing Premium Wheat Burger with gourmet bun, premium patty, cheese, lettuce, and secret sauce!&quot;)<br><br><br># Product 2 --&gt; GarlicBread<br>class GarlicBread(ABC):<br>    @abstractmethod<br>    def prepare(self):<br>        pass<br><br><br>class BasicGarlicBread(GarlicBread):<br>    def prepare(self):<br>        print(&quot;Preparing Basic Garlic Bread with butter and garlic!&quot;)<br><br><br>class StandardGarlicBread(GarlicBread):<br>    def prepare(self):<br>        print(&quot;Preparing Standard Garlic Bread with extra cheese and butter!&quot;)<br><br><br>class PremiumGarlicBread(GarlicBread):<br>    def prepare(self):<br>        print(&quot;Preparing Premium Garlic Bread with extra cheese and butter!&quot;)<br><br><br># Factory and its concretions<br>class MealFactory(ABC):<br>    @abstractmethod<br>    def create_burger(self, burger_type: str) -&gt; Burger | None:<br>        pass<br><br>    @abstractmethod<br>    def create_garlic_bread(self, garlic_bread_type: str) -&gt; GarlicBread | None:<br>        pass<br><br><br>class SinghBurger(MealFactory):<br>    def create_burger(self, burger_type: str) -&gt; Burger | None:<br>        if burger_type == &quot;basic&quot;:<br>            return BasicBurger()<br>        elif burger_type == &quot;standard&quot;:<br>            return StandardBurger()<br>        elif burger_type == &quot;premium&quot;:<br>            return PremiumBurger()<br>        else:<br>            print(&quot;Invalid burger type!&quot;)<br>            return None<br><br>    def create_garlic_bread(self, garlic_bread_type: str) -&gt; GarlicBread | None:<br>        if garlic_bread_type == &quot;basic&quot;:<br>            return BasicGarlicBread()<br>        elif garlic_bread_type == &quot;cheese&quot;:<br>            return StandardGarlicBread()<br>        else:<br>            print(&quot;Invalid Garlic bread type!&quot;)<br>            return None<br><br><br>class KingBurger(MealFactory):<br>    def create_burger(self, burger_type: str) -&gt; Burger | None:<br>        if burger_type == &quot;basic&quot;:<br>            return BasicWheatBurger()<br>        elif burger_type == &quot;standard&quot;:<br>            return StandardWheatBurger()<br>        elif burger_type == &quot;premium&quot;:<br>            return PremiumWheatBurger()<br>        else:<br>            print(&quot;Invalid burger type!&quot;)<br>            return None<br><br>    def create_garlic_bread(self, garlic_bread_type: str) -&gt; GarlicBread | None:<br>        if garlic_bread_type == &quot;basic&quot;:<br>            return BasicGarlicBread()<br>        elif garlic_bread_type == &quot;standard&quot;:<br>            return PremiumGarlicBread()<br>        elif garlic_bread_type == &quot;premium&quot;:<br>            return PremiumWheatBurger()<br>        else:<br>            print(&quot;Invalid Garlic bread type!&quot;)<br>            return None<br><br><br>def main():<br>    burger_type = &quot;basic&quot;<br>    garlic_bread_type = &quot;standard&quot;<br><br>    meal_factory = KingBurger()<br><br>    burger = meal_factory.create_burger(burger_type)<br>    garlic_bread = meal_factory.create_garlic_bread(garlic_bread_type)<br><br>    burger.prepare()<br>    garlic_bread.prepare()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>Output</h4><pre>Preparing Basic Wheat Burger with bun, patty, and ketchup!<br>Preparing Premium Garlic Bread with extra cheese and butter!</pre><h4>Standard UML Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EiNc4HMuRS1Up5M8BBzoBQ.png" /></figure><h3>Real world Examples</h3><p>Notification System</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4enQgwnvA77UJV-gACd7TQ.png" /></figure><ul><li>The above can also be made using Strategy Design Pattern. It depends on us to choose the solution which suits best in our case.</li></ul><p><strong>NOTE: </strong>Rule of thub is: For Algoritmic problem choose Stratety design pattern and for Object Creation choose Factory Design Pattern.</p><p><strong><em>Thank you for reading the blog. In our next blog we will be learning about Singleton Design Pattern.</em></strong></p><p><strong><em>Credits:</em></strong><em> </em><a href="https://www.youtube.com/playlist?list=PLQEaRBV9gAFvzp6XhcNFpk1WdOcyVo9qT"><strong><em>Aditya Tandon</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbbe550c39a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy Design Pattern]]></title>
            <link>https://medium.com/@neuron_sama/strategy-design-pattern-1490bca4d36c?source=rss-b1b53ca4306e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1490bca4d36c</guid>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[strategy-design-pattern]]></category>
            <dc:creator><![CDATA[Irfan]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 07:32:26 GMT</pubDate>
            <atom:updated>2026-02-19T07:38:17.536Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s blog and the upcoming ones we will be discussing about various design patterns. Officially there are 23 designs patterns.</p><p>First of all, what do you mean by design pattern ? A design pattern simply means an approach to solve any we face while developing any application.</p><p>People faced similar problems earlier and come up with 23 design patterns. Instead of reinventing the wheel we use these patterns whenever we we face some specific problem, which we will be discussing in depth.</p><p>Fundamentally all these design patterns says the same thing in different dfferent ways. In every application there will be two major parts, one part is that changes and the other part that doesn’t changes.</p><p>The main objective of these design patterns is to extract the dynamic part and make it a seeprate entity.</p><h3>Introduction</h3><p>strategy design pattern makes us realise that inheritance is bad. Let’s consider an example of an application thaat simulates robots</p><p><strong>Ex:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*3m00FWkf_wkxFvjAtG2LPg.png" /></figure><ul><li>Let say we have a Robot class with two concrete methods walk() and talk(). walk() defines how different robots walk and talk() defines how they talk.</li><li>we also have an abstract method projection which tells us how the robots look like.</li><li>So we can clearly inherit the Robot class with Companion R and Worker R. There is no problem in it.</li></ul><p>Let’s say now a new type of robots came which can fly</p><p><strong>Ex:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*ErHvUewk-rE85-3nd6siaQ.png" /></figure><ul><li>But the problem is for every new type of robots that can fly we have to write the fly() method logic again and again.</li><li>So let’s increase the inehritance hierarchy to solve this problem.</li></ul><p><strong>Ex:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*34KZy0Po_QMGp46DeVbwOw.png" /></figure><p>Problem: Suppose a new type of flying robots comes which flies using jets. To solve this problem we again have to increase the ineheritance hierarchy.</p><p><strong>Ex:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lvEE_2Y-m6tTmdVx0cAblw.png" /></figure><p>The problem will keep on rising if different types of robot comes.</p><blockquote><strong>NOTE:</strong> THe solution to inheritance should not be more inheritance.</blockquote><p><em>To solve this type of problem we use Strategy design pattern. Strategy Design pattern defines a family of algoritm, puts them into seperate classes so that they can be changed at runtime.</em></p><p>Ex: The above situation can be perfectly depicted using the below UML digram. Instead of using only inheritance we will be uisng composition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wG2cvskR_Kzv-Qgb5TIOGg.png" /></figure><ul><li>In the above diagram if different robots shows projection differently for different then again we will face the same problem.</li><li>So we can make a seperate abstract class Projectable and inherit it to NormalProjection and NoProjection and proceed accordingly.</li></ul><h3>Implementaion</h3><pre>from abc import ABC, abstractmethod<br><br># --- Strategy Interface for Walk ---<br>class WalkableRobot(ABC):<br>    @abstractmethod<br>    def walk(self):<br>        pass<br><br><br># --- Concrete Strategies for walk ---<br>class NormalWalk(WalkableRobot):<br>    def walk(self):<br>        print(&quot;Walking normally...&quot;)<br><br><br>class NoWalk(WalkableRobot):<br>    def walk(self):<br>        print(&quot;Cannot walk.&quot;)<br><br><br># --- Strategy Interface for Talk ---<br>class TalkableRobot(ABC):<br>    @abstractmethod<br>    def talk(self):<br>        pass<br><br><br># --- Concrete Strategies for Talk ---<br>class NormalTalk(TalkableRobot):<br>    def talk(self):<br>        print(&quot;Talking normally...&quot;)<br><br><br>class NoTalk(TalkableRobot):<br>    def talk(self):<br>        print(&quot;Cannot talk.&quot;)<br><br><br># --- Strategy Interface for Fly ---<br>class FlyableRobot(ABC):<br>    @abstractmethod<br>    def fly(self):<br>        pass<br><br><br>class NormalFly(FlyableRobot):<br>    def fly(self):<br>        print(&quot;Flying normally...&quot;)<br><br><br>class NoFly(FlyableRobot):<br>    def fly(self):<br>        print(&quot;Cannot fly.&quot;)<br><br><br># --- Robot Base Class ---<br>class Robot(ABC):<br>    def __init__(self, w: WalkableRobot, t: TalkableRobot, f: FlyableRobot):<br>        self.__walkBehavior: WalkableRobot = w<br>        self.__talkBehavior: TalkableRobot = t<br>        self.__flyBehavior: FlyableRobot = f<br><br>    def walk(self):<br>        self.__walkBehavior.walk()<br><br>    def talk(self):<br>        self.__talkBehavior.talk()<br><br>    def fly(self):<br>        self.__flyBehavior.fly()<br><br>    @abstractmethod<br>    def projection(self):<br>        pass  # Abstract method for subclasses<br><br><br># --- Concrete Robot Types ---<br>class CompanionRobot(Robot):<br>    def __init__(self, w: WalkableRobot, t: TalkableRobot, f: FlyableRobot):<br>        super().__init__(w, t, f)<br><br>    def projection(self):<br>        print(&quot;Displaying friendly companion features...&quot;)<br><br><br>class WorkerRobot(Robot):<br>    def __init__(self, w: WalkableRobot, t: TalkableRobot, f: FlyableRobot):<br>        super().__init__(w, t, f)<br><br>    def projection(self):<br>        print(&quot;Displaying worker efficiency stats...&quot;)<br><br><br># --- Main Function ---<br>if __name__ == &quot;__main__&quot;:<br>    robot1 = CompanionRobot(NormalWalk(), NormalTalk(), NoFly())<br>    robot1.walk()<br>    robot1.talk()<br>    robot1.fly()<br>    robot1.projection()<br><br>    print(&quot;--------------------&quot;)<br><br>    robot2 = WorkerRobot(NoWalk(), NoTalk(), NormalFly())<br>    robot2.walk()<br>    robot2.talk()<br>    robot2.fly()<br>    robot2.projection()</pre><h4>Output</h4><pre>Walking normally...<br>Talking normally...<br>Cannot fly.<br>Displaying friendly companion features...<br>--------------------<br>Cannot walk.<br>Cannot talk.<br>Flying normally...<br>Displaying worker efficiency stats...</pre><h3>Real Life Example</h3><p>In payment systems we can pay with different ways, like w can use Credit Card, Debit Card, UPI, NEFT etc etc. In this we can use strategy design pattern.</p><p><strong><em>Thank you for reading the blog. In our next blog we will be learning about Factory Design Pattern.</em></strong></p><p><strong><em>Credits:</em></strong><em> </em><a href="https://www.youtube.com/playlist?list=PLQEaRBV9gAFvzp6XhcNFpk1WdOcyVo9qT"><strong><em>Aditya Tandon</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1490bca4d36c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLD of a Document Editor (like google docs)]]></title>
            <link>https://medium.com/@neuron_sama/lld-of-a-document-editor-like-google-docs-3d62d58a1271?source=rss-b1b53ca4306e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d62d58a1271</guid>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Irfan]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 15:01:35 GMT</pubDate>
            <atom:updated>2026-02-17T15:01:35.795Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous blogs we talked about SOLID design principle in depth. Today we will use that knowledge and try to build a LLD of a document editor.</p><h3>Introduction</h3><p>First of all we need to be clear that we donot have to design the whole features of google docs. We assume some parts and try make a design around them while keeping in mind about scalability.</p><p><strong>Ex:</strong> Let’s assume for now our document editor implements the text and image feature only. The design we will be building should scalable i.e. we should be easily able to implement new features like support for tables, videos, fonts etc without much effort.</p><blockquote><strong>NOTE: </strong>For solving any LLD problem we have to approach. One is <strong>Top Down approach</strong> (first build the topmost class then the lower ones) and the other is <strong>Bottom Up approach</strong> (first build the lowermost classes then the higher classes).</blockquote><p><em>Usually bottom up approach is preffered but in some problems top down approach is more feasible. In this problem we will be implementing bottom up approach.</em></p><h3>Bad Design</h3><p>Let’s first try to build a bad desing. This is important because this design will come into our mind at the start. After building this we findout the problem and solve them accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*WJdvCjJo7IKEREThpmn40Q.png" /></figure><ul><li>Code for bad design</li></ul><pre>from typing import List<br><br>class DocumentEditor:<br>    def __init__(self):<br>        self.__documentElements: List[str] = []<br>        self.__renderedDocument: str = &quot;&quot;<br><br>    # Adds text as a plain string<br>    def addText(self, text: str):<br>        self.__documentElements.append(text)<br><br>    # Adds an image represented by its file path<br>    def addImage(self, imagePath: str):<br>        self.__documentElements.append(imagePath)<br><br>    # Renders the document by checking the type of each element at runtime<br>    # In LLD business logic doesnot matters <br>    def renderDocument(self) -&gt; str:<br>        if not self.__renderedDocument:<br>            result = &quot;&quot;<br>            for element in self.__documentElements:<br>                if len(element) &gt; 4 and (element[len(element) - 4:] == &quot;.jpg&quot; or element[len(element) - 4:] == &quot;.png&quot;):<br>                    result += &quot;[Image: &quot; + element + &quot;]&quot; + &quot;\n&quot;<br>                else:<br>                    result += element + &quot;\n&quot;<br>            self.__renderedDocument = result<br>        return self.__renderedDocument<br><br>    def saveToFile(self):<br>        try:<br>            with open(&quot;document.txt&quot;, &quot;w&quot;) as file:<br>                file.write(self.renderDocument())<br>                print(&quot;Document saved to document.txt&quot;)<br>        except:<br>            print(&quot;Error: Unable to open file for writing.&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    editor = DocumentEditor()<br>    editor.addText(&quot;Hello, world!&quot;)<br>    editor.addImage(&quot;picture.jpg&quot;)<br>    editor.addText(&quot;This is a document editor.&quot;)<br><br>    print(editor.renderDocument())<br><br>    editor.saveToFile()</pre><p><strong>Output</strong></p><pre>Hello, world!<br>[Image: picture.jpg]<br>This is a document editor.<br><br>Document saved to document.txt</pre><p><strong>Problem:</strong> Breaks SRP and OCP</p><h3>Good Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kghBSrhOKziNtzO7S2uogA.png" /></figure><ul><li>The render() method in Document class deligates it’s task to DocumentElement class.</li><li>Also the renderDocument() method in DocumentEditor class deligates it’s task to the render() method of Document class.</li><li>Likewise, the save() method in DocumentEditor class also deligates it’s tasl to Persiatnce class.</li><li>The above design now follows SOLID principle.</li></ul><p>Below is the implementation of good design:</p><pre>from abc import ABC, abstractmethod<br>from typing import List<br><br># Abstraction for document elements<br>class DocumentElement(ABC):<br>    @abstractmethod<br>    def render(self) -&gt; str:<br>        pass<br><br><br># Concrete implementation for text elements<br>class TextElement(DocumentElement):<br>    def __init__(self, text: str):<br>        self.__text: str = text<br><br>    def render(self) -&gt; str:<br>        return self.__text<br><br><br># Concrete implementation for image elements<br>class ImageElement(DocumentElement):<br>    def __init__(self, imagePath: str):<br>        self.__imagePath: str = imagePath<br><br>    def render(self) -&gt; str:<br>        return &quot;[Image: &quot; + self.__imagePath + &quot;]&quot;<br><br><br># NewLineElement represents a line break in the document.<br>class NewLineElement(DocumentElement):<br>    def render(self) -&gt; str:<br>        return &quot;\n&quot;<br><br><br># TabSpaceElement represents a tab space in the document.<br>class TabSpaceElement(DocumentElement):<br>    def render(self) -&gt; str:<br>        return &quot;\t&quot;<br><br><br># Document class responsible for holding a collection of elements<br>class Document:<br>    def __init__(self):<br>        self.__documentElements: List[DocumentElement] = []<br><br>    def addElement(self, element: DocumentElement):<br>        self.__documentElements.append(element)<br><br>    # Renders the document by concatenating the render output of all elements.<br>    def render(self) -&gt; str:<br>        result = &quot;&quot;<br>        for element in self.__documentElements:<br>            result += element.render()<br>        return result<br><br><br># Persistence abstraction<br>class Persistence(ABC):<br>    @abstractmethod<br>    def save(self, data: str):<br>        pass<br><br><br># FileStorage implementation of Persistence<br>class FileStorage(Persistence):<br>    def save(self, data: str):<br>        try:<br>            with open(&quot;document.txt&quot;, &quot;w&quot;) as outFile:<br>                outFile.write(data)<br>            print(&quot;Document saved to document.txt&quot;)<br>        except:<br>            print(&quot;Error: Unable to open file for writing.&quot;)<br><br><br># Placeholder DBStorage implementation<br>class DBStorage(Persistence):<br>    def save(self, data: str):<br>        # Save to DB<br>        pass<br><br><br># DocumentEditor class managing client interactions<br>class DocumentEditor:<br>    def __init__(self, document: Document, storage: Persistence):<br>        self.__document: Document = document<br>        self.__storage: Persistence = storage<br>        self.__renderedDocument: str = &quot;&quot;<br><br>    def addText(self, text: str):<br>        self.__document.addElement(TextElement(text))<br><br>    def addImage(self, imagePath: str):<br>        self.__document.addElement(ImageElement(imagePath))<br><br>    # Adds a new line to the document.<br>    def addNewLine(self):<br>        self.__document.addElement(NewLineElement())<br><br>    # Adds a tab space to the document.<br>    def addTabSpace(self):<br>        self.__document.addElement(TabSpaceElement())<br><br>    def renderDocument(self) -&gt; str:<br>        if not self.__renderedDocument:<br>            self.__renderedDocument = self.__document.render()<br>        return self.__renderedDocument<br><br>    def saveDocument(self):<br>        self.__storage.save(self.renderDocument())<br><br><br># Client usage example<br>if __name__ == &quot;__main__&quot;:<br>    document = Document()<br>    persistence = FileStorage()<br><br>    editor = DocumentEditor(document, persistence)<br><br>    # Simulate a client using the editor with common text formatting features.<br>    editor.addText(&quot;Hello, world!&quot;)<br>    editor.addNewLine()<br>    editor.addText(&quot;This is a real-world document editor example.&quot;)<br>    editor.addNewLine()<br>    editor.addTabSpace()<br>    editor.addText(&quot;Indented text after a tab space.&quot;)<br>    editor.addNewLine()<br>    editor.addImage(&quot;picture.jpg&quot;)<br><br>    # Render and display the final document.<br>    print(editor.renderDocument())<br><br>    editor.saveDocument()</pre><p><strong>Output</strong></p><pre>Hello, world!<br>This is a real-world document editor example.<br>        Indented text after a tab space.<br>[Image: picture.jpg]<br>Document saved to document.txt</pre><blockquote>NOTE: Although in DocumentEditor class and Document class some of the methods are beign deligated, still we need to know about this methods. So it can consider a violation of SRP (Single Responsibility Principle).</blockquote><p><em>It is a very subjective matter. It depends on the usecase. Let suppose we are considering that our work is working on deligacy then the design is good. Otherwise it can be considered a vioaltion of SRP. We and the interviewer / senior have to come to conclusion about which road to take.</em></p><h3>Enhancement of good design</h3><p>Let’s suppose we considered the above diagram a violation of SRP. Then we can consider the below design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iC28M5X9oiCjVA5hiOYWvg.png" /></figure><ul><li>Model class means a class which only performs CRUD operations</li><li>Now it is not violating the SRP</li><li>But it breaks Principle of Least Knowledge</li></ul><blockquote>NOTE: Principle of Least Knowledge is a design principle which states that a class should always intearact with those objects which are directly related to the class. If it is not followed then couping increases.</blockquote><p><em>As i said earlier we an our senior/interviewer have to come to the same page and decided which one to choose.</em></p><p><strong><em>Thankyou for reading the blog. In our next blog we will be learning about Strategy Design Pattern.</em></strong></p><p><strong><em>Credits:</em></strong><em> </em><a href="https://www.youtube.com/playlist?list=PLQEaRBV9gAFvzp6XhcNFpk1WdOcyVo9qT"><strong><em>Aditya Tandon</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d62d58a1271" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solid Design Principle part 4]]></title>
            <link>https://medium.com/@neuron_sama/solid-design-principle-part-4-545813c0a34c?source=rss-b1b53ca4306e------2</link>
            <guid isPermaLink="false">https://medium.com/p/545813c0a34c</guid>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Irfan]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 10:35:56 GMT</pubDate>
            <atom:updated>2026-02-12T10:35:56.422Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s blow we will be learning about ISP (Interface Segragation Principle) and DIP (Dependency Inversion Principle)</p><h3>ISP Introduction</h3><p>It states that:</p><ul><li>Many client specific interfaces and better than one general purpose interface.</li><li>client should not be forced to implement methods they donot need.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYlXSb6DGhDhMITNwLT2bA.png" /></figure><ul><li>In the above example we have a general purpose interface Shape.</li><li>Problem is that Square and Rectangle are 2D objects and they donot have volume, so we have to through some exception after inhereting the volume() method.</li><li>This breaks ISP.</li></ul><p>Instead of making a general purpose Interface, we can make two different interfaces for 2D shape and 3D shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEf95XFMduQHdjMZhg1sPw.png" /></figure><ul><li>Below is the code that violates ISP</li></ul><pre>from abc import ABC, abstractmethod<br><br># Single interface for all shapes (Violates ISP)<br>class Shape(ABC):<br>    @abstractmethod<br>    def area(self) -&gt; float:<br>        pass<br><br>    @abstractmethod<br>    def volume(self) -&gt; float:   # 2D shapes don&#39;t have volume!<br>        pass<br><br><br># Square is a 2D shape but is forced to implement volume()<br>class Square(Shape):<br>    def __init__(self, side: float):<br>        self.side = side<br><br>    def area(self) -&gt; float:<br>        return self.side * self.side<br><br>    def volume(self) -&gt; float:<br>        raise RuntimeError(&quot;Volume not applicable for Square&quot;)  # Unnecessary method<br><br><br># Rectangle is also a 2D shape but is forced to implement volume()<br>class Rectangle(Shape):<br>    def __init__(self, length: float, width: float):<br>        self.length = length<br>        self.width = width<br><br>    def area(self) -&gt; float:<br>        return self.length * self.width<br><br>    def volume(self) -&gt; float:<br>        raise RuntimeError(&quot;Volume not applicable for Rectangle&quot;)  # Unnecessary method<br><br><br># Cube is a 3D shape, so it actually has a volume<br>class Cube(Shape):<br>    def __init__(self, side: float):<br>        self.side = side<br><br>    def area(self) -&gt; float:<br>        return 6 * self.side * self.side<br><br>    def volume(self) -&gt; float:<br>        return self.side ** 3<br><br><br>def main():<br>    square: Shape = Square(5)<br>    rectangle: Shape = Rectangle(4, 6)<br>    cube: Shape = Cube(3)<br><br>    print(&quot;Square Area:&quot;, square.area())<br>    print(&quot;Rectangle Area:&quot;, rectangle.area())<br>    print(&quot;Cube Area:&quot;, cube.area())<br>    print(&quot;Cube Volume:&quot;, cube.volume())<br><br>    try:<br>        print(&quot;Square Volume:&quot;, square.volume())  # Will raise error<br>    except RuntimeError as e:<br>        print(&quot;Exception:&quot;, e)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><ul><li>Below is the code that follows ISP</li></ul><pre>from abc import ABC, abstractmethod<br><br># Separate interface for 2D shapes<br>class TwoDimensionalShape(ABC):<br>    @abstractmethod<br>    def area(self) -&gt; float:<br>        pass<br><br><br># Separate interface for 3D shapes<br>class ThreeDimensionalShape(ABC):<br>    @abstractmethod<br>    def area(self) -&gt; float:<br>        pass<br><br>    @abstractmethod<br>    def volume(self) -&gt; float:<br>        pass<br><br><br># Square implements only the 2D interface<br>class Square(TwoDimensionalShape):<br>    def __init__(self, side: float):<br>        self.side = side<br><br>    def area(self) -&gt; float:<br>        return self.side * self.side<br><br><br># Rectangle implements only the 2D interface<br>class Rectangle(TwoDimensionalShape):<br>    def __init__(self, length: float, width: float):<br>        self.length = length<br>        self.width = width<br><br>    def area(self) -&gt; float:<br>        return self.length * self.width<br><br><br># Cube implements the 3D interface<br>class Cube(ThreeDimensionalShape):<br>    def __init__(self, side: float):<br>        self.side = side<br><br>    def area(self) -&gt; float:<br>        return 6 * self.side * self.side<br><br>    def volume(self) -&gt; float:<br>        return self.side ** 3<br><br><br>def main():<br>    square: TwoDimensionalShape = Square(5)<br>    rectangle: TwoDimensionalShape = Rectangle(4, 6)<br>    cube: ThreeDimensionalShape = Cube(3)<br><br>    print(&quot;Square Area:&quot;, square.area())<br>    print(&quot;Rectangle Area:&quot;, rectangle.area())<br>    print(&quot;Cube Area:&quot;, cube.area())<br>    print(&quot;Cube Volume:&quot;, cube.volume())<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>DIP Introduction</h3><p>It states that higher level module (modules that deals with business) should not depend on lower level modules (modules that interacts with system, eg; interaction db, calling api etc).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pas_4Ke2yOqUATSWCVsW6g.png" /></figure><p>The above is an example demonstrating DIP.</p><ul><li>Persistance acts as an interface between higher level module and lower level level module.</li></ul><blockquote>NOTE: If we want to follow OCP then we also must have to follow DIP i.e. if OCP is the taarget than DIP is the solution.</blockquote><ul><li>Below is the code violating DIP</li></ul><pre># Low-level module<br>class MySQLDatabase:<br>    def save_to_sql(self, data: str):<br>        print(f&quot;Executing SQL Query: INSERT INTO users VALUES(&#39;{data}&#39;);&quot;)<br><br><br># Low-level module<br>class MongoDBDatabase:<br>    def save_to_mongo(self, data: str):<br>        print(f&quot;Executing MongoDB Function: db.users.insert({{&#39;name&#39;: &#39;{data}&#39;}})&quot;)<br><br><br># High-level module (Tightly coupled)<br>class UserService:<br>    def __init__(self):<br>        self.sql_db = MySQLDatabase()      # direct dependency<br>        self.mongo_db = MongoDBDatabase() # direct dependency<br><br>    def store_user_to_sql(self, user: str):<br>        self.sql_db.save_to_sql(user)<br><br>    def store_user_to_mongo(self, user: str):<br>        self.mongo_db.save_to_mongo(user)<br><br><br>def main():<br>    service = UserService()<br>    service.store_user_to_sql(&quot;Irfan&quot;)<br>    service.store_user_to_mongo(&quot;Mehmud&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><ul><li>Below is the code violating DIP</li></ul><pre>from abc import ABC, abstractmethod<br><br># Abstraction (Interface)<br>class Database(ABC):<br>    @abstractmethod<br>    def save(self, data: str):<br>        pass<br><br><br># MySQL implementation (Low-level module)<br>class MySQLDatabase(Database):<br>    def save(self, data: str):<br>        print(f&quot;Executing SQL Query: INSERT INTO users VALUES(&#39;{data}&#39;);&quot;)<br><br><br># MongoDB implementation (Low-level module)<br>class MongoDBDatabase(Database):<br>    def save(self, data: str):<br>        print(f&quot;Executing MongoDB Function: db.users.insert({{&#39;name&#39;: &#39;{data}&#39;}})&quot;)<br><br><br># High-level module (Loosely coupled)<br>class UserService:<br>    def __init__(self, database: Database):<br>        self._db = database   # dependency injection<br><br>    def store_user(self, user: str):<br>        self._db.save(user)<br><br><br>def main():<br>    mysql = MySQLDatabase()<br>    mongodb = MongoDBDatabase()<br><br>    service1 = UserService(mysql)<br>    service1.store_user(&quot;Irfan&quot;)<br><br>    service2 = UserService(mongodb)<br>    service2.store_user(&quot;Mehmud&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong><em>Thankyou for reading the blog. In our next blog we will be learning about ISP together build a LLD of a document editor.</em></strong></p><p><strong><em>Credits:</em></strong><em> </em><a href="https://www.youtube.com/playlist?list=PLQEaRBV9gAFvzp6XhcNFpk1WdOcyVo9qT"><strong><em>Aditya Tandon</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=545813c0a34c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID design priciple part 3]]></title>
            <link>https://medium.com/@neuron_sama/solid-design-priciple-part-3-c1ad13bd1045?source=rss-b1b53ca4306e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1ad13bd1045</guid>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[liskov-substitution]]></category>
            <dc:creator><![CDATA[Irfan]]></dc:creator>
            <pubDate>Sat, 31 Jan 2026 07:00:19 GMT</pubDate>
            <atom:updated>2026-01-31T07:00:19.890Z</atom:updated>
            <content:encoded><![CDATA[<p>In our last 2 blogs we learned about what is SOLID design principle and got in depth of SRP, OCP,LSP and it’s signature rule. In today’s blog we will be learning about the remaining rules of LSP i.e. Property and Method rule.</p><h3>Property Rule</h3><p>It ensures that the sub-class maintains key properties of it’s parent class. It is of two types:</p><ol><li><strong>Class Invariant</strong></li></ol><ul><li>Any invariant (a condition that must always hold true) specified on the parent must not be violated by the subclass.</li><li>In other words child class must follow the rules of parent class as it is or it may strengthen it but not weaken it.</li></ul><p><strong>eg</strong>: A parent class may have a rule of not having negative balance, then the child class must follow the same rule or it may strengthen it , like it may say balance should be greater than 5.</p><ul><li>Below is the code that demonstrates violation of class inavariant.</li></ul><pre>class BankAccount:<br>    # Invariant: balance must never be negative<br>    def __init__(self, balance: float):<br>        if balance &lt; 0:<br>            raise ValueError(&quot;Balance can&#39;t be negative&quot;)<br>        self._balance = balance<br><br>    def withdraw(self, amount: float):<br>        if self._balance - amount &lt; 0:<br>            raise RuntimeError(&quot;Insufficient funds&quot;)<br>        self._balance -= amount<br>        print(f&quot;Amount withdrawn. Remaining balance is {self._balance}&quot;)<br><br><br># This class violates the parent&#39;s invariant.<br># It allows the balance to go negative, breaking LSP.<br>class CheatAccount(BankAccount):<br>    def withdraw(self, amount: float):<br>        # LSP violation: parent rules are ignored<br>        self._balance -= amount<br>        print(f&quot;Amount withdrawn. Remaining balance is {self._balance}&quot;)<br><br><br>def main():<br>    account = BankAccount(100)<br>    account.withdraw(100)<br><br>    # Uncomment to see the LSP break:<br>    # cheat = CheatAccount(100)<br>    # cheat.withdraw(150)   # negative balance<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>Output</strong></p><p>Amount withdrawn. Remaining balance is 0</p><p>2. <strong>History Constraint</strong></p><ul><li>The subclass must preserve the “history” or lifecycle behavior of the parent. It cannot remove or disable operations that clients expect to always work.</li></ul><p>eg: If parent class always allows withdrawal then it’s child must also allow withdrawal.</p><ul><li>Below is the code that demonstrates violation of History constraint.</li></ul><pre>class BankAccount:<br>    # Invariant: balance must never be negative<br>    def __init__(self, balance: float):<br>        if balance &lt; 0:<br>            raise ValueError(&quot;Balance can&#39;t be negative&quot;)<br>        self._balance = balance<br><br>    # History Constraint:<br>    # withdraw() must always be a valid operation<br>    def withdraw(self, amount: float):<br>        if self._balance - amount &lt; 0:<br>            raise RuntimeError(&quot;Insufficient funds&quot;)<br>        self._balance -= amount<br>        print(f&quot;Amount withdrawn. Remaining balance is {self._balance}&quot;)<br><br><br>class FixedDepositAccount(BankAccount):<br>    # LSP violation:<br>    # Parent allowed withdraw(), but child forbids it.<br>    # This changes valid state transitions and breaks client code.<br>    def withdraw(self, amount: float):<br>        raise RuntimeError(&quot;Withdraw not allowed in Fixed Deposit&quot;)<br><br><br>def main():<br>    account = BankAccount(100)<br>    account.withdraw(100)<br><br>    # Uncomment to see the history constraint break:<br>    # fd = FixedDepositAccount(100)<br>    # fd.withdraw(10)   # RuntimeError<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>Output</strong></p><p>Amount withdrawn. Remaining balance is 0</p><blockquote><strong>NOTE: </strong>If in parent class some of the behaviours are <strong>immutable</strong> (means if methods are immutable then they cannot be overrrided and if a class is immutable then it cannot be inherited) and child class make these behaviours <strong>mutable</strong> then also it will break <strong>History constraint</strong>.</blockquote><h3>Method Rule</h3><p>It is of two types:</p><ol><li><strong>Pre condition</strong></li></ol><ul><li>Preconditions specify what must be true before a method executes.</li><li>A subclass may weaken (make less strict) the precondition (accept a broader range of inputs), but must not strengthen it (require more than the parent).</li></ul><p><strong>eg: </strong>If in parent class a method accepts accepts value ranging from 0 to 5 then the child class can accept values ranging from 0 to 10 but not something strict like 0 to 4.</p><ul><li>Code demonstrating pre condition</li></ul><pre>class User:<br>    # Precondition: password must be at least 8 characters<br>    def set_password(self, password: str):<br>        if len(password) &lt; 8:<br>            raise ValueError(&quot;Password must be at least 8 characters long!&quot;)<br>        print(&quot;Password set successfully&quot;)<br><br><br>class AdminUser(User):<br>    # Weakened precondition:<br>    # Now only 6 characters are required (LSP is respected)<br>    def set_password(self, password: str):<br>        if len(password) &lt; 6:<br>            raise ValueError(&quot;Password must be at least 6 characters long!&quot;)<br>        print(&quot;Password set successfully&quot;)<br><br><br>def main():<br>    user: User = AdminUser()   # polymorphism<br>    user.set_password(&quot;Admin1&quot;)  # Works fine (length = 6)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>Output</strong></p><p>Password set successfully</p><p>2. <strong>Post condition</strong></p><ul><li>Postconditions specify what must be true after a method completes.</li><li>A subclass may strengthen the postcondition (guarantee more), but must not weaken it (guarantee less).</li></ul><p><strong>eg:</strong> Parent <strong>brake()</strong> method guarantees “speed decreases”; a subclass<br>HybridCar may also increase battery charge (strengthening), but must never leave speed unchanged or increased (weakening).</p><ul><li>Code demonstrating Post condition</li></ul><pre>class Car:<br>    def __init__(self):<br>        self._speed = 0<br><br>    def accelerate(self):<br>        print(&quot;Accelerating&quot;)<br>        self._speed += 20<br><br>    # Postcondition: speed must reduce after brake<br>    def brake(self):<br>        print(&quot;Applying brakes&quot;)<br>        self._speed -= 20<br><br><br># Subclass strengthens the postcondition (LSP-safe)<br>class HybridCar(Car):<br>    def __init__(self):<br>        super().__init__()<br>        self._charge = 0<br><br>    # Postconditions:<br>    # 1. speed must reduce<br>    # 2. charge must increase<br>    def brake(self):<br>        print(&quot;Applying brakes&quot;)<br>        self._speed -= 20<br>        self._charge += 10<br><br><br>def main():<br>    car: Car = HybridCar()   # polymorphism<br>    car.brake()             # works: speed reduced, charge also increased<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>Output</strong></p><p>Applying brakes</p><p><strong><em>Thankyou for reading the blog. In our next blog we will be learning about ISP (Interface segregation principle) and DIP (Dependency inversion principle).</em></strong></p><p><strong><em>Credits:</em></strong><em> </em><a href="https://www.youtube.com/playlist?list=PLQEaRBV9gAFvzp6XhcNFpk1WdOcyVo9qT"><strong><em>Aditya Tandon</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1ad13bd1045" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID design principle part 2]]></title>
            <link>https://medium.com/@neuron_sama/solid-design-principle-part-2-lsp-d8cc609be0d9?source=rss-b1b53ca4306e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8cc609be0d9</guid>
            <category><![CDATA[liskov-substitution]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Irfan]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 16:45:31 GMT</pubDate>
            <atom:updated>2026-02-16T15:17:39.169Z</atom:updated>
            <content:encoded><![CDATA[<p>In our earlier blog we talked about Single Responsibility and Open-Close Principle (<a href="https://medium.com/@neuron_/what-is-solid-design-principle-dc95a5eaf54c"><strong>Checkout</strong></a>). In today’s blog we will be learning about <strong>Liscov Substitution Principle.</strong></p><h3>Introduction</h3><p>LSP states that a sub-class (child class) should be substitutable for it’s base-class (parent class). In other words, there should not be any error in the program if we substitute any class with it’s child class.</p><h4>Example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xQoC3-Kv3BmOB-pF7FMHQ.png" /></figure><ul><li>In the above example we have a Client class which have many accounts. The accounts may be of different types like: SavingAcount, CurrentAccount and FixedDepositAccount.</li><li>As we know Fixed Deposit Accounts doesnot allows us to withdraw frequently like normal accounts.</li><li>So when the Client class tries to access the withdraw() method of FixedDepositAccount, it will be throwing Exception.</li><li>The above example is violating the <strong>LSP</strong> because the Client class only knows about the Account class, it doesnot have any idea about it’s sub-classess.</li><li>That is the parent class(<strong>Account</strong>) is not substitutible by it’s child class (<strong>FixedDepositAccount</strong>).</li></ul><h4>Solution</h4><ul><li>Logically a child class should extend the features of it’s parent class but in the above case, the <strong>FixedDepositAccount</strong> class is reducing the features of it’s parent class Account.</li><li>So <strong>FixedDepositAccount</strong> should not be a child class of Account in the first place.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGeZIDa1oBHzPB69mGeD-w.png" /></figure><h3>Implementation</h3><ul><li>Below code violates LSP</li></ul><pre>from abc import ABC, abstractmethod<br><br><br>class Account(ABC):<br>    @abstractmethod<br>    def deposit(self, amount):<br>        pass<br><br>    @abstractmethod<br>    def withdraw(self, amount):<br>        pass<br><br><br>class SavingAccount(Account):<br>    def __init__(self):<br>        self.balance = 0<br><br>    def deposit(self, amount):<br>        self.balance += amount<br>        print(f&quot;Deposited: {amount} in Savings Account. New Balance: {self.balance}&quot;)<br><br>    def withdraw(self, amount):<br>        if self.balance &gt;= amount:<br>            self.balance -= amount<br>            print(f&quot;Withdrawn: {amount} from Savings Account. New Balance: {self.balance}&quot;)<br>        else:<br>            print(&quot;Insufficient funds in Savings Account!&quot;)<br><br><br>class CurrentAccount(Account):<br>    def __init__(self):<br>        self.balance = 0<br><br>    def deposit(self, amount):<br>        self.balance += amount<br>        print(f&quot;Deposited: {amount} in Current Account. New Balance: {self.balance}&quot;)<br><br>    def withdraw(self, amount):<br>        if self.balance &gt;= amount:<br>            self.balance -= amount<br>            print(f&quot;Withdrawn: {amount} from Current Account. New Balance: {self.balance}&quot;)<br>        else:<br>            print(&quot;Insufficient funds in Current Account!&quot;)<br><br><br>class FixedTermAccount(Account):<br>    def __init__(self):<br>        self.balance = 0<br><br>    def deposit(self, amount):<br>        self.balance += amount<br>        print(f&quot;Deposited: {amount} in Fixed Term Account. New Balance: {self.balance}&quot;)<br><br>    def withdraw(self, amount):<br>        raise Exception(&quot;Withdrawal not allowed in Fixed Term Account!&quot;)<br><br><br>class BankClient:<br>    def __init__(self, accounts):<br>        self.accounts = accounts<br><br>    def process_transactions(self):<br>        for acc in self.accounts:<br>            acc.deposit(1000)  # All accounts allow deposits<br><br>            # Assuming all accounts support withdrawal (LSP Violation)<br>            try:<br>                acc.withdraw(500)<br>            except Exception as e:<br>                print(f&quot;Exception: {e}&quot;)<br><br><br># Main execution<br>if __name__ == &quot;__main__&quot;:<br>    accounts = []<br>    accounts.append(SavingAccount())<br>    accounts.append(CurrentAccount())<br>    accounts.append(FixedTermAccount())<br><br>    client = BankClient(accounts)<br>    client.process_transactions()  # Raises exception for FixedTermAccount</pre><ul><li>Below code follows LSP</li></ul><pre>from abc import ABC, abstractmethod<br><br><br># Deposit-only interface<br>class DepositOnlyAccount(ABC):<br>    @abstractmethod<br>    def deposit(self, amount):<br>        pass<br><br><br># Withdrawable interface extends DepositOnlyAccount<br>class WithdrawableAccount(DepositOnlyAccount):<br>    @abstractmethod<br>    def withdraw(self, amount):<br>        pass<br><br><br>class SavingAccount(WithdrawableAccount):<br>    def __init__(self):<br>        self.balance = 0<br><br>    def deposit(self, amount):<br>        self.balance += amount<br>        print(f&quot;Deposited: {amount} in Savings Account. New Balance: {self.balance}&quot;)<br><br>    def withdraw(self, amount):<br>        if self.balance &gt;= amount:<br>            self.balance -= amount<br>            print(f&quot;Withdrawn: {amount} from Savings Account. New Balance: {self.balance}&quot;)<br>        else:<br>            print(&quot;Insufficient funds in Savings Account!&quot;)<br><br><br>class CurrentAccount(WithdrawableAccount):<br>    def __init__(self):<br>        self.balance = 0<br><br>    def deposit(self, amount):<br>        self.balance += amount<br>        print(f&quot;Deposited: {amount} in Current Account. New Balance: {self.balance}&quot;)<br><br>    def withdraw(self, amount):<br>        if self.balance &gt;= amount:<br>            self.balance -= amount<br>            print(f&quot;Withdrawn: {amount} from Current Account. New Balance: {self.balance}&quot;)<br>        else:<br>            print(&quot;Insufficient funds in Current Account!&quot;)<br><br><br>class FixedTermAccount(DepositOnlyAccount):<br>    def __init__(self):<br>        self.balance = 0<br><br>    def deposit(self, amount):<br>        self.balance += amount<br>        print(f&quot;Deposited: {amount} in Fixed Term Account. New Balance: {self.balance}&quot;)<br><br><br># Client class<br>class BankClient:<br>    def __init__(self, withdrawable_accounts, deposit_only_accounts):<br>        self.withdrawable_accounts = withdrawable_accounts<br>        self.deposit_only_accounts = deposit_only_accounts<br><br>    def process_transactions(self):<br>        for acc in self.withdrawable_accounts:<br>            acc.deposit(1000)<br>            acc.withdraw(500)<br><br>        for acc in self.deposit_only_accounts:<br>            acc.deposit(5000)<br><br><br># Main execution<br>if __name__ == &quot;__main__&quot;:<br>    withdrawable_accounts = []<br>    withdrawable_accounts.append(SavingAccount())<br>    withdrawable_accounts.append(CurrentAccount())<br><br>    deposit_only_accounts = []<br>    deposit_only_accounts.append(FixedTermAccount())<br><br>    client = BankClient(withdrawable_accounts, deposit_only_accounts)<br>    client.process_transactions()</pre><h3>Why LSP breaks often ?</h3><ul><li>Inheritance ensures that subclasses have the same methods, but not necessarily the same behavior or contractual guarantees.</li><li>Without clear rules, a subclass may override a method incorrectly (e.g., throwing unexpected exceptions, changing return values or method signatures), causing client code to fail.</li></ul><p><strong><em>To solve this problem we have three rules to follow in LSP:</em></strong></p><ol><li>Signature rule.</li><li>Property rule.</li><li>Method rule.</li></ol><h3>What is Signature rule ?</h3><ul><li>It says that there should not be any abnormal behaviour of the child class methods while inhereting the parent class mehods.</li><li>To ensure the Signature rule we keep in mind of three things:</li></ul><ol><li><strong>Method Argument Rule:</strong></li></ol><ul><li>The overridden method in the subclass must accept the same argument types as the parent, or wider (a “broader” type up the inheritance chain).</li></ul><p><strong>Example:</strong>If a parent method is designed to accept a certain type (e.g., <strong>str</strong>), the overridden method in the subclass must accept the same type or a more general (broader) type, but must not require a more specific or unrelated type.</p><pre># Python allows dynamic typing, so signature matching is not enforced<br><br>class Parent:<br>    def print(self, msg):<br>        print(&quot;Parent:&quot;, msg)<br><br><br>class Child(Parent):<br>    def print(self, msg):<br>        print(&quot;Child:&quot;, msg)<br><br><br># Client that passes string as msg as client expects.<br>class Client:<br>    def __init__(self, p: Parent):<br>        self.p = p<br><br>    def printMsg(self):<br>        self.p.print(&quot;Hello&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    parent = Parent()<br>    child = Child()<br><br>    # client = Client(parent)<br>    client = Client(child)<br><br>    client.printMsg()</pre><p>2. <strong>Return Type Rule</strong></p><ul><li>The subclass’s return type must be the same as the parent’s, or narrower (a subtype).</li><li>​ Covariant returns are allowed (<strong>e.g. </strong>parent returns Animal; child can return Dog), but not contravariant (<strong>e.g. </strong>child cannot return <strong>object</strong> if the parent returns <strong>Animal</strong>).</li></ul><pre># Python does NOT enforce this at runtime, but type hints can express it.<br><br>class Animal:<br>    # some common Animal methods<br>    pass<br><br><br>class Dog(Animal):<br>    # Additional Dog methods specific to Dogs.<br>    pass<br><br><br>class Parent:<br>    def get_animal(self) -&gt; Animal:<br>        print(&quot;Parent : Returning Animal instance&quot;)<br>        return Animal()<br><br><br>class Child(Parent):<br>    # Can return Dog (subtype of Animal) — covariant return type<br>    def get_animal(self) -&gt; Dog:<br>        print(&quot;Child : Returning Dog instance&quot;)<br>        return Dog()<br><br><br>class Client:<br>    def __init__(self, p: Parent):<br>        self.p = p<br><br>    def take_animal(self):<br>        animal = self.p.get_animal()<br>        # We can still treat it as Animal<br>        return animal<br><br><br>if __name__ == &quot;__main__&quot;:<br>    parent = Parent()<br>    child = Child()<br><br>    client = Client(child)<br>    # client = Client(parent)<br><br>    client.take_animal()</pre><p>3. <strong>Exception Rule</strong></p><ul><li>The subclass may throw fewer or more specific exceptions than the parent, but never broader exceptions that the client is not expecting.</li><li><strong>Example:</strong> If a parent method is documented to raise <strong>ValueError</strong>, the child method may raise a more specific exception such as IndexError or a custom subclass of <strong>ValueError</strong>, but it should <strong>not</strong> raise an unrelated exception like <strong>RuntimeError</strong> or <strong>TypeError</strong>, because client code written for the parent may not handle those.</li></ul><pre># Parent Class<br>class Parent:<br>    def get_value(self):<br>        # Parent throws a &quot;logic-like&quot; error<br>        raise ValueError(&quot;Parent error&quot;)<br><br><br># Child Class<br>class Child(Parent):<br>    def get_value(self):<br>        # Child throws a narrower exception (subtype-like)<br>        raise IndexError(&quot;Child error&quot;)<br><br>        # ❌ Wrong according to LSP:<br>        # raise RuntimeError(&quot;Child error&quot;)   # Broader / unrelated<br><br><br># Client Class<br>class Client:<br>    def __init__(self, p: Parent):<br>        self.p = p<br><br>    def take_value(self):<br>        try:<br>            self.p.get_value()<br>        except ValueError as e:<br>            print(&quot;Logic-like exception occurred:&quot;, e)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    parent = Parent()<br>    child = Child()<br><br>    client = Client(parent)<br>    # client = Client(child)<br><br>    client.take_value()</pre><p>Thank you for reading the blog. Follow me for such amazing blogs.<strong><em> In our next blog we will be learning about the other rules of LSP and also ISP (Interface Segregation Principle).</em></strong></p><p><strong><em>Credits:</em></strong><em> </em><a href="https://www.youtube.com/playlist?list=PLQEaRBV9gAFvzp6XhcNFpk1WdOcyVo9qT"><strong><em>Aditya Tandon</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8cc609be0d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is SOLID design Principle ?]]></title>
            <link>https://medium.com/@neuron_sama/what-is-solid-design-principle-dc95a5eaf54c?source=rss-b1b53ca4306e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc95a5eaf54c</guid>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Irfan]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 05:58:24 GMT</pubDate>
            <atom:updated>2026-01-10T05:58:24.264Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is SOLID design Principle ?</h3><p>In today’s blog we will be learning about <strong>design principles.</strong> We use some design principles so that we have less issue of: <strong>Maintainability</strong>, <strong>Scalability</strong> and <strong>bugs</strong>.</p><h3>Introduction</h3><p><strong>SOLID </strong>is not a single design principle. It consists of <strong>5 design principles.</strong> It is an acronym of:</p><ul><li>S: Single Responsibility Principle (SRP)</li><li>O: Open-close Principle (OCP)</li><li>L: Liscov Substitution Principle (LSP)</li><li>I: Interface Segregation Principle (ISP)</li><li>D: Dependency Inversion Principle (DIP)</li></ul><p>In today’s blog we will go through the <strong>first 2 principles.</strong></p><h3>Single Responsibility Principle (SRP)</h3><p>This principle states that a class should have only one reason to change i.e. it should have only one responsibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*Bn95-hnG3n43GOYcGOTpbQ.png" /></figure><ul><li>In the above example we have a Product class containing price &amp; name. We also have a ShopingCart class containing three methods (responsibilities): <strong>calTotalPrice()</strong>, <strong>printInvoice()</strong> and <strong>saveToSQLDB()</strong>.</li><li>The ShopingCart class <strong>has-a</strong> relationship with the Product class. Since the ShopingCart class can have multiple Products in it so we have shown this scenario with <strong>1..*</strong></li></ul><h4>Problem:</h4><ul><li>The above example is breaking SRP because in future if we need to change the logic in any of the three methods, the ShopingCart class code will change.</li></ul><h4>Solution:</h4><ul><li>Use composition in the UML diagram.</li></ul><p>The below example now follows SRP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pX8yMrMdJEUOyD4qUbmBGg.png" /></figure><h4>Implementation</h4><ul><li>Below is the code that is violating SRP.</li></ul><pre># Product class representing any item of any ECommerce.<br>class Product:<br>    def __init__(self, name, price):<br>        self.name = name<br>        self.price = price<br><br><br># Violating SRP: ShoppingCart is handling multiple responsibilities<br>class ShoppingCart:<br>    def __init__(self):<br>        self.products = []   <br><br>    def add_product(self, p):<br>        self.products.append(p)<br><br>    def get_products(self):<br>        return self.products<br><br>    # 1. Calculates total price in cart.<br>    def calculate_total(self):<br>        total = 0<br>        for p in self.products:<br>            total += p.price<br>        return total<br><br>    # 2. Violating SRP - Prints invoice (Should be in a separate class)<br>    def print_invoice(self):<br>        print(&quot;Shopping Cart Invoice:&quot;)<br>        for p in self.products:<br>            print(f&quot;{p.name} - Rs {p.price}&quot;)<br>        print(f&quot;Total: Rs {self.calculate_total()}&quot;)<br><br>    # 3. Violating SRP - Saves to DB (Should be in a separate class)<br>    def save_to_database(self):<br>        print(&quot;Saving shopping cart to database...&quot;)<br><br><br><br>if __name__ == &quot;__main__&quot;:<br>    cart = ShoppingCart()<br><br>    cart.add_product(Product(&quot;Laptop&quot;, 50000))<br>    cart.add_product(Product(&quot;Mouse&quot;, 2000))<br><br>    cart.print_invoice()<br>    cart.save_to_database()</pre><ul><li>Below is the code that is following SRP.</li></ul><pre># Product class representing any item in eCommerce.<br>class Product:<br>    def __init__(self, name, price):<br>        self.name = name<br>        self.price = price<br><br><br># 1. ShoppingCart: Only responsible for Cart related business logic.<br>class ShoppingCart:<br>    def __init__(self):<br>        self.products = []   <br><br>    def add_product(self, p):<br>        self.products.append(p)<br><br>    def get_products(self):<br>        return self.products<br><br>    # Calculates total price in cart.<br>    def calculate_total(self):<br>        total = 0<br>        for p in self.products:<br>            total += p.price<br>        return total<br><br><br># 2. ShoppingCartPrinter: Only responsible for printing invoices<br>class ShoppingCartPrinter:<br>    def __init__(self, cart):<br>        self.cart = cart<br><br>    def print_invoice(self):<br>        print(&quot;Shopping Cart Invoice:&quot;)<br>        for p in self.cart.get_products():<br>            print(f&quot;{p.name} - Rs {p.price}&quot;)<br>        print(f&quot;Total: Rs {self.cart.calculate_total()}&quot;)<br><br><br># 3. ShoppingCartStorage: Only responsible for saving cart to DB<br>class ShoppingCartStorage:<br>    def __init__(self, cart):<br>        self.cart = cart<br><br>    def save_to_database(self):<br>        print(&quot;Saving shopping cart to database...&quot;)<br><br><br><br>if __name__ == &quot;__main__&quot;:<br>    cart = ShoppingCart()<br><br>    cart.add_product(Product(&quot;Laptop&quot;, 50000))<br>    cart.add_product(Product(&quot;Mouse&quot;, 2000))<br><br>    printer = ShoppingCartPrinter(cart)<br>    printer.print_invoice()<br><br>    db = ShoppingCartStorage(cart)<br>    db.save_to_database()</pre><blockquote><strong>NOTE:</strong> SRP doesn’t says that one class will have only one method. A class can have multiple methods but all these method’s responsibility should be same.</blockquote><h3>Open-Close Principle (OCP)</h3><p>It states that a class should be open for extension (adding new features) but close for modification (changing old features).</p><p>In our earlier example, suppose we want to store the data in MongoDB and in files also. So we may something like the below diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2K2TsZtmpboum3Qzz7iJQ.png" /></figure><h4>Problem:</h4><p>The above diagram is violating OCP because for adding new features (saving to MongoDb and File), we changed our old code.</p><h4>Solution:</h4><p>To follow OCP we use Abstraction, Inheritance and Polymorphism.</p><p>The below diagram now follows OCP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kvcXPZSoxCJJ2ZhqEs-erA.png" /></figure><ul><li>Instead of making a concreate class (CartDBStorage), we will be making an abstract class DBPersistence.</li><li>Then we will make seperate class for each feature and make them inherit the abstract class.</li><li>Now each class will have it’s own implementation of save() method.</li></ul><h3>Implementation</h3><ul><li>Below code is violating OCP</li></ul><pre># Product class representing any item in eCommerce.<br>class Product:<br>    def __init__(self, name, price):<br>        self.name = name<br>        self.price = price<br><br><br># 1. ShoppingCart: Only responsible for Cart related business logic.<br>class ShoppingCart:<br>    def __init__(self):<br>        self.products = []<br><br>    def add_product(self, p):<br>        self.products.append(p)<br><br>    def get_products(self):<br>        return self.products<br><br>    # Calculates total price in cart.<br>    def calculate_total(self):<br>        total = 0<br>        for p in self.products:<br>            total += p.price<br>        return total<br><br><br># 2. ShoppingCartPrinter: Only responsible for printing invoices<br>class ShoppingCartPrinter:<br>    def __init__(self, cart):<br>        self.cart = cart<br><br>    def print_invoice(self):<br>        print(&quot;Shopping Cart Invoice:&quot;)<br>        for p in self.cart.get_products():<br>            print(f&quot;{p.name} - Rs {p.price}&quot;)<br>        print(f&quot;Total: Rs {self.cart.calculate_total()}&quot;)<br><br><br># 3. ShoppingCartStorage: Only responsible for saving cart to DB / File<br>class ShoppingCartStorage:<br>    def __init__(self, cart):<br>        self.cart = cart<br><br>    def save_to_sql_database(self):<br>        print(&quot;Saving shopping cart to SQL DB...&quot;)<br><br>    def save_to_mongo_database(self):<br>        print(&quot;Saving shopping cart to Mongo DB...&quot;)<br><br>    def save_to_file(self):<br>        print(&quot;Saving shopping cart to File...&quot;)<br><br><br># Main execution<br>if __name__ == &quot;__main__&quot;:<br>    cart = ShoppingCart()<br><br>    cart.add_product(Product(&quot;Laptop&quot;, 50000))<br>    cart.add_product(Product(&quot;Mouse&quot;, 2000))<br><br>    printer = ShoppingCartPrinter(cart)<br>    printer.print_invoice()<br><br>    db = ShoppingCartStorage(cart)<br>    db.save_to_sql_database()</pre><p>Below code is following OCP</p><pre>from abc import ABC, abstractmethod<br><br><br># Product class representing any item in eCommerce.<br>class Product:<br>    def __init__(self, name, price):<br>        self.name = name<br>        self.price = price<br><br><br># 1. ShoppingCart: Only responsible for Cart related business logic.<br>class ShoppingCart:<br>    def __init__(self):<br>        self.products = []<br><br>    def add_product(self, p):<br>        self.products.append(p)<br><br>    def get_products(self):<br>        return self.products<br><br>    # Calculates total price in cart.<br>    def calculate_total(self):<br>        total = 0<br>        for p in self.products:<br>            total += p.price<br>        return total<br><br><br># 2. ShoppingCartPrinter: Only responsible for printing invoices<br>class ShoppingCartPrinter:<br>    def __init__(self, cart):<br>        self.cart = cart<br><br>    def print_invoice(self):<br>        print(&quot;Shopping Cart Invoice:&quot;)<br>        for p in self.cart.get_products():<br>            print(f&quot;{p.name} - Rs {p.price}&quot;)<br>        print(f&quot;Total: Rs {self.cart.calculate_total()}&quot;)<br><br><br># Abstract class (Persistence Interface)<br>class Persistence(ABC):<br>    @abstractmethod<br>    def save(self, cart):<br>        pass<br><br><br>class SQLPersistence(Persistence):<br>    def save(self, cart):<br>        print(&quot;Saving shopping cart to SQL DB...&quot;)<br><br><br>class MongoPersistence(Persistence):<br>    def save(self, cart):<br>        print(&quot;Saving shopping cart to MongoDB...&quot;)<br><br><br>class FilePersistence(Persistence):<br>    def save(self, cart):<br>        print(&quot;Saving shopping cart to a file...&quot;)<br><br><br># Main execution<br>if __name__ == &quot;__main__&quot;:<br>    cart = ShoppingCart()<br>    cart.add_product(Product(&quot;Laptop&quot;, 50000))<br>    cart.add_product(Product(&quot;Mouse&quot;, 2000))<br><br>    printer = ShoppingCartPrinter(cart)<br>    printer.print_invoice()<br><br>    db = SQLPersistence()<br>    mongo = MongoPersistence()<br>    file = FilePersistence()<br><br>    db.save(cart)     # Save to SQL database<br>    mongo.save(cart)  # Save to MongoDB<br>    file.save(cart)   # Save to File</pre><blockquote><strong>NOTE:</strong> Practically OCP is not followed strictly.</blockquote><p>Thankyou for reading my blog. Follow me for such amazing blogs. In our next blog we will be learning about the other principles.</p><p><strong><em>Credits:</em></strong><em> </em><a href="https://www.youtube.com/playlist?list=PLQEaRBV9gAFvzp6XhcNFpk1WdOcyVo9qT"><strong><em>Aditya Tandon</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc95a5eaf54c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make Sequence Diagrams in LLD ?]]></title>
            <link>https://medium.com/@neuron_sama/how-to-make-sequence-diagrams-in-lld-004d354fe921?source=rss-b1b53ca4306e------2</link>
            <guid isPermaLink="false">https://medium.com/p/004d354fe921</guid>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[sequence-diagrams]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Irfan]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 06:18:55 GMT</pubDate>
            <atom:updated>2026-01-07T06:18:55.684Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to make Sequence Diagrams in LLD ?</h3><p>In our previous blogs we learned about <a href="https://medium.com/@neuron_/what-are-uml-diagrams-in-lld-47275009e0de"><strong>Class diagrams</strong></a><strong>,</strong> how we can make Class diagrams and also we learned about <a href="https://medium.com/@neuron_/sequence-diagram-in-lld-2efc4ae1534a"><strong>Sequence diagram. </strong></a>In today’s blog we will be learning how to make these Sequence diagram.</p><h3>Introduction</h3><p>Consider we are making the diagram for <strong>ATM Transaction Flow</strong>. Befor making any sequence diagram we need to ensure two things. First one is to define the <strong>usecase</strong>, and the second one is to <strong>indentify objects</strong>.</p><h4>Defining the usecase:</h4><p>User withdraws from ATM using account no. &amp; amount. ATM then makes a Transaction object and this object is responsible for verifying the account no. &amp; tell the cash dispenser for money.</p><blockquote><strong>NOTE:</strong> We can make as many usecases as possible. And there will different Sequence diagrams for different usecase. For now we are just considering a simple usecase.</blockquote><h4>Indentifying the Objects:</h4><p>In our usecase the objects present are:</p><ul><li>ATM</li><li>User</li><li>Transaction</li><li>Account</li><li>Cash Dispenser</li></ul><h3>Sequence Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXEtinSYanNec8V9T59ViA.png" /></figure><ul><li>The objects User, ATM, Transaction, Account and Cash Dispenser will be present <strong>throughtout the flow.</strong></li><li>First, User object sends a message withdraw to the ATM object.</li><li>The ATM object then sends a create message to the Transaction Object.</li><li>Transaction object then sends a <strong>Sync Message</strong> to the Account Object.</li><li>After that if all things are good the Account Object sends a <strong>destroy message</strong> to the Transaction object beacuse the Transaction object has no work to do.</li><li>The ATM then sends a withDrawCash message to the Cash Dispenser object and then only the Cash Dispenser object activates and sends the amount (message) back to the ATM object.</li><li>At last the ATM then sends the message (cash) to the User object.</li></ul><p><strong>Thus we conclude making the Sequence diagram for our usecase.</strong></p><blockquote><strong>NOTE: </strong>We also have some other important terms in the Sequence diagram. They are: alt (to represent if-else), option (to represent if) and loop (to represent for &amp; while loops). These are rarely used beacuse we draw happy flow (diagram where all things returns true) Sequence diagram.</blockquote><p>Thank you for reading. In our next blog we will be learning the SOLID design principles. Follow me on <a href="https://x.com/learnatick"><strong><em>Twitter</em></strong></a><strong><em> </em></strong><em>and medium for more such content.</em></p><p><strong><em>Credits:</em></strong><em> </em><a href="https://www.youtube.com/playlist?list=PLQEaRBV9gAFvzp6XhcNFpk1WdOcyVo9qT"><strong><em>Aditya Tandon</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=004d354fe921" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Sequence diagram in LLD]]></title>
            <link>https://medium.com/@neuron_sama/sequence-diagram-in-lld-2efc4ae1534a?source=rss-b1b53ca4306e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2efc4ae1534a</guid>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[sequence-diagrams]]></category>
            <dc:creator><![CDATA[Irfan]]></dc:creator>
            <pubDate>Tue, 06 Jan 2026 07:25:37 GMT</pubDate>
            <atom:updated>2026-02-16T15:20:16.199Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous blog we learned about <a href="https://medium.com/@neuron_/what-are-uml-diagrams-in-lld-47275009e0de"><strong>Class diagram</strong></a>. We learned associations and there types (<strong>class association</strong> &amp; <strong>object association</strong>). In today’s blog we will go through the sequence diagram.</p><blockquote><strong>NOTE: </strong>While making class based diagram, sometimes we can clearly segregate what type of association we are dealing with. But there may come a scenario where we can’t clearly distinguish. In that time, the choise is <strong>purely subjective.</strong> No approach is wrong.</blockquote><h3>Introduction</h3><p>Sequence diagram are used to define the <strong>interaction/communication</strong> between different classes and tells us when and how the communication will take place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*YSaddflfZaat75e_zw6H6Q.png" /></figure><h3>Components of Sequence diagram</h3><p>It tells us what and how can i display different components like <strong>objects</strong>, <strong>life-line</strong>, <strong>activation bar,</strong> <strong>messages</strong> etc etc.</p><h4>1. Objects</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*moWt-fHfAx5ynRomHyzXcQ.png" /></figure><p>Here A, B, C and D are different objects. We donot need to define the structure of the objects.</p><h4>2. Life-line</h4><p>It tells us about the life-line i.e. time duration of the existence of any entity present in our App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*glih5WUlKz6ggpbOsWWruQ.png" /></figure><p>In the above example, we have 3 objects: A, B &amp; C. And we mentioned a timeline: App start &amp; App end.</p><p>The object A is created at the start of the App. C is created after sometime after the App start. At last the object B is created.</p><p>The objects A &amp; B will be present till the App end, while the object C will not be present till App end.</p><h4>3. Activation bar</h4><p>Tells us about the duration , when the object will be activated (means it can receive/ send messages).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Azy8hK0bP__t-gjYDrdQvQ.png" /></figure><h4>4. Message</h4><p>It means communication between Objects. There are of two types:</p><ol><li>Syncronous Message</li></ol><ul><li>Objects sends message and waits for response.</li></ul><p>2. Asyncronous Message</p><ul><li>Objects sends message and doesnot waits for response.</li></ul><p><strong>Sync Message:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*mfyMnGK4ydfdoWMKzRANvg.png" /></figure><p><strong>Async Message:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*mZS3n-E2o-2BkFx5orAqXA.png" /></figure><h4><strong>5. Create &amp; Destroy message</strong></h4><ul><li>During the running of the App, there will be situation where we need to create/destroy some objects.</li><li>In that situation we send create and destroy messages to create and destroy object respectively.</li></ul><p><strong>Create Message</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*LCb-CPtN2etqTp083brtww.png" /></figure><ul><li>After object A sends a create msg, the object B is created.</li></ul><p><strong>Destroy Message</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*A59RU79VM2ZwExe-pfZdJQ.png" /></figure><ul><li>After object A sends a destroymsg, the object B is destroyed.</li></ul><h4>6. Lost &amp; Found Message</h4><p><strong>Lost Message:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*AoloZ-xP2CF_gUCxXB-mIg.png" /></figure><ul><li>The message that is send by object A but is lost beacuse there may be a situation where the receiver of the msg is detroyed before receiving the msg.</li></ul><p><strong>Found Message:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*BBw0oucy3rDXhBIOIC6U_w.png" /></figure><ul><li>Here, the receiver don’t know about the sender, because the sender may be destroyed after sending the message.</li></ul><h3>Conclusion</h3><p>These are all about the sequence digram. In our next blog we will be learning , How can we create the sequence diagram by taking an example.</p><blockquote><em>Credits: </em><a href="https://www.youtube.com/playlist?list=PLQEaRBV9gAFvzp6XhcNFpk1WdOcyVo9qT"><strong><em>Aditya Tandon</em></strong></a></blockquote><p>Follow me on <a href="https://x.com/learnatick"><em>Twitter</em></a><em> and medium for more such content, Thank you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2efc4ae1534a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>