Mastering Python Logic: Template Method and Bridge Patterns
Overview
Software developers often struggle with classes that grow too large and carry too many responsibilities. This tutorial explores how to refactor a messy trading bot into a clean, modular system by using two underrated design patterns: the
Prerequisites
To follow this tutorial, you should have a solid grasp of
Key Libraries & Tools
- abc (Abstract Base Classes): A built-in Pythonmodule used to define blueprints for other classes, ensuring subclasses implement specific methods.
- Trading Bot Example: A practical context involving cryptocurrency exchanges like BinanceandCoinbaseto demonstrate real-world decoupling.
The Template Method Walkthrough
The Template Method defines the skeleton of an algorithm in a base class but lets subclasses override specific steps without changing the overall structure. We start by defining a TradingBot that outlines the check_prices process.

from abc import ABC, abstractmethod
class TradingBot(ABC):
def check_prices(self, coin):
self.exchange.connect()
prices = self.exchange.get_market_data(coin)
if self.should_buy(prices):
print(f"Buying {coin}")
if self.should_sell(prices):
print(f"Selling {coin}")
@abstractmethod
def should_buy(self, prices):
pass
@abstractmethod
def should_sell(self, prices):
pass
By making should_buy and should_sell abstract, we force specific implementations like an AverageTrader or MinMaxTrader to define their own logic while keeping the execution flow identical.
Bridging Independent Variations
While the Template Method handles internal logic steps, the
class Exchange(ABC):
@abstractmethod
def connect(self):
pass
class BinanceExchange(Exchange):
def connect(self):
print("Connecting to Binance...")
We pass an Exchange instance into the TradingBot. This allows us to swap
Tips & Gotchas
Always prioritize cohesion. A class should do one thing well. Avoid the temptation to use these patterns for very simple scripts where a basic function suffices; over-engineering adds unnecessary boilerplate. When debugging, remember that you cannot instantiate abstract classes directly—

Fancy watching it?
Watch the full video and context