0% found this document useful (0 votes)
16 views107 pages

Clean Code - by Hussain

Clean Code
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views107 pages

Clean Code - by Hussain

Clean Code
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

Clean Code

Hushen Savani

Clean Code is a reader-focused programming style that produces software


that's easy to write, read and maintain.
What is Programming?
or

Why do we write code?


What is Programming?
Programming is the art of telling another human what one wants the
computer to do.
Donald Knuth

Any fool can write the code that a computer can understand.
Good programmers write code that humans can understand.
Martin Fowler
Why it is important to write clean code?
• Writing code is easy. But reading code is hard!
• Code is like writing a stand up comedy script. If you have to explain
it, it's not good.
Fast
• Technical Debt can kill your product.
• Short cuts can be harmful in long term. Boss
Smart
Developer
• Deadline vs. Quality Dirty Clean
• It's okay to be lazy, but smart.
• Don't be the bad example in your company.
Slow
Good Developer is like an Author!
• An author writes book/article/text professionally.
• Each line is proofread multiple time.
• Author writes in a structured manner.
• Programmers are no different. Module

Chapter
Package 1 Package 2

Heading 1 Heading 2 Class 1 Class 2 Class 1 Class 2

Paragraph Paragraph Paragraph Paragraph


Method 1 Method 2 Method 1 Method 2 Method 1 Method 2 Method 1 Method 2
1 2 1 2
Three Principles for Clean Code

Right tool for the job.

High signal to noise Ratio

Self-Documenting Code
Right tool for the job
Right tool for the job
Right tool for the job
Boundaries Matter
HTML in JS &
Inline Style
JS in HTML

JavaScript HTML CSS

Dynamic JS String in Java HTML in SQL


Java,
Node.js, SQL
Python

Dynamic SQL String in Java


Right tool for the job
Boundaries Matter
HTML in JS &
Inline Style Stay as much Native as Possible!!
JS in HTML

JavaScript HTML CSS

Dynamic JS String in Java HTML in SQL


Java,
Node.js, SQL
Python

Dynamic SQL String in Java


Right tool for the job
Boundaries Matter
HTML in JS &
Inline Style Stay as much Native as Possible!!
JS in HTML
Caching

Syntax Checked

Syntax Highlighting
JavaScript HTML CSS
Separation of Concern

Dynamic JS String in Java HTML in SQL Reusability


Java,
Node.js, SQL
Python

Dynamic SQL String in Java


High Signal to Noise Ratio
Maximize S to N Ratio
Signal – TED Rule
• Terse
• Expressive
• Do one thing

Noise
• High Complexity • Long Methods
• Excessive Indentation • Repetitive Code
• Ghost Code • Redundant Conditions
• Unnecessary Comments
• Poor variable names
• Huge Classes
High Signal to Noise Ratio
Maximize S to N Ratio
Signal – TED Rule S to N Ratio is important, because
• Terse your brain is the computer while
• Expressive
• Do one thing
reading the code...

Noise
• High Complexity • Long Methods
• Excessive Indentation • Repetitive Code
• Ghost Code • Redundant Conditions
• Unnecessary Comments
• Poor variable names
• Huge Classes
Self-Documenting Code

Clear Intent

Layers of Abstraction

Format for Readability

Favor Code over Comments


Naming Matters
DIRTY

CLEAN
Naming Classes
DIRTY
• Utility
• Common
• MyClass
• MyFunctions
• HussainsObjects
• KaptivateUser
• UserInfo

CLEAN
• User
• Account
• QueryBuilder
• ProductRepository
• AccountDTO
• OrderService
Naming Classes
DIRTY
• Utility Guidelines
• Common
Noun
• MyClass
• MyFunctions • It should be a thing
• HussainsObjects • Can be instantiated
• KaptivateUser
Be Specific
• UserInfo
• Smaller
• Cohesive Classes
CLEAN
Single Responsibility
• User
• Account • It should do one thing
• QueryBuilder
• ProductRepository Avoid Generic Suffix
• AccountDTO • ProductInfo
• OrderService • AccountInfo
Naming Methods – It should say it all
Say What??
• get
• process
• pending
• doIt
• start
• onInit

Perfect
• getRegisteredUsers
• isValidDate
• importTemplate
• sendEmail
• processArchivedOrders
• startApplication
Naming Methods – Warning Signs
Watch out for
• And
• If
• Or

EXAMPLE,
• saveAndEmail
• loadAndPrint
• processOrDeny
• saveAndEmailIfUserFound
Naming Methods – Watch for Side Effects
Watch out for
• checkPassword – should not logout user
• isValidUser – should not save user
• createOrder – should not send email
• login – should not audit data
• getUser – should not update user info
Abbreviations
• We are not in 80's
• Storage is cheaper like never before
• We need more readability than saving space
Naming Variables – Booleans
DIRTY CLEAN
• open • isOpen
• start • isStarted
• status • isActive
• login • loggedIn

Boolean variables should sound like true/false questions


Naming Variables – Maintain symmetry

When dealing with state variables that toggles, be symmetrical

DIRTY CLEAN
• on <-> disable • on <-> off
• quick <-> slow • fast <-> slow
• lock <-> open • lock <-> unlock
• slow <-> max • min <-> max
Day-1 Ended
Conditions
Conditions – Booleans Comparison
DIRTY CLEAN
Conditions – Assign Booleans Implicitly
DIRTY CLEAN
Conditions – Assign Booleans Implicitly
DIRTY CLEAN

Fewer lines

No separate initialization

No repetition

Reads like natural speech


Conditions – Don't be Anti-negative
DIRTY
Conditions – Don't be Anti-negative
DIRTY CLEAN

Use positive conditionals


Conditions – Ternary is elegant
DIRTY CLEAN

Don't
Repeat
Yourself
Conditions – Don't be "Stringly" typed
DIRTY
Be "Strongly" typed

CLEAN
Conditions – Don't be "Stringly" typed
DIRTY
Be "Strongly" typed

CLEAN

Strongly typed -> No typos

No error prone

IntelliSense Support

Documents the states

Searchable
Conditions – Magic Numbers

DIRTY CLEAN

DIRTY CLEAN
Conditions – Complex Conditions

Intermediate Variables

Encapsulate in a function
Conditions – Complex Conditions
Intermediate Variables
DIRTY
What question is this trying to answer?

CLEAN
Conditions – Complex Conditions
Encapsulate Complex Conditions
DIRTY

CLEAN
Conditions – Complex Conditions
Encapsulate Complex Conditions
DIRTY

Principle: Favor expressive code over comments


CLEAN
Conditions – Polymorphism over Enums
DIRTY CLEAN
Conditions – Polymorphism over Enums
DIRTY CLEAN
Conditions – Polymorphism over Enums
Conditions – Be declarative than iterative
DIRTY

CLEAN
Conditions – Table Driven Methods
DIRTY CLEAN
insurance_rate_table
Conditions – Table Driven Methods
DIRTY CLEAN
insurance_rate_table

Great for dynamic logic

Avoids hard coding

Write less code

Easily changeable without code change or deployment


Functions
When to create a function?

Duplication

Excessive Indentation

Unclear Intent

> 1 task
Functions – Duplication

DRY: Don’t repeat yourself

Code is a liability

Less is more
Functions – Duplication
Look for Patterns
Functions – Duplication
Look for Patterns
Functions – Excessive Indentation
Functions – Excessive Indentation
Comprehension decreases beyond 3
levels of nested 'if' blocks as per a
study in 1986.

The Arrow Code


Functions – Excessive Indentation

SOLUTION

Extract Method

Return Early

Fail Fast
Excessive Indentation – Extract Method
Excessive Indentation – Return Early
Excessive Indentation – Return Early
Excessive Indentation – Fail Fast
Excessive Indentation – Fail Fast
Excessive Indentation – Fail Fast

Guard Conditions
Day-2 Ended
Functions – Convey Intent
DIRTY

CLEAN
Functions – Do one thing

Can you read a book if it has no paragraphs but all just flat text?
Functions – Do one thing

Advantages
Eases reading

Promotes reuse

Eases testing

Avoids side effects


Functions – How many parameters?
DIRTY

Strive for 0-3 parameters

Easy to understand

Easy to test

Helps assure function does one thing


Functions – How many parameters?
DIRTY

CLEAN
Functions – Too Long?
Functions – Too Long?
Symptoms of Long Functions

Too many whitespaces & comments

Scrolling required

Long function names with And, If, Or

Too many conditional branches

Hard to digest
Functions – Too Long?
Guidelines

Rarely be over 20 lines

Hardly ever over 100 lines

No more than 3 parameters


Classes
Classes are like headings in a book

Module

Chapter
Package 1 Package 2

Heading 1 Heading 2
Class 1 Class 2 Class 1 Class 2

Paragraph Paragraph Paragraph Paragraph


1 2 1 2 Method 1 Method 2 Method 1 Method 2 Method 1 Method 2 Method 1 Method 2
When to create a class?

New Concept • Abstract or Real World

Low Cohesion • Methods should relate

Promote Reuse • Small, targeted => Reuse

Reduce Complexity • Solve once, hide away

Clarify Parameters • Identify a group of data


Classes – High Cohesion
• High cohesion refers to how closely all the functions/methods in a class, or all
the code in a function, support a central purpose.
• Classes that contain strongly related functionalities are described as having high
cohesion
• The heuristic goal is to make cohesion as high as possible.
class
class DirtyClass class PrintService
EmailService
• checkEmail() • checkEmail() • printLetter()
• validateEmail() • validateEmail() • printAddress()
• sendEmail() • sendEmail()
• printLetter()
• printAddress()
Classes – High Cohesion
Then

Old Detroit Theatre,


Michigan
Classes – High Cohesion
Now

Old Detroit Theatre,


Michigan
Classes – High Cohesion
Class Responsibilities should be strongly related
• Enhances readability
• Increases likelihood of reuse
• Avoids attracting the lazy
Watch out for:
• Methods that don't interact with the rest of the class
• Fields that are only used by one method
• Classes that change often
Classes – Detecting low cohesive classes
DIRTY

• Utility
• Common
• MyClass
• MyFunctions
• HussainsObjects
Classes – Primitive Obsession
DIRTY

CLEAN
Classes – Primitive Obsession
DIRTY

CLEAN
Advantages
Helps reader conceptualize

Implecit->Explicit

Encapsulation

Aids maintainance
Classes – Principle of Proximity
• Strive to make code read top to bottom when possible.
• Keep related actions together
/* */

Comments
Comments
Comments

Prefer expressive
code over comments
Comments to Avoid
Redundant

Intent

Apology

Warning

Zombie Code

Divider

Brace Tracker

Defect Log
Redundant Comments
DIRTY
Redundant Comments
DIRTY

Assume that users can read

Don't repeat yourself


Intent Comments
DIRTY

CLEAN
Apology Comments
DIRTY

• Don't apologize
• Fix it before commit/merge
• Add a TODO Marker if you must
Warning Comments
DIRTY

• To avoid warning, refactor!!


Comments – Zombie Code
Comments – Zombie Code
DIRTY
Comments – Zombie Code

Common Causes

Risk aversion

Hoarding mentality
Comments – Zombie Code
A mental checklist

• About to comment out code? Ask yourself:


• When, if ever, would this be uncommented?
• Can I just get it from GIT later on?
• Is this an incomplete work to be done in other branch?
• Is that a configuration that can be added to a config file?
• Did I refactor out this code and it's outdated now?
Divider Comments
DIRTY
Brace Tracker Comments
DIRTY
Defect Log Comments
DIRTY
Good Comments
CLEAN
Logs
Clean Logs
https://iamhussa.in/logging-with-context
Stay Clean
When to refactor to Clean Code?

Clean it for you and your team, not for the future developers

You are finding it difficult to comprehend or change

You have sufficient time and knowledge to test the code


Accept No Broken Windows

Broken
Windows
Theory

March 1982 – Atlantic Building


Code Reviews

Promote Proactive Cleanliness

Strive for Readability

Set Guidelines and Expectations


Pair Programming

Real-time code reviews

Increase code quality

Refactoring easier
The Volunteer Rule

Always leave the code you're editing a little better than you found it.
Robert C. Martin
Resources
https://mooc.aptikom.or.id/pluginfile.php/1174/mod_resource/content/1/Clean%20Code_%20A%20Handboo
k%20of%20Agile%20Software%20C%20-%20Robert%20C.%20Martin.pdf
Thank You
Questions?

@hussainsavaani

You might also like