SlideShare a Scribd company logo
1 of 28
Download to read offline
SIMPLIFYING 
CODE 
MONSTER TO ELEGANT 
IN N<5 STEPS 
Tute Costa - @tutec
REFACTORING PATTERNS 
(And all these buzz words.)
ABOUT TUTE
20**: STUDENT/FREELANCER 
I learned CS theory at school 
I practiced at home different languages 
I built small projects as a freelancer 
Learned web dev alongside good mentors
2011/2012: CHEFSURFING 
We wrote so much code. 
Every 2 months complexity would bite us. 
Stop-the-world. Refactor. 
Not predictable. Not sustainable.
CHEF SURFING FELT LIKE
2013: GENERAL ASSEMBLY 
Rails app in BAD shape. But well tested. 
I was told “refactor allthethings!“ 
Improved productivity week after week
GENERAL ASSEMBLY FELT 
LIKE
2014: THOUGHTBOT 
Code Quality is daily bread and butter 
We heavily prioritize what to build 
Technical Debt is not allowed 
Makes for developers and clients' 
happiness
THOUGHTBOT FEELS LIKE
ANOMALY 1: CODE DOESN'T READ WELL 
Before: 
if hash[row[1]][date] != row[0] 
# ... 
After: 
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. 
And the code describes itself.
INTENTION REVEALING METHOD 
Comments are now code. 
And the code describes itself. 
MASSIVE 
SUCCESS.
INTENTION REVEALING METHOD 
It's arguably the easiest pattern. 
But the hardest as well.
ANOMALY 2: WHAT IS NIL? 
Hint: it's a troublemaker. 
Source of hard to spot errors: 
Undefined method `name' for nil 
session[:current_user] # => nil 
session[:current_dinozauh] # => nil 
if (false) then 1 end # => nil 
empty_method() # => nil
ANOMALY 2: WHAT IS NIL? 
A symbol is better than nil: 
# In Ruby: 
# 'a' || 'b' # => 'a' 
# nil || 'b' # => 'b' 
# false || 'b' # => 'b' 
def current_user 
User.find_by_id(id) || :guest_user 
end 
current_user.name 
undefined method `name' for 
:guest_user:Symbol
ANOMALY 2: SO MANY IFS! 
If there may be nil we need to enclose it 
with an if: 
if current_user 
"Hi #{current_user.name}!" 
else 
"Hi guest!" 
end
PATTERN: NULL OBJECTS 
Instead of nil, return a new object 
class NullUser 
def name 
'guest' 
end 
end 
def current_user 
User.find_by_id(id) || 
NullUser.new 
end 
"Ohai, #{current_user.name}!"
ANOMALY 3: GINORMOUS METHOD 
class ExportJob 
# Instance variables 
# Many other methods 
# And... 
def row_per_day_format(file_name) 
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| 
measurement_date = date + (i-13) 
# If NumDiasDeChuva is empty it means no data 
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
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
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-# hash[NivelConsistencia][date] = [[value, hash = { '1' => {}, '2' => {} } 
dates = [] 
str = '' 
CSV.parse(file, col_sep: ';').each do |row|
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
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
REPLACE METHOD WITH METHOD OBJECT 
http://confreaks.com/videos/1071-cascadiaruby2012- 
therapeutic-refactoring
WE COVERED 
Intention Revealing Method 
Turns comments unnecessary. Code reads better. 
Null Objects 
Avoids nil objects and ifs. 
Replace Method with Method Object 
Refactor big methods at ease in a clean new container. 
QUESTIONS ABOUT THESE?
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, bug-chase, 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 
QUESTIONS ABOUT ANYTHING?

More Related Content

What's hot

Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à RubyMicrosoft
 
SproutCore is Awesome - HTML5 Summer DevFest
SproutCore is Awesome - HTML5 Summer DevFestSproutCore is Awesome - HTML5 Summer DevFest
SproutCore is Awesome - HTML5 Summer DevFesttomdale
 
jQuery Plugin Creation
jQuery Plugin CreationjQuery Plugin Creation
jQuery Plugin Creationbenalman
 
Introduccion app engine con python
Introduccion app engine con pythonIntroduccion app engine con python
Introduccion app engine con pythonsserrano44
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design PatternsRobert Casanova
 
Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)andrewnacin
 
Writing Software not Code with Cucumber
Writing Software not Code with CucumberWriting Software not Code with Cucumber
Writing Software not Code with CucumberBen Mabey
 
Hooked on WordPress: WordCamp Columbus
Hooked on WordPress: WordCamp ColumbusHooked on WordPress: WordCamp Columbus
Hooked on WordPress: WordCamp ColumbusShawn Hooper
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2RORLAB
 
Denver emberjs-sept-2015
Denver emberjs-sept-2015Denver emberjs-sept-2015
Denver emberjs-sept-2015Ron White
 
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRaimonds Simanovskis
 
16.mysql stored procedures in laravel
16.mysql stored procedures in laravel16.mysql stored procedures in laravel
16.mysql stored procedures in laravelRazvan Raducanu, PhD
 
Build a bot workshop async primer - php[tek]
Build a bot workshop  async primer - php[tek]Build a bot workshop  async primer - php[tek]
Build a bot workshop async primer - php[tek]Adam Englander
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax pluginsInbal Geffen
 
Powershell to the People #suguk
Powershell to the People #sugukPowershell to the People #suguk
Powershell to the People #sugukChris McKinley
 
How To Write a WordPress Plugin
How To Write a WordPress PluginHow To Write a WordPress Plugin
How To Write a WordPress PluginAndy Stratton
 
Rails for Beginners - Le Wagon
Rails for Beginners - Le WagonRails for Beginners - Le Wagon
Rails for Beginners - Le WagonAlex Benoit
 
Cheap tricks for startups
Cheap tricks for startupsCheap tricks for startups
Cheap tricks for startupsSimon Willison
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 

What's hot (20)

Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à Ruby
 
SproutCore is Awesome - HTML5 Summer DevFest
SproutCore is Awesome - HTML5 Summer DevFestSproutCore is Awesome - HTML5 Summer DevFest
SproutCore is Awesome - HTML5 Summer DevFest
 
jQuery Plugin Creation
jQuery Plugin CreationjQuery Plugin Creation
jQuery Plugin Creation
 
Introduccion app engine con python
Introduccion app engine con pythonIntroduccion app engine con python
Introduccion app engine con python
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design Patterns
 
Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)
 
Writing Software not Code with Cucumber
Writing Software not Code with CucumberWriting Software not Code with Cucumber
Writing Software not Code with Cucumber
 
Hooked on WordPress: WordCamp Columbus
Hooked on WordPress: WordCamp ColumbusHooked on WordPress: WordCamp Columbus
Hooked on WordPress: WordCamp Columbus
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
Denver emberjs-sept-2015
Denver emberjs-sept-2015Denver emberjs-sept-2015
Denver emberjs-sept-2015
 
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
 
16.mysql stored procedures in laravel
16.mysql stored procedures in laravel16.mysql stored procedures in laravel
16.mysql stored procedures in laravel
 
Build a bot workshop async primer - php[tek]
Build a bot workshop  async primer - php[tek]Build a bot workshop  async primer - php[tek]
Build a bot workshop async primer - php[tek]
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
 
Django
DjangoDjango
Django
 
Powershell to the People #suguk
Powershell to the People #sugukPowershell to the People #suguk
Powershell to the People #suguk
 
How To Write a WordPress Plugin
How To Write a WordPress PluginHow To Write a WordPress Plugin
How To Write a WordPress Plugin
 
Rails for Beginners - Le Wagon
Rails for Beginners - Le WagonRails for Beginners - Le Wagon
Rails for Beginners - Le Wagon
 
Cheap tricks for startups
Cheap tricks for startupsCheap tricks for startups
Cheap tricks for startups
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 

Similar to Simplifying Code: Monster to Elegant in 5 Steps

Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby MetaprogrammingThaichor Seng
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Simplifying Code: Koombea TechTalks
Simplifying Code: Koombea TechTalks Simplifying Code: Koombea TechTalks
Simplifying Code: Koombea TechTalks Koombea
 
TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016CiaranMcNulty
 
Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)Andre Foeken
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Brian Hogan
 
Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in StyleBhavin Javia
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends旻琦 潘
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the BasicsMichael Koby
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principlesEdorian
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new thingsDavid Black
 
Ruby for .NET developers
Ruby for .NET developersRuby for .NET developers
Ruby for .NET developersMax Titov
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?ColdFusionConference
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Coxlachie
 

Similar to Simplifying Code: Monster to Elegant in 5 Steps (20)

Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Simplifying Code: Koombea TechTalks
Simplifying Code: Koombea TechTalks Simplifying Code: Koombea TechTalks
Simplifying Code: Koombea TechTalks
 
TDD with PhpSpec
TDD with PhpSpecTDD with PhpSpec
TDD with PhpSpec
 
TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016
 
Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
 
Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in Style
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the Basics
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principles
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new things
 
Oops in php
Oops in phpOops in php
Oops in php
 
Ruby for .NET developers
Ruby for .NET developersRuby for .NET developers
Ruby for .NET developers
 
Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
 
Introduction Php
Introduction PhpIntroduction Php
Introduction Php
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
Rails by example
Rails by exampleRails by example
Rails by example
 

Recently uploaded

CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
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
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
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
 
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
 
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
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 

Recently uploaded (20)

CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
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
 
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
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
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
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
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
 
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...
 
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
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 

Simplifying Code: Monster to Elegant in 5 Steps

  • 1. SIMPLIFYING CODE MONSTER TO ELEGANT IN N<5 STEPS Tute Costa - @tutec
  • 2. REFACTORING PATTERNS (And all these buzz words.)
  • 4. 20**: STUDENT/FREELANCER I learned CS theory at school I practiced at home different languages I built small projects as a freelancer Learned web dev alongside good mentors
  • 5. 2011/2012: CHEFSURFING We wrote so much code. Every 2 months complexity would bite us. Stop-the-world. Refactor. Not predictable. Not sustainable.
  • 7. 2013: GENERAL ASSEMBLY Rails app in BAD shape. But well tested. I was told “refactor allthethings!“ Improved productivity week after week
  • 9. 2014: THOUGHTBOT Code Quality is daily bread and butter We heavily prioritize what to build Technical Debt is not allowed Makes for developers and clients' happiness
  • 11. ANOMALY 1: CODE DOESN'T READ WELL Before: if hash[row[1]][date] != row[0] # ... After: if remove_duplicates?(row, date) # ... def remove_duplicates?(data, date)
  • 12. 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. And the code describes itself.
  • 13. INTENTION REVEALING METHOD Comments are now code. And the code describes itself. MASSIVE SUCCESS.
  • 14. INTENTION REVEALING METHOD It's arguably the easiest pattern. But the hardest as well.
  • 15. ANOMALY 2: WHAT IS NIL? Hint: it's a troublemaker. Source of hard to spot errors: Undefined method `name' for nil session[:current_user] # => nil session[:current_dinozauh] # => nil if (false) then 1 end # => nil empty_method() # => nil
  • 16. ANOMALY 2: WHAT IS NIL? A symbol is better than nil: # In Ruby: # 'a' || 'b' # => 'a' # nil || 'b' # => 'b' # false || 'b' # => 'b' def current_user User.find_by_id(id) || :guest_user end current_user.name undefined method `name' for :guest_user:Symbol
  • 17. ANOMALY 2: SO MANY IFS! If there may be nil we need to enclose it with an if: if current_user "Hi #{current_user.name}!" else "Hi guest!" end
  • 18. PATTERN: NULL OBJECTS Instead of nil, return a new object class NullUser def name 'guest' end end def current_user User.find_by_id(id) || NullUser.new end "Ohai, #{current_user.name}!"
  • 19. ANOMALY 3: GINORMOUS METHOD class ExportJob # Instance variables # Many other methods # And... def row_per_day_format(file_name) 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| measurement_date = date + (i-13) # If NumDiasDeChuva is empty it means no data 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
  • 20. 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
  • 21. 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-# hash[NivelConsistencia][date] = [[value, hash = { '1' => {}, '2' => {} } dates = [] str = '' CSV.parse(file, col_sep: ';').each do |row|
  • 22. 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
  • 23. 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
  • 24. REPLACE METHOD WITH METHOD OBJECT http://confreaks.com/videos/1071-cascadiaruby2012- therapeutic-refactoring
  • 25. WE COVERED Intention Revealing Method Turns comments unnecessary. Code reads better. Null Objects Avoids nil objects and ifs. Replace Method with Method Object Refactor big methods at ease in a clean new container. QUESTIONS ABOUT THESE?
  • 26. 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
  • 27. WHY REFACTORING Not only about aesthetics, but shared understanding, bug-chase, 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.
  • 28. EL FIN @tutec QUESTIONS ABOUT ANYTHING?