SlideShare a Scribd company logo
1 of 71
Refactor Like A Boss
a few techniques for everyday Ruby hacking
Refactoring
The process of changing code
 without modifying behavior
Ungoals of refactoring



• Brevity   for the sake of brevity

• To   demonstrate mastery of Ruby or design patterns
Goals of refactoring

• Improve   readability

• Improve   maintainability

• Improve   extensibility

• Promote   an expressive API

• Reduce   complexity
Ruby freebies
DRY Assignment


if 1 > 0
  @foo = 'bar'
else
  @foo = 'baz'
end

@foo # => 'bar'
DRY Assignment


@foo = if 1 > 0
         'bar'
       else
         'baz'
       end

@foo # => 'bar'
DRY Assignment

@foo = case 1
       when 0..1
         'bar'
       else
         'baz'
       end

@foo # => 'bar'
Ternary operator



@foo = 1 > 0 ? 'bar' : 'qux'

@foo # => 'bar'
Ternary operator


def postive?(number)
  number > 0 ? 'yes' : 'no'
end

positive?(100) # => 'yes'
Bang bang


def foo?
  if @foo
    true
  else
    false
  end
end
Bang bang



def foo?
  @foo ? true : false
end
Bang bang



def foo?
  !!@foo
end
Conditional assignment



if not @foo
  @foo = 'bar'
end
Conditional assignment



unless @foo
  @foo = 'bar'
end
Conditional assignment



@foo = 'bar' unless @foo
Conditional assignment



@foo ||= 'bar'
Parallel assignment



@foo   = 'baz'
@bar   = 'qux'
# =>   "baz"
# =>   "qux"
Parallel assignment



@foo, @bar = 'baz', 'qux'
# => ["baz", "qux"]

@foo # => "baz"
Multiple return

def get_with_benchmark(uri)
  res = nil
  bench = Benchmark.measure do
    res = Net::HTTP.get_response(uri)
  end
  return res, bench.real
end

@response, @benchmark = get_with_benchmark(@uri)
# => [#<Net::HTTPOK 200 OK>, 0.123]
Implied begin

def my_safe_method
  begin
    do_something_dangerous()
    true
  rescue
    false
  end
end
Implied begin


def my_safe_method
  do_something_dangerous()
  true
rescue
  false
end
Exception lists
def self.likelihood_of_rain
  Hpricot::XML(weather_xml)/'probability-of-rain'
rescue Net::HTTPBadResponse,
       Net::HTTPHeaderSyntaxError,
       Net::ProtocolError
  return false
end

def self.likelihood_of_snow
  Hpricot::XML(weather_xml)/'probability-of-snow'
rescue Net::HTTPBadResponse,
       Net::HTTPHeaderSyntaxError,
       Net::ProtocolError
  return false
end
Exception lists
NET_EXCEPTIONS = [ Net::HTTPBadResponse,
                   Net::HTTPHeaderSyntaxError,
                   Net::ProtocolError ]

def self.likelihood_of_rain
  Hpricot::XML(weather_xml)/'probability-of-rain'
rescue NET_EXCEPTIONS
  return false
end

def self.likelihood_of_snow
  Hpricot::XML(weather_xml)/'probability-of-snow'
rescue NET_EXCEPTIONS
  return false
end
Symbol to Proc



(1..5).map{|number| number.to_s }
# => ["1", "2", "3", "4", "5"]
Symbol to Proc



(1..5).map(&:to_s)
# => ["1", "2", "3", "4", "5"]
MapReduce


def fibonacci_sum
  sum = 0
  [1,1,2,3,5,8,13].each{|int| sum += int }
  sum
end

fibonacci_sum() # => 33
MapReduce


def fibonacci_sum
  [1,1,2,3,5,8,13].reduce(0){|sum, int| sum + int }
end

fibonacci_sum() # => 33
MapReduce


{:foo => 'bar'}.inject({}) do |memo, (key, value)|
  memo[value] = key
  memo
end

# => {"bar" => :foo}
Regex captures


match_data = 'my lil string'.match(/my (w+) (w+)/)
match_data.captures[0] # => "lil"
match_data.captures[1] # => "string"
match_data.captures[2] # => nil
Regex captures


'my lil   string'.match(/my (w+) (w+)/)
$1 # =>   "lil"
$2 # =>   "string"
$3 # =>   nil
Regex captures


'my lil   string' =~ /my (w+) (w+)/
$1 # =>   "lil"
$2 # =>   "string"
$3 # =>   nil
tap


def Resource.create
  resource = Resource.new
  resource.save
  resource
end
# => #<Resource:0xffffff>
tap


def Resource.create
  Resource.new.tap{|resource| resource.save }
end
# => #<Resource:0xffffff>
sprintf

sprintf("%d as hexadecimal: %04x", 123, 123)
# => "123 as hexadecimal: 007b"

"%d as hexadecimal: %04x" % [123, 123]
# => "123 as hexadecimal: 007b"

"%s string" % ['my']
# => "my string"
case equality

def cerealize(val)
  if val.is_a?(Numeric) || val.is_a?(String)
    val
  elsif val.is_a?(Enumerable)
    val.to_json
  else
    val.to_s
  end
end
case equality

def cerealize(val)
  case val
  when Numeric, String
    val
  when Enumerable
    val.to_json
  else
    val.to_s
  end
end
case equality

if command =~ /sudo/
  raise 'Danger!'
elsif command =~ /^rm /
  puts 'Are you sure?'
else
  puts 'Run it.'
end
case equality

case command
when /sudo/
  raise 'Danger!'
when /^rm /
  puts 'Are you sure?'
else
  puts 'Run it.'
end
Splat Array
def shopping_list(ingredients)
  unless ingredients.is_a?(Array)
    ingredients = [ingredients]
  end
  ingredients.join(", ")
end

shopping_list("eggs")
# => "eggs"
shopping_list(["eggs", "bacon"])
# => "eggs, bacon"
Splat Array
def shopping_list(ingredients)
  [ingredients].flatten.join(", ")
end

shopping_list("eggs")
# => "eggs"
shopping_list(["eggs", "bacon"])
# => "eggs, bacon"
Splat Array
def shopping_list(ingredients)
  [*ingredients].join(", ")
end

shopping_list("eggs")
# => "eggs"
shopping_list(["eggs", "bacon"])
# => "eggs, bacon"
Splat args
def shopping_list(*ingredients)
  ingredients.join(", ")
end

shopping_list("eggs")
# => "eggs"
shopping_list(["eggs", "bacon"])
# => "eggs, bacon"

shopping_list("eggs", "bacon")
# => "eggs, bacon"
Rails freebies
blank?


if @user.name and !@user.name.empty?
  puts @user.name
else
  puts "no name"
end
blank?


if @user.name.blank?
  puts "no name"
else
  puts @user.name
end
present?


if @user.name.present?
  puts @user.name
else
  puts "no name"
end
presence



puts @user.name.presence || "no name"
truncate


opening = "A long time ago in a galaxy far, far away"
if opening.size > 20
  opening[0..16] + "..."
end
# => "A long time ago i..."
truncate


opening = "A long time ago in a galaxy far, far away"
opening.truncate(20)
# => "A long time ago i..."
truncate


opening = "A long time ago in a galaxy far, far away"
opening.truncate(20, :separator => ' ')
# => "A long time ago..."
try



@existing = User.find_by_email(@new.email)
@existing.destroy if @existing
try



User.find_by_email(@new.email).try(:destroy)
in?



if admin_roles.include? @user.role
  puts "Hi Admin!"
end
in?



if @user.role.in? admin_roles
  puts "Hi Admin!"
end
Delegation
class User

  has_one :account

  def balance
    self.account.balance
  end

  def balance=(amount)
    self.account.balance=(amount)
  end

end
Delegation

class User

  has_one :account

  delegate :balance, :balance=, :to => :account

end
Memoization
class Avatar

  def file_size
    if @file_size
      return @file_size
    else
      result = some_expensive_calculation
      result += more_expensive_calculation
      @file_size = result
    end
  end

end
Memoization
class Avatar

  extend ActiveSupport::Memoizable

  def file_size
    result = some_expensive_calculation
    result += more_expensive_calculation
  end
  memoize :file_size

end
alias_method_chain

alias_method :translate_without_log, :translate

def translate_with_log(*args)
  result = translate_without_log(*args)
  Rails.logger.info result
  result
end

alias_method :translate, :translate_with_log
alias_method_chain


def translate_with_log(*args)
  result = translate_without_log(*args)
  Rails.logger.info result
  result
end

alias_method_chain :translate, :log
class_attribute
class Resource
  class < self

    def host=(name)
      @host = hame
    end
    def host
      @host
    end

  end
end
class_attribute


class Resource
  class < self

    attr_accessor :host

  end
end
class_attribute


class Resource

  class_attribute :host

end
Hash#symbolize_keys


my_hash = { 'foo' => 123 }.symbolize_keys
my_hash['foo']
# => nil
my_hash[:foo]
# => 123
Hash#stringify_keys


my_hash = { :foo => 123 }.stringify_keys
my_hash['foo']
# => 123
my_hash[:foo]
# => nil
HashWithIndifferentAccess


my_hash = { :foo => 123 }
my_hash['foo']
# => nil
my_hash[:foo]
# => 123
HashWithIndifferentAccess


my_hash = { :foo => 123 }.with_indifferent_access
my_hash['foo']
# => 123
my_hash[:foo]
# => 123
forty_two


my_array = []
my_array[41] = "the answer"

my_array[41]
# => "the answer"
forty_two


my_array = []
my_array[41] = "the answer"

my_array.forty_two
# => "the answer"
slideshare   gsterndale

   github    gsterndale

       irc   sternicus

More Related Content

What's hot

Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP GeneratorsMark Baker
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsMark Baker
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP ArraysAhmed Swilam
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in OptimizationDavid Golden
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Workhorse Computing
 
The Perl6 Type System
The Perl6 Type SystemThe Perl6 Type System
The Perl6 Type Systemabrummett
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
 
Introduction to Perl Best Practices
Introduction to Perl Best PracticesIntroduction to Perl Best Practices
Introduction to Perl Best PracticesJosé Castro
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - phpHung-yu Lin
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6 brian d foy
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010leo lapworth
 
The Magic Of Tie
The Magic Of TieThe Magic Of Tie
The Magic Of Tiebrian d foy
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginnersleo lapworth
 
Investigating Python Wats
Investigating Python WatsInvestigating Python Wats
Investigating Python WatsAmy Hanlon
 
Writing Maintainable Perl
Writing Maintainable PerlWriting Maintainable Perl
Writing Maintainable Perltinypigdotcom
 
Slaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubySlaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubyJason Yeo Jie Shun
 

What's hot (20)

Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
Php functions
Php functionsPhp functions
Php functions
 
Perl6 in-production
Perl6 in-productionPerl6 in-production
Perl6 in-production
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.
 
The Perl6 Type System
The Perl6 Type SystemThe Perl6 Type System
The Perl6 Type System
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Introduction to Perl Best Practices
Introduction to Perl Best PracticesIntroduction to Perl Best Practices
Introduction to Perl Best Practices
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - php
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
The Magic Of Tie
The Magic Of TieThe Magic Of Tie
The Magic Of Tie
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
 
Investigating Python Wats
Investigating Python WatsInvestigating Python Wats
Investigating Python Wats
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
 
Ruby 2.0
Ruby 2.0Ruby 2.0
Ruby 2.0
 
Writing Maintainable Perl
Writing Maintainable PerlWriting Maintainable Perl
Writing Maintainable Perl
 
Slaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubySlaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in Ruby
 

Viewers also liked

Library As Teaching Resource
Library As Teaching ResourceLibrary As Teaching Resource
Library As Teaching ResourceBritt Fagerheim
 
School Presentation Scuola Statale 5° Circolo Didattico “G. Verdi”
School Presentation Scuola Statale 5° Circolo Didattico “G. Verdi”School Presentation Scuola Statale 5° Circolo Didattico “G. Verdi”
School Presentation Scuola Statale 5° Circolo Didattico “G. Verdi”Tiina Sarisalmi
 
School Presentation Szkoła Podstawowa nr 6 im. Janusza Korczaka
School Presentation Szkoła Podstawowa nr 6 im. Janusza KorczakaSchool Presentation Szkoła Podstawowa nr 6 im. Janusza Korczaka
School Presentation Szkoła Podstawowa nr 6 im. Janusza KorczakaTiina Sarisalmi
 
WELD, Why, Content Marketing & Gamification
WELD, Why, Content Marketing & GamificationWELD, Why, Content Marketing & Gamification
WELD, Why, Content Marketing & GamificationReid Williams
 
Double Trouble
Double TroubleDouble Trouble
Double Troublegsterndale
 
Breakfast and Lunch Recipes from Scotland
Breakfast and Lunch Recipes from ScotlandBreakfast and Lunch Recipes from Scotland
Breakfast and Lunch Recipes from ScotlandTiina Sarisalmi
 
Amia Chi Citizen Public Health V2
Amia Chi Citizen Public Health V2Amia Chi Citizen Public Health V2
Amia Chi Citizen Public Health V2bonander
 
plaY [commercial]
plaY [commercial]plaY [commercial]
plaY [commercial]smwarfield
 
Christmas Handicraft by Thanasis
Christmas Handicraft by ThanasisChristmas Handicraft by Thanasis
Christmas Handicraft by ThanasisTiina Sarisalmi
 
Relief 2.0 in Japan (Japanese Version)
Relief 2.0 in Japan (Japanese Version)Relief 2.0 in Japan (Japanese Version)
Relief 2.0 in Japan (Japanese Version)Carlos Miranda Levy
 
N E O L I T H I C A G E
N E O L I T H I C  A G EN E O L I T H I C  A G E
N E O L I T H I C A G EAlfonso Poza
 
Change history with Git
Change history with GitChange history with Git
Change history with Gitgsterndale
 
All Objects are created .equal?
All Objects are created .equal?All Objects are created .equal?
All Objects are created .equal?gsterndale
 
School Presentation St Peter's RC Primary School and Nursery
School Presentation St Peter's RC Primary School and NurserySchool Presentation St Peter's RC Primary School and Nursery
School Presentation St Peter's RC Primary School and NurseryTiina Sarisalmi
 

Viewers also liked (20)

Library As Teaching Resource
Library As Teaching ResourceLibrary As Teaching Resource
Library As Teaching Resource
 
School Presentation Scuola Statale 5° Circolo Didattico “G. Verdi”
School Presentation Scuola Statale 5° Circolo Didattico “G. Verdi”School Presentation Scuola Statale 5° Circolo Didattico “G. Verdi”
School Presentation Scuola Statale 5° Circolo Didattico “G. Verdi”
 
School Presentation Szkoła Podstawowa nr 6 im. Janusza Korczaka
School Presentation Szkoła Podstawowa nr 6 im. Janusza KorczakaSchool Presentation Szkoła Podstawowa nr 6 im. Janusza Korczaka
School Presentation Szkoła Podstawowa nr 6 im. Janusza Korczaka
 
WELD, Why, Content Marketing & Gamification
WELD, Why, Content Marketing & GamificationWELD, Why, Content Marketing & Gamification
WELD, Why, Content Marketing & Gamification
 
Credentials - ways2engage
Credentials - ways2engageCredentials - ways2engage
Credentials - ways2engage
 
Double Trouble
Double TroubleDouble Trouble
Double Trouble
 
Breakfast and Lunch Recipes from Scotland
Breakfast and Lunch Recipes from ScotlandBreakfast and Lunch Recipes from Scotland
Breakfast and Lunch Recipes from Scotland
 
Amia Chi Citizen Public Health V2
Amia Chi Citizen Public Health V2Amia Chi Citizen Public Health V2
Amia Chi Citizen Public Health V2
 
The vmware story
The vmware storyThe vmware story
The vmware story
 
plaY [commercial]
plaY [commercial]plaY [commercial]
plaY [commercial]
 
Christmas Handicraft by Thanasis
Christmas Handicraft by ThanasisChristmas Handicraft by Thanasis
Christmas Handicraft by Thanasis
 
Relief 2.0 in Japan (Japanese Version)
Relief 2.0 in Japan (Japanese Version)Relief 2.0 in Japan (Japanese Version)
Relief 2.0 in Japan (Japanese Version)
 
Czech Day in Kozani
Czech Day in KozaniCzech Day in Kozani
Czech Day in Kozani
 
N E O L I T H I C A G E
N E O L I T H I C  A G EN E O L I T H I C  A G E
N E O L I T H I C A G E
 
Change history with Git
Change history with GitChange history with Git
Change history with Git
 
plaY [pera]
plaY [pera]plaY [pera]
plaY [pera]
 
All Objects are created .equal?
All Objects are created .equal?All Objects are created .equal?
All Objects are created .equal?
 
Relief 2.0, B2B and Enterprise
Relief 2.0, B2B and EnterpriseRelief 2.0, B2B and Enterprise
Relief 2.0, B2B and Enterprise
 
School Presentation St Peter's RC Primary School and Nursery
School Presentation St Peter's RC Primary School and NurserySchool Presentation St Peter's RC Primary School and Nursery
School Presentation St Peter's RC Primary School and Nursery
 
Orivesi Countryside
Orivesi CountrysideOrivesi Countryside
Orivesi Countryside
 

Similar to Refactor Like A Boss: Techniques for Everyday Ruby Hacking

Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosEdgar Suarez
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScriptniklal
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Wen-Tien Chang
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersGiovanni924
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick touraztack
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptxrani marri
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record.toster
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is AwesomeAstrails
 
Decent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsDecent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsLeonardo Soto
 
Beware: Sharp Tools
Beware: Sharp ToolsBeware: Sharp Tools
Beware: Sharp Toolschrismdp
 
Hidden treasures of Ruby
Hidden treasures of RubyHidden treasures of Ruby
Hidden treasures of RubyTom Crinson
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Coxlachie
 
Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangSean Cribbs
 

Similar to Refactor Like A Boss: Techniques for Everyday Ruby Hacking (20)

Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
My First Ruby
My First RubyMy First Ruby
My First Ruby
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
Ruby
RubyRuby
Ruby
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is Awesome
 
Decent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsDecent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivars
 
Beware: Sharp Tools
Beware: Sharp ToolsBeware: Sharp Tools
Beware: Sharp Tools
 
Hidden treasures of Ruby
Hidden treasures of RubyHidden treasures of Ruby
Hidden treasures of Ruby
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
Beware sharp tools
Beware sharp toolsBeware sharp tools
Beware sharp tools
 
2013 28-03-dak-why-fp
2013 28-03-dak-why-fp2013 28-03-dak-why-fp
2013 28-03-dak-why-fp
 
Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In Erlang
 

Recently uploaded

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Refactor Like A Boss: Techniques for Everyday Ruby Hacking

Editor's Notes

  1. for clean, DRY, expressive code.\n\n
  2. Code refactoring is the process of changing a computer program&apos;s source code without modifying its external functional behavior in order to improve some of the nonfunctional attributes of the software.\n\nIt can be as simple as renaming a method or a class or making cosmetic changes (e.g. adding whitespace, aligning indentation or breaking long lines of code). Though that&amp;#x2019;s a worthy topic, I am not going to focus on cosmetic style choices today. Instead I&amp;#x2019;m going to share some examples of simple recurring code patterns that are candidates for refactoring.\n\nDisclaimer: You may find that some of the following techniques convolute logic. If so, don&amp;#x2019;t use them. Work with your team to establish what is acceptable and develop your own style guide. Also, if performance is a concern, always profile.\n
  3. The goal is to improve readability, not impede it.\n\nWe&amp;#x2019;re not compressing javascript files here.\n\nIn fact, refactoring may be removing unnecessarily complex implementations or use of design patterns.\n\n
  4. Advantages include \nimproved code readability and reduced complexity to improve the maintainability of the source code,\nas well as a more expressive internal architecture or object model to improve extensibility.\n
  5. \n
  6. You&amp;#x2019;ll see that I have a title for each of these patterns. Some came from the internets, some from people I&amp;#x2019;ve worked with, and some I just made up.\n
  7. \n
  8. \n
  9. \n
  10. \n
  11. Forces a boolean return value. True unless @foo is nil or false.\n\nTwo logical NOT operators\n
  12. Using the ternary operator\n
  13. Forces a boolean return value. True unless @foo is nil or false.\n\nTwo logical NOT operators\n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. http://blog.hasmanythrough.com/2006/3/7/symbol-to-proc-shorthand\n
  27. This may have a negative effect on performance!\n\nhttp://blog.hasmanythrough.com/2006/3/7/symbol-to-proc-shorthand\n
  28. \n
  29. reduce AKA inject\n
  30. Significance == (key, value)\n
  31. \n
  32. \n
  33. \n
  34. \n
  35. tap always returns the object it&amp;#x2019;s called on, even if the block returns some other result\n\n
  36. Uses the String as a format specification, and returns the result of applying it to the Array\n
  37. uses the === operator\n
  38. note the two conditions separated by a comma\n
  39. \n
  40. \n
  41. \n
  42. This will flatten ingredients to one dimension if it&amp;#x2019;s a multidimensional Array!\n
  43. \n
  44. Note that we can now call shopping_list with multiple arguments and they will be bunched into an Array\n
  45. \n
  46. \n
  47. \n
  48. \n
  49. Ruby allows you to define any character you want as a string delimiter simply by prefixing the desired character with a %\n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. Chaining try()s is a code smell.\n\nDon&amp;#x2019;t overuse this.\n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. first, second, third, forth, fifth and forty_two\n
  80. \n
  81. See also #extract\n
  82. \n