RussOlsenTemplateMethod

Refactoringの順序

  1. 初期code(p.55)を入力
  2. legacy code(p.56)を入力
  3. p.60まで読む
  4. p.68にならいrefactor開始
  5. p.68を3枚print outして,下記に書き換え
    • Report (Abstract class)
    • HTMLReport < Report (Concrete class I)
    • PlainTextReport < Report (Concrete class II)
  6. raise, hook, concrete methodを峻別
  7. そのとおりにrefactoring, まちがってたらraiseが起こる.

template55.rb

class Report
  def initialize
    @title = '月次報告'
    @text = ['順調','さいこ〜〜〜']
  end
  
  def output_report
    puts '<html>'
    puts ' <head>'
    puts ' <meta charset="UTF-8">'
    puts " <title>#{@title}</title>"
    puts ' </head>'
    puts ' <body>'
    @text.each{|line|
      puts(" <p>#{line}</p>")
    }
    puts ' </body>'
    puts '</html>'
  end
end

report = Report.new
report.output_report

template68.rb

No.4のHTMLのrefactor修了後,これを3枚印刷

class Report
  def initialize
    @title = '月次報告'
    @text = ['順調','さいこ〜〜〜']
  end
  
  def output_report
    output_start
    output_head
    output_body_start
    output_body
    output_body_end
    output_end
  end
  def output_start
    puts ' <html>'
  end
  def output_head
    puts ' <head>'
    puts '  <meta charset="UTF-8">'
    puts "  <title>#{@title}</title>"
    puts ' </head>'
  end
  def output_body_start
    puts ' <body>'
  end
  def output_body
    @text.each{|line|
      output_line(line)
    }
  end
  def output_line(line)
    puts " <p>#{line}</p>"
  end

  def output_body_end
    puts ' </body>'
  end
  def output_end
    puts '</html>'
  end
end

template61-1.rb(最終版)

class Report
  def initialize
    @title = '月次報告'
    @text = ['順調','さいこ〜〜〜']
  end
  
  def output_report
    output_start
    output_head
    output_body_start
    output_body
    output_body_end
    output_end
  end

  def output_start;  end
  def output_head
    raise 'Called absract method: output_head'
  end
  def output_body_start;  end
  def output_body
    @text.each{|line|
      output_line(line)
    }
  end
  def output_line(line)
    raise 'Called absract method: output_line'
  end
  def output_body_end;  end
  def output_end;  end
end

class HTMLReport < Report
  def output_start
    puts ' <html>'
  end
  def output_head
    puts ' <head>'
    puts '  <meta charset="UTF-8">'
    puts "  <title>#{@title}</title>"
    puts ' </head>'
  end
  def output_body_start
    puts ' <body>'
  end
  def output_line(line)
    puts " <p>#{line}</p>"
  end
  def output_body_end
    puts ' </body>'
  end
  def output_end
    puts '</html>'
  end
end

class PlainTextReport < Report
  def output_head
    puts "***#{@title}***"
  end
  def output_line(line)
    puts "#{line}"
  end
end

report = HTMLReport.new
report.output_report

report = PlainTextReport.new
report.output_report
Last modified:2016/07/19 12:42:27
Keyword(s):
References: