SlideShare a Scribd company logo
The Art of Readable Code
Simple and Practical Techniques for Writing Better Code
Code Should Be Easy to
Understand
for (Node* node = list->head; 

node != NULL; 

node = node->next) {

Print(node->data);

}

Node* node = list->head;	
if (node == NULL) return;	
while (node->next != NULL) {	
Print(node->data);	
node = node->next;	
}	
if (node != NULL) {	
Print(node->data);	
}
(_=[_=[]][(_+!![])[$=(!!_/!!_)]+(!!$+_)[-~-~$]+'v'+(!
(_/_)+[])[-~-~$]+(!([]/($))+[])[$]+([]+!_)[-~-~$]+(!!
{}+[])[-~-~$]])()[(!({}+_)+_)[$]+(!({}+[])+[])[-~$]+
((''+!![]+''))[-~-~$]+(!![]+'')[$]+((!!_+[]))[$-$]]($/
$);

alert(1)
Key Idea
• Code should be easy to understand.	

• Minimize the time it would take for
someone else to understand it.
Is Smaller Always Better?
Conflict with Other Goals?
Easy to Test

Well-Architected

Code Efficient

Highly Maintainable

…
Three Levels
• Surface Level	

• Loops & Logic	

• Reorganizing
Surface-Level
Packing Information into
Names
• Specific	

• Avoid Generic Names	

• Prefer Concrete Names	

• Extra Information	

• Length vs Meaning	

• Formatting
Word

Alternative

send

deliver, dispatch, announce, distribute, route

find

search, extract, locate, recover

start

launch, create, begin, open

make

create, set up, build, generate, compose, add, new
Naming Conventions
• Noun for variable name, object name, class
name, property name, arguments name	


• Verb for function name, method name
Case
maptypeCtrl.streetMapMgr(true);

A Better One
maptypeCtrl.showStreetMap();
Length
• Shorter names for shorter scopes	

• Longer names for larger scopes
Names That Can’t Be
Misconstrued
Key Idea

• Asking yourself, “What other meanings

could someone interpret from this name?”
• Prefer min and max for(inclusive) limits	

• Naming booleans	

• Matching expectations of Users
Case
var read_password = true;

A Better One
var need_password = true;	
var user_authenticated = true;
Case
map.getBestMap(points);

A Better One
map.setViewport(points);
Aesthetic
Aesthetic
• Use consistent layout.	

• Make similar code look similar.	

• Group related lines of code into blocks.
Knowing What to
Comment
Key Idea

• The purpose of commenting is to help the
reader know as much as the writer did.
What NOT to Comment
• KEY IDEA:Don’t comment on the facts

that can be derived quickly from the code
itself
Case
!

// 延时关闭信息窗⼝口	
setTimeout(function(){	
map.closeInfoWindow();	
}, 100);
Case
!

// 添加为全局对象;

window.mapSubway = me;
Recording Your Thoughts
• Include “Director Commentary”	

• Comment the Flaws in Your Code	

• Comment on Your Constants
Put Yourself in the
Reader’s Shoes
• Anticipating Likely Questions	

• Advertising Likely Pitfalls	

• “Big Picture”	

• Summary
Precise & Compact
Comments
• Keep Comments Compact	

• Describe Function Behavior Precisely	

• Use Examples	

• State the Intent
Case
// 返回⽂文件⾏行数

int CountLines(string filename) {...}

A Better One
// 计算换⾏行符'n'的个数

int CountLines(string filename) {...}
Case
if (mode ==
var a =
b =
minutes

"bustime") {

minutes % 10, 

parseInt(minutes / 10);

= a != 0 ? 

(a > 5 ? 

(++b * 10) : b ?

(b * 10) : 5): 

minutes;

Need Examples!
Loops & Logic
Making Control Flow
Easy to Read
KEY IDEA

• Make your logic as “natural” as possible
Case
if (length >= 10)	
if (10 <= length)

while (bytes_received < bytes_expected)	
while (bytes_expected > bytes_received)
Order of if/else Blocks
• Positive First	

• Simpler First	

• Interesting First
?: Conditional Expression

• Often Less Readable
KEY IDEA
• Minimize the time needed for someone to
understand it instead of minimizing the
number of lines.
ADVICE

• Use ternary ?: only for the simplest cases.
• Avoid do/while Loops	

• Returning Early form a Function	

• Minimize Nesting	

• Flow of Execution
Breaking Down Giant
Expressions
• Explaining Variables	

• Summary Variables	

• Use De Morgan’s Laws	

• Break Down Giant Statements
Case
if (line.split(':')[0] == 'admin')

var userName = line.split(':')[0];

if (userName == 'admin')
Case
if (navigator.userAgent.indexOf('UC') > -1)	
if (navigator.userAgent.indexOf('UC') == -1)	

var isUC =
navigator.userAgent.indexOf('UC') > -1;	
if (isUC)	
if (!isUC)
Case
var update_highlight = function (message_num) {	
if ($("#vote_value" + message_num).html() === "Up") {	
$("#thumbs_up" + message_num).addClass("highlighted");	
$("#thumbs_down" + message_num).removeClass("highlighted");	
} else if ($("#vote_value" + message_num).html() === "Down") {	
$("#thumbs_up" + message_num).removeClass("highlighted");	
$("#thumbs_down" + message_num).addClass("highlighted");	
} else {	
$("#thumbs_up" + message_num).removeClass("highighted");	
$("#thumbs_down" + message_num).removeClass("highlighted");	
}	
};
var update_highlight = function (message_num) {	
var thumbs_up = $("#thumbs_up" + message_num);	
var thumbs_down = $("#thumbs_down" + message_num);	
var vote_value = $("#vote_value" + message_num).html();	
var hi = "highlighted";	


if (vote_value === "Up") {	
thumbs_up.addClass(hi);	
thumbs_down.removeClass(hi);	
} else if (vote_value === "Down") {	
thumbs_up.removeClass(hi);	
thumbs_down.addClass(hi);	
} else {	
thumbs_up.removeClass(hi);	
thumbs_down.removeClass(hi);	
}	
};
Variables
Problems
• More variables, harder to keep track of them	

• Bigger variable’s scope, longer you have to keep
track of them	


• More often variable changes, harder to keep
track of its current value
Eliminating Variables
• Useless Temporary Variables	

• Eliminating Intermediate Results	

• Eliminating Control Flow Variables
Case
var remove_one = function(array, value_to_remove) {

var index_to_remove = null;

for (var i = 0; i < array.length; i ++) {

if (array[i] === value_to_remove) {

index_to_remove = i;

break;

}

}

if (index_to_remove !== null) {

array.slice(index_to_remove, 1);

}

}
Case
var remove_one = function(array, value_to_remove) {

for (var i = 0; i < array.length; i ++) {

if (array[i] === value_to_remove) {

array.slice(i, 1);

return;

}

}

}
Shrink the Scope

• Make variable visible by as few lines of code
as possible.
Prefer write-once
variables
• KEY IDEA: The more places a variable is
manipulated, the harder it is to reason
about its current value.
Reorganizing
Extracting Unrelated
Subproblems
Case
function findClosestLocation(latLng, latLngs) {

var closest;

var closest_dist = Number.MAX_VALUE;



for each latlng in latLngs, calculate the

distance, if new distance is shorter than 

current, set closest to the new latlng





return closest;

}
What is the unrelated
subproblem?

Compute the
spherical distance
• Pure Utility Code	

• General-Purpose Code	

• Project-Specific Functionality	

• Simplifying an Existing Interface
Case
Cookie
setCookie(key, value);	
getCookie(key);	
deleteCookie(key);	
hasCookie(key);
Further Reading
One Task at a Time
KEY IDEA

• Code should be organized so that it’s doing
only one task at a time.
Turning Thoughts into Code
• Describe what code needs to do, in plain
English(we should use Chinese)	


• Pay attention to key words and phrases	

• Write your code to match description
Case
$is_admin = is_admin_request();

if ($document) {

if (!$is_admin 

&& ($document['username']) != $_SESSION['username'])){

return not_authorized();

}

} else {

if (!$is_admin) {

return not_authorized();

}

}



// continue rendering the page ...
Case
if (is_admin_request()) {

// authorized

} elseif ($document 

&& $document['username']) != 

$_SESSION['username'])) {

// authorized


} else {

return not_authorized();

}



// continue rendering the page ...
Writing Less Code
KEY IDEA
• The most readable code is

NO CODE AT ALL
Case

• Calculating Distance Between Two
Locations
• Don’t implement code that you won’t need	

• Simplify requirements	

• Keep your codebase small	

• Be familiar with Libraries around you
Further Reading
Further Reading
Further Reading
Q&A

More Related Content

What's hot

Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
jgrahamc
 
Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)
Scott Wlaschin
 
Golang
GolangGolang
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
C4Media
 
The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)
Scott Wlaschin
 
Python Basics
Python BasicsPython Basics
Python Basics
primeteacher32
 
LLVM Instruction Selection
LLVM Instruction SelectionLLVM Instruction Selection
LLVM Instruction Selection
Shiva Chen
 
UI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QMLUI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QML
Emertxe Information Technologies Pvt Ltd
 
LLVM Register Allocation
LLVM Register AllocationLLVM Register Allocation
LLVM Register Allocation
Wang Hsiangkai
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
Ishin Vin
 
クロージャデザインパターン
クロージャデザインパターンクロージャデザインパターン
クロージャデザインパターン
Moriharu Ohzu
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go lang
Amal Mohan N
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Scott Wlaschin
 
LLVM 總是打開你的心:從電玩模擬器看編譯器應用實例
LLVM 總是打開你的心:從電玩模擬器看編譯器應用實例LLVM 總是打開你的心:從電玩模擬器看編譯器應用實例
LLVM 總是打開你的心:從電玩模擬器看編譯器應用實例
National Cheng Kung University
 
Quine・難解プログラミングについて
Quine・難解プログラミングについてQuine・難解プログラミングについて
Quine・難解プログラミングについて
mametter
 
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an Overview
Roberto Casadei
 
Apache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystem
Kostas Saidis
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)
Thai Pangsakulyanont
 
DWARF Data Representation
DWARF Data RepresentationDWARF Data Representation
DWARF Data Representation
Wang Hsiangkai
 

What's hot (20)

Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)
 
Golang
GolangGolang
Golang
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
 
The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)
 
Python Basics
Python BasicsPython Basics
Python Basics
 
LLVM Instruction Selection
LLVM Instruction SelectionLLVM Instruction Selection
LLVM Instruction Selection
 
UI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QMLUI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QML
 
LLVM Register Allocation
LLVM Register AllocationLLVM Register Allocation
LLVM Register Allocation
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
クロージャデザインパターン
クロージャデザインパターンクロージャデザインパターン
クロージャデザインパターン
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go lang
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
 
LLVM 總是打開你的心:從電玩模擬器看編譯器應用實例
LLVM 總是打開你的心:從電玩模擬器看編譯器應用實例LLVM 總是打開你的心:從電玩模擬器看編譯器應用實例
LLVM 總是打開你的心:從電玩模擬器看編譯器應用實例
 
Quine・難解プログラミングについて
Quine・難解プログラミングについてQuine・難解プログラミングについて
Quine・難解プログラミングについて
 
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an Overview
 
The Internals of "Hello World" Program
The Internals of "Hello World" ProgramThe Internals of "Hello World" Program
The Internals of "Hello World" Program
 
Apache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystem
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)
 
DWARF Data Representation
DWARF Data RepresentationDWARF Data Representation
DWARF Data Representation
 

Similar to The Art Of Readable Code

CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35
Bilal Ahmed
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
Alex Payne
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
Hugo Gävert
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
Nate Abele
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
Nate Abele
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
Scalding big ADta
Scalding big ADtaScalding big ADta
Scalding big ADta
b0ris_1
 
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
BizTalk360
 
Couchbas for dummies
Couchbas for dummiesCouchbas for dummies
Couchbas for dummies
Qureshi Tehmina
 
Performance patterns
Performance patternsPerformance patterns
Performance patterns
Stoyan Stefanov
 
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun..."ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
Julia Cherniak
 
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
NoSQLmatters
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
Wim Godden
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
Wim Godden
 
Beyond php it's not (just) about the code
Beyond php   it's not (just) about the codeBeyond php   it's not (just) about the code
Beyond php it's not (just) about the code
Wim Godden
 
Hidden Gems in Swift
Hidden Gems in SwiftHidden Gems in Swift
Hidden Gems in Swift
Netguru
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)
Paul Chao
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
Wim Godden
 
Advanced Technology for Web Application Design
Advanced Technology for Web Application DesignAdvanced Technology for Web Application Design
Advanced Technology for Web Application DesignBryce Kerley
 
Gpu programming with java
Gpu programming with javaGpu programming with java
Gpu programming with java
Gary Sieling
 

Similar to The Art Of Readable Code (20)

CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Scalding big ADta
Scalding big ADtaScalding big ADta
Scalding big ADta
 
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
 
Couchbas for dummies
Couchbas for dummiesCouchbas for dummies
Couchbas for dummies
 
Performance patterns
Performance patternsPerformance patterns
Performance patterns
 
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun..."ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
 
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
Beyond php it's not (just) about the code
Beyond php   it's not (just) about the codeBeyond php   it's not (just) about the code
Beyond php it's not (just) about the code
 
Hidden Gems in Swift
Hidden Gems in SwiftHidden Gems in Swift
Hidden Gems in Swift
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
Advanced Technology for Web Application Design
Advanced Technology for Web Application DesignAdvanced Technology for Web Application Design
Advanced Technology for Web Application Design
 
Gpu programming with java
Gpu programming with javaGpu programming with java
Gpu programming with java
 

The Art Of Readable Code