Refactoring2-3

関数への移行

二つ以上の作業をさせないという基本方針にしたがって,それぞれの重要な動作は関数へ移行させる.

main-loopにあるpolylineを関数に.

>|ruby| refact前

  <polyline fill=\"none\" stroke=\"#333\" stroke-width=\"1\"
    points = \"#{points.join(' ')}\" />
<

>|ruby| refact後

def polyline(points)
  %Q{<polyline fill=\"none\" stroke=\"#333\" stroke-width=\"1\"
    points = \"#{points.join(' ')}\" />}
end
<

>|ruby| 呼び出し側の変更

  #{polyline(points)}
<

line関数

次にline関数を作成.最初は, >|ruby| refact前

 <line x1="0" y1="200" x2="#{NUMBER_OF_TOSSES}" y2="200"
           stroke="#999" stroke-width="1" />
<

>|ruby| refact後 def line()

 %Q{<line x1="0" y1="200" x2="#{NUMBER_OF_TOSSES}" y2="200"
           stroke="#999" stroke-width="1" />}

end

 #{line()}
<

でいいが,関数の汎用性を考えた引数に変更. >|ruby| refact前

def line()
 %Q{<line x1="0" y1="200" x2="#{NUMBER_OF_TOSSES}" y2="200"
           stroke="#999" stroke-width="1" />}

end

 #{line()}
<

>|ruby| refact後 def line(x1,y1,x2,y2)

 %Q{<line x1="#{x1}" y1="#{y1}" x2="#{x2}" y2="#{y2}"
           stroke="#999" stroke-width="1" />}

end

 #{line(0,200,NUMBER_OF_TOSSES,200)}
<

spark関数からrect, text関数を作成

>|ruby| refact前 def spark(centre_x, centre_y, value)

 %Q{<rect x="#{centre_x-2}" y="#{centre_y-2}"
   width="4" height="4"
   fill="red" stroke="none" stroke-width="0" />
 <text x="#{centre_x+6}" y="#{centre_y+4}"
   font-family="Verdana" font-size="9"
   fill="red" >#{value}</text>}

end

<

>|ruby| refact後 def rect(cx,cy)

 %Q{<rect x="#{cx-2}" y="#{cy-2}"
   width="4" height="4"
   fill="red" stroke="none" stroke-width="0" />}

end

def text(cx,cy,value)

 %Q{<text x="#{cx}" y="#{cy}"
   font-family="Verdana" font-size="9"
 fill="red" >#{value}</text>}

end def spark(cx, cy, value)

 %Q{#{rect(cx,cy)}
  1. {text(cx+6,cy+4,value)}}

end

<

ついでにM-x query-replaceでcentre_をcに換える.

Last modified:2024/04/20 06:40:59
Keyword(s):
References:[Refactoring2] [RubyPrimary]