Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Refactoring (Ruby edition)

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

Refactoring (Ruby edition)

Avatar for 高見龍

高見龍

May 31, 2018
Tweet

More Decks by 高見龍

Other Decks in Programming

Transcript

  1. a.k.a Eddie 愛現! 喜歡冷門的玩具 Ruby/Rails/iOS app 開發者、講師 Ruby 技術推廣、教育、諮詢 台灣、日本等國內外

    Ruby 技術研討會講者 目前於五倍紅寶石擔任紅寶石鑑定商職務 部落格:https://kaochenlong.com 高見龍 photo by Eddie @eddiekao
  2. • 什麼是重構? • 動手作! (50 mins) • 何時該進行重構? • 何時不該進行重構?

    • 程式碼的壞味道 • 常見重構手法介紹 • Ruby 風味之程式整理手法
  3. base_price = @quantity * @item_price if base_price > 1000 base_price

    * 0.95 else base_price * 0.98 end 使⽤用前
  4. if base_price > 1000 base_price * 0.95 else base_price *

    0.98 end def base_price @quantity * @item_price end 使⽤用後
  5. is_mac_os = platform.upcase.index("MAC") is_ie_browser = browser.upcase.index("IE") was_resized = resize >

    0 if (is_mac_os && is_ie_browser && initialized? && was_resized) # do something end 使⽤用後
  6. temp = 2 * (@height + @width) puts temp temp

    = @height * @width puts temp 使⽤用前
  7. perimeter = 2 * (@height + @width) puts perimeter area

    = @height * @width puts area 使⽤用後
  8. 以方法物件取代方法 Replace Method with Method Object • 有時候方法太複雜,無法用 Extract Method

    或 Replace Temp with Query 手法處理… • 新增一個類別,把方法包進去
  9. class Account def gamma(input_val, quantity, year_to_date) important_value1 = (input_val *

    quantity) + delta important_value2 = (input_val * year_to_date) + 100 if (year_to_date - important_value1) > 100 important_value2 -= 20 end important_value3 = important_value2 * 7 # and so on. important_value3 - 2 * important_value1 end end 使⽤用前
  10. class Person attr_reader :first_name, :last_name def initialize first_name, last_name @first_name

    = first_name @last_name = last_name end end class Male < Person def full_name first_name + " " + last_name end def gender "M" end end 使⽤用前 class Female < Person def full_name first_name + " " + last_name end def gender "F" end end
  11. class Person attr_reader :first_name, :last_name def initialize first_name, last_name @first_name

    = first_name @last_name = last_name end def full_name first_name + " " + last_name end end class MalePerson < Person def gender "M" end end 使⽤用後 class FemalePerson < Person def gender "F" end end