Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

書籍 リファクタリング−プログラマーの体質改善 | 条件式の単純化 | 条件式の分解

内容

リファクタリング

条件式の分解

適用ケース要約

複雑な条件文(if-then-else)がある

適用内容要約

条件部、"then"部、"else"部からメソッドを抽出する。

適用詳細

プログラムの可読性を下げる大きな要因となる分岐の記述を
完結にするため、分岐条件・分岐中の処理などをメソッドとして抽出して
適切な名前を付けることで可読性を高めます。

サンプル

角の数、幅、高さを元に三角形か四角形か判断して面積を返却する機能を実装します。

サンプルコード

リファクタリング

# encoding: Shift_JIS

def get_figure_area(angle_count,height,width)
  result=0
  if angle_count==3
    result=(height*width)/2
  elsif angle_count==4
    result=height*width
  else
    raise 'error'
  end
  return result
end

puts get_figure_area(3,5,10)
puts get_figure_area(4,5,10)

リファクタリング

# encoding: Shift_JIS

def get_figure_area(angle_count,height,width)
  result=0
  if is_triangle(angle_count)
    result=calculate_triangle(height,width)
  elsif is_square(angle_count)
    result=calculate_square(height,width)
  else
    raise 'error'
  end
  return result
end

def is_triangle(angle_count)
  return angle_count==3
end

def is_square(angle_count)
  return angle_count==4
end

def calculate_triangle(height,width)
  return (height*width)/2
end

def calculate_square(height,width)
  return height*width
end

puts get_figure_area(3,5,10)
puts get_figure_area(4,5,10)

出力(共通)

25
50