SlideShare a Scribd company logo
Clean Architecture
Building Clean Apps in Python
Subhash Bhushan
Team8 Solutions, LLC
1
2 . 1
Technical Debt
Dependencies slow you down
2 . 2
3 . 1
Clean Architecture
Reduce Technical Debt by Reducing Dependencies
Thou shalt only
look inward!
3 . 2
Example
1. Check Balance in Account 1
2. Initiate Transaction
3. Debit Account 1
4. Credit Account 2
5. Record Transfer
6. Commit Transaction
An Implementation of Account to Account Transfer
4 . 1
Entities
from datetime import datetime
class Account:
# Look Ma, No DB!
def __init__(self, name, balance):
self.name = name
self.balance = balance
def validate(self):
pass
def has_sufficient_balance(self, amount):
return self.balance >= amount
def debit(self, amount):
if self.has_sufficient_balance(amount):
self.balance -= amount
def credit(self, amount):
self.balance += amount
class Transfer:
def __init__(self, from_account: Account, to_account: Account, amount: float):
self.from_account = from_account
self.to_account = to_account
self.amount = amount
self.transaction_date = datetime.now()
4 . 2
UseCase
from core.entities import Transfer
from db.repository import TransferRepository
class TransferUseCase:
def __init__(self, repository: TransferRepository): # Dependency... Injected.
self.repository = repository
def create(self, transfer: Transfer):
if transfer.from_account.validate() 
and transfer.to_account.validate() 
and transfer.from_account.has_sufficient_balance(transfer.amount)
and self._validate_transfer_request(transfer):
with self.repository.atomic():
transfer = self.repository.save(transfer)
return transfer
def _validate_transfer_request(self, transfer: Transfer):
pass
4 . 3
Data Adapters
from typing import NamedTuple # Don't Type Hints make your code look great?
from core.entities import Transfer
from core.usecase import TransferUseCase
from db.repository import TransferRepository
class AccountData(NamedTuple):
name: str
balance: float
class TransferData(NamedTuple):
from_account: AccountData
to_account: AccountData
amount: float
transaction_date: str
4 . 4
Interface Adapters
from typing import NamedTuple
from core.entities import Transfer
from core.usecase import TransferUseCase
from db.repository import TransferRepository
class TransferAdapter:
def __init__(self, repository: TransferRepository): # Some more... Injection.
self.usecase = TransferUseCase(repository)
def create(self, transfer_data: TransferData) -> TransferData:
transfer = self._data_to_transfer(transfer_data)
transfer = self.usecase.create(transfer) # Warning: No Exceptions Please!
return self._transfer_to_data(transfer)
@classmethod
def _transfer_to_data(cls, transfer: Transfer) -> TransferData:
pass
@classmethod
def _data_to_transfer(cls, transfer_data: TransferData) -> Transfer:
pass
4 . 5
Repository
from typing import ContextManager
from core.entities import Transfer
class TransferRepository:
def save(self, transfer: Transfer) -> Transfer:
# And Finally...
# Persist Transfer AND Accounts
raise NotImplementedError()
def atomic(self) -> ContextManager:
raise NotImplementedError()
4 . 6
Views
import json
from flask import request
from flask_restful import Resource, Api
from core.adapters import TransferAdapter
from db.repository import TransferRepository
class TransferResource(Resource):
def __init__(self, *args, **kwargs):
self.super().__init__(*args, **kwargs)
self.adapter = TransferAdapter(TransferRepository()) # Inject... Dependency
@app.route('/api/v1.0/transfer', methods=['POST'])
def post(self):
transfer_data = self.adapter.create(request.form['data'])
return transfer_data, 201 # Again, No Exceptions, Please!
4 . 7
Cons
Everyone needs to respect rules
Difficult to leverage frameworks
Cannot take advantage of Active Record pattern
Can result in Significant Boilerplate
Higher Complexity
There ain't no such thing as a Free Lunch
5
The Principle of
Last Responsible Moment
A good architecture allows you to defer critical decisions
6 . 1
Resources
The Clean Architecture -
Robert C. Martin's Clean Architecture -
Alistair Cockburn -
Clean Architecture Python Apps -
Clean Architecture is Screaming -
Github Repo -
8thlight.com
Amazon.com
Hexagonal Architecture
@haxoza
DZone
Clean Transfer
All Icons are courtesy of the good folks at The Noun Project
6 . 2
Thank you!
Questions?
subhash@team8solutions.com
6 . 3

More Related Content

What's hot

Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...
Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...
Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...
ENSET, Université Hassan II Casablanca
 
github-actions.pdf
github-actions.pdfgithub-actions.pdf
github-actions.pdf
AbhaymithraReddy1
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
Victor Rentea
 
Cours design pattern m youssfi partie 5 adapter
Cours design pattern m youssfi partie 5 adapterCours design pattern m youssfi partie 5 adapter
Cours design pattern m youssfi partie 5 adapter
ENSET, Université Hassan II Casablanca
 
Maven et industrialisation du logiciel
Maven et industrialisation du logicielMaven et industrialisation du logiciel
Maven et industrialisation du logiciel
ENSET, Université Hassan II Casablanca
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
José Paumard
 
Asp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkAsp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity Framework
Shravan A
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
Naphachara Rattanawilai
 
Sécurité des Applications Web avec Json Web Token (JWT)
Sécurité des Applications Web avec Json Web Token (JWT)Sécurité des Applications Web avec Json Web Token (JWT)
Sécurité des Applications Web avec Json Web Token (JWT)
ENSET, Université Hassan II Casablanca
 
Traitement distribue en BIg Data - KAFKA Broker and Kafka Streams
Traitement distribue en BIg Data - KAFKA Broker and Kafka StreamsTraitement distribue en BIg Data - KAFKA Broker and Kafka Streams
Traitement distribue en BIg Data - KAFKA Broker and Kafka Streams
ENSET, Université Hassan II Casablanca
 
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfiJava entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
ENSET, Université Hassan II Casablanca
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
Xcat Liu
 
Cours python avancé
Cours python avancéCours python avancé
Cours python avancépierrepo
 
introduction à MongoDB
introduction à MongoDBintroduction à MongoDB
introduction à MongoDB
Abdoulaye Dieng
 
Formation Spring Avancé gratuite par Ippon 2014
Formation Spring Avancé gratuite par Ippon 2014Formation Spring Avancé gratuite par Ippon 2014
Formation Spring Avancé gratuite par Ippon 2014
Ippon
 
Spring boot
Spring bootSpring boot
Spring boot
sdeeg
 
Cours design pattern m youssfi partie 4 composite
Cours design pattern m youssfi partie 4 compositeCours design pattern m youssfi partie 4 composite
Cours design pattern m youssfi partie 4 composite
ENSET, Université Hassan II Casablanca
 
Cours javascript
Cours javascriptCours javascript
Cours javascript
krymo
 

What's hot (20)

Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...
Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...
Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...
 
github-actions.pdf
github-actions.pdfgithub-actions.pdf
github-actions.pdf
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Cours design pattern m youssfi partie 5 adapter
Cours design pattern m youssfi partie 5 adapterCours design pattern m youssfi partie 5 adapter
Cours design pattern m youssfi partie 5 adapter
 
Maven et industrialisation du logiciel
Maven et industrialisation du logicielMaven et industrialisation du logiciel
Maven et industrialisation du logiciel
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
Asp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkAsp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity Framework
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Sécurité des Applications Web avec Json Web Token (JWT)
Sécurité des Applications Web avec Json Web Token (JWT)Sécurité des Applications Web avec Json Web Token (JWT)
Sécurité des Applications Web avec Json Web Token (JWT)
 
Traitement distribue en BIg Data - KAFKA Broker and Kafka Streams
Traitement distribue en BIg Data - KAFKA Broker and Kafka StreamsTraitement distribue en BIg Data - KAFKA Broker and Kafka Streams
Traitement distribue en BIg Data - KAFKA Broker and Kafka Streams
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfiJava entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 
Cours python avancé
Cours python avancéCours python avancé
Cours python avancé
 
introduction à MongoDB
introduction à MongoDBintroduction à MongoDB
introduction à MongoDB
 
Formation Spring Avancé gratuite par Ippon 2014
Formation Spring Avancé gratuite par Ippon 2014Formation Spring Avancé gratuite par Ippon 2014
Formation Spring Avancé gratuite par Ippon 2014
 
Spring boot
Spring bootSpring boot
Spring boot
 
Cours design pattern m youssfi partie 4 composite
Cours design pattern m youssfi partie 4 compositeCours design pattern m youssfi partie 4 composite
Cours design pattern m youssfi partie 4 composite
 
Cours javascript
Cours javascriptCours javascript
Cours javascript
 

Similar to Clean Architecture Applications in Python

Test Doubles - stubs, spies & mocks
Test Doubles - stubs, spies & mocksTest Doubles - stubs, spies & mocks
Test Doubles - stubs, spies & mocks
Rubén Bernárdez
 
Bdd for-dso-1227123516572504-8
Bdd for-dso-1227123516572504-8Bdd for-dso-1227123516572504-8
Bdd for-dso-1227123516572504-8Frédéric Delorme
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patterns
Tomasz Kowal
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
msharshitha03s
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-people
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutionsbenewu
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010
Plataformatec
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
Max Klymyshyn
 
The Steel industry, Elixir, PostgreSQL & file_fdw
The Steel industry, Elixir, PostgreSQL & file_fdwThe Steel industry, Elixir, PostgreSQL & file_fdw
The Steel industry, Elixir, PostgreSQL & file_fdw
Florian Kraft
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
satvirsandhu9
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
Naresh Jain
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Frameworkvhazrati
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
IndicThreads
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
Xebia IT Architects
 
Introduction to coding using Python
Introduction to coding using PythonIntroduction to coding using Python
Introduction to coding using Python
Dan D'Urso
 
Django tricks (2)
Django tricks (2)Django tricks (2)
Django tricks (2)
Carlos Hernando
 
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdf
Account.h  Definition of Account class. #ifndef ACCOUNT_H #d.pdfAccount.h  Definition of Account class. #ifndef ACCOUNT_H #d.pdf
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdf
anujmkt
 
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Codemotion
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
IT Weekend
 

Similar to Clean Architecture Applications in Python (20)

Test Doubles - stubs, spies & mocks
Test Doubles - stubs, spies & mocksTest Doubles - stubs, spies & mocks
Test Doubles - stubs, spies & mocks
 
Bdd for-dso-1227123516572504-8
Bdd for-dso-1227123516572504-8Bdd for-dso-1227123516572504-8
Bdd for-dso-1227123516572504-8
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patterns
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
TDD, BDD and mocks
TDD, BDD and mocksTDD, BDD and mocks
TDD, BDD and mocks
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
The Steel industry, Elixir, PostgreSQL & file_fdw
The Steel industry, Elixir, PostgreSQL & file_fdwThe Steel industry, Elixir, PostgreSQL & file_fdw
The Steel industry, Elixir, PostgreSQL & file_fdw
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 
Introduction to coding using Python
Introduction to coding using PythonIntroduction to coding using Python
Introduction to coding using Python
 
Django tricks (2)
Django tricks (2)Django tricks (2)
Django tricks (2)
 
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdf
Account.h  Definition of Account class. #ifndef ACCOUNT_H #d.pdfAccount.h  Definition of Account class. #ifndef ACCOUNT_H #d.pdf
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdf
 
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
 

Recently uploaded

Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 

Recently uploaded (20)

Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 

Clean Architecture Applications in Python

  • 1. Clean Architecture Building Clean Apps in Python Subhash Bhushan Team8 Solutions, LLC 1
  • 5. Clean Architecture Reduce Technical Debt by Reducing Dependencies Thou shalt only look inward! 3 . 2
  • 6. Example 1. Check Balance in Account 1 2. Initiate Transaction 3. Debit Account 1 4. Credit Account 2 5. Record Transfer 6. Commit Transaction An Implementation of Account to Account Transfer 4 . 1
  • 7. Entities from datetime import datetime class Account: # Look Ma, No DB! def __init__(self, name, balance): self.name = name self.balance = balance def validate(self): pass def has_sufficient_balance(self, amount): return self.balance >= amount def debit(self, amount): if self.has_sufficient_balance(amount): self.balance -= amount def credit(self, amount): self.balance += amount class Transfer: def __init__(self, from_account: Account, to_account: Account, amount: float): self.from_account = from_account self.to_account = to_account self.amount = amount self.transaction_date = datetime.now() 4 . 2
  • 8. UseCase from core.entities import Transfer from db.repository import TransferRepository class TransferUseCase: def __init__(self, repository: TransferRepository): # Dependency... Injected. self.repository = repository def create(self, transfer: Transfer): if transfer.from_account.validate() and transfer.to_account.validate() and transfer.from_account.has_sufficient_balance(transfer.amount) and self._validate_transfer_request(transfer): with self.repository.atomic(): transfer = self.repository.save(transfer) return transfer def _validate_transfer_request(self, transfer: Transfer): pass 4 . 3
  • 9. Data Adapters from typing import NamedTuple # Don't Type Hints make your code look great? from core.entities import Transfer from core.usecase import TransferUseCase from db.repository import TransferRepository class AccountData(NamedTuple): name: str balance: float class TransferData(NamedTuple): from_account: AccountData to_account: AccountData amount: float transaction_date: str 4 . 4
  • 10. Interface Adapters from typing import NamedTuple from core.entities import Transfer from core.usecase import TransferUseCase from db.repository import TransferRepository class TransferAdapter: def __init__(self, repository: TransferRepository): # Some more... Injection. self.usecase = TransferUseCase(repository) def create(self, transfer_data: TransferData) -> TransferData: transfer = self._data_to_transfer(transfer_data) transfer = self.usecase.create(transfer) # Warning: No Exceptions Please! return self._transfer_to_data(transfer) @classmethod def _transfer_to_data(cls, transfer: Transfer) -> TransferData: pass @classmethod def _data_to_transfer(cls, transfer_data: TransferData) -> Transfer: pass 4 . 5
  • 11. Repository from typing import ContextManager from core.entities import Transfer class TransferRepository: def save(self, transfer: Transfer) -> Transfer: # And Finally... # Persist Transfer AND Accounts raise NotImplementedError() def atomic(self) -> ContextManager: raise NotImplementedError() 4 . 6
  • 12. Views import json from flask import request from flask_restful import Resource, Api from core.adapters import TransferAdapter from db.repository import TransferRepository class TransferResource(Resource): def __init__(self, *args, **kwargs): self.super().__init__(*args, **kwargs) self.adapter = TransferAdapter(TransferRepository()) # Inject... Dependency @app.route('/api/v1.0/transfer', methods=['POST']) def post(self): transfer_data = self.adapter.create(request.form['data']) return transfer_data, 201 # Again, No Exceptions, Please! 4 . 7
  • 13. Cons Everyone needs to respect rules Difficult to leverage frameworks Cannot take advantage of Active Record pattern Can result in Significant Boilerplate Higher Complexity There ain't no such thing as a Free Lunch 5
  • 14. The Principle of Last Responsible Moment A good architecture allows you to defer critical decisions 6 . 1
  • 15. Resources The Clean Architecture - Robert C. Martin's Clean Architecture - Alistair Cockburn - Clean Architecture Python Apps - Clean Architecture is Screaming - Github Repo - 8thlight.com Amazon.com Hexagonal Architecture @haxoza DZone Clean Transfer All Icons are courtesy of the good folks at The Noun Project 6 . 2