SlideShare a Scribd company logo
1 of 45
Clean Code (ROR)
Md. Tauhidul Islam
Software Engineer
Nascenia Ltd.
Table of Content
Source Code Layout
Syntax
Comments
Source Code Layout
Indentation
Use two spaces per indentation level (aka soft tabs). No hard tabs.
# bad - four spaces
def some_method
do_something
end
# good - two space
def some_method
do_something
end
Line endings
Use Unix-style line endings. (*BSD/Solaris/Linux/OS X users are covered by
default, Windows users have to be extra careful.)
$ git config --global core.autocrlf true
Statements & Expressions
Don't use ; to separate statements and expressions. As a corollary - use one
expression per line.
# good
puts 'foobar'
puts 'foo'
puts 'bar'
puts 'foo', 'bar'
# bad
puts 'foobar';
puts 'foo'; puts 'bar'
Use spaces
Use spaces around operators, after commas, colons and semicolons.
The only exception is the exponent operator
sum = 1 + 2
a, b = 1, 2
class FooError < StandardError; end
# bad
e = M * c ** 2
# good
e = M * c**2
Use spaces
No spaces after (, [ or before ], ). Use spaces around { and before }
For hash literals two styles are considered acceptable
With interpolated expressions, there should be no padded-spacing inside the
braces.
{one: 1, two: 2}{ one: 1, two: 2 }
[1, 2, 3].each { |e| puts e }
# bad
"From: #{ user.name }"
# good
"From: #{user.name}"
Use spaces
No space after !
No space inside range literals
# bad
! something
# good
!something
# bad
1 .. 3
'a' … 'z'
# good
1..3
'a'...'z'
When-Case
Indent when as deep as case
# bad
case
when song.name == 'Misty'
puts 'Not again!'
when song.duration > 120
puts 'Too long!'
when Time.now.hour > 21
puts "It's too late"
else
song.play
end
# good
case
when song.name == 'Misty'
puts 'Not again!'
when song.duration > 120
puts 'Too long!'
when Time.now.hour > 21
puts "It's too late"
else
song.play
end
Alignment: assigning a conditional expression
When assigning the result of a conditional expression to a variable, preserve the
usual alignment of its branches
kind =
case year
when 1850..1889 then 'Blues'
when 1890..1909 then 'Ragtime'
when 1910..1929 then 'New Orleans Jazz'
when 1930..1939 then 'Swing'
when 1940..1950 then 'Bebop'
else 'Jazz'
end
result =
if some_cond
calc_something
else
calc_something_else
end
Empty lines
Use empty lines between method definitions and also to break up methods into
logical paragraphs internally
def some_method
data = initialize(options)
data.manipulate!
data.result
end
def some_method
result
end
Assigning default values to method parameters
Use spaces around the = operator when assigning default values to method
parameters
# bad
def some_method(arg1=:default, arg2=nil, arg3=[])
# do something...
End
# good
def some_method(arg1 = :default, arg2 = nil, arg3 = [])
# do something...
end
Align the parameters of a method call
When aligning parameters is not appropriate due to line-length constraints, single
indent for the lines after the first is also acceptable
def send_mail(source)
Mailer.deliver(
to: 'bob@example.com',
from: 'us@example.com',
subject: 'Important message',
body: source.text
)
end
def send_mail(source)
Mailer.deliver(to: 'bob@example.com',
from: 'us@example.com',
subject: 'Important message',
body: source.text)
end
Align the elements of array
Align the elements of array literals spanning multiple lines
# bad - single indent
menu_item = ['Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam',
'Baked beans', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam']
# good
menu_item = [
'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam',
'Baked beans', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam'
]
# good
menu_item =
['Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam',
'Baked beans', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam']
Add underscores to large numeric
Add underscores to large numeric literals to improve their readability
# bad - how many 0s are there?
num = 1000000
# good - much easier to parse for the human brain
num = 1_000_000
Use Rdoc and its conventions for API documentation. Don't put an empty line
between the comment block and the def
Limit lines to 80 characters
Avoid trailing whitespace
End each file with a newline
Syntax
Methods with parentheses
Use def with parentheses when there are parameters
# bad
def some_method()
# body omitted
end
# good
def some_method
# body omitted
end
# bad
def some_method_with_parameters param1, param2
# body omitted
end
# good
def some_method_with_parameters(param1, param2)
# body omitted
end
Optional arguments
Define optional arguments at the end of the list of arguments
# bad
def some_method(a = 1, b = 2, c, d)
puts "#{a}, #{b}, #{c}, #{d}"
end
# good
def some_method(c, d, a = 1, b = 2)
puts "#{a}, #{b}, #{c}, #{d}"
end
Parallel assignment
Avoid the use of parallel assignment for defining variables
# bad
a, b, c, d = 'foo', 'bar', 'baz', 'foobar'
# good
a = 'foo'
b = 'bar'
c = 'baz'
d = 'foobar'
a = 'foo'
b = 'bar'
a, b = b, a
puts a # => 'bar'
puts b # => 'foo'
Nested ternary operator
Use one expression per branch in a ternary operator. This also means that ternary
operators must not be nested
# bad
some_condition ? (nested_condition ? nested_something : nested_something_else) : something_else
# good
if some_condition
nested_condition ? nested_something : nested_something_else
else
something_else
end
Expressions which return a result
Leverage the fact that if and case are expressions which return a result
# good
result =
if condition
x
else
y
end
# bad
if condition
result = x
else
result = y
end
result = condition ? x : y
and - or
Always use && and || instead of “and” and “or”
# bad
if some_condition and some_other_condition
do_something
end
# good
if some_condition && some_other_condition
do_something
end
Condition of single-line body
Favor modifier if/unless usage when you have a single-line body
# bad
if some_condition
do_something
end
# good
do_something if some_condition
# another good option
some_condition && do_something
Avoid if for negative conditions
Favor unless over if for negative conditions (or control flow ||)
# bad
do_something if !some_condition
# bad
do_something if not some_condition
# good
do_something unless some_condition
# another good option
some_condition || do_something
unless with else
Do not use unless with else. Rewrite these with the positive case first
# good
if success?
puts 'success'
else
puts 'failure'
end
# bad
unless success?
puts 'failure'
else
puts 'success'
end
Parentheses around the condition
Don't use parentheses around the condition of an if/unless/while/until
# good
if x > 10
# body omitted
end
# bad
if (x > 10)
# body omitted
end
while/until: single-line body
Favor modifier while/until usage when you have a single-line body
# bad
while some_condition
do_something
end
# good
do_something while some_condition
while for negative conditions
Favor until over while for negative conditions
# bad
do_something while !some_condition
# good
do_something until some_condition
Parentheses with no arguments
Omit parentheses for method calls with no arguments
# bad
Kernel.exit!()
2.even?()
fork()
'test'.upcase()
# good
Kernel.exit!
2.even?
fork
'test'.upcase
Use the proc invocation shorthand when the invoked method is the only operation
of a block
# bad
names.map { |name| name.upcase }
# good
names.map(&:upcase)
do...end for block
Prefer {...} over do...end for single-line blocks. Avoid using {...} for multi-line blocks
# bad
names.select do |name|
name.start_with?('S')
end.map { |name| name.upcase }
# good
names.select { |name| name.start_with?('S')
}.map(&:upcase)
# bad
names.each do |name|
puts name
end
# good
names.each { |name| puts name }
Return keyword
Avoid return where not required for flow of control
# bad
def some_method(some_arr)
return some_arr.size
end
# good
def some_method(some_arr)
some_arr.size
end
Self keyword
Avoid self where not required. (It is only required when calling a self write
accessor.)
# good
def ready?
if last_reviewed_at > last_updated_at
worker.update(content, options)
self.status = :in_progress
end
status == :verified
end
# bad
def ready?
if self.last_reviewed_at > self.last_updated_at
self.worker.update(self.content, self.options)
self.status = :in_progress
end
self.status == :verified
end
Self assignment operators
Use shorthand self assignment operators whenever applicable
# good
x += y
x *= y
x **= y
x /= y
x ||= y
x &&= y
# bad
x = x + y
x = x * y
x = x**y
x = x / y
x = x || y
x = x && y
Initialize variables if nil
Use ||= to initialize variables only if they're not already initialized
# bad
name = name ? name : 'Bozhidar'
# bad
name = 'Bozhidar' unless name
# good - set name to 'Bozhidar', only if it's nil or false
name ||= 'Bozhidar'
Space before parenthesis of method params
Do not put a space between a method name and the opening parenthesis
# bad
f (3 + 2) + 1
# good
f(3 + 2) + 1
Comments
Comments
Good code is its own best documentation. As you're about to add a comment, ask
yourself, "How can I improve the code so that this comment isn't needed?"
Improve the code and then document it to make it even clearer.
-- Steve McConnell
Comments
Write self-documenting code and ignore the rest of this section. Seriously!
Write comments in English
Use one space between the leading # character of the comment and the text of
the comment
Keep existing comments up-to-date. An outdated comment is worse than no
comment at all
Avoid writing comments to explain bad code. Refactor the code to make it self-
explanatory
Superfluous comments
Avoid superfluous comments
# bad
counter += 1 # Increments counter by one.
Block comments
Don't use block comments
# bad
=begin
comment line
another comment line
=end
# good
# comment line
# another comment line
References
https://github.com/bbatsov/ruby-style-guide
Questions?

More Related Content

What's hot

Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for javamaheshm1206
 
Matching with Regular Expressions
Matching with Regular ExpressionsMatching with Regular Expressions
Matching with Regular Expressionsprimeteacher32
 
Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3Randy Scovil
 
A Quick Taste of C
A Quick Taste of CA Quick Taste of C
A Quick Taste of Cjeremyrand
 
Regular Expressions in PHP
Regular Expressions in PHPRegular Expressions in PHP
Regular Expressions in PHPAndrew Kandels
 
Ch5 Selection Statements
Ch5 Selection StatementsCh5 Selection Statements
Ch5 Selection StatementsSzeChingChen
 
Processing with Regular Expressions
Processing with Regular ExpressionsProcessing with Regular Expressions
Processing with Regular Expressionsprimeteacher32
 
Decision making and loop in C#
Decision making and loop in C#Decision making and loop in C#
Decision making and loop in C#Prasanna Kumar SM
 
Standards For Java Coding
Standards For Java CodingStandards For Java Coding
Standards For Java CodingRahul Bhutkar
 
Documenting with xcode
Documenting with xcodeDocumenting with xcode
Documenting with xcodeGoran Blazic
 
Ad hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and CatsAd hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and CatsPhilip Schwarz
 
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...Philip Schwarz
 
Doppl development iteration #7
Doppl development   iteration #7Doppl development   iteration #7
Doppl development iteration #7Diego Perini
 

What's hot (20)

Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
Matching with Regular Expressions
Matching with Regular ExpressionsMatching with Regular Expressions
Matching with Regular Expressions
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3
 
A Quick Taste of C
A Quick Taste of CA Quick Taste of C
A Quick Taste of C
 
Andrei's Regex Clinic
Andrei's Regex ClinicAndrei's Regex Clinic
Andrei's Regex Clinic
 
Regular Expressions in PHP
Regular Expressions in PHPRegular Expressions in PHP
Regular Expressions in PHP
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
String functions
String functionsString functions
String functions
 
Ch5 Selection Statements
Ch5 Selection StatementsCh5 Selection Statements
Ch5 Selection Statements
 
Processing with Regular Expressions
Processing with Regular ExpressionsProcessing with Regular Expressions
Processing with Regular Expressions
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
 
JAVASCRIPT - LinkedIn
JAVASCRIPT - LinkedInJAVASCRIPT - LinkedIn
JAVASCRIPT - LinkedIn
 
3 Datatypes
3 Datatypes3 Datatypes
3 Datatypes
 
Decision making and loop in C#
Decision making and loop in C#Decision making and loop in C#
Decision making and loop in C#
 
Standards For Java Coding
Standards For Java CodingStandards For Java Coding
Standards For Java Coding
 
Documenting with xcode
Documenting with xcodeDocumenting with xcode
Documenting with xcode
 
Ad hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and CatsAd hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and Cats
 
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
 
Doppl development iteration #7
Doppl development   iteration #7Doppl development   iteration #7
Doppl development iteration #7
 

Similar to Clean code

Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in StyleBhavin Javia
 
Ruby introduction part1
Ruby introduction part1Ruby introduction part1
Ruby introduction part1Brady Cheng
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on RailsMasymbol
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Languagezone
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoobirbal
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming LanguageRaghavan Mohan
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de JavascriptBernard Loire
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5thConnex
 
Part 2 in depth guide on word-press coding standards for css &amp; js big
Part 2  in depth guide on word-press coding standards for css &amp; js bigPart 2  in depth guide on word-press coding standards for css &amp; js big
Part 2 in depth guide on word-press coding standards for css &amp; js bigeSparkBiz
 
In-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTMLIn-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTMLeSparkBiz
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 

Similar to Clean code (20)

Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in Style
 
Ruby introduction part1
Ruby introduction part1Ruby introduction part1
Ruby introduction part1
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
Ruby Style Guide
Ruby Style GuideRuby Style Guide
Ruby Style Guide
 
Lập trình C
Lập trình CLập trình C
Lập trình C
 
Dsl
DslDsl
Dsl
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Javascript
JavascriptJavascript
Javascript
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 
Part 2 in depth guide on word-press coding standards for css &amp; js big
Part 2  in depth guide on word-press coding standards for css &amp; js bigPart 2  in depth guide on word-press coding standards for css &amp; js big
Part 2 in depth guide on word-press coding standards for css &amp; js big
 
In-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTMLIn-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTML
 
03-fortran.ppt
03-fortran.ppt03-fortran.ppt
03-fortran.ppt
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
test ppt
test ppttest ppt
test ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 

More from Nascenia IT

Introduction to basic data analytics tools
Introduction to basic data analytics toolsIntroduction to basic data analytics tools
Introduction to basic data analytics toolsNascenia IT
 
Communication workshop in nascenia
Communication workshop in nasceniaCommunication workshop in nascenia
Communication workshop in nasceniaNascenia IT
 
The Art of Statistical Deception
The Art of Statistical DeceptionThe Art of Statistical Deception
The Art of Statistical DeceptionNascenia IT
 
করোনায় কী করি!
করোনায় কী করি!করোনায় কী করি!
করোনায় কী করি!Nascenia IT
 
GDPR compliance expectations from the development team
GDPR compliance expectations from the development teamGDPR compliance expectations from the development team
GDPR compliance expectations from the development teamNascenia IT
 
Writing Clean Code
Writing Clean CodeWriting Clean Code
Writing Clean CodeNascenia IT
 
History & Introduction of Neural Network and use of it in Computer Vision
History & Introduction of Neural Network and use of it in Computer VisionHistory & Introduction of Neural Network and use of it in Computer Vision
History & Introduction of Neural Network and use of it in Computer VisionNascenia IT
 
Ruby on Rails: Coding Guideline
Ruby on Rails: Coding GuidelineRuby on Rails: Coding Guideline
Ruby on Rails: Coding GuidelineNascenia IT
 
iphone 11 new features
iphone 11 new featuresiphone 11 new features
iphone 11 new featuresNascenia IT
 
Software quality assurance and cyber security
Software quality assurance and cyber securitySoftware quality assurance and cyber security
Software quality assurance and cyber securityNascenia IT
 
Job Market Scenario For Freshers
Job Market Scenario For Freshers Job Market Scenario For Freshers
Job Market Scenario For Freshers Nascenia IT
 
Modern Frontend Technologies (BEM, Retina)
Modern Frontend Technologies (BEM, Retina)Modern Frontend Technologies (BEM, Retina)
Modern Frontend Technologies (BEM, Retina)Nascenia IT
 
CSS for Developers
CSS for DevelopersCSS for Developers
CSS for DevelopersNascenia IT
 
Big commerce app development
Big commerce app developmentBig commerce app development
Big commerce app developmentNascenia IT
 
Integrating QuickBooks Desktop with Rails Application
Integrating QuickBooks Desktop with Rails ApplicationIntegrating QuickBooks Desktop with Rails Application
Integrating QuickBooks Desktop with Rails ApplicationNascenia IT
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideNascenia IT
 
Ruby conf 2016 - Secrets of Testing Rails 5 Apps
Ruby conf 2016 - Secrets of Testing Rails 5 AppsRuby conf 2016 - Secrets of Testing Rails 5 Apps
Ruby conf 2016 - Secrets of Testing Rails 5 AppsNascenia IT
 
COREXIT: Microsoft’s new cross platform framework
COREXIT: Microsoft’s new cross platform frameworkCOREXIT: Microsoft’s new cross platform framework
COREXIT: Microsoft’s new cross platform frameworkNascenia IT
 
An overview on the Reddot Ruby Conf 2016, Singapore
An overview on the Reddot Ruby Conf 2016, SingaporeAn overview on the Reddot Ruby Conf 2016, Singapore
An overview on the Reddot Ruby Conf 2016, SingaporeNascenia IT
 

More from Nascenia IT (20)

Introduction to basic data analytics tools
Introduction to basic data analytics toolsIntroduction to basic data analytics tools
Introduction to basic data analytics tools
 
Communication workshop in nascenia
Communication workshop in nasceniaCommunication workshop in nascenia
Communication workshop in nascenia
 
The Art of Statistical Deception
The Art of Statistical DeceptionThe Art of Statistical Deception
The Art of Statistical Deception
 
করোনায় কী করি!
করোনায় কী করি!করোনায় কী করি!
করোনায় কী করি!
 
GDPR compliance expectations from the development team
GDPR compliance expectations from the development teamGDPR compliance expectations from the development team
GDPR compliance expectations from the development team
 
Writing Clean Code
Writing Clean CodeWriting Clean Code
Writing Clean Code
 
History & Introduction of Neural Network and use of it in Computer Vision
History & Introduction of Neural Network and use of it in Computer VisionHistory & Introduction of Neural Network and use of it in Computer Vision
History & Introduction of Neural Network and use of it in Computer Vision
 
Ruby on Rails: Coding Guideline
Ruby on Rails: Coding GuidelineRuby on Rails: Coding Guideline
Ruby on Rails: Coding Guideline
 
iphone 11 new features
iphone 11 new featuresiphone 11 new features
iphone 11 new features
 
Software quality assurance and cyber security
Software quality assurance and cyber securitySoftware quality assurance and cyber security
Software quality assurance and cyber security
 
Job Market Scenario For Freshers
Job Market Scenario For Freshers Job Market Scenario For Freshers
Job Market Scenario For Freshers
 
Modern Frontend Technologies (BEM, Retina)
Modern Frontend Technologies (BEM, Retina)Modern Frontend Technologies (BEM, Retina)
Modern Frontend Technologies (BEM, Retina)
 
CSS for Developers
CSS for DevelopersCSS for Developers
CSS for Developers
 
Big commerce app development
Big commerce app developmentBig commerce app development
Big commerce app development
 
Integrating QuickBooks Desktop with Rails Application
Integrating QuickBooks Desktop with Rails ApplicationIntegrating QuickBooks Desktop with Rails Application
Integrating QuickBooks Desktop with Rails Application
 
Shopify
ShopifyShopify
Shopify
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation Guide
 
Ruby conf 2016 - Secrets of Testing Rails 5 Apps
Ruby conf 2016 - Secrets of Testing Rails 5 AppsRuby conf 2016 - Secrets of Testing Rails 5 Apps
Ruby conf 2016 - Secrets of Testing Rails 5 Apps
 
COREXIT: Microsoft’s new cross platform framework
COREXIT: Microsoft’s new cross platform frameworkCOREXIT: Microsoft’s new cross platform framework
COREXIT: Microsoft’s new cross platform framework
 
An overview on the Reddot Ruby Conf 2016, Singapore
An overview on the Reddot Ruby Conf 2016, SingaporeAn overview on the Reddot Ruby Conf 2016, Singapore
An overview on the Reddot Ruby Conf 2016, Singapore
 

Recently uploaded

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 

Recently uploaded (20)

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 

Clean code

  • 1. Clean Code (ROR) Md. Tauhidul Islam Software Engineer Nascenia Ltd.
  • 2. Table of Content Source Code Layout Syntax Comments
  • 4. Indentation Use two spaces per indentation level (aka soft tabs). No hard tabs. # bad - four spaces def some_method do_something end # good - two space def some_method do_something end
  • 5. Line endings Use Unix-style line endings. (*BSD/Solaris/Linux/OS X users are covered by default, Windows users have to be extra careful.) $ git config --global core.autocrlf true
  • 6. Statements & Expressions Don't use ; to separate statements and expressions. As a corollary - use one expression per line. # good puts 'foobar' puts 'foo' puts 'bar' puts 'foo', 'bar' # bad puts 'foobar'; puts 'foo'; puts 'bar'
  • 7. Use spaces Use spaces around operators, after commas, colons and semicolons. The only exception is the exponent operator sum = 1 + 2 a, b = 1, 2 class FooError < StandardError; end # bad e = M * c ** 2 # good e = M * c**2
  • 8. Use spaces No spaces after (, [ or before ], ). Use spaces around { and before } For hash literals two styles are considered acceptable With interpolated expressions, there should be no padded-spacing inside the braces. {one: 1, two: 2}{ one: 1, two: 2 } [1, 2, 3].each { |e| puts e } # bad "From: #{ user.name }" # good "From: #{user.name}"
  • 9. Use spaces No space after ! No space inside range literals # bad ! something # good !something # bad 1 .. 3 'a' … 'z' # good 1..3 'a'...'z'
  • 10. When-Case Indent when as deep as case # bad case when song.name == 'Misty' puts 'Not again!' when song.duration > 120 puts 'Too long!' when Time.now.hour > 21 puts "It's too late" else song.play end # good case when song.name == 'Misty' puts 'Not again!' when song.duration > 120 puts 'Too long!' when Time.now.hour > 21 puts "It's too late" else song.play end
  • 11. Alignment: assigning a conditional expression When assigning the result of a conditional expression to a variable, preserve the usual alignment of its branches kind = case year when 1850..1889 then 'Blues' when 1890..1909 then 'Ragtime' when 1910..1929 then 'New Orleans Jazz' when 1930..1939 then 'Swing' when 1940..1950 then 'Bebop' else 'Jazz' end result = if some_cond calc_something else calc_something_else end
  • 12. Empty lines Use empty lines between method definitions and also to break up methods into logical paragraphs internally def some_method data = initialize(options) data.manipulate! data.result end def some_method result end
  • 13. Assigning default values to method parameters Use spaces around the = operator when assigning default values to method parameters # bad def some_method(arg1=:default, arg2=nil, arg3=[]) # do something... End # good def some_method(arg1 = :default, arg2 = nil, arg3 = []) # do something... end
  • 14. Align the parameters of a method call When aligning parameters is not appropriate due to line-length constraints, single indent for the lines after the first is also acceptable def send_mail(source) Mailer.deliver( to: 'bob@example.com', from: 'us@example.com', subject: 'Important message', body: source.text ) end def send_mail(source) Mailer.deliver(to: 'bob@example.com', from: 'us@example.com', subject: 'Important message', body: source.text) end
  • 15. Align the elements of array Align the elements of array literals spanning multiple lines # bad - single indent menu_item = ['Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Baked beans', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam'] # good menu_item = [ 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Baked beans', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam' ] # good menu_item = ['Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Baked beans', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam']
  • 16. Add underscores to large numeric Add underscores to large numeric literals to improve their readability # bad - how many 0s are there? num = 1000000 # good - much easier to parse for the human brain num = 1_000_000
  • 17. Use Rdoc and its conventions for API documentation. Don't put an empty line between the comment block and the def Limit lines to 80 characters Avoid trailing whitespace End each file with a newline
  • 19. Methods with parentheses Use def with parentheses when there are parameters # bad def some_method() # body omitted end # good def some_method # body omitted end # bad def some_method_with_parameters param1, param2 # body omitted end # good def some_method_with_parameters(param1, param2) # body omitted end
  • 20. Optional arguments Define optional arguments at the end of the list of arguments # bad def some_method(a = 1, b = 2, c, d) puts "#{a}, #{b}, #{c}, #{d}" end # good def some_method(c, d, a = 1, b = 2) puts "#{a}, #{b}, #{c}, #{d}" end
  • 21. Parallel assignment Avoid the use of parallel assignment for defining variables # bad a, b, c, d = 'foo', 'bar', 'baz', 'foobar' # good a = 'foo' b = 'bar' c = 'baz' d = 'foobar' a = 'foo' b = 'bar' a, b = b, a puts a # => 'bar' puts b # => 'foo'
  • 22. Nested ternary operator Use one expression per branch in a ternary operator. This also means that ternary operators must not be nested # bad some_condition ? (nested_condition ? nested_something : nested_something_else) : something_else # good if some_condition nested_condition ? nested_something : nested_something_else else something_else end
  • 23. Expressions which return a result Leverage the fact that if and case are expressions which return a result # good result = if condition x else y end # bad if condition result = x else result = y end result = condition ? x : y
  • 24. and - or Always use && and || instead of “and” and “or” # bad if some_condition and some_other_condition do_something end # good if some_condition && some_other_condition do_something end
  • 25. Condition of single-line body Favor modifier if/unless usage when you have a single-line body # bad if some_condition do_something end # good do_something if some_condition # another good option some_condition && do_something
  • 26. Avoid if for negative conditions Favor unless over if for negative conditions (or control flow ||) # bad do_something if !some_condition # bad do_something if not some_condition # good do_something unless some_condition # another good option some_condition || do_something
  • 27. unless with else Do not use unless with else. Rewrite these with the positive case first # good if success? puts 'success' else puts 'failure' end # bad unless success? puts 'failure' else puts 'success' end
  • 28. Parentheses around the condition Don't use parentheses around the condition of an if/unless/while/until # good if x > 10 # body omitted end # bad if (x > 10) # body omitted end
  • 29. while/until: single-line body Favor modifier while/until usage when you have a single-line body # bad while some_condition do_something end # good do_something while some_condition
  • 30. while for negative conditions Favor until over while for negative conditions # bad do_something while !some_condition # good do_something until some_condition
  • 31. Parentheses with no arguments Omit parentheses for method calls with no arguments # bad Kernel.exit!() 2.even?() fork() 'test'.upcase() # good Kernel.exit! 2.even? fork 'test'.upcase
  • 32. Use the proc invocation shorthand when the invoked method is the only operation of a block # bad names.map { |name| name.upcase } # good names.map(&:upcase)
  • 33. do...end for block Prefer {...} over do...end for single-line blocks. Avoid using {...} for multi-line blocks # bad names.select do |name| name.start_with?('S') end.map { |name| name.upcase } # good names.select { |name| name.start_with?('S') }.map(&:upcase) # bad names.each do |name| puts name end # good names.each { |name| puts name }
  • 34. Return keyword Avoid return where not required for flow of control # bad def some_method(some_arr) return some_arr.size end # good def some_method(some_arr) some_arr.size end
  • 35. Self keyword Avoid self where not required. (It is only required when calling a self write accessor.) # good def ready? if last_reviewed_at > last_updated_at worker.update(content, options) self.status = :in_progress end status == :verified end # bad def ready? if self.last_reviewed_at > self.last_updated_at self.worker.update(self.content, self.options) self.status = :in_progress end self.status == :verified end
  • 36. Self assignment operators Use shorthand self assignment operators whenever applicable # good x += y x *= y x **= y x /= y x ||= y x &&= y # bad x = x + y x = x * y x = x**y x = x / y x = x || y x = x && y
  • 37. Initialize variables if nil Use ||= to initialize variables only if they're not already initialized # bad name = name ? name : 'Bozhidar' # bad name = 'Bozhidar' unless name # good - set name to 'Bozhidar', only if it's nil or false name ||= 'Bozhidar'
  • 38. Space before parenthesis of method params Do not put a space between a method name and the opening parenthesis # bad f (3 + 2) + 1 # good f(3 + 2) + 1
  • 40. Comments Good code is its own best documentation. As you're about to add a comment, ask yourself, "How can I improve the code so that this comment isn't needed?" Improve the code and then document it to make it even clearer. -- Steve McConnell
  • 41. Comments Write self-documenting code and ignore the rest of this section. Seriously! Write comments in English Use one space between the leading # character of the comment and the text of the comment Keep existing comments up-to-date. An outdated comment is worse than no comment at all Avoid writing comments to explain bad code. Refactor the code to make it self- explanatory
  • 42. Superfluous comments Avoid superfluous comments # bad counter += 1 # Increments counter by one.
  • 43. Block comments Don't use block comments # bad =begin comment line another comment line =end # good # comment line # another comment line

Editor's Notes

  1. Source Code Layout Syntax Comments
  2. Whitespace might be (mostly) irrelevant to the Ruby interpreter, but its proper use is the key to writing easily readable code.