SlideShare une entreprise Scribd logo
1  sur  40
Télécharger pour lire hors ligne
SIMPLIFYING
CODE
MONSTER TO ELEGANT
IN N<5 STEPS
Tute Costa - @tutec
WE'LL LEARN HOW TO
TRANSFORM THIS
// fax
if (!empty($this->post['fax'])) {
$site->fax = $this->post['fax'][0];
}
// Facebook & Twitter
if ($this->post['social_media']) {
if (!empty($this->post['facebook'])) {
$facebookURL = $this->post['facebook'];
if (strpos($this->post['facebook'], 'http://') === fal
$facebookURL = "http://" . $this->post['facebook'];
}
$site->facebook_url = $facebookURL;
}
if (!empty($this->post['twitter'])) {
$twitterURL = $this->post['twitter'];
if (strpos($this->post['twitter'], 'http://') === fals
Into THIS
current_user
.public_profiles
.update(params)
ABOUT YOU
ABOUT TUTE
ABOUT TUTE
ABOUT TUTE
ABOUT TUTE
ABOUT TUTE
Alright if we'll go all technical I'll say "bug".
2011/2012: CHEFSURFING
We wrote so much code.
Every 2 months complexity would bite us.
Stop-the-world. Test && Refactor.
Not predictable. Not sustainable.
2013: GENERAL ASSEMBLY
Rails app in BAD shape. But well tested.
I was told “refactor allthethings!“
Improved productivity week after week
I want to repeat (and improve!) this story.
PRECONDITION:
THERE'S TESTS
REFACTORING PATTERNS
1. Intention Revealing Method
2. Special Case Object
3. Replace Method with Method Object
4. Service Object
INTENTION REVEALING METHOD
Why it's called is more important than
how/what it does.
# Remove duplicates?
if hash[row[1]][date] != row[0]
# ...
if remove_duplicates?(row, date)
# ...
def remove_duplicates?(data, date)
INTENTION REVEALING METHOD
1. Add comments if code needs it
2. Transform comments into methods
Transform them syntactically, then create the method.
3. Comments are now code.
Code describes itself.
INTENTION REVEALING METHOD
git clone
http://github.com/tute/
refactoring-workshop
INTENTION REVEALING METHOD
<5 lines per method
No problem!
INTENTION REVEALING METHOD
It's arguably the easiest pattern.
But the hardest as well.
INTENTION REVEALING METHOD
RESOURCES
http://ntcoding.blogspot.com.ar/2011/05/clea
code-tricks-intention-revealing.html
http://www.codinghorror.com/blog/2008/07/
without-comments.html
http://c2.com/cgi/wiki?ExtractMethod
2. SPECIAL CASE OBJECTS
No more ifs or trys.
2. SPECIAL CASE OBJECTS
nil is a troublemaker.
Source of hard to trace exceptions:
Undefined method `email' for
nil:NilClass
session[:current_user] # => nil
if (false) then 1 end # => nil
empty_method() # => nil
2. SPECIAL CASE OBJECTS
A symbol is better than nil:
def current_user
User.find_by_id(params[:id]) ||
:guest_user
end
current_user.email
undefined method `email' for
:guest_user:Symbol
2. SPECIAL CASE OBJECTS
If there may be nilwe need to enclose it
with an if:
if current_user
"Ohai, #{current_user.email}!"
else
'Ohai, guest!'
end
2. SPECIAL CASE OBJECTS
Instead of nil, return a new object
class NullUser
def email
'guest'
end
end
def current_user
User.find(session[:user_id]) ||
NullUser.new
end
"Ohai, #{current_user.email}!"
2. SPECIAL CASE OBJECTS
RESOURCES
RubyTapas #112
http://devblog.avdi.org/2011/05/30/null-objec
falsiness/
http://martinfowler.com/eaaCatalog/specialC
http://www.cs.oberlin.edu/~jwalker/nullObjPa
http://nickknowlson.com/blog/2013/04/16/w
maybe-is-better-than-null/
3. REPLACE METHOD WITH METHOD OBJECT
How to refactor a GIGANTIC method
without getting lost in the cold night.
defrow_per_day_format(file_name)
file=File.openfile_name,'r:ISO-8859-1'
#hash[NivelConsistencia][date]=[[value,status]]
hash={'1'=>{},'2'=>{}}
dates=[]
str=''
CSV.parse(file,col_sep:';').eachdo|row|
nextifrow.empty?
nextifrow[0]=~/^///
date=Date.parse(row[2])
(13..43).eachdo|i|
measurement_date=date+(i-13)
#IfNumDiasDeChuvaisemptyitmeansnodata
value =row[7].nil??-99.9:row[i]
status=row[i+31]
hash_value=[value,status]
dates<<measurement_date
hash[row[1]][measurement_date]=hash_value
3. REPLACE METHOD WITH METHOD OBJECT
1/5. Look carefully at the code. Get scared.
defrow_per_day_format(file_name)
file=File.openfile_name,'r:ISO-8859-1'
#hash[NivelConsistencia][date]=[[value,status]]
hash={'1'=>{},'2'=>{}}
dates=[]
str=''
CSV.parse(file,col_sep:';').eachdo|row|
nextifrow.empty?
nextifrow[0]=~/^///
date=Date.parse(row[2])
(13..43).eachdo|i|
measurement_date=date+(i-13)
#IfNumDiasDeChuvaisemptyitmeansnodata
value =row[7].nil??-99.9:row[i]
status=row[i+31]
hash_value=[value,status]
dates<<measurement_date
hash[row[1]][measurement_date]=hash_value
end
end
3. REPLACE METHOD WITH METHOD OBJECT
1/4. Create a class with same initialization
arguments as BIG method
class FormatAtoB
def initialize(file_name)
@file_name = file_name
end
end
3. REPLACE METHOD WITH METHOD OBJECT
2/4. Copy & Paste the method's body in
the new class, with no arguments
class FormatAtoB
def initialize(file_name)
@file_name = file_name
end
def row_per_day_format
file = File.open file_name, 'r:ISO-8859-1'
# hash[NivelConsistencia][date] = [[value, status]]
hash = { '1' => {}, '2' => {} }
dates = []
str = ''
CSV.parse(file, col_sep: ';').each do |row|
next if row.empty?
next if row[0] =~ /^///
date = Date.parse(row[2])
(13..43).each do |i|
3. REPLACE METHOD WITH METHOD OBJECT
3/4. Replace original method with a call to
the new class
def row_per_day_format(file_name)
FormatAtoB.new(file_name).row_per_day_format
end
3. REPLACE METHOD WITH METHOD OBJECT
4/4. Apply "Intention Revealing Method" to
the class. Voilà.
class FormatAtoB
def initialize(file_name)
@file_name = file_name
end
def row_per_day_format
load_file_a
format_data
end
private
def load_file_a
# [...]
end
end
3. REPLACE METHOD WITH METHOD OBJECT
RESOURCES
http://www.refactoring.com/catalog/replaceM
http://confreaks.com/videos/1071-cascadiaru
refactoring
4. SERVICE OBJECTS
Decoupling different concerns
from chubby classes
4. SERVICE OBJECTS
IF WE ADD NEW FUNCTIONALITY TO AN OBJECT:
It couples to a new dependency
It loses cohesion
Testing gets harder and slower
We can't describe the model without
connectors "and"/"or". SRP.
4. SERVICE OBJECTS
If it's a domain concept, it's an Object.
If it's only an algorithm (no state) we call
it a Service.
4. SERVICE OBJECTS
RESOURCES
http://blog.codeclimate.com/blog/2012/10/17
ways-to-decompose-fat-activerecord-
models/#service-objects
http://railscasts.com/episodes/398-service-
objects
NEXT STEPS
Send Pull Requests to GitHub.
It's a gold mine:
sferik/rails_admin
Code Climate
TracksApp/tracks
Code Climate
NEXT STEPS: " "4 RULES
1. Classes of at most 100 lines of code
2. Methods of at most 5 lines of code
3. A method accepts at most 4 arguments
4. A controller instantiates only one object
WHY REFACTORING
Not only about aesthetics, but shared
understanding, performance.
We work with the tools with which we
work. We are users and creators.
If I have a bias I choose "over-
engineering". "Under-engineering" is
risky, expensive, and over-crowded.
-
EL FIN
@tutec github.com/tute

Contenu connexe

Tendances

Menu func-sh(1)
Menu func-sh(1)Menu func-sh(1)
Menu func-sh(1)
Ben Pope
 
Advance Techniques In Php
Advance Techniques In PhpAdvance Techniques In Php
Advance Techniques In Php
Kumar S
 
Dasar dasar network planning
Dasar dasar network planningDasar dasar network planning
Dasar dasar network planning
BagusSunantoA5
 
Python Usage (5-minute-summary)
Python Usage (5-minute-summary)Python Usage (5-minute-summary)
Python Usage (5-minute-summary)
Ohgyun Ahn
 
Selected Bash shell tricks from Camp CDL breakout group
Selected Bash shell tricks from Camp CDL breakout groupSelected Bash shell tricks from Camp CDL breakout group
Selected Bash shell tricks from Camp CDL breakout group
John Kunze
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
pugpe
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cython
Anderson Dantas
 

Tendances (20)

Menu func-sh(1)
Menu func-sh(1)Menu func-sh(1)
Menu func-sh(1)
 
Clang2018 class3
Clang2018 class3Clang2018 class3
Clang2018 class3
 
R で解く FizzBuzz 問題
R で解く FizzBuzz 問題R で解く FizzBuzz 問題
R で解く FizzBuzz 問題
 
Advance Techniques In Php
Advance Techniques In PhpAdvance Techniques In Php
Advance Techniques In Php
 
Elixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitElixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicit
 
Elixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitElixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicit
 
Elixir pattern matching and recursion
Elixir pattern matching and recursionElixir pattern matching and recursion
Elixir pattern matching and recursion
 
Refsim (R program)
Refsim (R program)Refsim (R program)
Refsim (R program)
 
Dasar dasar network planning
Dasar dasar network planningDasar dasar network planning
Dasar dasar network planning
 
Share test
Share testShare test
Share test
 
Python Usage (5-minute-summary)
Python Usage (5-minute-summary)Python Usage (5-minute-summary)
Python Usage (5-minute-summary)
 
Codigos
CodigosCodigos
Codigos
 
ERPsimulate_script
ERPsimulate_scriptERPsimulate_script
ERPsimulate_script
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to Elixir
 
Selected Bash shell tricks from Camp CDL breakout group
Selected Bash shell tricks from Camp CDL breakout groupSelected Bash shell tricks from Camp CDL breakout group
Selected Bash shell tricks from Camp CDL breakout group
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cython
 
Mr. E Kabayi(ZAPRA)2016..PDF
Mr. E Kabayi(ZAPRA)2016..PDFMr. E Kabayi(ZAPRA)2016..PDF
Mr. E Kabayi(ZAPRA)2016..PDF
 
MuseScore MusicHackDay Presentation
MuseScore MusicHackDay PresentationMuseScore MusicHackDay Presentation
MuseScore MusicHackDay Presentation
 
Functional perl
Functional perlFunctional perl
Functional perl
 

Similaire à Simplifying code monster to elegant in n 5 steps

R57shell
R57shellR57shell
R57shell
ady36
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Masahiro Nagano
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
Joe Jiang
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
qmmr
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
jhchabran
 
20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked about
Tatsuhiko Miyagawa
 
R57php 1231677414471772-2
R57php 1231677414471772-2R57php 1231677414471772-2
R57php 1231677414471772-2
ady36
 

Similaire à Simplifying code monster to elegant in n 5 steps (20)

R57shell
R57shellR57shell
R57shell
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
Extbase and Beyond
Extbase and BeyondExtbase and Beyond
Extbase and Beyond
 
distill
distilldistill
distill
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
 
Developing applications for performance
Developing applications for performanceDeveloping applications for performance
Developing applications for performance
 
Javascript
JavascriptJavascript
Javascript
 
Php functions
Php functionsPhp functions
Php functions
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
Functional Pe(a)rls version 2
Functional Pe(a)rls version 2Functional Pe(a)rls version 2
Functional Pe(a)rls version 2
 
20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked about
 
Creating a compiler in Perl 6
Creating a compiler in Perl 6Creating a compiler in Perl 6
Creating a compiler in Perl 6
 
The HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageThe HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup language
 
FMDB - SLC-Cocoaheads
FMDB - SLC-CocoaheadsFMDB - SLC-Cocoaheads
FMDB - SLC-Cocoaheads
 
Get into the FLOW with Extbase
Get into the FLOW with ExtbaseGet into the FLOW with Extbase
Get into the FLOW with Extbase
 
R57php 1231677414471772-2
R57php 1231677414471772-2R57php 1231677414471772-2
R57php 1231677414471772-2
 
Unix 5 en
Unix 5 enUnix 5 en
Unix 5 en
 

Dernier

notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Dernier (20)

notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 

Simplifying code monster to elegant in n 5 steps