SlideShare a Scribd company logo
Write code for humans, not machines.
Narendran R
Backend Engineer @ MadStreetDen
Internet handle : @DudeWhoCode
website : dudewho.codes
Are you a "great" programmer?Are you a "great" programmer?
Are you a "good" programmer?Are you a "good" programmer?
Variables
Functions
Loop/Indentation
Error handling
Variables
temp = some_important_API.get(‘production_data’)
Our all time favourite temp.
Been there, done that. Hand up..
Short and self explanatory
For example, If you are selecting student names from DB
? = cursor.execute(query)
res ❌
tmp ❌
data ❌
students ✅
student_names ✅
names ✅
Try not to use i, j, k in for loops and short scopes, you won’t be able to find
those variable names in large codebase.
Use ii, jj, kk instead
temp = []
with open(‘product_catalog.txt’, ‘w’) as file:
for i in file:
i = i.split(‘:’)[-1].strip()
temp.append(i)
(vs)
products = []
with open(‘product_catalog.txt’, ‘w’) as f:
for product in f:
product = product.split(‘:’)[-1].strip()
products.append(product)
Functions/Methods
Every function should have single responsibility
import json
import psycopg2
conn = psycopg2.connect(“*your database credentials*”)
cur = conn.cursor()
# Responsibilities : Read from a .txt file, check integrity of the
query, then insert to DB
def insert_db(queries_file):
queries = open(queries_file)
for query in queries:
# check the query integrity
if query.startswith(‘INSERT’):
cur.execute(query)
conn.commit()
else:
print(‘Invalid query’)
continue
if __name__ = ‘__main__’:
insert_db(‘queries.txt’)
import json
import psycopg2
conn = psycopg2.connect(“*your database credentials*”)
# Responsibility : Return query one by one from a given .txt file
def load_queries(fname):
queries = open(queries_file)
for query in queries:
yield query
# Responsibility : Check integrity of a given query
def check_query(query):
if query.startswith(‘INSERT’):
return True
# All other query checks goes here
return False
# Responsibility : Insert a given query into DB
def insert_db(query):
cur = conn.execute(query)
conn.commit()
# Responsibility : Put all functions from the script to a meaningful
use
def run(queryfile):
for query in load_queries(queryfile):
if check_query(query):
insert_db(query)
else:
print(‘Invalid query’)
continue
if __name__ = ‘__main__’:
run(‘queries.txt')
Loops and Indentation
Keep your nested loops to maximum 3 levels of indentation
def check_list_of_list_of_strings(data):
if isinstance(data, list):
for items in data:
if isinstance(items, list):
for item in items:
if isinstance(item, str):
if item.endswith('_name'):
return True
| 1 | 2| 3| 4| 5| 6| -> 6 levels of indentation
def check_list_of_list_of_strings(data):
if not isinstance(data, list):
return False
for items in data:
if not isinstance(items, list):
return False
for item in items:
if not (isinstance(item, str)):
return False
if not item.endswith('_name’):
return False
| 1 | 2 | 3 | -> 3 levels of indentation
Error handling
The common anti-pattern
The silent killer
try:
# do something
except:
pass
Allowing the error to silently pass through
The loud loser
try:
# do something
except:
raise
The above try/except is meaningless as its going to raise an error with or
without the try/except clause
Hey pssssst.. !, Trust me you can't
bio = {‘first_name’: ‘Bruce’, ‘last_name’: 35, ‘age’: ‘Wayne',
‘super_power’: ‘being rich’}
try:
fname = bio[‘first_name’]
lname = bio[‘last_name’]
full_name = fname + lname # Throws TypeError
super_power = bio[‘superPower’] # Throws KeyError
except Exception as e:
log.Error(e) # You are logging only TypeError
# How do you take an action without knowing the error?
bio = [‘first_name’: ‘Bruce’, ‘last_name’: 35, ‘age’: ‘Wayne',
‘superPower’: ‘being rich’]
try:
fname = bio[‘first_name’]
lname = bio[‘last_name’]
full_name = fname + lname # Throws TypeError
super_power = bio[‘superPower’] # Throws KeyError
except KeyError:
log.Error(‘key not found’)
# Take appropriate actions as per the error
except TypeError:
log.Error(‘Unable to concatenate’)
# Take appropriate actions as per the error
except Exception as e:
log.Error(‘Unexpected Error’, e)
# Expect the unexpected
Try not to swap :
except Exception as e:
log.Error(‘Unexpected Error’, e)
# Expect the unexpected
# Unreachable Code
except KeyError:
log.Error(‘key not found’)
# Take appropriate actions as per the error
except TypeError:
log.Error(‘Unable to concatenate’)
# Take appropriate actions as per the error
Summary
Variables :
Short, meaningful, use underscores if necessary and no temp, temp1, data1
please.
Easy readability
Functions :
Give only one responsibility to a function
Easy unit testing and readability
Summary
Loops :
Don’t overdo the levels of nested loop
Error handling :
Don’t try to catch them all
No “raise” or “pass" inside except clause
Know what error you are going to expect
Whats next?
1. Go home, open the code that you wrote >6 months ago.
2. Read the code assuming that you are a new/junior programmer appointed to
maintain above code.
3. Try not to punch yourself on the face.
- Just kidding
Whats really next?
1. Read PEP-8 and python anti-patterns.
2. Read open source code in your leisure time.
3. Develop good programming habits.
4. Make fellow humans happy.
I am not a great programmer, I am a good programmer with great habits.
- Kent beck
twitter, github :
@DudeWhoCode
slides :
dudewho.codes/talks

More Related Content

What's hot

Create and analyse programs
Create and analyse programsCreate and analyse programs
Create and analyse programs
Dr. C.V. Suresh Babu
 
Matching with Regular Expressions
Matching with Regular ExpressionsMatching with Regular Expressions
Matching with Regular Expressions
primeteacher32
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
Karin Lagesen
 
Effective PHP. Part 2
Effective PHP. Part 2Effective PHP. Part 2
Effective PHP. Part 2
Vasily Kartashov
 
Effective PHP. Part 5
Effective PHP. Part 5Effective PHP. Part 5
Effective PHP. Part 5
Vasily Kartashov
 
C++
C++C++
Using Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingUsing Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingMike Clement
 
Python functions
Python functionsPython functions
Python functions
Aliyamanasa
 
Functions in php
Functions in phpFunctions in php
Functions in php
AbdulAzizSapra
 
String Interpolation in Scala
String Interpolation in ScalaString Interpolation in Scala
String Interpolation in Scala
Knoldus Inc.
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
Sarfaraz Ghanta
 
Effective PHP. Part 3
Effective PHP. Part 3Effective PHP. Part 3
Effective PHP. Part 3
Vasily Kartashov
 
Effective PHP. Part 4
Effective PHP. Part 4Effective PHP. Part 4
Effective PHP. Part 4
Vasily Kartashov
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akka
AD_
 
Mutability for good not evil
Mutability for good not evilMutability for good not evil
Mutability for good not evil
Nick Sarbicki
 
Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
primeteacher32
 
Effective PHP. Part 1
Effective PHP. Part 1Effective PHP. Part 1
Effective PHP. Part 1
Vasily Kartashov
 
Effective PHP. Part 6
Effective PHP. Part 6Effective PHP. Part 6
Effective PHP. Part 6
Vasily Kartashov
 
Intro To BOOST.Spirit
Intro To BOOST.SpiritIntro To BOOST.Spirit
Intro To BOOST.Spirit
Will Shen
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
Jaganadh Gopinadhan
 

What's hot (20)

Create and analyse programs
Create and analyse programsCreate and analyse programs
Create and analyse programs
 
Matching with Regular Expressions
Matching with Regular ExpressionsMatching with Regular Expressions
Matching with Regular Expressions
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Effective PHP. Part 2
Effective PHP. Part 2Effective PHP. Part 2
Effective PHP. Part 2
 
Effective PHP. Part 5
Effective PHP. Part 5Effective PHP. Part 5
Effective PHP. Part 5
 
C++
C++C++
C++
 
Using Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingUsing Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit Testing
 
Python functions
Python functionsPython functions
Python functions
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
String Interpolation in Scala
String Interpolation in ScalaString Interpolation in Scala
String Interpolation in Scala
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
Effective PHP. Part 3
Effective PHP. Part 3Effective PHP. Part 3
Effective PHP. Part 3
 
Effective PHP. Part 4
Effective PHP. Part 4Effective PHP. Part 4
Effective PHP. Part 4
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akka
 
Mutability for good not evil
Mutability for good not evilMutability for good not evil
Mutability for good not evil
 
Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
 
Effective PHP. Part 1
Effective PHP. Part 1Effective PHP. Part 1
Effective PHP. Part 1
 
Effective PHP. Part 6
Effective PHP. Part 6Effective PHP. Part 6
Effective PHP. Part 6
 
Intro To BOOST.Spirit
Intro To BOOST.SpiritIntro To BOOST.Spirit
Intro To BOOST.Spirit
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
 

Similar to Write codeforhumans

Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
CatherineVania1
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
noelrap
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
Python Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-FinallyPython Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-Finally
Vinod Srivastava
 
TDD & BDD
TDD & BDDTDD & BDD
TDD & BDD
Arvind Vyas
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
Mohd Aves Malik
 
Feature Engineering in NLP.pdf
Feature Engineering in NLP.pdfFeature Engineering in NLP.pdf
Feature Engineering in NLP.pdf
bilaje4244prolugcom
 
Notes5
Notes5Notes5
Notes5hccit
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
Hans Jones
 
How to write maintainable code without tests
How to write maintainable code without testsHow to write maintainable code without tests
How to write maintainable code without tests
Juti Noppornpitak
 
Java tut1
Java tut1Java tut1
Java tut1
Ajmal Khan
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
Abdul Aziz
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
guest5c8bd1
 
All you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsAll you need to know about JavaScript Functions
All you need to know about JavaScript Functions
Oluwaleke Fakorede
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
Syed Farjad Zia Zaidi
 

Similar to Write codeforhumans (20)

Python basic
Python basicPython basic
Python basic
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-FinallyPython Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-Finally
 
pyton Notes9
pyton Notes9pyton Notes9
pyton Notes9
 
TDD & BDD
TDD & BDDTDD & BDD
TDD & BDD
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
 
Feature Engineering in NLP.pdf
Feature Engineering in NLP.pdfFeature Engineering in NLP.pdf
Feature Engineering in NLP.pdf
 
Notes5
Notes5Notes5
Notes5
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
How to write maintainable code without tests
How to write maintainable code without testsHow to write maintainable code without tests
How to write maintainable code without tests
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
All you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsAll you need to know about JavaScript Functions
All you need to know about JavaScript Functions
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
 

Recently uploaded

A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
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
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
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
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
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
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
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
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 

Recently uploaded (20)

A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.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)
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
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
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
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
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
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
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
 

Write codeforhumans

  • 1. Write code for humans, not machines. Narendran R Backend Engineer @ MadStreetDen Internet handle : @DudeWhoCode website : dudewho.codes
  • 2. Are you a "great" programmer?Are you a "great" programmer?
  • 3. Are you a "good" programmer?Are you a "good" programmer?
  • 6. temp = some_important_API.get(‘production_data’) Our all time favourite temp. Been there, done that. Hand up..
  • 7. Short and self explanatory For example, If you are selecting student names from DB ? = cursor.execute(query) res ❌ tmp ❌ data ❌ students ✅ student_names ✅ names ✅
  • 8. Try not to use i, j, k in for loops and short scopes, you won’t be able to find those variable names in large codebase.
  • 9. Use ii, jj, kk instead
  • 10. temp = [] with open(‘product_catalog.txt’, ‘w’) as file: for i in file: i = i.split(‘:’)[-1].strip() temp.append(i) (vs) products = [] with open(‘product_catalog.txt’, ‘w’) as f: for product in f: product = product.split(‘:’)[-1].strip() products.append(product)
  • 12. Every function should have single responsibility import json import psycopg2 conn = psycopg2.connect(“*your database credentials*”) cur = conn.cursor() # Responsibilities : Read from a .txt file, check integrity of the query, then insert to DB def insert_db(queries_file): queries = open(queries_file) for query in queries: # check the query integrity if query.startswith(‘INSERT’): cur.execute(query) conn.commit() else: print(‘Invalid query’) continue if __name__ = ‘__main__’: insert_db(‘queries.txt’)
  • 13. import json import psycopg2 conn = psycopg2.connect(“*your database credentials*”) # Responsibility : Return query one by one from a given .txt file def load_queries(fname): queries = open(queries_file) for query in queries: yield query # Responsibility : Check integrity of a given query def check_query(query): if query.startswith(‘INSERT’): return True # All other query checks goes here return False # Responsibility : Insert a given query into DB def insert_db(query): cur = conn.execute(query) conn.commit() # Responsibility : Put all functions from the script to a meaningful use def run(queryfile): for query in load_queries(queryfile): if check_query(query): insert_db(query) else: print(‘Invalid query’) continue if __name__ = ‘__main__’: run(‘queries.txt')
  • 15. Keep your nested loops to maximum 3 levels of indentation
  • 16. def check_list_of_list_of_strings(data): if isinstance(data, list): for items in data: if isinstance(items, list): for item in items: if isinstance(item, str): if item.endswith('_name'): return True | 1 | 2| 3| 4| 5| 6| -> 6 levels of indentation
  • 17. def check_list_of_list_of_strings(data): if not isinstance(data, list): return False for items in data: if not isinstance(items, list): return False for item in items: if not (isinstance(item, str)): return False if not item.endswith('_name’): return False | 1 | 2 | 3 | -> 3 levels of indentation
  • 19. The common anti-pattern The silent killer try: # do something except: pass Allowing the error to silently pass through
  • 20. The loud loser try: # do something except: raise The above try/except is meaningless as its going to raise an error with or without the try/except clause
  • 21. Hey pssssst.. !, Trust me you can't
  • 22. bio = {‘first_name’: ‘Bruce’, ‘last_name’: 35, ‘age’: ‘Wayne', ‘super_power’: ‘being rich’} try: fname = bio[‘first_name’] lname = bio[‘last_name’] full_name = fname + lname # Throws TypeError super_power = bio[‘superPower’] # Throws KeyError except Exception as e: log.Error(e) # You are logging only TypeError # How do you take an action without knowing the error?
  • 23. bio = [‘first_name’: ‘Bruce’, ‘last_name’: 35, ‘age’: ‘Wayne', ‘superPower’: ‘being rich’] try: fname = bio[‘first_name’] lname = bio[‘last_name’] full_name = fname + lname # Throws TypeError super_power = bio[‘superPower’] # Throws KeyError except KeyError: log.Error(‘key not found’) # Take appropriate actions as per the error except TypeError: log.Error(‘Unable to concatenate’) # Take appropriate actions as per the error except Exception as e: log.Error(‘Unexpected Error’, e) # Expect the unexpected
  • 24. Try not to swap : except Exception as e: log.Error(‘Unexpected Error’, e) # Expect the unexpected # Unreachable Code except KeyError: log.Error(‘key not found’) # Take appropriate actions as per the error except TypeError: log.Error(‘Unable to concatenate’) # Take appropriate actions as per the error
  • 25. Summary Variables : Short, meaningful, use underscores if necessary and no temp, temp1, data1 please. Easy readability Functions : Give only one responsibility to a function Easy unit testing and readability
  • 26. Summary Loops : Don’t overdo the levels of nested loop Error handling : Don’t try to catch them all No “raise” or “pass" inside except clause Know what error you are going to expect
  • 27.
  • 28. Whats next? 1. Go home, open the code that you wrote >6 months ago. 2. Read the code assuming that you are a new/junior programmer appointed to maintain above code. 3. Try not to punch yourself on the face.
  • 29. - Just kidding Whats really next? 1. Read PEP-8 and python anti-patterns. 2. Read open source code in your leisure time. 3. Develop good programming habits. 4. Make fellow humans happy.
  • 30. I am not a great programmer, I am a good programmer with great habits. - Kent beck twitter, github : @DudeWhoCode slides : dudewho.codes/talks