Clean Code - by Hussain
Clean Code - by Hussain
Hushen Savani
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
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
Syntax Checked
Syntax Highlighting
JavaScript HTML CSS
Separation of Concern
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
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
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
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
No error prone
IntelliSense Support
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
CLEAN
Conditions – Table Driven Methods
DIRTY CLEAN
insurance_rate_table
Conditions – Table Driven Methods
DIRTY CLEAN
insurance_rate_table
Duplication
Excessive Indentation
Unclear Intent
> 1 task
Functions – Duplication
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.
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
Easy to understand
Easy to test
CLEAN
Functions – Too Long?
Functions – Too Long?
Symptoms of Long Functions
Scrolling required
Hard to digest
Functions – Too Long?
Guidelines
Module
Chapter
Package 1 Package 2
Heading 1 Heading 2
Class 1 Class 2 Class 1 Class 2
• 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
CLEAN
Apology Comments
DIRTY
• Don't apologize
• Fix it before commit/merge
• Add a TODO Marker if you must
Warning Comments
DIRTY
Common Causes
Risk aversion
Hoarding mentality
Comments – Zombie Code
A mental checklist
Clean it for you and your team, not for the future developers
Broken
Windows
Theory
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