Object	Calisthenics
9	steps	to	better	OO	code
Agenda
Learn	how	to	make	our	code	more:
readable
reusable
testable
maintainable
Raise	you	hand	if	you	know
one	of	the	following:
DRY
KISS
SOLID
YAGNI
Zen	of	Python
Calisthenics
Cal	•	is	•	then	•	ics	-	/ˌkaləsˈTHeniks/
"Calisthenics	are	exercises	consisting	of	a
variety	of	gross	motor	movements;	often
rhythmical	and	generally	without	equipment
or	apparatus."
Wikipedia
Object	Calisthenics
Jeff	Bay
Written	for	Java
Why	bother?
Code	is	read	more
than	it's	written
Author	unknown
You	need	to	write	code	that
minimizes	the	time	it	would
take	someone	else	to
understand	it	-	even	if	that
someone	else	is	you
Art	of	Readable	Code	by	Dustin	Boswell,
Trevor	Foucher
Rule	#1
Only	one	level	of
indentation	per	method
class	Board(object):
				def	__init__(self,	data):
								#	Level	0
								self.buf	=	""
								for	i	in	range(10):
												#	Level	1
												for	j	in	range(10):
																#	Level	2
																self.buf	+=	data[i][j]
class	Board(object):
				def	__init__(self,	data):
								self.buf	=	""
								self.collect_rows(data)
				
				def	collect_rows(self,	data):
								for	i	in	range(10):
												self.collect_row(data[i])
												
				def	collect_row(self,	row):
								for	j	in	range(10):
												self.buf	+=	row[j]
products	=	self.get_products_by_user(...)
if	products	is	None:
				products	=	self.get_products_by_media(...)
				if	products	is	None:
								products	=	self.get_products_by_domain(...)
								if	products	is	None:
												products	=	self.get_any_products(...):
												if	products	is	None:
																raise	Exception('Access	denied')
												else:
																...
								else:
												...
				else:
								...
else:
				...
Chain	of	command
Benefits
Single	responsibility
Better	naming
Shorter	methods
Reusable	methods
Rule	#2
Do	not	use	else	keyword
if	options.get_categories()	is	None:
				...
elif	len(options.get_categories())	==	1:
				...
elif	SPECIAL_CATEGORY	in	options.get_categories():
				...
elif	options.get_categories()	and	options.get_query():
				...
elif	options.get_content_type():
				...
def	login	(self,	request):
				if	request.user.is_authenticated():
								return	redirect("homepage")
				else:
								messages.add_message(request,	
																													messages.INFO,	
																													'Bad	credentials')
								return	redirect("login")
def	login	(self,	request):
				if	request.user.is_authenticated():
								return	redirect("homepage")
				messages.add_message(request,	
																									messages.INFO,	
																									'Bad	credentials')
				return	redirect("login")
def	function(param):
				if	param	is	not	None:
								value	=	param
				else:
								value	=	"default"
				return	value
def	function(param):
				value	=	"default"
				if	param	is	not	None:
								value	=	param
				return	value
Object Calisthenics (PyCon Slovakia 2017)
Extract	code
Default	value
Polymorphism
Strategy	pattern
State	pattern
Examples
https://github.com/gennad/Design-Patterns-in-Python
https://www.quora.com/Is-it-true-that-a-good-
programmer-uses-fewer-if-conditions-than-an-amateur
Benefits
Avoids	code	duplication
Lower	complexity
Readability
Rule	#3
Wrap	primitive	types	if	it
has	behaviour
Value	Object	in	DDD
class	Validator(object):
				def	check_date(self,	year,	month,	day):
								pass
#	10th	of	December	or	12th	of	October?
validator	=	Validator()
validator.check_date(2016,	10,	12)
class	Validator(object):
				def	check_date(self,	year:	Year,	month:	Month,	day:	Day)	->	bool:
								pass
#	Function	call	leaves	no	doubt.
validator.check_date(Year(2016),	Month(10),	Day(12))
Benefits
Encapsulation
Type	hinting
Attracts	similar	behaviour
Rule	#4
Only	one	dot	per	line
OK:	Fluent	interface
class	Poem(object):
				def	__init__(self,	content):
								self.content	=	content
				def	indent(self,	spaces):
								self.content	=	"	"	*	spaces	+	self.content
								return	self
				def	suffix(self,	content):
								self.content	=	self.content	+	"	-	"	+	content
								return	self
Poem("Road	Not	Travelled").indent(4)
				.suffix("Robert	Frost")
				.content
Not	OK:	getter	chain
class	CartService(object):
				def	get_token(self):
								token	=	self.get_service('auth')
												.auth_user('user',	'password')
												.get_result()
												.get_token()
								return	token
#	1.	What	if	None	is	returned	instead	of	object?
#	2.	How	about	exceptions	handling?
class	Field(object):
				def	__init__(self):
								self.current	=	Piece()
class	Piece(object):
				def	__init__(self):
								self.representation	=	"	"
class	Board(object):
				def	board_representation(self,	board):
								buf	=	''
								for	field	in	board:
												buf	+=	field.current.representation
								return	buf
class	Field(object):
				def	__init__(self):
								self.current	=	Piece()
								
				def	add_to(self,	buffer):
								return	self.current.add_to(buffer)
class	Piece(object):
				def	__init__(self):
								self.representation	=	"	"
								
				def	add_to(self,	buffer):
								return	buffer	+	self.representation
class	Board(object):
				def	board_representation(self,	board):
								buf	=	''
								for	field	in	board:
												buf	=	field.add_to(buf)
								return	buf
Benefits
Encapsulation
Demeter's	law
Open/Closed	Principle
Rule	#5
Do	not	abbreviate
Why	abbreviate?
Too	many	responsibilities
Name	too	long?
Split	&	extract
Duplicated	code?
Refactor!
class	Order(object):
				def	ship_order(self):
								pass
order	=	Order()
order.ship_order()
//	vs
class	Order(object):
				def	ship(self):
								pass
order	=	Order()
order.ship()
acc	=	0
//	accumulator?	accuracy?
pos	=	100
//	position?	point	of	sale?	positive?
auth	=	None
//	authentication?	authorization?	both?
Benefits
Clear	intentions
Indicate	underlying	problems
Rule	#6
Keep	your	classes	small
What	is	small	class?
15-20	lines	per	method
50	lines	per	class
10	classes	per	module
Benefits
Single	Responsibility
Smaller	modules
Rule	#7
No	more	than	2	instance
	variable	per	class
Class	should	handle	single
variable	state
In	some	cases	it	might	be
two	variables
Object Calisthenics (PyCon Slovakia 2017)
class	CartService(object):
				def	__init__(self):
								self.logger	=	Logger()
								self.cart	=	CartCollection()
								self.translationService	=	TranslationService()
								self.auth_service	=	AuthService()
								self.user_service	=	UserService()
Benefits
High	cohesion
Encapsulation
Fewer	dependencies
Rule	#8
First	class	collections
collections	module
Benefits
Single	Responsibility
Rule	#9
Do	not	use	setters/getters
Accessors	are	fine
Don't	make	decisions
outside	of	class
Let	class	do	it's	job
Tell,	don't	ask
class	Game(object):
				def	__init__(self):
								self.score	=	0
				def	set_score(self,	score):
								self.score	=	score
				def	get_score(self):
								return	self.score
#	Usage
ENEMY_DESTROYED_SCORE	=	10
game	=	Game()
game.set_score(game.get_score()	+	ENEMY_DESTROYED_SCORE)
class	Game(object):
				def	__init__(self):
								self.score	=	0
				
				def	add_score(self,	score):
								self.score	+=	score
#	Usage
ENEMY_DESTROYED_SCORE	=	10
game	=	Game()
game.add_score(ENEMY_DESTROYED_SCORE)
Benefits
Open/Closed	Principle
Catch	'em	all!
Catch	'em	all!	
1.	 Only	one	level	of	indentation	per	method,
2.	 Do	not	use	else	keyword,
3.	 Wrap	primitive	types	if	it	has	behavior,
4.	 Only	one	dot	per	line,
5.	 Don’t	abbreviate,
6.	 Keep	your	entities	small,
7.	 No	more	than	two	instance	variable	per	class,
8.	 First	Class	Collections,
9.	 Do	not	use	accessors
Catch	'em	all!	
1.	 Only	one	level	of	indentation	per	method,
2.	 Do	not	use	else	keyword,
3.	 Wrap	primitive	types	if	it	has	behavior,
4.	 Only	one	dot	per	line,
5.	 Don’t	abbreviate,
6.	 Keep	your	entities	small,
7.	 No	more	than	two	instance	variable	per	class,
8.	 First	Class	Collections,
9.	 Do	not	use	accessors
10.	 ???
11.	 PROFIT!
Homework
Create	new	project	up	to
1000	lines	long
Apply	presented	rules	as
strictly	as	possible
Draw	your	own	conculsions
Customize	these	rules
Final	thoughts
These	are	not	best	practices
These	are	just	guidelines
Use	with	caution!
Questions?
Links
https://en.wikipedia.org/wiki/Calisthenics
https://www.cs.helsinki.fi/u/luontola/tdd-
2009/ext/ObjectCalisthenics.pdf
https://pragprog.com/book/twa/thoughtworks-anthology
https://github.com/gennad/Design-Patterns-in-Python
https://en.wikipedia.org/wiki/Law_of_Demeter
https://www.quora.com/Is-it-true-that-a-good-
programmer-uses-fewer-if-conditions-than-an-amateur
Thank	you!

More Related Content

PDF
Object Calisthenics (Code Europe 2017)
PDF
Object calisthenics (PyCon Poland 2016)
PPTX
Palestra 2 sobre o pau-brasil ( Projeto Poupança Verde )
PDF
Encouraging Engagement on Standardized Testing
PPTX
Healthy Heart Imaging ppt marketing USE THIS ONE
PDF
Present simple tense
PPTX
Using PGP for securing the email
DOCX
Ma trận và đề kiểm tra môn Toán học kì 2 lớp 4 theo thông tư 22
Object Calisthenics (Code Europe 2017)
Object calisthenics (PyCon Poland 2016)
Palestra 2 sobre o pau-brasil ( Projeto Poupança Verde )
Encouraging Engagement on Standardized Testing
Healthy Heart Imaging ppt marketing USE THIS ONE
Present simple tense
Using PGP for securing the email
Ma trận và đề kiểm tra môn Toán học kì 2 lớp 4 theo thông tư 22

Viewers also liked (20)

PDF
Edición perfil estudiante
PPT
operating system
PPTX
Tipologia y caracter
DOCX
Planeación (cuidemos nuestra ciudad) (1)
PPTX
Utilizing social media to sustain your club - Soroptimist edition
DOCX
5 mathematic03
PDF
Object calisthenics (PHPCon Poland 2016)
PPTX
Dulce caraballo arquitectura barroc
PPTX
Αερόβια -αναερόβια ασκηση
PPT
Lesiones cuadro comparativo
PPTX
Haemangioma
PDF
REVISTA PSICOLOGIA CLINICA
PPTX
Complessità, Flessibilità, Semplessità
PPTX
Measuring Learning Outcomes
DOCX
Planeacion camino a la escuela (1)
PPTX
Intoxicación por acetaminofén y escopolamina
TXT
Ingresantes a la UNT sede Trujillo grupo Ciencias
PDF
Listados escritura 5 b
 
PDF
Listados escritura 5 a
 
PPTX
Minerales de la tecnología
Edición perfil estudiante
operating system
Tipologia y caracter
Planeación (cuidemos nuestra ciudad) (1)
Utilizing social media to sustain your club - Soroptimist edition
5 mathematic03
Object calisthenics (PHPCon Poland 2016)
Dulce caraballo arquitectura barroc
Αερόβια -αναερόβια ασκηση
Lesiones cuadro comparativo
Haemangioma
REVISTA PSICOLOGIA CLINICA
Complessità, Flessibilità, Semplessità
Measuring Learning Outcomes
Planeacion camino a la escuela (1)
Intoxicación por acetaminofén y escopolamina
Ingresantes a la UNT sede Trujillo grupo Ciencias
Listados escritura 5 b
 
Listados escritura 5 a
 
Minerales de la tecnología
Ad

Similar to Object Calisthenics (PyCon Slovakia 2017) (20)

PPT
Sep 15
PPT
Core java Basics
PPT
Sep 15
PDF
Weaponizing Neural Networks. In your browser!
PDF
Object Calisthenics
PDF
Introduction to the Android NDK
PPTX
Intro to iOS: Object Oriented Programming and Objective-C
PPT
Java Course — Mastering the Fundamentals
PPTX
DevOps. If it hurts, do it more often.
PPTX
GOTO Night with Charles Nutter Slides
PPT
Core_java_ppt.ppt
PDF
Method Swizzling with Objective-C
PPT
Presentation to java
PPTX
Python basic
PPT
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
PDF
Clean Code 2
PDF
Core java part1
PPT
JAVA BASICS
PDF
Python for Image Understanding: Deep Learning with Convolutional Neural Nets
Sep 15
Core java Basics
Sep 15
Weaponizing Neural Networks. In your browser!
Object Calisthenics
Introduction to the Android NDK
Intro to iOS: Object Oriented Programming and Objective-C
Java Course — Mastering the Fundamentals
DevOps. If it hurts, do it more often.
GOTO Night with Charles Nutter Slides
Core_java_ppt.ppt
Method Swizzling with Objective-C
Presentation to java
Python basic
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
Clean Code 2
Core java part1
JAVA BASICS
Python for Image Understanding: Deep Learning with Convolutional Neural Nets
Ad

More from Paweł Lewtak (8)

PDF
Jak rozwalić dowolny projekt w 10 prostych krokach
PDF
Good project from scratch - from developer's point of view
PDF
Long-term IT projects
PDF
2nd hardest problem in computer science
PDF
Improve your developer's toolset
PDF
2nd hardest thing in computer science
PDF
2nd hardest problem in computer science
PDF
2nd hardest problem in computer science
Jak rozwalić dowolny projekt w 10 prostych krokach
Good project from scratch - from developer's point of view
Long-term IT projects
2nd hardest problem in computer science
Improve your developer's toolset
2nd hardest thing in computer science
2nd hardest problem in computer science
2nd hardest problem in computer science

Recently uploaded (20)

PDF
Ableton Live Suite for MacOS Crack Full Download (Latest 2025)
PDF
How Tridens DevSecOps Ensures Compliance, Security, and Agility
PPTX
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
PDF
EaseUS PDF Editor Pro 6.2.0.2 Crack with License Key 2025
PDF
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
PDF
AI Guide for Business Growth - Arna Softech
PDF
Topaz Photo AI Crack New Download (Latest 2025)
PPTX
assetexplorer- product-overview - presentation
PDF
Time Tracking Features That Teams and Organizations Actually Need
PDF
DNT Brochure 2025 – ISV Solutions @ D365
PPTX
Oracle Fusion HCM Cloud Demo for Beginners
PDF
Salesforce Agentforce AI Implementation.pdf
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PPTX
Tech Workshop Escape Room Tech Workshop
PPTX
WiFi Honeypot Detecscfddssdffsedfseztor.pptx
PDF
Microsoft Office 365 Crack Download Free
PDF
AI/ML Infra Meetup | Beyond S3's Basics: Architecting for AI-Native Data Access
PDF
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
PPTX
GSA Content Generator Crack (2025 Latest)
PDF
Types of Token_ From Utility to Security.pdf
Ableton Live Suite for MacOS Crack Full Download (Latest 2025)
How Tridens DevSecOps Ensures Compliance, Security, and Agility
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
EaseUS PDF Editor Pro 6.2.0.2 Crack with License Key 2025
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
AI Guide for Business Growth - Arna Softech
Topaz Photo AI Crack New Download (Latest 2025)
assetexplorer- product-overview - presentation
Time Tracking Features That Teams and Organizations Actually Need
DNT Brochure 2025 – ISV Solutions @ D365
Oracle Fusion HCM Cloud Demo for Beginners
Salesforce Agentforce AI Implementation.pdf
Why Generative AI is the Future of Content, Code & Creativity?
Tech Workshop Escape Room Tech Workshop
WiFi Honeypot Detecscfddssdffsedfseztor.pptx
Microsoft Office 365 Crack Download Free
AI/ML Infra Meetup | Beyond S3's Basics: Architecting for AI-Native Data Access
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
GSA Content Generator Crack (2025 Latest)
Types of Token_ From Utility to Security.pdf

Object Calisthenics (PyCon Slovakia 2017)