Two UNDERRATED Design Patterns ๐Ÿ’ก Write BETTER PYTHON CODE Part 6

ArjanCodes ยท Beginner ยท๐Ÿ—๏ธ Systems Design & Architecture ยท5y ago

Key Takeaways

Explains two underrated design patterns in Python

Full Transcript

today i'm gonna show you a design pattern that i think is underrated it's called the template method it's really nice i recently kind of rediscovered it and started using it more i have an interesting example for you this time everybody's talking about bitcoin and the stock is moving faster than a tesla model s in ludicrous mode so i'm gonna use a trading bot as an example i'll show you how you can use the template method design pattern to improve the code and then i'll show you another pattern the bridge that takes this example to the next level so let's get started the core of this example is the check prices method that for a certain coin gets the price information and determines whether you should buy or sell something of that coin it starts with connecting with the exchange then it gets price data for that particular coin then it determines whether it should buy or sell given that price data and then it prints out a status message now normally this would be the point where you would place orders and things like that each of these methods is in the application class and for the moment they're mostly dummy methods like the connecting method for example just prints out a message getting market data just returns a couple of numbers obviously normally this would be api calls when you create an instance of this application you also provide a trading strategy default this is average but another option is min max both of these strategies are actually pretty bad so really please if you are into trading just don't use these but they're purely serving as an example in the should buy and should sell method then depending on that trading strategy we use a different algorithm to determine whether we should buy something or whether we should sell something with the min max strategy you will only buy when the price is lower than all of the previous prices and with the average strategy you will only buy if the price is lower than the average of the last few prices and should sell is the other way around so finally in this example i create an instance of the application and then i check the prices for a particular kind of cryptocurrency and if i run this then you get this kind of result so sell bitcoin i'm not saying you should sell bitcoin by the way maybe you should buy bitcoin if i take another strategy here and then i run the application again i get a different result for bitcoin because the buying and selling strategy is different let's analyze this example the application class has lots of responsibilities it's responsible for connecting with the exchange getting the data determining whether you should buy or sell and what those specific algorithms are and it's also responsible for the overall process of what a trading bot should do that's a lot of different things and ideally when you design software you want to avoid that a class has this many different responsibilities now what you could do is use a strategy pattern for each of the steps in the process so for example you could use a strategy for whether you should buy and another strategy for what you should sell and then perhaps here replace this also by different strategies depending on the action that you want to take that leads to a lot of extra classes because every strategy basically means you have to introduce a class abstract class and then you have to add sub classes for each of the different strategies so that leads to a lot of boilerplate another nice design pattern that you could use for this is the so called template method what the template method does is that it helps you standardize a process so it's in particular suitable for things where you have a fixed process but the steps in the process may be different for example if you have a web shop the order flow is going to be pretty standardized a customer places an order you have to handle the order then you have to go to logistics send the order out and then there is a return item process and so on so this is kind of a fixed process that's happening but the steps may be different because for digital products you may have to send an email instead of sending it via the regular mail physical products may be sent by different logistics partners that means the process is the same for the order flow but the steps in the process may be different depending on the type of product or the situation another example is customer support ticket handling there's also a standardized process of a ticket that comes in that's assigned to somebody that somebody deals with it but also there the steps might be different for example in some cases a support ticket may require a physical visit to the customer's base of operations to fix something and otherwise a phone call or an email is enough this is what the template method does you have a standard process but the steps are different here's a class diagram of what it looks like a trading bot is also a good example of where you can apply the template method because the process is always the same you check prices you check what you should buy you check what you should sell then you take the steps to actually buy or sell something but the strategy you use for buying or selling might be different so let's change the example that we have here and use the template method design pattern to improve the way that the code is structured as a first step let's create a trading bot that contains the overall check prices process method and then abstract methods for the different parts of this process so first i'm going to import the abstract base class which obviously is what we're going to need for this and then let's create a trading bot class the trading bot class is going to contain the main methods that are currently in application so for now i'm just going to copy these over and then we're going to restructure them later so instead of explicitly modeling methods like should buy and should sell we're going to make those abstract so that we can create subclasses that perform a particular version of the step that we would like to have so i'm going to remove all this code here and i'm going to turn this should buy and shoot cell methods into abstract methods and actually now that should bind should sell abstract we don't need this list average method here anymore because it belongs to a particular version of should buy and should sell so i can remove it from this class actually the next step is that we will create trading bots that follow specific versions of this process for now i'm just going to ignore the connect to an exchange and getting market data from an exchange i'll do something different with that a little bit later so let's focus for now on the should buy and should sell steps in the process so for that i'm going to create different classes depending on the type of strategy i would like my trading bot to follow let's first create an average trader that takes the average of the prices and determines based on that if you want to buy or sell now that i'm following the template method design pattern i should make a sub class of my trading bot that i created a few minutes ago the only thing i need to do here is provide the actual implementations for the should buy and should sell methods here i'm going to need this list average function i'm just going to copy it over to this class and then i'll copy over the code needed for determining whether we should buy or sell there you go and in a similar way i can create a trader for the min max strategy should remove this abstract method call obviously now we have an average trader which uses the average of the prices and we have a min max trader that uses the minimum and maximum of the prices what's really nice now is that we've decoupled the process which is checking prices and determining whether you should buy or sell from the actual algorithms or strategies needed to buy or sell now let me just remove this class here because we don't need it anymore and then what we're going to do is we're going to create a min max trader and then we're going to check the prices and you get this result if i want a different trading strategy i use the average trader what's really nice now is i can add extra trading bots classes here without actually having to do anything in the original check prices method this works completely independently from the steps in the process that i'm going through so here you see very clearly that the process is completely standardized but you can change the steps without adding too much boilerplate code there's one more thing i'm going to do with this example and that's i'm going to introduce a second design pattern to make it even better the problem is that currently in trading bot we have also methods for things that a trading bot should not really do such as connecting to an exchange or getting market data from exchange that's something that doesn't belong here that should be something else what we're going to do is use another pattern called the bridge to solve this problem the bridge is a really nice pattern you don't see it used that much but it's actually really cool if you can incorporate it in your design the thing that the bridge solves for you is if you have two separate things that vary in this case you have exchanges you may use different exchanges and you have different trading bots and what the bridge sold for you is that it gives you the capability of adding an extra exchange or adding an extra trading bot without having to do anything on the other side of the bridge so the bridge is kind of a mechanism to have two separate class hierarchies two variations that can change independently from each other and that's really nice because obviously if we want to add another exchange to our example program let's say we started with binance but now we also want to add coinbase or bitfinex or whatever we don't want to have to change anything in our trading bots we simply want to add an extra exchange class and we want the system to be able to work with that and similarly if we think of a new trading strategy we don't want to have to change things over at the different types of exchanges that we're using because that has nothing to do with trading algorithm this is a class diagram of the bridge pattern it looks a bit complicated but it will be clear to you once we start implementing it in the example the main thing that we need to do is create a separate hierarchy of classes for the different exchanges so i'm going to create an exchange abstract class and for now that class has just a few methods one for connecting to the exchange and one for getting the market data normally you'd have lots of different methods here for getting prices volume uh placing orders and so on and so on but obviously in this example we're not going to deal with all those things so in essence in this example there are only two methods which is connect and getting market data and because these are abstracts i'm just going to write pass here instead of trading bot having these two methods trading bots should now have a reference to a particular exchange like so and let's add the exchange type hint information here to make clear that this is actually something of type exchange so trading bot has an exchange and then in the check prices method i'm using that exchange to get the data that i need the bridge in this example has this connection here is the connection between the trading bot object and the exchange object and the interesting thing here is that this connection happens completely on the abstract level so you can't make exchange instances because it's an abstract class you can't make trading bot instance because it's also an abstract class but trading bot has an exchange and that means we now have a structure where we can have different types of exchanges and different types of trading bots on the other end and they can vary independently from each other and that's the power of the bridge pattern let's add a few sample exchanges to show how it works so first i'm going to make a binance exchange and this is a subclass of the abstract exchange class another thing i need to do here is implement the connect and get market data methods again i'm just putting in some random numbers here so this is the binance exchange let's make a second one coinbase and we're going to change the numbers here so we can also see a few different results so i have two exchanges i have two trading bots and when i create the trader trading bot i need to provide the exchange let's start with coinbase [Applause] and then we get this connected to coinbase you should sell bitcoin us dollar if you want to change the exchange that i'm using i can simply provide a different object here and apparently according to both binance and coinbase i should sell bitcoin if i'm using the min max trader i can also use that and change it here without having to do anything on with the exchange so here i have the min max according to mimex we shouldn't need to do anything and i can change this to coinbase and coinbase has a slightly different prices so there we should actually sell bitcoin but this shows exactly the power of the bridge pattern we can change what this object is we can change what that object is and we don't have to make any changes in the actual classes here because the bridge pattern solved that problem for us and the trading bot in turn uses the template method design pattern so the process of what a trading bot should do is standardized but the steps in the process can be changed by the different subclasses so what i've shown today is actually something that you will see quite commonly is that you will never just use a single design pattern but you will use them together and by combining these design patterns to cover various aspects of your application in the end it's going to help you a lot with writing code with much better coupling and cohesion if you look at this example you see that the trading bot now purely deals with the process so that's just one responsibility which is really nice we have the exchange that's purely dealing with connecting with the exchange and doing the jobs there that you need to do and the way it's combined is also with very low coupling because the trading bot is not dependent on implementation details of specific exchanges such as binance or coinbase you've just seen an example where i apply two design patterns to improve the code of a trading bot there's a caveat though don't use that code directly to start trading cryptocurrencies you're gonna lose a lot of money trust me i've been there i noticed that there is some resistance in the python community on using design patterns i don't really know why that is perhaps it's post-traumatic stress syndrome from when you had to learn design patterns in your studies or perhaps you're just using python to write very simple scripts i still think though that things like design patterns and principles and software design in general is really important if you're a painter you also care about quality brushes and quality paint so you can make nice paintings as a software developer if you want to improve your craft you need to learn about these design patterns and design principles and apply them rigorously to your code so you can deliver a quality product in the end i'd say even if you're writing smaller scripts it's never too early to start thinking about software design so you can reuse the code later on in a much easier way anyway the code that i showed today in the trading bot example is in the github repository there's a link in the description below if you're enjoying this series consider subscribing and hit the notification bell so you don't miss out on any new content that i publish thanks for watching take care and see you in the next video [Music] you

Original Description

๐Ÿ’ก Learn how to design great software in 7 steps: https://arjan.codes/designguide. In this video, I talk about two underrated design patterns in Python: the template method pattern and the bridge design pattern. They're both really useful and when used in combination, they complement each other really well. You can find the code I worked on in this episode in my GitHub repository: https://github.com/arjancodes/betterpython ๐ŸŽ“ ArjanCodes Courses: https://www.arjancodes.com/courses/ ๐Ÿ”– Chapters: 0:00 Intro 0:33 Analysis of the example 3:20 Template method explanation 5:03 Implementing the template method 9:09 Bridge pattern explanation 10:56 Implementing the bridge pattern 15:59 Final thoughts #python #programming #designpatterns
Watch on YouTube โ†— (saves to browser)
Sign in to unlock AI tutor explanation ยท โšก30

Playlist

Uploads from ArjanCodes ยท ArjanCodes ยท 7 of 60

1 Full stack WEB DEVELOPMENT in 2021 - the ULTIMATE tech stack for FAST web app development
Full stack WEB DEVELOPMENT in 2021 - the ULTIMATE tech stack for FAST web app development
ArjanCodes
2 FROM PRODUCT IDEA TO SOFTWARE - turn your idea into reality in a few steps
FROM PRODUCT IDEA TO SOFTWARE - turn your idea into reality in a few steps
ArjanCodes
3 Cohesion and Coupling: Write BETTER PYTHON CODE Part 1
Cohesion and Coupling: Write BETTER PYTHON CODE Part 1
ArjanCodes
4 Build a GLASSMORPHISM React Component - Typescript & Material-UI
Build a GLASSMORPHISM React Component - Typescript & Material-UI
ArjanCodes
5 Observer Pattern Tutorial: I NEVER Knew Events Were THIS Powerful ๐Ÿš€
Observer Pattern Tutorial: I NEVER Knew Events Were THIS Powerful ๐Ÿš€
ArjanCodes
6 100% CODE COVERAGE - Think You're Done? Think AGAIN.โ˜
100% CODE COVERAGE - Think You're Done? Think AGAIN.โ˜
ArjanCodes
โ–ถ Two UNDERRATED Design Patterns ๐Ÿ’ก Write BETTER PYTHON CODE Part 6
Two UNDERRATED Design Patterns ๐Ÿ’ก Write BETTER PYTHON CODE Part 6
ArjanCodes
8 1000 Subscribers! ๐Ÿš€ WHY I Started this Channel and WHAT'S NEXT
1000 Subscribers! ๐Ÿš€ WHY I Started this Channel and WHAT'S NEXT
ArjanCodes
9 Channel Trailer ArjanCodes - March 2021
Channel Trailer ArjanCodes - March 2021
ArjanCodes
10 Exception Handling Tips in Python โš  Write Better Python Code Part 7
Exception Handling Tips in Python โš  Write Better Python Code Part 7
ArjanCodes
11 Monadic Error Handling in Python โš  Write Better Python Code Part 7B
Monadic Error Handling in Python โš  Write Better Python Code Part 7B
ArjanCodes
12 GW BASIC Games I Wrote When I Was a Kid ๐ŸŽฎ Running 30 Year Old Code
GW BASIC Games I Wrote When I Was a Kid ๐ŸŽฎ Running 30 Year Old Code
ArjanCodes
13 Why You Should Think About SOFTWARE ARCHITECTURE in Python ๐Ÿ’ก
Why You Should Think About SOFTWARE ARCHITECTURE in Python ๐Ÿ’ก
ArjanCodes
14 Uncle Bobโ€™s SOLID Principles Made Easy ๐Ÿ€ - In Python!
Uncle Bobโ€™s SOLID Principles Made Easy ๐Ÿ€ - In Python!
ArjanCodes
15 QUESTIONABLE Object Creation Patterns in Python ๐Ÿค”
QUESTIONABLE Object Creation Patterns in Python ๐Ÿค”
ArjanCodes
16 If Youโ€™re Not Using Python DATA CLASSES Yet, You Should ๐Ÿš€
If Youโ€™re Not Using Python DATA CLASSES Yet, You Should ๐Ÿš€
ArjanCodes
17 CODE ROAST: Yahtzee - New Python Code Refactoring Series!
CODE ROAST: Yahtzee - New Python Code Refactoring Series!
ArjanCodes
18 7 UX Design Tips for Developers
7 UX Design Tips for Developers
ArjanCodes
19 Going All-in on Software Design in Python + an ANNOUNCEMENT ๐ŸŽ™
Going All-in on Software Design in Python + an ANNOUNCEMENT ๐ŸŽ™
ArjanCodes
20 ๐ŸŽ™ Interview with Sybren Stรผvel, Developer @ Blender 3D
๐ŸŽ™ Interview with Sybren Stรผvel, Developer @ Blender 3D
ArjanCodes
21 Do We Still Need Dataclasses? // PYDANTIC Tutorial
Do We Still Need Dataclasses? // PYDANTIC Tutorial
ArjanCodes
22 7 Python Mistakes That Instantly Expose Junior Developers
7 Python Mistakes That Instantly Expose Junior Developers
ArjanCodes
23 Answering Your Most Frequently Asked Python Questions // Q&A 07-2021
Answering Your Most Frequently Asked Python Questions // Q&A 07-2021
ArjanCodes
24 GitHub Copilot ๐Ÿค– The Future of Software Development?
GitHub Copilot ๐Ÿค– The Future of Software Development?
ArjanCodes
25 More Python Code Smells: Avoid These 7 Smelly Snags
More Python Code Smells: Avoid These 7 Smelly Snags
ArjanCodes
26 Test-Driven Development In Python // The Power of Red-Green-Refactor
Test-Driven Development In Python // The Power of Red-Green-Refactor
ArjanCodes
27 5 Tips To Keep Technical Debt Under Control
5 Tips To Keep Technical Debt Under Control
ArjanCodes
28 Refactoring A Tower Defense Game In Python // CODE ROAST
Refactoring A Tower Defense Game In Python // CODE ROAST
ArjanCodes
29 The Factory Design Pattern is Obsolete in Python
The Factory Design Pattern is Obsolete in Python
ArjanCodes
30 Why the Plugin Architecture Gives You CRAZY Flexibility
Why the Plugin Architecture Gives You CRAZY Flexibility
ArjanCodes
31 Refactoring A Data Science Project Part 1 - Abstraction and Composition
Refactoring A Data Science Project Part 1 - Abstraction and Composition
ArjanCodes
32 Refactoring A Data Science Project Part 2 - The Information Expert
Refactoring A Data Science Project Part 2 - The Information Expert
ArjanCodes
33 Refactoring A Data Science Project Part 3 - Configuration Cleanup
Refactoring A Data Science Project Part 3 - Configuration Cleanup
ArjanCodes
34 Purge These 7 Code Smells From Your Python Code
Purge These 7 Code Smells From Your Python Code
ArjanCodes
35 Running A Software Development YouTube Channel
Running A Software Development YouTube Channel
ArjanCodes
36 Refactoring A PDF And Web Scraper Part 1 // CODE ROAST
Refactoring A PDF And Web Scraper Part 1 // CODE ROAST
ArjanCodes
37 Refactoring A PDF And Web Scraper Part 2 // CODE ROAST
Refactoring A PDF And Web Scraper Part 2 // CODE ROAST
ArjanCodes
38 How To Easily Do Asynchronous Programming With Asyncio In Python
How To Easily Do Asynchronous Programming With Asyncio In Python
ArjanCodes
39 The Software Designer Mindset
The Software Designer Mindset
ArjanCodes
40 NEVER Worry About Data Science Projects Configs Again
NEVER Worry About Data Science Projects Configs Again
ArjanCodes
41 Powerful VSCode Tips And Tricks For Python Development And Design
Powerful VSCode Tips And Tricks For Python Development And Design
ArjanCodes
42 8 Python Coding Tips - From The Google Python Style Guide
8 Python Coding Tips - From The Google Python Style Guide
ArjanCodes
43 What Is Encapsulation And Information Hiding?
What Is Encapsulation And Information Hiding?
ArjanCodes
44 8 Tips For Becoming A Senior Developer
8 Tips For Becoming A Senior Developer
ArjanCodes
45 Building A Custom Context Manager In Python: A Closer Look
Building A Custom Context Manager In Python: A Closer Look
ArjanCodes
46 GraphQL vs REST: What's The Difference And When To Use Which?
GraphQL vs REST: What's The Difference And When To Use Which?
ArjanCodes
47 You Can Do Really Cool Things With Functions In Python
You Can Do Really Cool Things With Functions In Python
ArjanCodes
48 Announcing The Black VS Code Theme (Launching April 1st)
Announcing The Black VS Code Theme (Launching April 1st)
ArjanCodes
49 7 DevOps Best Practices For Launching A SaaS Platform
7 DevOps Best Practices For Launching A SaaS Platform
ArjanCodes
50 Refactoring a Rock Paper Scissors Lizard Spock Game // Code Roast Part 1
Refactoring a Rock Paper Scissors Lizard Spock Game // Code Roast Part 1
ArjanCodes
51 Refactoring a Rock Paper Scissors Lizard Spock Game // Part 2
Refactoring a Rock Paper Scissors Lizard Spock Game // Part 2
ArjanCodes
52 Things Are Going To Change Around Here
Things Are Going To Change Around Here
ArjanCodes
53 Dependency Injection Explained In One Minute // Python Tips
Dependency Injection Explained In One Minute // Python Tips
ArjanCodes
54 How To Setup A MacBook Pro M1 For Software Development
How To Setup A MacBook Pro M1 For Software Development
ArjanCodes
55 A Simple & Effective Way To Improve Python Class Performance
A Simple & Effective Way To Improve Python Class Performance
ArjanCodes
56 How To Write Unit Tests For Existing Python Code // Part 1 of 2
How To Write Unit Tests For Existing Python Code // Part 1 of 2
ArjanCodes
57 How To Write Unit Tests For Existing Python Code // Part 2 of 2
How To Write Unit Tests For Existing Python Code // Part 2 of 2
ArjanCodes
58 Make Sure You Choose The Right Data Structure // Python Tips
Make Sure You Choose The Right Data Structure // Python Tips
ArjanCodes
59 5 Tips For Object-Oriented Programming Done Well - In Python
5 Tips For Object-Oriented Programming Done Well - In Python
ArjanCodes
60 Next-Level Concurrent Programming In Python With Asyncio
Next-Level Concurrent Programming In Python With Asyncio
ArjanCodes

Related AI Lessons

โšก
Monolith vs Microservices: A Real-World Architectural Autopsy
Learn to decide between monolith and microservices architectures for your project and why it matters for scalability and maintainability
Dev.to ยท Erwin Wilson Ceniza2
โšก
FOV in FPS Games: The Math Behind Field of View Settings
Learn the math behind Field of View settings in FPS games and how to optimize your gameplay experience
Dev.to ยท Alex Carter
โšก
How I Structured My Next.js 14 App Router Project โ€” And Why It Scales
Learn how to structure a scalable Next.js 14 App Router project for better organization and maintainability
Dev.to ยท Mbanefo Emmanuel Ifechukwu
โšก
Letโ€™s write a simple Lexer in Go
Learn to build a simple lexer in Go to understand source code tokenization
Medium ยท Programming

Chapters (7)

Intro
0:33 Analysis of the example
3:20 Template method explanation
5:03 Implementing the template method
9:09 Bridge pattern explanation
10:56 Implementing the bridge pattern
15:59 Final thoughts
Up next
Retracing It All With My Son
Ginny Clarke
Watch โ†’