<?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 Marcus T on Medium]]></title>
        <description><![CDATA[Stories by Marcus T on Medium]]></description>
        <link>https://medium.com/@markusfarkus?source=rss-c5ded6402cba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*rEphWotSzEoFcPR8ErxkYA.jpeg</url>
            <title>Stories by Marcus T on Medium</title>
            <link>https://medium.com/@markusfarkus?source=rss-c5ded6402cba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:38:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@markusfarkus/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[Python Type Hints Meet Dependency Injection]]></title>
            <link>https://markusfarkus.medium.com/python-type-hints-meet-dependency-injection-508251ae272a?source=rss-c5ded6402cba------2</link>
            <guid isPermaLink="false">https://medium.com/p/508251ae272a</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Marcus T]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 16:47:28 GMT</pubDate>
            <atom:updated>2026-08-18T16:47:28.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYI6_ioko-IoCcfexehjwQ.png" /></figure><p>I took some time recently to actually understand a pattern I had just been blindly copying and using in FastAPI.</p><pre>from typing import Annotated <br>from fastapi import Depends <br><br>def get_user_service( service: Annotated[UserService, Depends()] ): ...</pre><p>What is actually going on here?</p><p>Is Annotated a type hint?</p><p>Is Depends() creating a UserService?</p><p>Is FastAPI inspecting the type hint?</p><p>It’s something I’ve just been using without a deep understanding of it. So I decided to spend a little time breaking it down.</p><h3>First: What Is Annotated?</h3><p>Consider a normal Python type hint:</p><pre>def process_user(user: User):<br>    ...</pre><p>The annotation informs tools such as your IDE, type checker, and static analyzer:</p><blockquote><em>user is expected to be a </em><em>User.</em></blockquote><p>Python itself generally does not enforce that annotation at runtime.</p><p>Now consider this:</p><pre>from typing import Annotated</pre><pre>def process_user(<br>    user: Annotated[User, &quot;some metadata&quot;]<br>):<br>    ...</pre><p>The actual type is still User but now there is some additional information to it. Annotated was introduced as a way to attach context-specific metadata to an existing type without changing the underlying type. A tool that understands the metadata can use it. A tool that doesn&#39;t will simply treat the annotation as the original type. A framework such as FastAPI uses this to attach information about how a parameter should be handled.</p><h3>Enter Depends</h3><p>FastAPI has its own dependency injection system. Normally we might write a dependency like this:</p><pre>def get_database():<br>    return DatabaseConnection()</pre><p>And then tell FastAPI that an endpoint depends on it:</p><pre>@app.get(&quot;/users&quot;)<br>def get_users(<br>    database = Depends(get_database)<br>):<br>    return database.get_users()</pre><p>When the request arrives, FastAPI sees:</p><pre>Depends(get_database)</pre><p>This is essentially telling the framework to call get_database() before calling get_users() and give the results to the database parameter. FastAPI handles resolving that dependency as part of its request dependency graph. Dependencies can themselves have dependencies, allowing FastAPI to recursively resolve a tree of requirements.</p><p>With modern Python type annotations, however, we can write this more clearly:</p><pre>@app.get(&quot;/users&quot;)<br>def get_users(<br>    database: Annotated[DatabaseConnection, Depends(get_database)]<br>):<br>    return database.get_users()</pre><p>Now we have separated two ideas.</p><p>The first:</p><pre>DatabaseConnection</pre><p>answers “<em>what kind of object is this?</em>”</p><p>The second:</p><pre>Depends(get_database)</pre><p>answers “<em>How should FastAPI obtain it?”</em></p><p>Combine them:</p><pre>Annotated[<br>    DatabaseConnection,<br>    Depends(get_database)<br>]</pre><p>and we have both <strong>type information</strong> and <strong>framework metadata</strong> in one annotation.</p><h3>So What Does Annotated[ClassName, Depends()] Mean?</h3><p>This is where I felt the deep understanding is especially beneficial. Suppose we have:</p><pre>class UserService:<br>    def get_user(self, user_id: int):<br>        ...</pre><p>And the endpoint looks like this:</p><pre>@app.get(&quot;/users/{user_id}&quot;)<br>def get_user( <br>  user_id: int, <br>  service: Annotated[UserService, Depends()] <br>): <br>    return service.get_user(user_id)</pre><p>Notice that we did not write Depends(UserService)</p><p>We wrote Depends()with no argument.</p><p>So what is FastAPI supposed to call?</p><p>FastAPI can infer the dependency from the type annotation. In this case, Annoted[UserService, Depends()] effectively tells FastAPI that this parameter has type UserService, and UserService itself is the dependency. FastAPI supports this shortcut for classes used as dependencies. When the dependency is the same class named by the type annotation, Depends() doesn&#39;t need the class repeated. FastAPI can call the class to construct the instance.</p><pre>service: Annotated[<br>    UserService,<br>    Depends()<br>]</pre><p>means roughly the same thing as:</p><pre>service: Annotated[<br>    UserService,<br>    Depends(UserService)<br>]</pre><p>FastAPI sees the Depends() metadata, looks at the annotated type, determines that UserService is the dependency, calls it, and injects the resulting instance. So our endpoint receives UserService() without constructing it itself. That’s the important part.</p><h4>Why Not Just Do This?</h4><pre>@app.get(&quot;/users/{user_id}&quot;)<br>def get_user(user_id: int):<br>    service = UserService()<br>    return service.get_user(user_id)</pre><p>That’s perfectly reasonable, especially for small applications. But in this implementation, the endpoint is now responsible for two things:</p><pre>HTTP request<br>    ↓<br>Endpoint<br>    ├── create UserService<br>    └── use UserService</pre><p>The endpoint doesn’t simply use a service. It also decides how that service gets created. That becomes more relevant in real-world applications.</p><h3>Dependencies Usually Have Dependencies</h3><p>Our UserService probably doesn&#39;t work alone. Perhaps it needs a repository:</p><pre>class UserRepository: <br>    def __init__(self, database: Database): <br>        self.database = database <br><br>    def get_by_id(self, user_id: int): <br>        ...</pre><p>UserService needs that repository</p><pre>class UserService: <br>    def __init__(self, repository: UserRepository): <br>        self.repository = repository <br><br>    def get_user(self, user_id: int): <br>        return self.repository.get_by_id(user_id)</pre><p>Without dependency injection, the endpoint expands to this:</p><pre>@app.get(&quot;/users/{user_id}&quot;) <br>def get_user(user_id: int): <br>    database = Database() <br>    repository = UserRepository(database) <br>    service = UserService(repository) <br><br>    return service.get_user(user_id)</pre><p>Now the endpoint has too many concerns. It’s doing a lot of wiring, and that’s not the endpoint’s job.</p><h3>Let FastAPI Build the Dependency Graph</h3><p>Instead, we can define each dependency separately.</p><pre>def get_database() -&gt; Database: <br>    return Database()</pre><p>Then:</p><pre>def get_repository( <br>    database: Annotated[ <br>        Database, <br>        Depends(get_database) <br>    ] <br>) -&gt; UserRepository:</pre><p>Then:</p><pre>def get_user_service( <br>    repository: Annotated[ <br>        UserRepository, <br>        Depends(get_repository) <br>    ] <br>) -&gt; UserService: return UserService(repository)</pre><p>Finally:</p><pre>@app.get(&quot;/users/{user_id}&quot;) <br>def get_user( <br>    user_id: int, <br>    service: Annotated[ <br>        UserService, <br>        Depends(get_user_service) <br>    ] <br>): <br><br>return service.get_user(user_id)</pre><p>The endpoint no longer knows how the service is constructed. It only knows that it needs a UserService. FastAPI resolves the rest. Dependencies can declare their own sub-dependencies, and FastAPI resolves the resulting graph. This is something I have just been out of routine, but now I understand how it is dependency injection doing something useful.</p><h3>OK, But How Does That Depends() Work Without an Argument?</h3><p>Say you have a service with a constructor that describes its dependencies.</p><pre>class UserService: <br>    def __init__( self, repository: Annotated[ UserRepository, Depends() ] ): <br>        self.repository = repository</pre><p>And the repository also describes its dependencies.</p><pre>def __init__( self, database: Annotated[ Database, Depends() ] ): <br>    self.database = database</pre><p>Now the endpoint can use the service like so:</p><pre>@app.get(&quot;/users/{user_id}&quot;) <br>def get_user( user_id: int, service: Annotated[ UserService, Depends() ] ): <br>    return service.get_user(user_id)</pre><p>We have effectively built a dependency graph using type annotations:</p><pre>UserService <br>    │ <br>    ▼ <br>UserRepository <br>    │ <br>    ▼ <br>Database</pre><p>Each class says what it needs. FastAPI figures out how to build it. It’s a powerful concept worth understanding before using.</p><h3>The Big Payoff: Interfaces</h3><p>In Python, an interface is a blueprint or contract that defines a set of behaviors (methods and properties) a class must provide, without specifying how those behaviors are implemented.</p><p>Revisiting our payment processor class from a <a href="https://markusfarkus.medium.com/abstract-classes-in-python-designing-code-like-an-architect-bef39e1aa962">previous article</a>:</p><pre>from abc import ABC, abstractmethod<br>from datetime import datetime<br><br><br>class PaymentProcessor(ABC):<br>    &quot;&quot;&quot;<br>    Abstract base class for payment processors.<br>    Defines the interface all processors must implement.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, merchant_id: str):<br>        self.merchant_id = merchant_id<br>        self._transaction_log: list[dict] = []<br><br>        # Abstract methods — must be implemented by subclasses<br>        @abstractmethod<br>        def charge(self, amount: float, currency: str) -&gt; bool:<br>            &quot;&quot;&quot;Charge the given amount. Returns True on success.&quot;&quot;&quot;<br>            ...</pre><p>An implementation can look like this:</p><pre>class StripePaymentGateway(PaymentProcessor): <br>    def charge( self, amount: float ) -&gt; None: <br>        print( f&quot;Charging ${amount} with Stripe&quot; )</pre><p>The service depends on the abstraction:</p><pre>class OrderService: <br>    def __init__( self, payment_processor: PaymentProcessor ): <br>        self.payment_processor = payment_processor <br><br>    def checkout( self, total: float ): <br>        self.payment_processor.charge(total)</pre><p>This is good design. OrderService does not know about Stripe. It only knows about PaymentProcessor.</p><h3>Provider Functions Connect Abstractions to Implementations</h3><p>If we used:</p><pre>gateway: Annotated[ PaymentGateway, Depends() ]</pre><p>What class would FastAPI instantiate. PaymentProcessor is abstract. We don’t want PaymentProcessor, we want StripePaymentProcessor. This is where an explicit provider function is useful.</p><p>We can define a provider function like so:</p><pre>def get_payment_processor() -&gt; PaymentGateway: <br>    return StripePaymentProcessor()</pre><p>And use it like so:</p><pre>def get_order_service( <br>    processor: Annotated[ <br>        PaymentProcessor, <br>        Depends(get_payment_processor) <br>    ] ) -&gt; OrderService: <br><br>    return OrderService(processor)<br><br><br>@app.post(&quot;/orders&quot;) <br>def create_order( <br>    order: OrderCreate, <br>    service: Annotated[ <br>        OrderService, <br>        Depends(get_order_service) <br>    ] ): <br><br>    return service.checkout(order.total)</pre><p>Now the dependency graph looks like this:</p><pre>Endpoint<br>   │<br>   ▼<br>OrderService<br>   │<br>   ▼<br>PaymentGateway<br>   │<br>   ▼<br>StripePaymentGateway</pre><p>OrderService never mentions Stripe. That decision happens outside the service. There is a clear boundary between application logic and application configuration.</p><h3>Type Hints Have Become More Than Documentation</h3><p>Frameworks like FastAPI have increasingly made use of type information at runtime.</p><p>A signature like:</p><pre>def create_order( <br>    order: OrderCreate, <br>    service: Annotated[ <br>        OrderService, <br>        Depends(get_order_service) <br>    ] <br>):</pre><p>communicates several things simultaneously.</p><ul><li>To the developer:<br>service is an OrderService</li><li>To the IDE:<br>Provide OrderService autocomplete</li><li>To a static type checker:<br>Validate how OrderService is used</li><li>And to the framework (FastAPI)<br>Resolve this parameter through the dependency injection system.</li></ul><p>A lot of architectural information is packed into one function signature.</p><h3>When Should You Use Annotated[..., Depends()]?</h3><p>This is the question I had to ask myself. I didn’t have a deep understanding of this concept, but I was using it, and it worked, and I didn’t question it. But after exploring this more, I’ve concluded that this is most useful when FastAPI needs an actual application service or infrastructure dependency. I already had good habits for separation of concerns, but could I explain it like this? Hopefully, now <em>you</em> can.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=508251ae272a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing God Classes In Python]]></title>
            <link>https://markusfarkus.medium.com/stop-writing-god-classes-in-python-2554e899eb22?source=rss-c5ded6402cba------2</link>
            <guid isPermaLink="false">https://medium.com/p/2554e899eb22</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Marcus T]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 17:03:17 GMT</pubDate>
            <atom:updated>2026-08-10T17:03:17.972Z</atom:updated>
            <content:encoded><![CDATA[<p>Some classes start off innocently enough. However, they may keep taking on more and more responsibility and turn into 1000-line monsters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1a4YZn9-zxKbJlgXK1gd1A.png" /></figure><p>It starts off well-intentioned. Say you need to process orders, so you create an OrderManager class. It processes orders. Great. Then it starts to do more.</p><ul><li>Validate orders</li><li>Save orders</li><li>Calculate tax and shipping</li><li>Process payments</li><li>Send notifications</li></ul><p>The clean object you started with is now hundreds of lines long and no one wants to touch it.</p><pre>class OrderManager:<br>    def create_order(self, customer, items):<br>    ...<br><br>    def validate_order(self, order):<br>    ...<br><br>    def calculate_total(self, order):<br>    ...<br><br>    def calculate_tax(self, order):<br>    ...<br><br>    def calculate_shipping(self, order)<br>    ...<br>    <br>    def apply_discount(self, order):<br>    ...<br><br>    def save_order(self, order):<br>    ...<br><br>    def process_payment(self, order):<br>    ...<br><br>    def send_confirmation(self, order):<br>    ...<br><br>    def generate_invoice(self, order):<br>    ...</pre><p>Looking at each function individually, it makes sense. But no matter how well written these methods are, they don’t all belong in the same class.</p><h3>What Is a God Class?</h3><p>A <strong>God Class</strong> is a class that knows too much, controls too much, or is responsible for too many unrelated parts of a system.</p><p>Typical symptoms:</p><ul><li>Huge number of methods</li><li>Lots of dependencies</li><li>Changes for many unrelated reasons</li><li>Difficult to test without extensive mocking</li><li>Frequently touched by unrelated features</li><li>Other classes mostly exist to feed data into it</li></ul><p>God classes are rarely designed. They accumulate responsibility over time due to increased business logic or requirements.</p><blockquote><em>A large class isn’t automatically a God class.</em></blockquote><p>A 500-line parser with one cohesive responsibility might be fine. A 150-line UserManager that handles authentication, database persistence, emails, billing, and analytics probably isn&#39;t. It ignores the <a href="http://geeksforgeeks.org/system-design/single-responsibility-in-solid-design-principle/">Single Responsibility Principle</a>. Robert C. Martin provided a commonly cited formula:</p><blockquote>A module should have one reason to change.</blockquote><p>In the case of the overloaded OrderManager it has many reasons to change:</p><ul><li>Tax rules changed</li><li>Payment provider changed</li><li>Email template changed</li><li>Database schema changed</li><li>Discount rules changed</li><li>Invoice format changed</li></ul><p>Each is an independent reason to modify this class.</p><h3>Refactoring the God Class</h3><p>Rather than immediately producing ten tiny classes, refactor incrementally.</p><h4>Example — Extract validation</h4><pre>class OrderValidator:<br>    def validate(self, order):<br>        if not order.items:<br>            raise ValueError(&quot;Order must contain items&quot;)</pre><p>Becomes:</p><pre>class OrderService:<br>    def __init__(self, validator):<br>        self.validator = validator<br><br>    def place_order(self, order):<br>        self.validator.validate(order)</pre><p>Any changes to how an order is validated are handled externally and minimally affect the flow of the OrderManager class.</p><h4>Example — Extract payment</h4><pre>class PaymentProcessor:<br>    def charge(self, order):<br>        ...</pre><p>If multiple payment providers are required later, we can consider an <a href="https://medium.com/@markusfarkus/abstract-classes-in-python-designing-code-like-an-architect-bef39e1aa962">abstract class</a>, <a href="https://medium.com/@markusfarkus/design-patterns-for-practical-python-development-a6f53e97c8c6">Protocol, or Strategy pattern</a>.</p><h4>Example — Extract notification</h4><pre>class OrderNotifier:<br>    def send_confirmation(self, order):<br>        ...</pre><p>Notification implementations become <a href="https://medium.com/@markusfarkus/building-an-extensible-system-in-python-181e39009a6f">extensible</a>.</p><p>Eventually, the new architecture will resemble this:</p><pre>                    OrderService<br>                         │<br>          ┌──────────────┼───────────────┐<br>          │              │               │<br>          ▼              ▼               ▼<br>   OrderValidator   PricingService   PaymentProcessor<br>                                          │<br>                         ┌────────────────┴─────┐<br>                         ▼                      ▼<br>                  OrderRepository         OrderNotifier<br><br><br>class OrderService:<br>    def __init__(<br>        self,<br>        validator,<br>        pricing,<br>        payments,<br>        repository,<br>        notifier<br>    ):<br>        self.validator = validator<br>        self.pricing = pricing<br>        self.payments = payments<br>        self.repository = repository<br>        self.notifier = notifier<br><br>    def place_order(self, order):<br>        self.validator.validate(order)<br><br>        total = self.pricing.calculate(order)<br><br>        self.payments.charge(order.customer, total)<br><br>        self.repository.save(order)<br><br>        self.notifier.send_confirmation(order)</pre><blockquote><em>Coordinating many responsibilities is different from owning many responsibilities.</em></blockquote><p>Composition is doing the heavy lifting now. The system is assembled from collaborators. The lesson is to design objects that have capabilities rather than objects that inherit every capability.</p><h3>Common Mistakes</h3><p>This fits the established structure of the series.</p><h4>❌ Mistake #1: Measuring responsibilities by method count</h4><p>Ten cohesive methods can be better than three unrelated ones.</p><h4>❌ Mistake #2: Creating interfaces for everything</h4><pre>class AbstractOrderValidatorFactoryInterface(ABC):</pre><p>Don’t introduce abstractions until they solve an actual problem.</p><h4>❌ Mistake #3: Confusing orchestration with a God class</h4><p>A service coordinating five components isn’t necessarily violating the single responsibility principle.</p><h4>❌ Mistake #4: Refactoring everything at once</h4><p>Extract responsibilities incrementally and keep tests passing.</p><h4>❌ Mistake #5: Treating SRP as “one method per class”</h4><p>That’s not what Single Responsibility means.</p><h3>How to Spot a God Class in Your Own Code</h3><p>When looking at a suspicious class, ask:</p><ol><li>How many unrelated reasons could this class change?</li><li>How many external systems does it know about?</li><li>Can I describe its job in one sentence without using “and”?</li><li>Do unrelated features keep modifying this file?</li><li>Are tests difficult because everything is coupled together?</li><li>Would extracting one responsibility make another part easier to change independently?</li></ol><h3>Set Up Boundaries</h3><p>The God class is really a symptom of missing boundaries.</p><p>Earlier in the series we learned about:</p><ul><li>Abstract classes → contracts</li><li>Duck typing → behavioral flexibility</li><li>Composition → assembling behavior</li><li>Design patterns → organizing recurring design problems</li><li>Extensible systems → adding implementations without rewriting the core</li></ul><p>Now we’re learning something more fundamental:</p><blockquote><strong><em>Software architecture starts by deciding where responsibilities belong.</em></strong></blockquote><p>That’s the bridge from <em>writing classes</em> toward <em>thinking in systems</em>. A God class isn’t bad because it’s long. It’s bad because decisions that should be independent have become tangled together. The solution isn’t blindly creating more classes. It’s identifying the boundaries already hiding inside your code.</p><p>Validation changes for one reason. <br>Payments change for another. <br>Persistence changes for another.</p><p>Separate those responsibilities, compose them into a system, and suddenly the code becomes easier to understand, test, replace, and extend.</p><p>That’s when you’re no longer just organizing code.</p><p><strong>You’re designing a system.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2554e899eb22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rotating a Matrix 90°: The Transpose-and-Reverse Trick]]></title>
            <link>https://markusfarkus.medium.com/rotating-a-matrix-90-the-transpose-and-reverse-trick-be39ea7f5105?source=rss-c5ded6402cba------2</link>
            <guid isPermaLink="false">https://medium.com/p/be39ea7f5105</guid>
            <category><![CDATA[missy-elliott]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Marcus T]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 18:36:01 GMT</pubDate>
            <atom:updated>2026-08-02T18:36:01.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsnCA4-lTsIWwS3cqxl9vA.png" /></figure><p>Rotating a 2D matrix by 90° is one of those interview problems that looks hard at first and then becomes more obvious once you see the trick. In this article, we’ll explore the underlying logic, derive the index-mapping rule, and then implement it in three languages— Python, JavaScript, and Java. We will also include an in-place version that uses no extra memory. Hopefully, by the end, you’ll have the methods to rotate a matrix clockwise and counter-clockwise in your bag of tricks.</p><h3>The Problem</h3><p>Given a square n × n matrix, rotate it 90° clockwise. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*7cTiH0BmxHlKSn60Do_6oQ.png" /></figure><p>Observe what happens to the first column 1, 4, 7. It becomes the first <em>row</em>, but not quite in reversed order. It&#39;s the top row read bottom-to-top: 7, 4, 1. That single observation is the whole algorithm.</p><h3>The dance move: transpose, then reverse</h3><h4>Step 1 — Transpose</h4><p>Transposing a matrix <em>flips</em> it across its main diagonal (top-left to bottom-right). Every element at position (i, j) swaps with the element at (j, i). Rows become columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*SEd_SO8v8MHXeQP9QBLlhQ.png" /></figure><h4>Step 2— Reverse Each Row</h4><p>Now reverse the elements in each row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*hbCoIoo-xBB1zo50_JAutg.png" /></figure><p>Now the 90° rotation is complete.</p><h3>Counter-clockwise is the mirror image</h3><p>To rotate the matrix 90° counter-clockwise, you just swap the order of the two steps: reverse columns instead of rows:</p><ul><li>Reverse each row first, then transpose, or</li><li>Transpose first, then reverse the row order (reverse the outer list).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*VEgDCg7lnpF9NWKcYY1mxQ.png" /></figure><h3>The Index-Mapping Rule</h3><p>We can think about this logic strictly mathematically; there’s a clean formula. For an n × n matrix rotated 90° clockwise, the element at (i, j) moves to:</p><pre>(i, j)  -&gt;  (j, n - 1 - i)</pre><p>For counter-clockwise:</p><pre>(i, j)  -&gt;  (n - 1 - j, i)</pre><p>This formula is what lets us build a rotated <em>copy</em> in a single pass without the two-step dance. This is useful when the matrix isn’t square (an m × n matrix rotates into an n × m one).</p><h3>Python Implementation</h3><p>Python’s zip(*matrix) transposes a matrix in one expression, and slicing ([::-1]) handles the reversal. That makes the copy-based version delightfully short.</p><pre>def rotate_matrix(matrix, counter_clockwise=False):<br>    if counter_clockwise:<br>        # Transpose, then reverse the row order.<br>        return [list(row) for row in zip(*matrix)][::-1]<br>    else:<br>        # Reverse the row order, then transpose.<br>        return [list(row) for row in zip(*matrix[::-1])]</pre><p>zip(*matrix) unpacks each row as an argument to zip, which pairs up elements column-wise — that&#39;s the transpose. The only quirk is that zip yields tuples, so we wrap each one in list(...).</p><h3>In-place, O(1) extra space</h3><p>If the matrix is square and you want to avoid allocating a new one, mutate it directly. Transpose by swapping across the diagonal, then reverse each row.</p><pre>def rotate_in_place(matrix):<br>    n = len(matrix)<br>    # Transpose: swap across the main diagonal.<br>    for i in range(n):<br>        for j in range(i, n):<br>            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]<br>    # Reverse each row.<br>    for row in matrix:<br>        row.reverse()</pre><p>Note the inner loop starts at j = i, not j = 0. Swapping only the upper triangle avoids double-swapping (which would put everything back where it started).</p><h3>JavaScript Implementation</h3><p>JavaScript has no built-in zip, so we build the rotated copy directly from the index-mapping rule. This version also works for non-square matrices.</p><pre>function rotateMatrix(matrix, counterClockwise = false) {<br>    const rows = matrix.length;<br>    const cols = matrix[0].length;<br>    const result = [];<br>    <br>    if (counterClockwise) {<br>        // Element (i, j) moves to (cols - 1 - j, i)<br>        for (let j = cols - 1; j &gt;= 0; j--) {<br>            const newRow = [];<br>            for (let i = 0; i &lt; rows; i++) {<br>                newRow.push(matrix[i][j]);<br>            }<br>            result.push(newRow);<br>        }<br>    } else {<br>        // Element (i, j) moves to (j, rows - 1 - i)<br>        for (let j = 0; j &lt; cols; j++) {<br>            const newRow = [];<br>            for (let i = rows - 1; i &gt;= 0; i--) {<br>                newRow.push(matrix[i][j]);<br>            }<br>            result.push(newRow);<br>        }<br>    }<br>    return result;<br>}</pre><h3>In-place version</h3><p>The square in-place version mirrors Python’s — transpose via diagonal swaps, then reverse each row. JavaScript’s array destructuring makes the swap a one-liner.</p><pre>function rotateInPlace(matrix) {<br>    const n = matrix.length;<br>    // Transpose.<br>    for (let i = 0; i &lt; n; i++) {<br>        for (let j = i; j &lt; n; j++) {<br>            [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];<br>        }<br>    }<br>    // Reverse each row.<br>    for (const row of matrix) {<br>        row.reverse();<br>    }<br>}</pre><h3>Java Implementation</h3><p>Java makes you work— no zip, no slicing, no destructuring — but the logic is identical. We allocate the result with swapped dimensions (new int[cols][rows]) and apply the mapping rule.</p><pre>static int[][] rotateMatrix(int[][] matrix, boolean counterClockwise) {<br>    int rows = matrix.length;<br>    int cols = matrix[0].length;<br>    int[][] result = new int[cols][rows];<br><br>    if (counterClockwise) {<br>        // Element (i, j) moves to (cols - 1 - j, i)<br>        for (int i = 0; i &lt; rows; i++) {<br>            for (int j = 0; j &lt; cols; j++) {<br>                result[cols - 1 - j][i] = matrix[i][j];<br>            }<br>        }<br>    } else {<br>        // Element (i, j) moves to (j, rows - 1 - i)<br>        for (int i = 0; i &lt; rows; i++) {<br>            for (int j = 0; j &lt; cols; j++) {<br>                result[j][rows - 1 - i] = matrix[i][j];<br>            }<br>        }<br>    }<br>    return result;<br>}</pre><h3>In-place version</h3><pre>static void rotateInPlace(int[][] matrix) {<br>    int n = matrix.length;<br>    // Transpose.<br>    for (int i = 0; i &lt; n; i++) {<br>        for (int j = i; j &lt; n; j++) {<br>            int tmp = matrix[i][j];<br>            matrix[i][j] = matrix[j][i];<br>            matrix[j][i] = tmp;<br>        }<br>    }<br>    // Reverse each row.<br>    for (int[] row : matrix) {<br>        for (int left = 0, right = n - 1; left &lt; right; left++, right--) {<br>            int tmp = row[left];<br>            row[left] = row[right];<br>            row[right] = tmp;<br>        }<br>    }<br>}</pre><h3>Complexity</h3><p>Every version above touches each element a constant number of times, so:</p><pre>Approach             Time         Extra<br>---------------------------------------<br>Copy-based           O(n²)        O(n²)<br>In-place (square)    O(n²)        O(1)</pre><p>You can’t beat O(n²) time because you have to move all n² elements. The only real lever is memory: the in-place version rearranges the existing array instead of allocating a new one.</p><h3>Choosing an approach</h3><ul><li><strong>Need a rotated copy or a non-square matrix?</strong> <br>Use the copy-based version with the index-mapping rule. Python’s zip makes it a one-liner; JavaScript and Java build it with a double loop.</li><li><strong>Square matrix and memory-constrained?</strong> <br>Use the in-place transpose-and-reverse. It’s the answer interviewers usually want for the classic “rotate image” problem.</li></ul><p>Now go work it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be39ea7f5105" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building An Extensible System in Python]]></title>
            <link>https://markusfarkus.medium.com/building-an-extensible-system-in-python-181e39009a6f?source=rss-c5ded6402cba------2</link>
            <guid isPermaLink="false">https://medium.com/p/181e39009a6f</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[python-abstract-classes]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Marcus T]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 23:57:17 GMT</pubDate>
            <atom:updated>2026-06-17T21:07:48.076Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kppb-jARD9v6P8JFL4oDGg.png" /></figure><p>So far in this series, we’ve covered several important object-oriented design concepts:</p><ul><li>Abstract Classes</li><li>Abstract Classes vs Duck Typing</li><li>Composition vs Inheritance</li><li>Common Design Patterns</li></ul><p>Each of these ideas is valuable on its own, but rarely are they used in isolation. In real projects, these concepts are used together to build systems that are flexible, maintainable, and easy to extend. So let’s build something real.</p><p>For this exercise, we’ll create a plugin-based notification system that can send messages through different channels such as email, SMS, and Slack. More importantly, we’ll design it so that new notification channels can be easily added without modifying existing code.</p><p>The completed system will be a practical example that demonstrates:</p><ul><li>Abstract Classes</li><li>Composition</li><li>The Strategy Pattern</li><li>Multiple Implementations</li><li>Extensibility Through Plugins</li></ul><p>Starting with a basic notification system, the requirements seem straightforward and manageable.</p><pre>def send_notification(notification_type, message): <br>  if notification_type == &quot;email&quot;: <br>    print(f&quot;Sending email: {message}&quot;) <br>    ...<br>  elif notification_type == &quot;sms&quot;: <br>    print(f&quot;Sending SMS: {message}&quot;)<br>    ...</pre><p>This works fine initially. But once the options for notification types starts expanding, this code has to be modified. This violates one of the most useful design principles in software engineering:</p><blockquote><em>Software entities should be open for extension but closed for modification.</em></blockquote><p>This is the Open-Closed Principle (OCP), the “O” in the SOLID principles of object-oriented design.</p><p>Let’s design something more versatile.</p><h3>Step 1: Define an Abstraction</h3><p>All notification channels share a common function. They send messages. This makes an abstract base class a natural fit.</p><pre>from abc import ABC, abstractmethod<br><br>class NotificationProvider(ABC):<br>    @abstractmethod<br>    def send(self, message: str) -&gt; None:<br>        passThis class defines a contract.</pre><p>This class defines a contract. Any notification provider must implement a send() method. Now the system doesn’t care whether a notification is sent through email, SMS, Slack, or something that hasn’t even been invented yet. It only cares that the object knows how to send a message.</p><h3>Step 2: Create Multiple Implementations</h3><p>Now let’s create a few concrete providers.</p><pre>class EmailProvider(NotificationProvider):<br>    def send(self, message: str) -&gt; None:<br>        print(f&quot;EMAIL: {message}&quot;)<br><br><br>class SMSProvider(NotificationProvider):<br>    def send(self, message: str) -&gt; None:<br>        print(f&quot;SMS: {message}&quot;)<br><br><br>class SlackProvider(NotificationProvider):<br>    def send(self, message: str) -&gt; None:<br>        print(f&quot;SLACK: {message}&quot;)</pre><p>Each class uses the same interface while providing different behavior. This is one of the primary benefits of abstract classes. Consumers of these classes don’t need to know the implementation details; they only need to know the contract.</p><h3>Step 3: Compose the System</h3><p>Now let’s create a service responsible for sending notifications. Instead of inheriting from a notification provider, we’ll use composition.</p><pre>class NotificationService:<br>    def __init__(self, provider: NotificationProvider):<br>        self.provider = provider<br>    def notify(self, message: str) -&gt; None:<br>        self.provider.send(This may seem like a small design decision, but it’s incredibly important.</pre><p>Notice what we’ve done. This may seem like a small design decision, but it’s incredibly important.</p><p>The service doesn’t know (or care):</p><ul><li>How emails work</li><li>How SMS works</li><li>How Slack works</li></ul><p>It only knows that it has been given an object capable of sending notifications. This is composition in action. The service is not tightly coupled to a specific implementation. Behavior is composed from interchangeable objects.</p><h3>Step 4: Use Different Strategies</h3><p>Now let’s use our system.</p><pre>email_service = NotificationService(<br>    EmailProvider()<br>)<br><br>email_service.notify(<br>    &quot;The TPS report is ready.&quot;<br>)<br></pre><p>Output: <em>“The TPS report is ready.”</em></p><p>Switching to SMS requires no changes to the service itself.</p><pre>sms_service = NotificationService(<br>    SMSProvider()<br>)<br><br>sms_service.notify(<br>    &quot;The TPS report is ready.&quot;<br>)</pre><p>Output: <em>“The TPS report is ready.”</em></p><p>The behavior changes while the surrounding code remains exactly the same. This is a textbook example of the Strategy Pattern. The notification provider acts as a strategy that can be swapped at runtime.</p><h3>Step 5: Adding a Factory</h3><p>Creating providers manually works fine for small examples. In larger systems, we often want to create providers dynamically. A simple factory can help.</p><pre>class NotificationFactory:<br><br>    @staticmethod<br>    def create(provider_type: str):<br>        providers = {<br>            &quot;email&quot;: EmailProvider,<br>            &quot;sms&quot;: SMSProvider,<br>            &quot;slack&quot;: SlackProvider,<br>        }<br><br>        provider_class = providers.get(<br>            provider_type.lower()<br>        )<br><br>        if not provider_class:<br>            raise ValueError(f&quot;Unknown provider: {provider_type}&quot;)<br><br>        return provider_class()</pre><p>Now we can create providers from configuration.</p><pre>provider = NotificationFactory.create(&quot;slack&quot;)<br><br>service = NotificationService(provider)<br>service.notify(&quot;Deployment completed successfully.&quot;)</pre><p>This separates object creation logic from business logic.</p><h3>Step 6: Extending the System</h3><p>Now we have a good system for sending notifications. Right on time, a product manager asks for Discord notifications.</p><p>How much existing code must we modify?</p><p>None.</p><p>We simply create a new provider.</p><pre>class DiscordProvider(NotificationProvider):<br>    def send(self, message: str) -&gt; None:<br>        print(f&quot;DISCORD: {message}&quot;)</pre><p>Then add it to the providers list.</p><pre>providers = {<br>    &quot;email&quot;: EmailProvider,<br>    &quot;sms&quot;: SMSProvider,<br>    &quot;slack&quot;: SlackProvider,<br>    &quot;discord&quot;: DiscordProvider,<br>}</pre><p>That’s it.</p><p>No changes to:</p><ul><li>NotificationService</li><li>Existing providers</li><li>Client code</li></ul><p>We’ve extended the system without modifying its core behavior. This is exactly the gload with extensible architecture.</p><h3>But Does It Scale?</h3><p>As applications grow, new requirements become inevitable.</p><p>Maybe tomorrow we need:</p><ul><li>Rate limiting</li><li>Retry logic</li><li>Message formatting</li><li>Multiple simultaneous notification channels</li><li>Logging</li><li>Metrics</li></ul><p>We built this system around abstractions and composition, so we can add capabilities incrementally. The core architecture remains stable while the system evolves around it. This is one of the biggest differences between code that survives for years and code that becomes difficult to maintain after a few months.</p><h3>Putting it all together</h3><p>Let’s review the architecture we’ve created.</p><pre>NotificationProvider (Abstract) <br>├── EmailProvider <br>├── SMSProvider <br>├── SlackProvider <br>└── DiscordProvider <br><br>NotificationService <br>        │ <br>        ▼ <br>NotificationProvider</pre><p>Notice how each concept from previous articles contributed to the final design.</p><ul><li>Abstract Classes gave us a common contract.</li><li>Composition allowed us to assemble behavior without inheritance.</li><li>The Strategy Pattern allowed implementations to be swapped dynamically.</li><li>The Factory Pattern simplified object creation.</li></ul><p>Together, these techniques create a system that is easier to understand, easier to extend, and easier to maintain. Our notification system is small, but the architecture is the same approach used in production systems every day.</p><p>The next time you’re tempted to add another if statement or another giant conditional block, ask yourself:</p><p><em>Could this be a new implementation of an existing abstraction instead?</em></p><p>Often, the answer is yes. And that’s where extensible software begins.</p><p>To illustrate these concepts, I have created an <a href="https://github.com/mturnbo/NotificationSystemModule">example project</a> on GitHub.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=181e39009a6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns For Practical Python Development]]></title>
            <link>https://markusfarkus.medium.com/design-patterns-for-practical-python-development-a6f53e97c8c6?source=rss-c5ded6402cba------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6f53e97c8c6</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Marcus T]]></dc:creator>
            <pubDate>Mon, 11 May 2026 16:01:02 GMT</pubDate>
            <atom:updated>2026-05-11T16:01:02.487Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_dtLudNYFfQJcr-yrYjjA.png" /></figure><p>Design patterns are typical solutions to problems that commonly occur in software design and architecture. They represent best practices that have evolved over time to address recurring design challenges.</p><p>In my previous articles on <a href="https://medium.com/@markusfarkus/abstract-classes-in-python-designing-code-like-an-architect-bef39e1aa962"><strong>Abstract Classes</strong></a> and <a href="https://medium.com/@markusfarkus/composition-vs-inheritance-in-python-b9bc31a74916"><strong>Composition vs Inheritance</strong></a>, we explored <em>how</em> to structure relationships between objects. If you’ve followed along, you already have most of what you need to recognize design patterns. You’ve been writing them. Perhaps you just didn’t have names for them. They’re the shapes that good code naturally settles into when you let it.</p><h3>Why Use Design Patterns?</h3><p>Good design isn’t about writing clever code — it’s about <a href="https://medium.com/javascript-in-plain-english/why-japanese-developers-code-differently-and-better-afe481ab8354">writing code that survives change.</a> Learning design patterns helps you:</p><ul><li>Reduce duplication</li><li>Increase flexibility</li><li>Avoid tight coupling</li><li>Make intent obvious</li></ul><p>Design patterns are tested, well-documented, and understood by experienced developers. Using them makes code more standardized, portable, and easier to understand, as they provide a common language of sorts.</p><p>We’re going to look at three essential design patterns every Python developer should have in their toolbox:</p><ul><li><strong>Template Method</strong> (a bridge from abstract classes to real-world structure)</li><li><strong>Strategy Pattern</strong> (composition in action)</li><li><strong>Factory Pattern</strong> (clean object creation)</li></ul><h3>Template Method Pattern</h3><p>The idea behind the template method pattern is to define the <strong>skeleton of an algorithm </strong>and use subclasses to fill in specific steps. The base class is in charge. The subclasses customize. This pattern is a natural fit for Python’s abstract base class (abc), which we covered previously.</p><h4>When to Use It</h4><ul><li>You have a process with <strong>strictly defined steps</strong></li><li>Some steps vary between implementations</li><li>You want to enforce structure but allow flexibility</li></ul><h4>Example: A Data Processing Pipeline</h4><pre>from abc import ABC, abstractmethod<br><br>class DataProcessor(ABC):<br><br>    def process(self, data):<br>        self.load(data)<br>        self.transform()<br>        self.save()<br><br>    @abstractmethod<br>    def load(self, data):<br>        pass<br><br>    @abstractmethod<br>    def transform(self):<br>        pass<br><br>    def save(self):<br>        print(&quot;Saving processed data...&quot;)</pre><p>Concrete Implementation</p><pre>class JSONProcessor(DataProcessor):<br><br>    def load(self, data):<br>        print(&quot;Loading JSON data&quot;)<br><br>    def transform(self):<br>        print(&quot;Transforming JSON data&quot;)</pre><p>JSONProcessor().process() runs the full pipeline. The order — load, transform, save — is locked in by the DataProcessor base class. How each step is implemented is up to the subclass. This is useful when you have a process that’s <strong>the same shape every time but different in the details</strong>. ETL jobs. Test runners. Game loops. Web request handlers. The base class enforces the order so nobody can accidentally skip the transform step or run save before load. You probably have seen this pattern before. Django’s class-based views are Template Method. unittest.TestCase with its setUp / test_* / tearDown lifecycle is Template Method. Most ORM model save hooks are Template Method.</p><h4>⚠️ Common Mistake</h4><p>Don’t overuse inheritance.</p><p>Template Method’s failure mode is the same as inheritance’s: the base class does too much. You start with a clean four-step pipeline, and three years later it’s a fourteen-step monster with optional hooks, conditional steps, and a flag called legacy_mode preceded by comments telling developers “DO NOT TOUCH!”.</p><p>If behavior needs to change at runtime, this pattern isn’t the best fit.</p><p>👉 That’s where Strategy comes in.</p><h3>Strategy Pattern</h3><p>The idea behind the strategy pattern is to encapsulate interchangeable behaviors and make them <strong>pluggable at runtime</strong>. It is the pattern that falls out naturally when you take “favor composition over inheritance” seriously.</p><h4>When to Use It</h4><ul><li>You have multiple ways to perform a task</li><li>You want to switch behavior dynamically</li><li>You want to avoid large if/elif blocks</li></ul><p>Instead of locking behavior into a class via inheritance, you <strong>inject the behavior as an object</strong>. The class <em>uses</em> a thing instead of <em>being</em> a thing. And because the thing is just an object, it becomes dynamic. You can swap it at runtime, mock it in tests, or pick it from a config file.</p><h4>Example: Computing Shipping Costs</h4><p>Suppose you have an order class that needs to compute shipping costs based on region.</p><pre>class StandardShipping:<br>    def cost(self, order):<br>        return 5.00 + 0.50 * order.weight<br><br>class ExpressShipping:<br>    def cost(self, order):<br>        return 15.00 + 1.20 * order.weight<br><br>class FreeShipping:<br>    def cost(self, order):<br>        return 0.0</pre><pre>class Order:<br>    def __init__(self, items, shipping_strategy):<br>        self.items = items<br>        self.weight = sum(item.weight for item in items)<br>        self.shipping_strategy = shipping_strategy<br><br>    def total(self):<br>        subtotal = sum(item.price for item in self.items)<br>        return subtotal + self.shipping_strategy.cost(self)</pre><p>Order doesn&#39;t know or care which shipping rule applies. You inject the strategy:</p><pre>order = Order(items, ExpressShipping())</pre><p>This makes it easy to swap in new shipping methods for A/B testing or fixed values for unit tests.</p><h4>⚠️ Things To Avoid</h4><p>1) Over-application. If a method only has one variant and there’s no realistic chance of a second, Strategy is overkill. A plain method on the class is fine. Don’t increase complexity for flexibility you’ll never use.</p><p>2) Strategies need to share an interface. If StandardShipping.cost(order) returns a float but ExpressShipping.calculate(order) returns a dict, you don’t have strategies — you have three unrelated classes that happen to live in the same folder. This is exactly where an ABC or a typing.Protocol comes into play: it pins down the contract so all your strategies actually fit the same slot.</p><h3>Factory Pattern</h3><p>The idea behind the Factory pattern is to encapsulate object creation so your code isn’t riddled with if/else logic. You have the Template pattern for the skeleton. You have the Strategy pattern for the swappable behavior. But which one do we instantiate? The Factory pattern uses a function or class that uses configuration input to return the appropriate concrete class for the situation.</p><h4>When to Use It</h4><ul><li>Object creation is complex</li><li>You need to choose between multiple types</li><li>You want to decouple instantiation from usage</li></ul><p>Let’s implement a factory for the shipping strategy defined earlier:</p><pre>def shipping_for(user, region):<br>    if user.is_prime:<br>        return FreeShipping()<br>    if region == &quot;domestic&quot;:<br>        return StandardShipping()<br>    if region == &quot;international&quot;:<br>        return ExpressShipping()<br>    raise ValueError(f&quot;No shipping strategy for region {region}&quot;)</pre><p>Now the shipping strategy can be defined like so:</p><pre>strategy = shipping_for(user, region)<br>order = Order(items, strategy)</pre><p>The Order class still knows nothing about the rules. The calling code still knows nothing about the rules. The factory is the one place where the messy decision lives, and that&#39;s the primary benefit — the decision logic is in one place, not fifteen.</p><h4>⚠️ Common Mistake</h4><p>Don’t over-engineer factories for simple cases.<br>If creation is trivial, keep it simple.<br>Factories become less useful when they do too much. The shipping factory above is fine with three branches. At thirty branches, with nested conditions and string matching on user attributes, it’s a maintenance disaster disguised as a design pattern.</p><h3>How These Patterns Work Together</h3><p>These patterns solve different problems and they compose cleanly.</p><ul><li><strong>Template Method</strong> → controls structure (inheritance)</li><li><strong>Strategy</strong> → controls behavior (composition)</li><li><strong>Factory</strong> → controls creation (decoupling)</li></ul><p>They solve <em>different problems</em> — and often work best together. A realistic system uses all three. A ReportGenerator (Template Method) might delegate its formatting step to a Formatter strategy (CSV, JSON, PDF). The choice of which formatter to use comes from a formatter_for(report_type) factory. Each pattern stays in its lane; the system remains understandable.</p><p>That layering is the real lesson. Patterns aren’t standalone tricks — they’re a vocabulary for the structural decisions you’re making anyway. Knowing the names lets you make those decisions on purpose and communicate them better to others working on the same code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6f53e97c8c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Composition vs Inheritance in Python]]></title>
            <link>https://markusfarkus.medium.com/composition-vs-inheritance-in-python-b9bc31a74916?source=rss-c5ded6402cba------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9bc31a74916</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[class-inheritance]]></category>
            <dc:creator><![CDATA[Marcus T]]></dc:creator>
            <pubDate>Tue, 05 May 2026 16:41:42 GMT</pubDate>
            <atom:updated>2026-05-05T16:41:42.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSlSZ202mffhwYZ734WQgg.png" /></figure><p>If you read the <a href="https://medium.com/@markusfarkus/most-python-developers-dont-need-abstract-classes-here-s-when-you-do-a57598b82856">previous article on abstract classes</a>, you’ve already started thinking in terms of structure and contracts. Now we’re going one level deeper into design decisions — specifically:</p><blockquote><strong><em>How should objects relate to each other?</em></strong></blockquote><p>Two of the most common answers are:</p><ul><li><strong>Inheritance</strong> (the classic <em>is-a</em> relationship)</li><li><strong>Composition</strong> (the flexible <em>has-a</em> relationship)</li></ul><p>Both are powerful. <br>Both are useful. <br>Both can quietly make your code either elegant… or painful to maintain.</p><p>Let’s unpack them with real examples and practical intuition.</p><p>Inheritance feels like the right answer at the start. You see a few related things — cars, trucks, motorcycles — and the traditional education tells you to make a Vehicle base class and let everything else inherit from it. Clean. Object-oriented. Satisfying.</p><p>Then someone asks for an electric flying car, and your beautiful hierarchy collapses into a pile of override hacks and super() calls that nobody understands six months later.</p><h3>The Fragile Hierarchy</h3><p>Inheritance models a hierarchy. Here is a Vehicle hierarchy that looks reasonable on day one:</p><pre>class Vehicle:<br>    def __init__(self, name, max_speed):<br>        self.name = name<br>        self.max_speed = max_speed<br>    def start(self):<br>        print(f&quot;{self.name} engine started.&quot;)<br>    def move(self):<br>        print(f&quot;{self.name} is moving at {self.max_speed} mph.&quot;)<br><br>class Car(Vehicle):<br>    def __init__(self, name, max_speed, num_wheels=4):<br>        super().__init__(name, max_speed)<br>        self.num_wheels = num_wheels<br>    def drive(self):<br>        print(f&quot;{self.name} is driving on {self.num_wheels} wheels.&quot;)<br><br>class Truck(Car):<br>    def __init__(self, name, max_speed, cargo_capacity):<br>        super().__init__(name, max_speed)<br>        self.cargo_capacity = cargo_capacity<br>    def haul(self):<br>        print(f&quot;{self.name} is hauling {self.cargo_capacity} tons.&quot;)</pre><p>This works just fine until it doesn’t. Product comes along and says, <em>“We need an electric car.”</em></p><p>It seems like an easy update to define ElectricCar(Car). Override start() to be silent, add a battery_level attribute. Not as clean as the initial hierarchy, but manageable.</p><p>Then: <em>“We need a flying car.”</em></p><p>Now you’re stuck. Does FlyingCar inherit from Car? It has wheels, but it also flies. Do you add a fly() method to Vehicle so every car and truck pretends it can fly and raises NotImplementedError? Do you make a parallel Aircraft hierarchy and have FlyingCar inherit from both?</p><pre>class Aircraft(Vehicle):<br>    def fly(self):<br>        print(f&quot;{self.name} is flying.&quot;)<br><br>class FlyingCar(Car, Aircraft):  # multiple inheritance, here we go<br>    pass</pre><p>This compiles and runs. But now you’ve introduced the <strong>diamond problem</strong>: FlyingCar inherits from both Car and Aircraft, which both inherit from Vehicle. When you call start(), which path does Python take? Python resolves it with the <strong>MRO</strong> (Method Resolution Order, viewable via FlyingCar.__mro__), but the resolution is implicit and depends on the order you list parents. Change class FlyingCar(Aircraft, Car) and the behavior shifts subtly.</p><p>Now add: <em>“electric flying car.”</em> Do you make ElectricFlyingCar(ElectricCar, FlyingCar)? You&#39;ve got four-way inheritance, two diamond intersections, and a super().__init__() chain that you have to draw on a whiteboard to debug. The hierarchy is no longer modeling vehicles — it&#39;s modeling every possible <em>combination</em> of vehicle features, and that combinatorial explosion is what kills inheritance-heavy designs.</p><p>The real problem is deeper than syntax. Inheritance forced us to commit, up front, to a single axis of classification (what kind of vehicle is it?). Real vehicles vary along <em>several</em> independent axes: how they’re powered, how they move, what they carry. The tight coupling of inheritance can model one axis well. It cannot model many.</p><h3>The Same Problem, Composed</h3><p>Composition builds objects from smaller, reusable pieces. Instead of asking <em>“what is this thing?”</em> we ask <em>“what can this thing do, and what does it have?”</em> Each capability becomes its own small class, and a vehicle is assembled by injecting the capabilities it needs.</p><pre># Capabilities — each one does exactly one thing.<br>class GasEngine:<br>    def start(self, name):<br>        print(f&quot;{name} gas engine started with a vroom vroom.&quot;)<br><br>class ElectricMotor:<br>    def start(self, name):<br>        print(f&quot;{name} electric motor whirs to life silently.&quot;)<br><br>class WheeledMovement:<br>    def __init__(self, num_wheels=4):<br>        self.num_wheels = num_wheels<br>    def move(self, name):<br>        print(f&quot;{name} drives on {self.num_wheels} wheels.&quot;)<br><br>class FlightMovement:<br>    def move(self, name):<br>        print(f&quot;{name} takes off and flies.&quot;)<br><br>class CargoHold:<br>    def __init__(self, capacity, units):<br>        self.capacity = capacity<br>        self.units = units<br>    def haul(self, name):<br>        print(f&quot;{name} hauls {self.capacity} {self.units}.&quot;)<br><br># The vehicle itself is just a coordinator.<br>class Vehicle:<br>    def __init__(self, name, max_speed, power_source, movement, cargo=None):<br>        self.name = name<br>        self.max_speed = max_speed<br>        self.power_source = power_source<br>        self.movement = movement<br>        self.cargo = cargo<br>    def start(self):<br>        self.power_source.start(self.name)<br>    def move(self):<br>        self.movement.move(self.name)<br>    def haul(self):<br>        if self.cargo:<br>            self.cargo.haul(self.name)<br>        else:<br>            print(f&quot;{self.name} has no cargo hold.&quot;)</pre><p>Vehicle doesn’t inherit from GasEngine or ElectricMotor. It delegates behavior. Now building any vehicle is much easier.</p><pre>sedan         = Vehicle(&quot;Sedan&quot;, 120, GasEngine(), WheeledMovement(4))<br>electric_car  = Vehicle(&quot;Tesla&quot;, 150, ElectricMotor(), WheeledMovement(4))<br>truck         = Vehicle(&quot;Truck&quot;, 90, GasEngine(), WheeledMovement(6), CargoHold(10))<br>flying_car    = Vehicle(&quot;AeroMobil&quot;, 200, GasEngine(), FlightMovement())<br>electro_flyer = Vehicle(&quot;Skydrive&quot;, 180, ElectricMotor(), FlightMovement())</pre><h3>When inheritance is still the right call</h3><p>Favoring composition over inheritance is heavily emphasized in books like <a href="https://chatgpt.com/g/g-p-69ce8c106adc8191ad2e80446956e209-medium-articles/c/69ed7fae-7f40-83ea-a0d5-c8214ba86350#:~:text=books%20like%20Design-,Patterns,-%3A%20Elements%20of%20Reusable">Design Patterns: Elements of Reusable Object-Oriented Software</a>. But don’t think that you should never use inheritance. Rather, use inheritance carefully as it is expensive to change.</p><p>Inheritance is the right tool when:</p><ul><li>The relationship is genuinely <strong>is-a</strong> and <strong>stable</strong>. A SavingsAccount truly <em>is</em> a kind of BankAccount. A PermissionError truly <em>is</em> an OSError. These relationships don&#39;t shift when requirements change.</li><li>You’re extending a <strong>framework</strong> that expects subclassing. Django models, Python’s Exception hierarchy, Pytest fixtures — these are designed around inheritance, and fighting that is silly.</li><li>The hierarchy is <strong>shallow</strong> (one or two levels) and the parent class is <strong>abstract</strong> or <strong>stable</strong>. Most well-designed inheritance trees stop at depth two.</li></ul><p>The trouble starts when you reach for inheritance to share <em>behavior</em> between things that aren’t really the same kind of thing — that’s when composition is almost always better.</p><h3>When to Use Composition</h3><p>Use composition when:</p><ul><li>Behavior may <strong>change at runtime</strong></li><li>You want to <strong>mix and match features</strong></li><li>You want to avoid <strong>deep hierarchies</strong></li></ul><p>Think:</p><ul><li>Strategy pattern</li><li>Plugin systems</li><li>Configurable components</li></ul><h3>Final Thought</h3><p>Inheritance gives you <strong>structure</strong>.<br>Composition gives you <strong>freedom</strong>.</p><p>Most beginners overuse inheritance because it feels intuitive. Experienced developers lean toward composition because they’ve experienced the pain of using inheritance before.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9bc31a74916" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Most Python Developers Don’t Need Abstract Classes (Here’s When You Do)]]></title>
            <link>https://markusfarkus.medium.com/most-python-developers-dont-need-abstract-classes-here-s-when-you-do-a57598b82856?source=rss-c5ded6402cba------2</link>
            <guid isPermaLink="false">https://medium.com/p/a57598b82856</guid>
            <category><![CDATA[duck-typing]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[computer-programming]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Marcus T]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 13:01:02 GMT</pubDate>
            <atom:updated>2026-04-29T13:01:02.788Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2iGR5pLRu8-y5nD6RmwTQ.png" /></figure><blockquote>Python gives you abstract classes… but it doesn’t expect you to use them.</blockquote><p>If you’re using Java or C#, abstract classes feel like a natural starting point. You define an interface, enforce a contract, and make sure every subclass behaves correctly.</p><p>But Python has a different philosophy:</p><blockquote>“If it walks like a duck and quacks like a duck… it’s a duck.”</blockquote><p>So which one should you use?</p><ul><li><strong>Strict contracts (abstract classes)?</strong></li><li><strong>Flexible behavior (duck typing)?</strong></li></ul><p>The answer is: <strong>both — at the right time.</strong></p><p>Let’s break it down</p><h3>What Is Duck Typing?</h3><p>Python doesn’t care what type your object is. It cares what your object <em>can do</em>. If it has the right methods, Python will happily use it.</p><pre>class Dog:<br>    def speak(self):<br>        return &quot;Woof&quot;<br><br>class Cat:<br>    def speak(self):<br>        return &quot;Meow&quot;<br><br>def make_sound(animal):<br>    print(animal.speak())<br><br>make_sound(Dog())<br>make_sound(Cat())</pre><p>No inheritance.<br>No interfaces.<br>No base classes.</p><p>Just behavior.</p><p>Duck typing is the idea that Python checks what an object <em>can do</em> at the moment you ask it to do something, not when the object is declared or passed around. There’s no compile-time type check, no interface declaration, no inheritance requirement. You call animal.speak(), and if animal has a speak() method, it works. If it doesn&#39;t, you get an AttributeError.</p><p>The defensive flavor of duck typing uses hasattr() or try/except AttributeError to handle the case where the method might be missing:</p><pre>def make_it_speak_safely(animal):<br>    if hasattr(animal, &quot;speak&quot;):<br>        return animal.speak()<br>    return None</pre><h3>Why This Works So Well in Python</h3><p>Duck typing gives you:</p><ul><li>✅ <strong>Flexibility</strong> — Any object can participate</li><li>✅ <strong>Less boilerplate</strong> — No need to define hierarchies</li><li>✅ <strong>Faster iteration</strong> — Only implement what you need</li></ul><p>This is why a lot of Python code feels <em>lightweight and expressive</em>. For small scripts and internal code, this is often all you need.</p><h3>Where Duck Typing Silently Fails</h3><p>Imagine a payment-processing module. You’ve got an abstract concept — a processor charges a customer — and several implementations:</p><pre>class CreditCardProcessor:<br>    def charge(self, amount):<br>        # call Stripe, return transaction id<br>        return &quot;txn_cc_123&quot;<br><br><br>class PayPalProcessor:<br>    def charge(self, amount):<br>        # call PayPal API<br>        return &quot;txn_pp_456&quot;<br><br><br>def process_payment(processor, amount):<br>    return processor.charge(amount)</pre><p>Later, a new class is written and makes its way into production:</p><pre>class GiftCardProcessor:<br>    def __init__(self, card_number):<br>        self.card_number = card_number<br><br>    def debit(self, amount):<br>        # deduct from gift card balance<br>        return &quot;txn_gc_789&quot;</pre><p>See the bug? This class has a method namedebit() instead of charge().</p><ul><li>The code imports cleanly. Python doesn’t care that GiftCardProcessor has a differently-named method than the others — there&#39;s no contract for it to violate.</li><li>Unit tests for CreditCardProcessor and PayPalProcessor still pass.</li><li>Tests for GiftCardProcessor probably call debit() directly, so that passes too.</li><li>Staging might not catch it if the gift card flow isn’t exercised end-to-end.</li></ul><p>Then a customer tries to pay with a gift card in production:</p><pre>process_payment(GiftCardProcessor(&quot;1234-5678&quot;), 50.00)<br># AttributeError: &#39;GiftCardProcessor&#39; object has no attribute &#39;charge&#39;</pre><p>The error surfaces at the worst possible moment, in the worst possible place — deep in the call stack, during a real transaction, far from the file where the mistake actually lives. Someone is going to have to do an incident review next week.</p><p>That’s the tradeoff: <strong><em>Flexibility vs Safety</em></strong></p><h3>The ABC Version of the Same Code</h3><p>Abstract classes let you define a <strong>contract</strong> that subclasses must follow. Let’s rewrite it with an abstract base class:</p><pre>from abc import ABC, abstractmethod<br><br>class PaymentProcessor(ABC):<br>    @abstractmethod<br>    def charge(self, amount):<br>        &quot;&quot;&quot;Charge the customer the given amount. Return a transaction id.&quot;&quot;&quot;<br>        ...<br><br><br>class CreditCardProcessor(PaymentProcessor):<br>    def charge(self, amount):<br>        return &quot;txn_cc_123&quot;<br><br><br>class PayPalProcessor(PaymentProcessor):<br>    def charge(self, amount):<br>        return &quot;txn_pp_456&quot;</pre><p>What happens if you try to implement the gift card class the same way as before:</p><pre>class GiftCardProcessor(PaymentProcessor):<br>    def __init__(self, card_number):<br>        self.card_number = card_number<br><br>    def debit(self, amount):<br>        return &quot;txn_gc_789&quot;<br><br><br>GiftCardProcessor(&quot;1234-5678&quot;)<br># TypeError: Can&#39;t instantiate abstract class GiftCardProcessor<br># with abstract method charge</pre><p>The class fails to instantiate the moment it’s constructed — usually at import time, definitely before production, ideally during the first test run. The error message explicitly names the missing method. There’s no detective work, no stack trace to decode, no customer impact.</p><p>There is also a secondary benefit: the ABC is documentation. A new developer opening payment_processor.py sees the contract immediately. They don&#39;t have to read six subclasses and reverse-engineer what a &quot;processor&quot; is supposed to do. The @abstractmethod signature tells them: if you want to be a PaymentProcessor, you implement charge(amount). Everything else is up to you.</p><p>Abstract classes give you:</p><ul><li>✅ <strong>Explicit contracts</strong></li><li>✅ <strong>Early error detection</strong></li><li>✅ <strong>Clear intent for other developers</strong></li></ul><p>This becomes important as your system grows. The cost is small — a few extra lines, one import, an inheritance relationship. For a public contract, that cost is trivial compared to catching one production incident.</p><h3>Duck Typing vs Abstract Classes — The Decision Framework</h3><p>Here’s the checklist I actually use.</p><p><strong>Use abstract classes when:</strong></p><ul><li>Multiple implementers live in different modules, or will be written by different people at different times.</li><li>You’re defining a public API — a plugin interface, a library extension point, an SDK contract, anything external code will implement against.</li><li>The interface is stable and the cost of a wrong implementation is high: silent data corruption, production outages, security issues, anything that fails loudly only after it’s too late.</li><li>You want mypy and your IDE to verify the contract statically. ABCs give you real type information; duck typing gives you vibes.</li></ul><p><strong>Quack like a duck when:</strong></p><ul><li>You’re prototyping or exploring a design. Adding ceremony now will slow you down, and you’ll remove it later anyway.</li><li>The code is internal and fast-moving, and the set of implementers fits comfortably in one team’s head.</li><li>The “interface” is one or two methods, and formalizing it would obscure the actual logic.</li><li>You need to accept third-party objects that you can’t retroactively make inherit from your ABC. (This is the classic reason the Python world stays duck-typed — you can’t modify requests.Response to inherit from your ResponseLike base class.)</li></ul><h3>A Better Middle Ground: Protocols</h3><p>Protocols give you structural typing with static checks — mypy verifies that a class satisfies the “interface” without requiring any inheritance relationship. You get much of the safety of ABCs without the rigidity, at the cost of losing the runtime instantiation check. It’s a great fit for exactly the third-party-object case above.</p><p>As a rough rule of thumb: if code will cross a module boundary and a mistake will be noisy and expensive, formalize it. If it won’t, don’t.</p><p>Benefits:</p><ul><li>You keep <strong>duck typing flexibility</strong></li><li>You gain <strong>type checking (with tools like mypy)</strong></li></ul><p>No inheritance required.</p><h3>How This Evolves in Real Projects</h3><p>Most systems follow this path:</p><ol><li>Start with duck typing</li><li>Add structure as complexity grows</li><li>Introduce contracts where needed</li></ol><blockquote><em>Good design is not about being strict — it’s about </em><strong><em>knowing when to become strict</em></strong><em>.</em></blockquote><p>Python doesn’t force you into rigid structures.</p><p>That’s a feature — not a flaw.</p><p>The best Python developers don’t pick one approach…<br>They adapt their approach as the system evolves.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a57598b82856" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract Classes in Python: Designing Code Like an Architect]]></title>
            <link>https://markusfarkus.medium.com/abstract-classes-in-python-designing-code-like-an-architect-bef39e1aa962?source=rss-c5ded6402cba------2</link>
            <guid isPermaLink="false">https://medium.com/p/bef39e1aa962</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[classes-and-objects]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Marcus T]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 18:31:01 GMT</pubDate>
            <atom:updated>2026-04-24T18:31:01.354Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7GFA4lpFW4q9qtVe64KuQ.png" /></figure><p>When building software that’s meant to scale, one of the most valuable tools in your toolkit is the ability to define a <em>contract — </em>a guarantee that certain classes will always implement specific behaviour. But how do you enforce structure without locking yourself into rigid implementation? Python provides a mechanism for doing exactly that — <strong>abstract classes</strong>. An abstract class is a class that cannot be instantiated on its own and is designed to be a blueprint for other classes. They define <em>what must exist</em>, but leave the <em>how</em> up to the subclasses. Abstract classes help you design systems that are consistent, extensible, and easier to reason about.</p><h3>When to Use Abstract Classes</h3><p>Abstract classes shine in situations where you have a group of related classes that share a common interface but differ in their internal implementation. Consider a few scenarios:</p><ul><li><strong>Framework design</strong>: You’re building a plugin system and need to guarantee every plugin implements a run() method.</li><li><strong>Domain modelling</strong>: You have a Shape hierarchy where every shape must be able to compute its area and perimeter, but each does so differently.</li><li><strong>Enforcing contracts in teams</strong>: You want to ensure that any class a teammate writes conforms to an expected interface, catching mistakes at import time rather than at runtime.</li></ul><h3>Example Scenario</h3><p>Imagine you’re building a payment system:</p><ul><li>CreditCardPayment</li><li>PayPalPayment</li><li>CryptoPayment</li></ul><p>Each payment type must:</p><ul><li>Process a payment</li><li>Validate details</li></ul><p>But the implementation differs. This is a perfect use case for an abstract class.</p><h3>Abstract Base Classes (ABCs)</h3><p>Python’s abc module (Abstract Base Classes) provides the infrastructure for defining abstract classes. The two key imports are ABC and abstractmethod.</p><pre>from abc import ABC, abstractmethod</pre><p>A class becomes abstract by inheriting from ABC. On its own, this doesn&#39;t do much — the power comes from marking individual methods and properties with @abstractmethod.</p><pre>from abc import ABC, abstractmethod<br><br>class Payment(ABC):<br><br>    @abstractmethod<br>    def process_payment(self, amount):<br>        pass</pre><p>Here:</p><ul><li>Payment is an <strong>abstract base class</strong></li><li>process_payment is an <strong>abstract method</strong></li><li>Any subclass <em>must</em> implement process_payment. If it doesn’t, Python will refuse to instantiate it.</li></ul><h3>Abstract Methods</h3><p>An abstract method is a method declared in the abstract base class that <em>must</em> be overridden by any concrete subclass. It has no implementation in the base class — it’s purely a declaration of intent.</p><pre>class CreditCardPayment(Payment):<br><br>    def process_payment(self, amount):<br>        print(f&quot;Processing credit card payment of ${amount}&quot;)</pre><p>If a subclass does NOT implement the abstract method:</p><pre>class BrokenPayment(Payment):<br>    pass</pre><p>Trying to instantiate it will raise a TypeError — immediately, not buried somewhere deep in runtime logic.</p><pre>TypeError: Can&#39;t instantiate abstract class BrokenPayment</pre><h3>Abstract Properties</h3><p>Just like methods, properties can be made abstract. This is useful when subclasses should expose a particular attribute as a computed property rather than a plain instance variable.</p><p>Use @property with @abstractmethod.</p><pre>from abc import ABC, abstractmethod<br><br>class Shape(ABC):<br><br>    @property<br>    @abstractmethod<br>    def area(self) -&gt; float:<br>        &quot;&quot;&quot;Compute the area of the shape.&quot;&quot;&quot;<br>        ...<br><br>    @property<br>    @abstractmethod<br>    def perimeter(self) -&gt; float:<br>        &quot;&quot;&quot;Compute the perimeter of the shape.&quot;&quot;&quot;<br>        ...</pre><p>Implementation</p><pre>import math<br><br>class Circle(Shape):<br>    def __init__(self, radius: float):<br>        self.radius = radius<br><br>    @property<br>    def area(self) -&gt; float:<br>        return math.pi * self.radius ** 2<br><br>    @property<br>    def perimeter(self) -&gt; float:<br>        return 2 * math.pi * self.radius<br><br><br>class Rectangle(Shape):<br>    def __init__(self, width: float, height: float):<br>        self.width = width<br>        self.height = height<br><br>    @property<br>    def area(self) -&gt; float:<br>        return self.width * self.height<br><br>    @property<br>    def perimeter(self) -&gt; float:<br>        return 2 * (self.width + self.height)</pre><h3>Concrete Methods</h3><p>Abstract classes can also contain fully implemented (<em>concrete</em>) methods. This is one of their most underrated features. Concrete methods define shared behaviour that all subclasses inherit without having to re-implement it.</p><pre>class Payment(ABC):<br><br>    @abstractmethod<br>    def process_payment(self, amount):<br>        pass<br><br>    def print_receipt(self, amount):<br>        print(f&quot;Receipt: Paid ${amount}&quot;)</pre><p>Now every Payment automatically gets print_receipt() without duplicating code across subclasses:</p><pre>payment = CreditCardPayment()<br>payment.process_payment(100)<br>payment.print_receipt(100)</pre><p>This combination of enforced interface through abstract methods and shared logic through concrete methods is what makes abstract classes genuinely powerful compared to simple duck typing.</p><h3>Abstract Class Instantiation</h3><p>One of the first things to understand about abstract classes is that <strong>you cannot instantiate them directly</strong>. Attempting to do so raises a TypeError.</p><pre>s = Shape()<br># TypeError: Can&#39;t instantiate abstract class Shape<br># with abstract methods area, perimeter</pre><p>This is intentional and useful. It means Shape can only ever exist as a base (a contract), not as a standalone object. You must always work through a concrete subclass.</p><p>However, there’s a subtle edge case worth knowing: if a subclass inherits from an abstract class but <em>doesn’t</em> implement all the abstract methods, it too becomes abstract and cannot be instantiated.</p><pre>class PartialShape(Shape):<br>    @property<br>    def area(self) -&gt; float:<br>        return 0.0<br>    # perimeter is NOT implemented<br><br>p = PartialShape()<br># TypeError: Can&#39;t instantiate abstract class PartialShape<br># with abstract method perimeter</pre><p>Python checks at instantiation time whether all abstract members have been implemented. This makes it easy to catch incomplete implementations early.</p><h3>Putting It All Together: A Complete Example</h3><p>Here’s a more complete example that ties all the concepts together — a simple payment processing system:</p><pre>from abc import ABC, abstractmethod<br>from datetime import datetime<br><br><br>class PaymentProcessor(ABC):<br>    &quot;&quot;&quot;<br>    Abstract base class for payment processors.<br>    Defines the interface all processors must implement.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, merchant_id: str):<br>        self.merchant_id = merchant_id<br>        self._transaction_log: list[dict] = []<br><br>    # Abstract methods — must be implemented by subclasses<br>    @abstractmethod<br>    def charge(self, amount: float, currency: str) -&gt; bool:<br>        &quot;&quot;&quot;Charge the given amount. Returns True on success.&quot;&quot;&quot;<br>        ...<br><br>    @abstractmethod<br>    def refund(self, transaction_id: str, amount: float) -&gt; bool:<br>        &quot;&quot;&quot;Refund a previous transaction.&quot;&quot;&quot;<br>        ...<br><br>    # Abstract property — each processor must report its name<br>    @property<br>    @abstractmethod<br>    def processor_name(self) -&gt; str:<br>        ...<br><br>    # Concrete methods — shared logic across all processors<br>    def log_transaction(self, transaction_id: str, amount: float, status: str) -&gt; None:<br>        self._transaction_log.append({<br>            &quot;id&quot;: transaction_id,<br>            &quot;amount&quot;: amount,<br>            &quot;status&quot;: status,<br>            &quot;timestamp&quot;: datetime.now().isoformat(),<br>        })<br><br>    def get_transaction_count(self) -&gt; int:<br>        return len(self._transaction_log)<br><br>    def summary(self) -&gt; str:<br>        return (<br>            f&quot;[{self.processor_name}] Merchant: {self.merchant_id} | &quot;<br>            f&quot;Transactions: {self.get_transaction_count()}&quot;<br>        )<br><br><br>class StripeProcessor(PaymentProcessor):<br><br>    @property<br>    def processor_name(self) -&gt; str:<br>        return &quot;Stripe&quot;<br><br>    def charge(self, amount: float, currency: str) -&gt; bool:<br>        # Simulate Stripe API call<br>        print(f&quot;Stripe: charging {amount} {currency}&quot;)<br>        self.log_transaction(&quot;stripe-001&quot;, amount, &quot;success&quot;)<br>        return True<br><br>    def refund(self, transaction_id: str, amount: float) -&gt; bool:<br>        print(f&quot;Stripe: refunding {amount} for {transaction_id}&quot;)<br>        self.log_transaction(transaction_id, amount, &quot;refunded&quot;)<br>        return True<br><br><br>class PayPalProcessor(PaymentProcessor):<br><br>    @property<br>    def processor_name(self) -&gt; str:<br>        return &quot;PayPal&quot;<br><br>    def charge(self, amount: float, currency: str) -&gt; bool:<br>        print(f&quot;PayPal: charging {amount} {currency}&quot;)<br>        self.log_transaction(&quot;paypal-001&quot;, amount, &quot;success&quot;)<br>        return True<br><br>    def refund(self, transaction_id: str, amount: float) -&gt; bool:<br>        print(f&quot;PayPal: refunding {amount} for {transaction_id}&quot;)<br>        self.log_transaction(transaction_id, amount, &quot;refunded&quot;)<br>        return True<br><br><br># Usage<br>processors: list[PaymentProcessor] = [<br>    StripeProcessor(&quot;merchant-123&quot;),<br>    PayPalProcessor(&quot;merchant-456&quot;),<br>]<br><br>for processor in processors:<br>    processor.charge(99.99, &quot;USD&quot;)<br>    print(processor.summary())</pre><p>Output:</p><pre>Stripe: charging 99.99 USD<br>[Stripe] Merchant: merchant-123 | Transactions: 1<br>PayPal: charging 99.99 USD<br>[PayPal] Merchant: merchant-456 | Transactions: 1</pre><p>The calling code doesn’t care whether it’s dealing with Stripe or PayPal — it just works through the PaymentProcessor interface. This is the essence of what abstract classes enable.</p><h3>Common Pitfalls</h3><ul><li>❌ Forgetting to implement all abstract methods</li><li>❌ Trying to instantiate an abstract class</li><li>❌ Overusing abstraction for simple use cases</li><li>❌ Mixing up abstract methods with regular methods</li></ul><h3>Key Takeaways</h3><ul><li><strong>ABC</strong> is the base class that makes a class abstract.</li><li><strong>@abstractmethod</strong> marks methods and properties that subclasses <em>must</em> implement.</li><li><strong>Concrete methods</strong> in abstract classes provide shared logic and reduce duplication.</li><li><strong>Instantiation is blocked</strong> for any class with unimplemented abstract members.</li><li>Abstract classes are best used when you have a family of related classes that share a common interface but differ in implementation.</li></ul><h3>Final Thoughts: Code Like a System Designer</h3><p>Abstract classes force you to think differently.</p><p>Not:</p><blockquote><em>“How do I implement this?”</em></blockquote><p>But:</p><blockquote><em>“What </em>must always be true<em> about this system?”</em></blockquote><p>That shift — from implementation to design — is what separates good code from great systems. Abstract classes are one of Python’s most effective tools for writing code that’s both flexible and robust. They shift certain categories of bugs from runtime surprises to clear, early errors. And they communicate your design intent more clearly than any comment ever could.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bef39e1aa962" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Two S̶w̶o̶r̶d̶ Pointer Technique]]></title>
            <link>https://markusfarkus.medium.com/the-two-s%CC%B6w%CC%B6o%CC%B6r%CC%B6d%CC%B6-pointer-technique-a687c0558eee?source=rss-c5ded6402cba------2</link>
            <guid isPermaLink="false">https://medium.com/p/a687c0558eee</guid>
            <category><![CDATA[drum-and-bass]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Marcus T]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 13:01:02 GMT</pubDate>
            <atom:updated>2026-04-03T13:01:02.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SpwANJJorUJd2jiZc6xWGA.png" /></figure><p>One of my favorite artists of the 90’s is Photek. The intricate Drum&amp;Bass beats he crafted are classic. One song in particular that showcases his talent is <em>Ni Ten Ichi Ryu. </em>In this song, the rhythm combines 2 patterns moving at different tempos.</p><p>Niten Ichi Ryu, founded by the famous samurai <a href="https://www.google.com/search?q=Miyamoto+Musashi&amp;rlz=1C5CHFA_enUS1042US1042&amp;oq=ni+t&amp;gs_lcrp=EgZjaHJvbWUqDggAEEUYJxg7GIAEGIoFMg4IABBFGCcYOxiABBiKBTIGCAEQRRg5MgwIAhAAGEMYgAQYigUyDAgDEAAYQxiABBiKBTIMCAQQABhDGIAEGIoFMgYIBRBFGDwyBggGEEUYPDIGCAcQRRg80gEIMTIwNmowajGoAgCwAgA&amp;sourceid=chrome&amp;ie=UTF-8&amp;ved=2ahUKEwihy-qo74KTAxWKpIkEHbkkOk8QgK4QegYIAQgAEAM">Miyamoto Musashi</a>, translates to <strong>“School of the Strategy of Two Heavens as One”</strong>. It is a <em>koryū</em> (ancient) school of Japanese swordsmanship known for the simultaneous, coordinated use of the long sword (katana) and short sword (wakizashi), symbolizing the unity of heaven, earth, and the dual blades.</p><p>The idea is simple but powerful: instead of relying on a single weapon, you wield two simultaneously. Each serves a different role, but they work in perfect coordination.</p><p>In programming, we have a strikingly similar concept: the <strong>two-pointer technique</strong>.</p><p>Instead of scanning data with one index, we use two, moving independently, strategically, and often more efficiently. A lot of interview problems hinge on efficient traversal of data structures using two pointers (fast/slow, left/right).</p><h3>What Is the Two-Pointer Technique?</h3><p>The two-pointer technique involves using <strong>two indices (or pointers)</strong> to traverse a data structure such as an array, list, or string.</p><p>These pointers can:</p><ul><li>Start from opposite ends</li><li>Move at different speeds</li><li>Represent a dynamic window</li><li>Converge toward a solution</li></ul><p>The key benefit of using two pointers is reducing time complexity. An operation can often be reduced from O(n²) → O(n).</p><h3>️️️Pattern 1: Opposite Ends (The Classic Duel)</h3><blockquote>Like two swords closing in from different angles.</blockquote><p>A classic algorithmic coding problem for interviews is the Two-Sum problem. You are asked to find the indices of two distinct numbers in a <strong>sorted</strong> array (or list) that add up to a specific target value. It is guaranteed that there is exactly one solution, and the same element cannot be used twice. A naive solution would be to use a nested loop to compare each value to every other value to find the matching pair.</p><pre>def two_sum(nums, target):<br>    n = len(nums)<br><br>    # Iterate through each element in the array<br>    for i in range(n):<br>      <br>        # For each element nums[i], check every<br>        # other element nums[j] that comes after it<br>        for j in range(i + 1, n):<br>          <br>            # Check if the sum of the current pair<br>            # equals the target<br>            if nums[i] + nums[j] == target:<br>                return True<br>              <br>    # If no pair is found after checking<br>    # all possibilities<br>    return False<br></pre><p>While this does work, it becomes increasingly inefficient as the list becomes larger. Instead, we can use two pointers to compare values starting at opposite ends of the list.</p><pre>nums = [1, 2, 3, 4, 6, 8, 10]<br>target = 10<br><br>Step 1:<br>L → 1                     10 ← R<br>    [1, 2, 3, 4, 6, 8, 10]<br>     sum = 11 → too big → move R<br><br>Step 2:<br>L → 1                8 ← R<br>    [1, 2, 3, 4, 6, 8, 10]<br>     sum = 9 → too small → move L<br><br>Step 3:<br>      L → 2         8 ← R<br>    [1, 2, 3, 4, 6, 8, 10]<br>     sum = 10 ✅</pre><pre>def two_sum(nums, target):<br>    left, right = 0, len(nums) - 1<br>    <br>    # Iterate while left pointer is less than right<br>    while left &lt; right:<br>        current = nums[left] + nums[right]<br>        <br>        # Check if the sum matches the target<br>        if current == target:<br>            return [left, right]<br>        elif current &lt; target:<br>            left += 1    # Move left pointer to the right<br>        else:<br>            right -= 1   # Move right pointer to the left<br>          <br>     # If no pair is found  <br>    return None</pre><h3>💡Why It Works</h3><ul><li>If the sum is too small → move left pointer right</li><li>If too large → move right pointer left</li></ul><p>Instead of checking every pair (O(n²)), we solve it in <strong>O(n)</strong>.</p><p>🗡️ One sword probes low values.<br> 🗡️ The other controls high values.</p><h3>Pattern 2: Slow &amp; Fast Pointers (Timing Beats Strength)</h3><blockquote>Sometimes the swords move at different speeds.</blockquote><p>A l<a href="https://medium.com/@markusfarkus/revisiting-linked-lists-part-1-56ada8cff879">inked list</a> can contain a cycle — the end node points back to a previous node. How can we detect this? We can use two pointers moving at different speeds to see if they ever end up on the same node. The only way this could happen is if they end up “running” in a loop.</p><pre>Linked List with Cycle:<br><br>A → B → C → D → E<br>          ↑     ↓<br>          ← ← ← ←<br><br>Step progression:<br><br>slow: A → B → C → D → E → C ...<br>fast: A → C → E → D → C ...<br><br>Eventually:<br>          slow<br>           ↓<br>      C → D → E<br>      ↑       ↓<br>      ← ← fast</pre><pre>def has_cycle(head):<br>    slow = fast = head<br>    <br>    while fast and fast.next:<br>        # move the slow pointer forward 1 node<br>        slow = slow.next<br>        # move the fast pointer forward 2 nodes<br>        fast = fast.next.next<br>        <br>        if slow == fast:<br>            return True<br>            <br>    return False</pre><h3>💡 Why It Works</h3><ul><li>Fast pointer laps the slow pointer if there’s a cycle</li><li>If no cycle, fast reaches the end</li></ul><p>🗡️ One sword tracks reality<br> 🗡️ The other tests its limits</p><h3>Pattern 3: Sliding Window (Controlled Flow)</h3><blockquote>This is less of a duel and more of a coordinated <a href="https://baacoa.medium.com/kata-what-is-it-good-for-d1dfd6fdd697">kata</a>.</blockquote><p>Another common <a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/description/">leetcode question</a> is finding the longest substring without repeating characters.</p><pre>s = &quot;abcabcbb&quot;<br><br>Window expands →<br>[a b c]<br>^     ^<br>L     R<br><br>Next char = &#39;a&#39; (duplicate)<br><br>Shrink from left:<br>[a b c]<br>  ^<br>  L<br><br>Now:<br>[b c a]<br>  ^   ^<br>  L   R</pre><pre>def longest_unique_substring(s):<br>    char_set = set()<br>    left = 0<br>    max_length = 0<br>    <br>    for right in range(len(s)):<br>        while s[right] in char_set:<br>            char_set.remove(s[left])<br>            left += 1<br>            <br>        char_set.add(s[right])<br>        max_length = max(max_length, right - left + 1)<br>        <br>    return max_length</pre><h3>💡 Why It Works</h3><ul><li>Right pointer expands the window</li><li>Left pointer shrinks it when constraints break</li></ul><p>🗡️ One sword advances<br> 🗡️ The other maintains discipline</p><h3>Pattern 4: Removing Elements In-Place</h3><blockquote>Two swords — one reading, one writing.</blockquote><p>Say we want to remove duplicates from a sorted array. The naive solution typically involves using an extra data structure, such as a temporary array or a set, to store unique elements.</p><pre># Naive approach using a Set<br>def remove_duplicates_naive(nums):<br>    # Use set to find unique values<br>    unique_elements = sorted(list(set(nums)))  <br>    for i in range(len(unique_elements)):<br>        nums[i] = unique_elements[i]          # Overwriting original array<br>    return len(unique_elements)               # Returning new length</pre><p>Since the array is sorted, we do not need to maintain a hash set. All occurrences of a value would be consecutive. So we only need to check if the current element is the same as the previous element.</p><pre>nums = [1, 1, 2, 2, 3]<br><br>Initial:<br>R →<br>W →<br>[1, 1, 2, 2, 3]<br><br>Step:<br>R → 1 (skip duplicate)<br><br>R → 2 (new value)<br>        W →<br>[1, 2, _, _, _]<br><br>Final:<br>[1, 2, 3, _, _]</pre><pre>def remove_duplicates(nums):<br>    if not nums:<br>        return 0<br>    <br>    write = 1<br>    <br>    for read in range(1, len(nums)):<br>        if nums[read] != nums[read - 1]:<br>            nums[write] = nums[read]<br>            write += 1<br>            <br>    return write</pre><h3>💡 Why It Works</h3><ul><li>Read pointer scans</li><li>Write pointer builds result in-place</li></ul><p>Efficient, clean, and avoids extra space.</p><h3>Common Mistakes (Where Most Developers Slip)</h3><h4>Forgetting The Loop Condition</h4><pre>while left &lt; right   # ✅ correct<br>while left &lt;= right  # ❌ often wrong</pre><p>Using &lt;= can cause:</p><ul><li>Duplicate processing</li><li>Infinite loops (if pointers don’t move correctly)</li></ul><h4>Moving The Wrong Pointer</h4><pre>if current &lt; target:<br>    right -= 1   # ❌ WRONG</pre><h4>Not Updating Both Pointers Carefully</h4><pre># In Sliding Window<br><br>while s[right] in char_set:<br>    left += 1   # ❌ forgot to remove from set</pre><p>Leads to:</p><ul><li>Infinite loops</li><li>Incorrect window state</li></ul><pre># Correct<br><br>char_set.remove(s[left])<br>left += 1</pre><h4>Using Two Pointers on Unsorted Data</h4><p>Two-pointer from ends requires sorted input.</p><h4>Off-by-One Errors in Window Size</h4><pre>right - left      # ❌ off by one<br>right - left + 1  # ✅ correct</pre><p>This tiny bug causes:</p><ul><li>Wrong max lengths</li><li>Failing edge cases</li></ul><h4>Not Handling Edge Cases</h4><p>Always think about:</p><ul><li>Empty list</li><li>Single element</li><li>All duplicates</li><li>No valid solution</li></ul><h3>When Should You Use Two Pointers?</h3><p>Reach for this technique when:</p><ul><li>The data is <strong>sorted</strong></li><li>You need to find <strong>pairs or ranges</strong></li><li>You’re working with <strong>subarrays or substrings</strong></li><li>You want to <strong>optimize brute-force comparisons</strong></li><li>You need <strong>in-place transformations</strong></li></ul><h3>Mental Model: The Two-Sword Discipline</h3><p>Think of each pointer as a sword with a role:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rO5wJrfhpv9mVGf5J7up1w.png" /></figure><p>The power doesn’t come from having two — it comes from <strong>coordination</strong>.</p><h3>Closing Thought</h3><p>Much like <a href="https://www.youtube.com/watch?v=9qJKxaWb0_A&amp;list=RD9qJKxaWb0_A&amp;start_radio=1"><em>Ni Ten Ichi Ryu</em></a>, the two-pointer technique isn’t about complexity. It’s about balance, precision, and control.</p><p>Anyone can swing one sword wildly.</p><p>But mastering two?</p><p>That’s where elegance and performance converge.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a687c0558eee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revisiting Linked Lists (Part 1)]]></title>
            <link>https://markusfarkus.medium.com/revisiting-linked-lists-part-1-56ada8cff879?source=rss-c5ded6402cba------2</link>
            <guid isPermaLink="false">https://medium.com/p/56ada8cff879</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Marcus T]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 18:03:13 GMT</pubDate>
            <atom:updated>2026-03-02T18:04:00.093Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*9fG9dOBSD75uWXg8RUqRRA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@polarmermaid?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Anne Nygård</a> on <a href="https://unsplash.com/photos/silver-safety-pin-on-white-paper-Sl69Jw-o0rU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>After more than twenty years as a software developer, I’ve never actually implemented a linked list in the real world.</p><p>Sure, I’ve explained them in interviews, imported modules that utilized them in code I’d never see, and nodded along when someone said “O(1) insertions at the head.” But I have not actually built one myself since college.</p><p>So I did.</p><p>What started as a simple exercise to refresh my memory while preparing to interview (again) became a mini project to actually build a functional linked list class and a way to visualize it.</p><p>This is a story about revisiting a foundational data structure after two decades of shipping real products, realizing the gap between “knowing” and “doing”, and the quiet confidence that comes from finally wiring the pointers yourself.</p><h4>What Is A Linked List?</h4><p>A linked list is a linear data structure made up of <strong>nodes. E</strong>ach node stores a value and one or more <strong>pointers</strong> to other nodes. Instead of using contiguous memory like an array or list, a linked list connects nodes by references. To access elements, you <strong>traverse</strong> from the head node, following pointers until you reach the desired node.</p><p><strong>This sounds tedious. Can’t I just use an array?</strong></p><p>Although a linked list requires sequential traversal (you can’t jump to an index in constant time), it makes insertions and deletions at known positions more efficient than using an array.</p><p>In a <strong>singly linked list</strong>, each node points to the next node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*InFof0r78_nk7ypRqBhP8Q.png" /><figcaption>Single Linked List</figcaption></figure><p>In a <strong>doubly linked list</strong>, each node points to both the next and previous node, which makes backward traversal and deletions easier but requires extra memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LeDgwysbZOQBILeut6ppgQ.png" /><figcaption>Doubly Linked List</figcaption></figure><h4>Comparing Arrays and Linked Lists</h4><ul><li>Insertion and deletion of elements in an array is slow. It requires shifting all of the elements in memory. In a linked list, insertion and deletion only require changing or removing a pointer. The rest of the structure stays the same.</li><li>Accessing an element in an array using indexes is quite fast. Regardless of the size of the array, it takes the same amount of time to retrieve any element using an index. This is constant time complexity. Accessing an element in a linked list requires traversal to the desired node. The time required grows linearly with the size of the list.</li></ul><p>A linked list is preferable for fast insertion and deletion of elements in a data structure. If you need fast indexing of elements, you can use an array.</p><h4>Get To The Code Already!</h4><p>So let’s start with defining a Node class. It needs to store a value and a pointer to another node. I’ll be using Python for this exercise.</p><pre>class Node:<br>    def __init__(self, value):<br>        self.value = value<br>        self.next = None</pre><p>Since this object has no methods and is simply a way to structure nodes, we can use a dataclass. This is more memory efficient, and we will also define the types of data this node will store.</p><pre>from dataclasses import dataclass<br><br>@dataclass<br>class Node:<br>    value: int | float | str | bool<br>    next = None</pre><p>Now we can build a SinglyLinkedList class that manages the nodes. It’s not necessary to wrap a linked list this way to use it. You can pass the head to functions for operations, but creating this class helps encapsulate the different methods we want to use. We can define the head and tail nodes and keep track of the size of the linked list. Let’s also start with a method to add nodes to the end of the list.</p><pre>class SinglyLinkedList:<br>    def __init__(self):<br>        self.head: Node = None<br>        self.tail: Node = None<br>        self.size: int = 0<br>   <br>    def __len__(self):<br>        return self.size<br><br>    def append(self, value: int | float | str | bool):<br>        &quot;&quot;&quot;<br>        Adds a new node to the end of the linked list.<br>        Time complexity: O(1)<br>        &quot;&quot;&quot;<br>        new_node = Node(value)<br>        if self.head:<br>            self.tail.next = new_node<br>        else:<br>            self.head = new_node<br>        self.tail = new_node<br>        self.size += 1</pre><p>Adding a new node follows this logic:</p><ol><li>Create a new Node object</li><li>If there are existing nodes, set the pointer of the tail to the new node</li><li>If the list is empty, set the head as the new node</li><li>Set the tail to the new node</li><li>Increase the size by 1</li></ol><p>Now, we essentially have a working linked list. We can create an instance of this class and start adding nodes.</p><pre>linked_list = LinkedList()<br>linked_list.append(1)<br>linked_list.append(2)<br>linked_list.append(3)<br>linked_list.append(4)</pre><p>This is good so far, but how can we view this list? Let’s override the __str__ method for the LinkedList class to create a string representation of the data structure.</p><pre>def __str__(self):<br>    current_node = self.head<br>    node_list = []<br>    while current_node:<br>        node_list.append(current_node.value)                          <br>        current_node = current_node.next<br>    node_str = &quot; \u2102 &quot;.join(map(str, node_list))<br>    return f&quot;{self.size} Elements: [{node_str}]&quot;</pre><pre>&gt; print(linked_list)<br><br>&gt; 4 Elements: [1 ⇒ 2 ⇒ 3 ⇒ 4]</pre><p>Nice! Let’s add a few more methods to round out this class. We need to be able to insert a node at a specific index. We should also be able to remove or replace nodes. Let’s start with a method for adding a new node at the beginning.</p><pre>def prepend(self, value: int | float | str | bool):<br>    &quot;&quot;&quot;<br>    Prepends a new node with the specified value to the beginning of the list.<br>    Time complexity: O(1)<br>    &quot;&quot;&quot;<br>    new_node = Node(value)<br>    new_node.next = self.head<br>    self.head = new_node<br>    self.size += 1</pre><p>This simply replaces the head with a new node and sets the tail as the old head. Next, let’s define a method for inserting a node at a specific index. It will use a method for traversing the list.</p><pre>def get_node(self, index: int) -&gt; Node:<br>    &quot;&quot;&quot;<br>    Returns node at index, or head/tail if out of bounds<br>    Time complexity: O(n)<br>    &quot;&quot;&quot;<br>    if index &lt;= 0: return self.head<br>    if index &gt;= self.size - 1: return self.tail<br><br>    current_node = self.head<br>    for _ in range(index):<br>        current_node = current_node.next<br><br>    return current_node<br><br><br>def insert(self, index: int, value: int | float | str | bool):<br>    &quot;&quot;&quot;<br>    Inserts a new node at the specified index.<br>    Time complexity: O(n)<br>    &quot;&quot;&quot;<br>    if index == 0:<br>        self.prepend(value)<br>    elif index &gt;= self.size:<br>        self.append(value)<br>    else:<br>        new_node = Node(value)<br>        current_node = self.get_node(index -1)<br>        new_node.next = current_node.next<br>        current_node.next = new_node<br>        self.size += 1</pre><p>Remove a node at a specified index:</p><pre>def remove(self, index: int):<br>    &quot;&quot;&quot;<br>    Removes a node at the specified index.<br>    Time complexity: O(n)<br>    &quot;&quot;&quot;<br>    if index == 0:<br>        self.head = self.head.next<br>        self.size -= 1<br>    elif index &gt;= self.size - 1:<br>        self.trim()<br>    else:<br>        current_node = self.get_node(index - 1)<br>        current_node.next = current_node.next.next<br>        self.size -= 1</pre><p>Replace the value of a node at a specified index:</p><pre>def replace(self, index: int, value: int | float | str | bool):<br>    &quot;&quot;&quot;<br>    Replaces the value of a node at the specified index.<br>    Time complexity: O(n)<br>    &quot;&quot;&quot;<br>    current_node = self.get_node(index)<br>    current_node.value = value</pre><p>Now we have a very functional linked list class. As part of this exercise, let’s review the time complexity of these operations. O(1) is constant time complexity. O(n) is linear time complexity.</p><ul><li>Insert element at the end → O(1) <br>We can achieve this with our class since we are keeping track of the tail. We don’t need to traverse to it in order to append a new node. If we didn’t, append operations would be O(n)</li><li>Insert element at the start → O(1)</li><li>Insert at an index → O(n)</li><li>Remove node → O(n)</li><li>Traverse → O(n)</li></ul><p>Next, we’ll expand on this to create a Doubly Linked List.</p><p><a href="https://markusfarkus.medium.com/revisiting-linked-lists-part-2-729fdce1eba1">Part 2 →</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56ada8cff879" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>