<?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 Khyrulbashar   on Medium]]></title>
        <description><![CDATA[Stories by Khyrulbashar   on Medium]]></description>
        <link>https://medium.com/@kbashar?source=rss-d66d92747e31------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PD1cvHDzmP8JRP5dhLKwmg.jpeg</url>
            <title>Stories by Khyrulbashar   on Medium</title>
            <link>https://medium.com/@kbashar?source=rss-d66d92747e31------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:22:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kbashar/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[Understanding how authenticator apps generate OTPs offline]]></title>
            <link>https://medium.com/@kbashar/understanding-how-authenticator-apps-generate-otps-offline-1efb5cb68b39?source=rss-d66d92747e31------2</link>
            <guid isPermaLink="false">https://medium.com/p/1efb5cb68b39</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[rfc6238]]></category>
            <category><![CDATA[2fa-authentication]]></category>
            <category><![CDATA[hmacsha1]]></category>
            <dc:creator><![CDATA[Khyrulbashar  ]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 13:51:10 GMT</pubDate>
            <atom:updated>2026-01-15T13:51:10.421Z</atom:updated>
            <content:encoded><![CDATA[<p>I had been wondering for quite a while how these 2FA authenticator apps work!</p><p>I developed a CLI authenticator app to build an intuition of the process. Here is what I learned along the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WM37fHMsMZI-JLwS4j68Ag.png" /></figure><p>As a user, if I want to enable authenticator apps based 2FA in a service, I need to register the service in the app by scanning a QR code from the service.</p><p>When I am logging into the service, it will ask for a 6-digit OTP from the authenticator app before letting me in.</p><p>What’s amazing is that these OTPs work <strong>even offline</strong>. But then how does the service know which OTP will be generated by the authenticator app?</p><h3>The Hashing of Secrets</h3><p>The service and the authenticator app <strong><em>share a secret</em></strong>. By scanning the QR code we are copying the secret from the service to the app.</p><p>Now, how does one single secret let the app create an infinite stream of valid OTPs for the service?</p><p>The answer lies in a simple yet powerful idea; the same input to a hash function always gives the same output. There are many hash functions of varying strengths and properties, they all maintain this principle.</p><p>The hash output has a fancy name, <strong><em>digest</em></strong>. We will be using the term quite a few times later.</p><p>Authenticator apps follow the <a href="https://datatracker.ietf.org/doc/html/rfc6238">RFC 6238</a> and use cryptographic algorithm HMAC with SHA1 hash function. Together they are called <strong>HMAC-SHA1</strong>.</p><p>HMAC-SHA1 algorithm takes in a <strong>secret-key</strong> and a <strong>message</strong> and delivers a 160 bits long digest. You can already guess where this secret-key is coming from, the shared secret between the Service and the authenticator app.</p><p>Here the most interesting part is the <strong><em>message</em></strong> and it makes all the difference.</p><p>1. Message has to be same for both the service and the authenticator app, so they both will have exactly the same digest.</p><p>2. Message content needs to be continuously changing, so we are not stuck with one OTP for life.</p><p><strong>Unix timestamp</strong> fits the bill perfectly. It is continuously changing and we can assume it is the same for all the computers. From this usage of time as message to hash function these OTPs get the fancy name <strong>TOTP (Time-based OTP)</strong>.</p><p>Great! running <strong><em>hmac_sha1(secret-key, unix-timestamp)</em></strong> on both sides we are getting an<strong> exactly identical 160 bit digest</strong> at any time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8T0_UgNtvnE69DaW9-Ffw.png" /><figcaption>hashing of secrets</figcaption></figure><h3>The Math</h3><p>Though we need a 6-digit Integer instead of a bit stream. Imagine the UX, asking the user to enter 160 bits 😂 to confirm their authenticity.</p><p>Here comes Math to rescue us from such a torturous situation. The goal is to produce a 6-digit integer from 160 bits.</p><p>In simple terms, we are taking pseudo-randomly selected 4 bytes (32 bits) to get a 6-digit integer from all the bits. Selection of the 4 bytes is random yet deterministic. So both authenticator and service know which 32 bits to choose.</p><p>For the curious readers, the truncation that happens to get the ultimate result:</p><h3><strong>“Magic” of Truncation</strong></h3><p>The algorithm uses a process called <strong>Dynamic Truncation</strong> to ensure the result is deterministic yet distributed.</p><p>1. <strong>The Offset:</strong> Look at the very last byte of the 160-bit hash. We take the last 4 bits of that byte. This gives us a number in range <strong>0–15</strong>.</p><p>2. <strong>The Slice:</strong> We use that number as an index. We go to that position in the digest and take out the next <strong>4 consecutive bytes</strong> (32 bits).</p><p>3. <strong>The Mask:</strong> We strip the most significant bit (the very first bit) of these 4 bytes. This ensures the number is treated as a positive integer regardless of the system architecture.</p><p>4. <strong>The Result:</strong> Now that we have a 32-bit integer, we perform a modulo operation to get our digits:</p><p><strong><em>OTP = Positive-Number%10⁶</em></strong></p><p>5. <strong>The Padding:</strong> If the result is less than six digits (e.g., 54321), we pad it with a leading zero to get 6-digit string: 054321.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xFpe3y8N0VFNu_3NQVMKA.png" /><figcaption>Dynamic truncation</figcaption></figure><h3>Fight against time</h3><p>We have a constantly changing 6-digit OTP. But we must solve one issue before going all out celebrating. Time is changing, so is our Unix timestamp, every second.</p><p>With time the `message` input to HMAC-SHA1 algorithm changes and so does the digest of the hash.</p><p>If you are anything like me it takes at least 10 seconds to memorize from the authenticator app and enter the code to the service login form! Even if we copy-paste, the 1 second interval will be too tight for a human.</p><p>The solution is, <strong><em>message=floor(unix-timestamp/30)</em></strong> , so it remains same for every 30 seconds.</p><p>After all the shenanigans, we have an OTP with 30 seconds expiration. Best part is no real-time collaboration needed between the service and the authenticator app.</p><h3>One Last Boss</h3><p>Still remains one small edge case. Phone time could be off by 5–6 seconds from service server’s, or there is a network latency. There will be OTP mismatch. To make the system robust, services generally consider 3 consecutive OTPs when matching with user entered OTP, the previous and next OTP along with current OTP.</p><p>All the authenticator apps follow the same algorithm described in <strong><em>RFC 6238</em></strong>, as a result we users have a wide range of options to choose an authenticator app from. Authenticator by Google, Microsoft has one by the same name, also Twilio Authy is another option among many others.</p><p>For the same service any authenticator app will generate the same OTP at any given time.</p><h3>A <strong>Warning Sign</strong></h3><p>One thing is clear, the secret shared by QR scanning is the ultimate security token here. Better to guard this securely, anyone having access to this token can generate the OTPs anytime, anywhere.</p><h3><strong>At the End</strong></h3><p>While learning about the process I wrote a python script that can work as an authenticator app. It was fun to see Google’s authenticator and my hand baked python scripts showing the same OTP for a service.</p><p>Here is a link to the <a href="https://gist.github.com/kBashar/1bdd72a1b7887b86d7362bc35173f009">GitHub gist</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1efb5cb68b39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observer Pattern with Python]]></title>
            <link>https://medium.com/@kbashar/observer-pattern-with-python-f8aa54b06263?source=rss-d66d92747e31------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8aa54b06263</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[design-pattern-in-python]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <dc:creator><![CDATA[Khyrulbashar  ]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 14:30:48 GMT</pubDate>
            <atom:updated>2024-09-29T14:30:48.293Z</atom:updated>
            <content:encoded><![CDATA[<h4>The observer pattern and its variations are widely used in software systems. Understanding this pattern helps in implementing reactive and real-time update mechanisms efficiently.</h4><p>This article discusses situations where observer pattern is a better option and why. First we go through some example scenarios and then implementation details of the pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hkbg9ccKrRwkQxdy" /><figcaption>Photo by <a href="https://unsplash.com/@mvdheuvel?utm_source=medium&amp;utm_medium=referral">Maarten van den Heuvel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In many systems, one object changes and other objects of the system are interested to know about that change.</p><p>Objects that are interested to know about the change are called <strong>observers</strong> and we will call interesting objects <strong>subject</strong>. Observers observe the change of state in Subject. <em>change of state</em> is a fancy way to say some variable or attribute’s value has changed.</p><p>This is a one-to-many relation, where subject&#39;s change is propagated to many observers. <strong>Observer pattern</strong> suggests us a robust and flexible architecture to implement this Observer and Subject relation.</p><p>Lets study some example scenarios where observer pattern or some variations of it is in play.</p><h3>Example Scenarios</h3><h4>Phone OTP messages</h4><p>Bank apps often send OTPs for verification and automatically fill the code once received. So, definitely the bank app knows new message has arrived as soon as they arrive. And this is not special for bank apps, all kinds apps have this nice automated message reading and form fill up feature.</p><p>Interested applications are notified on arrival of the message inbox. If we map this scenario with our previously defined <strong>terms</strong>, message inbox is <strong>Subject</strong> and the apps that are waiting for OTP messages are <strong>Observers</strong>.</p><h4>E-Commerce Dashboard</h4><p>In E-Commerce dashboard, display cards show <strong>total order count</strong>, <strong>average revenue per order</strong>, and <strong>sales trends</strong>, all of which depend on the sales count, i.e. whenever there is a new sale, these cards need to be updated.</p><p>These three display cards total order count, average revenue per order and sales trend are <strong>Observers</strong> and they are observing <strong>Subject</strong> sales count.</p><h4>Smart Home</h4><p>We will use this example later in our code example below.</p><p>Our smart room has different smart devices security cameras, lights, thermostats etc. For demonstration purpose we will consider the simplest of the interactions. Devices like cameras and lights respond to changes in room occupancy:</p><ul><li>Security Cameras activates when there is human presence.</li><li>Smart Lights turn off automatically when there is no one in the room.</li></ul><p>In this case:</p><ul><li>Smart room is the <strong>Subject</strong>.</li><li>Devices like the Cameras and Lights are <strong>Observers</strong> that need to update their behavior based on the room’s status.</li></ul><p>Now that we have built the intuition how the <strong>Observers</strong> and <strong>Subject</strong> look like in a system, let&#39;s find out how they interact.</p><h3>How to notify observers?</h3><p>Question is how do we let Observers know the state of the Subject has changed?</p><p>We have two options,</p><ol><li>Observers <strong>poll</strong> the data at an interval to check if the Subject&#39;s state has changed</li><li>Subject <strong>push</strong> the update to the Observers whenever there is a change in its state.</li></ol><p>Polling is simple to implement but may miss rapid changes and real-time updates. There is potential of resource wastage.<br>Pushing makes real-time updates, efficient use of resources, ensures all changes are captured. Though it is complex to implement.</p><p>As our scenarios need a prompt reaction in Subject&#39;s state change, pushing notification is a better option for us.</p><p>And here comes the <strong>observer pattern</strong>, suggesting us a loosely coupled code organization that let Subject notify its Observers about the update without knowing much about the Observer class internals. Both Subject and Observers implement certain interfaces and they communicate to each other through those interfaces.</p><p>Now is a good time to take a look at the UML class diagram of observer pattern.</p><h3>UML Class Diagram</h3><p>Observer patterns UML class diagram will clarify the relation and interaction between subject and observers more. Let&#39;s take a look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*ZrdsUAPGiq5OCX0PxXywvw.png" /><figcaption>observer pattern class diagram</figcaption></figure><p>We have two interfaces <strong>Subject</strong> and <strong>Observer</strong>. While Interfaces will provide us with a blueprint, concrete implementation of these interfaces will actually implement the methods of the Interfaces.</p><p><strong>Subject</strong> has one attribute and three methods. While the attribute observers is a list of <strong>Observer</strong> instances, the methods do followings</p><ol><li><strong>addObserver</strong>: let an observer <strong>register</strong> itself for notifications from the Subject. After an Observer being added to the subject&#39;s observer list it will be notified on the updates of the Subject.</li><li><strong>removeObserver</strong>: if the observer does not want to listen to the changes of the Subject, it can <strong>remove</strong> itself from the list of observers and it will not be bothered anymore.</li><li><strong>notifyObservers</strong>: the function that will do the work of notifying the subject&#39;s observers.</li></ol><p>When notifying the observer on the change, usually changed data is also sent out. Another way is, observer fetching the data after it gets notified. We’ll use the second option in our example code.</p><p>Any and all classes that want to act as a <strong>Subject</strong> must implement above 3 methods.</p><p>Now let’s consider the Observer interface. It has one method update. Concrete observer classes will have to implement this method.</p><ol><li><strong>update</strong>: this method will be called from the Subject’s <strong>notifyObservers</strong> method to let the observer know of a state change in Subject. Observer will write logic to response to the change here.</li></ol><p>Now that we have seen the code organization let’s move on to the actual code.</p><h3>Example Code for Observer pattern</h3><p>Before coding let’s restate our goal, design a smart home system that will have rooms with security camera and lights. These light and camera will be responsive to the presence of human in the room. If there is human in the room the camera will start monitoring while light will turn on. So, both Camera and light are interested to know when there is a change in number of persons in the room.</p><p>From above discussion it might be already clear to us observers are <strong>Light</strong> and <strong>Camera</strong>. And they will observe the state of the room. <strong>Room</strong> is our subject. Whenever state of the room changes, light and camera will be notified.</p><p>Our examples will be in python. Python doesn’t have the concept of Interface. We can achieve the same using its Abstract Class concept. A brief on abstract class is <a href="https://medium.com/@kbashar/strategy-pattern-with-python-1aeb5ec00208">here</a>, look for the <strong>Abstract Class in Python</strong> section of the article. We will skip Abstract class related discussion here, as the article already got quite large.</p><h4>Subject and Observer Interfaces</h4><p>First we will design our <strong>Subject</strong> and <strong>Observer</strong> Interfaces aka Abstract classes.</p><pre>from abc import ABC, abstractmethod<br><br><br>class Observer(ABC):<br><br>    @abstractmethod<br>    def update(self):<br>        pass<br><br><br>class Subject(ABC):<br><br>    @abstractmethod<br>    def addObserver(self, observer: Observer):<br>        pass<br><br>    @abstractmethod<br>    def removeObserver(self, observer: Observer):<br>        pass<br><br>    @abstractmethod<br>    def notifyObservers(self):<br>        pass</pre><p>These classes are blueprint for our concrete classes. All abstract methods will be implemented there.</p><h4>Room Subject Concrete Class</h4><p>We have one <strong>Subject</strong> class <strong>Room</strong>. This class will implement all three methods of the <strong>Subject</strong> interface and two other methods to change and access its state. The implementation is kept simple and in-line comments are added. Hope this will be easy to follow.</p><pre>class Room(Subject):<br><br>    def __init__(self):<br>        # initialize the observers list<br>        self._observers = list()  <br><br>        # initialize the room with no person inside the room.<br>        self._number_of_persons = 0 <br>        print(&quot;Initiated an empty room!&quot;)<br><br>    # adds observer to the list<br>    def addObserver(self, observer: Observer):<br>        self._observers.append(observer)<br><br>    # removes observer from the list<br>    def removeObserver(self, observer: Observer):<br>        self._observers.remove(observer)<br><br>    # iterate through all listed observers and call their update method to notify them. <br>    def notifyObservers(self):  <br>        for observer in self._observers:<br>            observer.update()<br><br>    # class specific methods<br><br>    def setPerson(self, person: int):  # change the state<br>        self._number_of_persons = person<br><br>        # state has changed let&#39;s notify the observers<br>        self.notifyObservers()<br><br>    def getPerson(self):  # access the state<br>        return self._number_of_persons</pre><p>Apart from implementing 3 methods (addObserver, removeObserver and notifyObservers) from the <strong>Subject</strong> abstract class it has two extra methods i.e. setPerson and getPerson. These methods let outside code update or fetch the state of the <strong>Room</strong>. These are not mandatory for the pattern but necessary for the class to function in our context.</p><h4>Light and Camera Observer Concrete Class</h4><p>Now let’s code concrete observers. We have two observers Light and Camera classes, they will first register themselves to the <strong>Room</strong> subject&#39;s observers list through addObserver and implement the <strong>update</strong> method logic to response to the change in state of the <strong>Room</strong>.</p><pre>class Light(Observer):<br><br>    def __init__(self, room: Room):<br>        print(&quot;Initializing Lights!&quot;)<br>        self._room = room<br><br>        # register itself for door state change observation<br>        self._room.addObserver(self)<br><br>    def update(self):  # state of the room has changed<br><br>        # access the state from the subject<br>        number_of_persons = self._room.getPerson()<br><br>        # take some actions based on changed states<br>        if number_of_persons == 0:<br>            print(f&quot;Light: Shutting down. {number_of_persons} persons in the room.&quot;)<br>        else:<br>            print(f&quot;Light: Keep running. {number_of_persons} persons in the room.&quot;)</pre><pre>class Camera(Observer):<br>    def __init__(self, room: Room):<br>        print(&quot;Initializing Security Camera!&quot;)<br>        self._room = room<br><br>        # register itself for door state change observation<br>        self._room.addObserver(self)<br><br>    def update(self):  # state of the room has changed<br>        # access the state from the subject<br>        number_of_persons = self._room.getPerson()<br><br>        # take some actions based on changed states<br>        if number_of_persons == 0:<br>            print(f&quot;Camera: Shutting down. {number_of_persons} persons in the room.&quot;)<br>        else:<br>            print(f&quot;Camera: Keep running. {number_of_persons} persons in the room.&quot;)</pre><p>Now let’s add the calling code. For demonstration purpose we will put this code in main calling thread.<br>First we initialize the <strong>Room</strong> instance and use that instance to initialize the <strong>Light</strong> and <strong>Camera</strong> instances. To update the the number of persons in the room we call room.setState() method and in turn this will notify and update the state of light and camera.</p><pre>if __name__ == &quot;__main__&quot;:<br>    room = Room()<br><br>    light = Light(room)<br>    camera = Camera(room)<br><br>    room.setPerson(1)<br>    room.setPerson(0)  # camera and light will turn off<br>    room.setPerson(5)  # camera and light switched on again</pre><p>Upon running the code output will be like following</p><pre>Initiated an empty room!<br>Initializing Lights!<br>Initializing Security Camera!<br><br>Light: Keep running. 1 persons in the room.<br>Camera: Keep running. 1 persons in the room.<br><br>Light: Shutting down. 0 persons in the room.<br>Camera: Shutting down. 0 persons in the room.<br><br>Light: Keep running. 5 persons in the room.<br>Camera: Keep running. 5 persons in the room.</pre><h3>Wrapping up</h3><p>Couple of points on observer pattern,</p><ol><li>When working in multi-threading system we should code keep thread safety in mind during implementing observer pattern.</li><li>If real-time update is not necessary observer pattern might not be a good fit.</li><li>There are variations of this pattern, not all of them use the same OOP structure but the essence is same.</li><li>In more complex systems, the Publish-Subscribe pattern might be more suitable as it decouples the message sender from the receiver more thoroughly.</li></ol><p>In conclusion, Observer pattern is a handy toolkit to design and work with reactive systems. In web frameworks, UI frameworks or event-driven programming systems use this pattern to bridge objects or to establish communication channel between objects. For developers working with these tools, or any developer for that matter, observer pattern could be a great mental model to have to effectively use and extends these systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8aa54b06263" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy Pattern with Python]]></title>
            <link>https://medium.com/@kbashar/strategy-pattern-with-python-1aeb5ec00208?source=rss-d66d92747e31------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aeb5ec00208</guid>
            <category><![CDATA[strategy-pattern]]></category>
            <category><![CDATA[abstract-class]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[design-pattern-in-python]]></category>
            <dc:creator><![CDATA[Khyrulbashar  ]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 17:58:29 GMT</pubDate>
            <atom:updated>2024-09-27T15:30:32.533Z</atom:updated>
            <content:encoded><![CDATA[<p>This article introduces strategy design pattern with examples and use cases. The example codes are in python, also a brief intro to python abstract class is attached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XskC-SSV-YRg_dPM" /><figcaption>Photo by <a href="https://unsplash.com/@eprouzet?utm_source=medium&amp;utm_medium=referral">Eric Prouzet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Strategy Pattern</strong></h3><p>Strategy pattern suggests a simple but very useful paradigm to design OOP systems where there are multiple algorithms/strategies to do a task. The pattern prescribes encapsulating algorithms into a common interface and use that interface to use those algorithms. This gives the client (the part of the code that use the algorithms) the flexibility to choose any algorithm at runtime.</p><h3>Example Scenarios</h3><p>Let’s think of the map app we all have in our phones. Users can find routes from place A to place B through the map, also the app gives us couple of possible modes of transportation e.g walking, Cycling, Bike riding, Public Bus or Cars and the time they will take to go from A to B.</p><p>This feature will be a nice candidate to be implemented using strategy pattern. Where mode of transportation are different algorithms/strategies and a common interface will provide with how much time it will take to go from address A to B.</p><p>Let’s take a look at another example. A payment processor in an e-commerce site can take payment in multiple ways e.g. using cards, MFS(Mobile Financial System) or cryptocurrency. Designing this payment processor is a prime candidate for strategy pattern. Here mode of payments will be algorithms the pattern talks about and the client will be the payment processor.</p><h3>Code Examples</h3><p>Examples with codes are even better. Here I will use python but this pattern or any design pattern for that matter is applicable and implementable in all OOP supported languages.</p><p>So, We are designing a service for processing Payments for an E-Commerce. For starter, users can pay through Visa and Master cards. So what would the code structure for payment processing look like?</p><pre># visa card related processing<br>def visa_pay(self, amount):  <br>  print(&quot;Doing visa card related processing&quot;)<br>  print(f&quot;Receiving a payment through Visa card of amount {amount}&quot;)<br><br># master card related processing<br>def master_pay(self, amount):   <br>  print(&quot;Doing Master card related processing&quot;)<br>  print(f&quot;Receiving a payment through Master card of amount {amount}&quot;)<br><br># this is our payment processor<br>def payment_processor(payment_type: str, amount: float):<br>  if payment_type == &quot;visa&quot;:<br>    visa_pay(amount)<br>  else payment_type == &quot;master&quot;:<br>    master_pay(amount)</pre><p>Simple, Right? Now what if as our e-commerce gets more traction, more and more users wants to make payment with their American Express(Amex) cards. What can we do? We can add another function amex_payfor amex card processing and change the payment_processora bit to make room for the new payment mode.</p><pre>...<br><br>def amex_pay(self, amount):<br>  print(&quot;Doing Amex card related processing&quot;)<br>  print(f&quot;Receiving a payment through Amex card of amount {amount}&quot;)<br><br><br>def payment_processor(payment_type: str, amount: float):<br>  if payment_type == &quot;visa&quot;:<br>    visa_pay(amount)<br>  elif payment_type == &quot;master&quot;:<br>    master_pay(amount)<br>  elif payment_type == &quot;amex&quot;:<br>    amex_pay(amount)</pre><p>No matter how simple this looks, one thing is clear, every time we add support for a new payment mode we have to change the payment_processor method beside adding the code/functionality of the new payment mode. This is not very convenient, nor is it easy to extend. Our payment_processor code is totally dependent on the individual payment modes, even though all of the payment mode related functions takes same arguments and maybe returns same data too, not much different from each other.</p><p>In cases such as this, <strong>Strategy Pattern</strong> suggests a better way to organize our code and make it more extensible and portable. The suggestion is, payment modes will have a common interface and the payment processor payment_processor will code to that interface instead of individual payment mode functions. So we can add new new payment modes later without changing any code in payment_processor part. Our newly added payment modes will be supported by the payment_processor right of the bat.</p><p>Let’s try it out. But before that some python language pre-requisites. if you are familiar with python Abstract class system, you may skip the next section and jump to the code right away.</p><h4><strong>Abstract Class in Python</strong></h4><p>An interface provides a blueprint through abstract functions, and interface implementing classes must make concrete implementation of those abstract functions and thus all classes that implement the same interface will have the same API(a fancy way to say it will have same methods/functions available to call).</p><p>Now Python has no concept of Interface, as we see in Java or other OOP languages, abstract classes in python give us a way to have this same facility.</p><p>We declare an abstract class with abstract methods. And all concrete classes that are inherited from the abstract class will implement those abstract methods. Thus those classes will have the same methods.</p><p>One last point, to get abstract class we will need to use abc module from python standard library. This module supplies two important components we will use, ABCand abstractmethod. ABC is the class that all abstract classes themselves must inherit and abstractmethod is a decorator that all abstract methods must adorn themselves with.</p><h4><strong>Code Example of Strategy pattern</strong></h4><p>Now lets hop into the code-wagon.</p><pre>from abc import ABC, abstractmethod<br><br># our interface made out of an abstract class.<br>class PaymentInterface(ABC):<br><br>  # all payment mode will implement this abstract method<br>  @abstractmethod<br>  def pay(self, amount):<br>    pass<br><br><br>class VisaPayment(PaymentInterface):   # inherits the PaymentInterface and implements the `pay` method<br><br>  def pay(self, amount):<br>    print(&quot;Doing visa card related processing&quot;)<br>    print(f&quot;Receiving a payment through Visa of amount {amount}&quot;)<br><br><br>class MasterPayment(PaymentInterface):<br><br>  def pay(self, amount):<br>    print(&quot;Doing Master card related processing&quot;)<br>    print(f&quot;Receiving a payment through Master of amount {amount}&quot;)<br><br><br>class AmexPayment(PaymentInterface):<br><br>  def pay(self, amount):<br>    print(&quot;Doing Amex card related processing&quot;)<br>    print(f&quot;Receiving a payment through Amex of amount {amount}&quot;)<br><br><br><br>def payment_processor(payment_method: PaymentInterface, amount: float):<br>  payment_method.pay(amount)</pre><p>Nice, our payment_processor looks <strong>clean</strong> and very <strong>unlikely to need change</strong> if we add new payment modes, say we want to add a payment mode for Bkash(MFS), we would only need to add the Bkash payment processing code in the Bkash related class, No change in payment_processor function. This is definitely neat and a win for code maintainability.</p><p>How do we map names to actual PaymentMethod at runtime? There are several ways to accomplish this, one example could be as following</p><pre>class PaymentService:<br>    def __init__(self):<br>        self.payment_methods = {<br>            &quot;visa&quot;: VisaPayment(),<br>            &quot;master&quot;: MasterPayment(),<br>            &quot;amex&quot;: AmexPayment()<br>        }<br><br>    def process_payment(self, method: str, amount: float):<br>        if method not in self.payment_methods:<br>            raise ValueError(f&quot;Unsupported payment method: {method}&quot;)<br>        <br>        payment_method = self.payment_methods[method]<br>        payment_processor(payment_method, amount)</pre><p>In above example, the class initializes a dictionary payment_methods that maps payment method names to their corresponding PaymentInterface implementations. When there is a new Payment method added we will need to add the corresponding PaymentInterface class and an entry in the mapper.</p><p>This mapper part is totally dependent on the context of implementation.</p><h4><strong>When to use Strategy Pattern</strong></h4><ul><li>You’ve got a bunch of related algorithms, and you want to switch between them dynamically.</li><li>You want to avoid a monster “if-elif-else” chain in your code. Trust me, future you will thank present you for not creating that mess.</li></ul><p>Remember, design patterns are tools, not rules. Use only when you have time and reason to do so.</p><p><strong>Skip the Strategy Pattern when:</strong></p><ul><li>You’ve only got a couple of algorithms that rarely change.</li><li>The algorithms and their context are super simple. Sometimes, a simple if-else is all you need. Don’t over-complicate things!</li></ul><h4><strong>Wrapping Up</strong></h4><p>Strategy pattern is a cool code-toolkit, gives us</p><ul><li><strong>Flexibility:</strong> Let us add new strategies or algorithms without changing or impacting previous client codes.</li><li><strong>Cleaner Code:</strong> Makes code clean, no more long list of `if-else-if`.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aeb5ec00208" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>