Tbpgr Blog

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

書籍 リファクタリング−プログラマーの体質改善 | データの再編成 | サブクラスによるタイプコードの置き換え

パンくず

リファクタリング-プログラマーの体質改善テクニック
データの再編成
サブクラスによるタイプコードの置き換え

内容

リファクタリング

サブクラスによるタイプコードの置き換え

適用ケース要約

クラスのふるまいに影響を与えるタイプコードが使われている

適用内容要約

タイプコードをクラスに書き換える。タイプコードの値1つに1つのクラスを作る

適用詳細

タイプコードで分岐するような処理をサブクラス+ポリモーフィズムで記述することにより、
拡張が容易になり、見通しのよいプログラムにすることが出来る。

サンプル

黄金比白銀比を算出する機能を実装します

サンプルコード

リファクタリング

# encoding: Shift_JIS

class RatioCalculator
  GOLDEN_RATIO = 1.618
  SILVER_RATIO = 1.4142
  RATIO_TYPE_GOLDEN = 1
  RATIO_TYPE_SILVER = 2

  def self.calculate_ratio(base_length, ratio_type)
    ratio = nil
    case ratio_type
    when RATIO_TYPE_GOLDEN
      ratio = GOLDEN_RATIO
    when RATIO_TYPE_SILVER
      ratio = SILVER_RATIO
    else
      raise "uncorrect ratio type #{ratio_type}"
    end
    return base_length*ratio
  end
end

(1..2).each {|base_length|
  print "黄金比 @@@base=",base_length,":result=",RatioCalculator.calculate_ratio(base_length,RatioCalculator::RATIO_TYPE_GOLDEN),"\n"
  print "白銀比 @@@base=",base_length,":result=",RatioCalculator.calculate_ratio(base_length,RatioCalculator::RATIO_TYPE_SILVER),"\n"
}

リファクタリング

# encoding: Shift_JIS

class RatioCalculator
  def self.calculate_ratio(base_length, ratio_type)
    return base_length*ratio_type.get_ratio
  end
end

class GoldenRatio
  GOLDEN_RATIO = 1.618
  def self.get_ratio()
    GOLDEN_RATIO
  end
end

class SilverRatio
  SILVER_RATIO = 1.4142
  def self.get_ratio()
    SILVER_RATIO
  end
end

(1..2).each {|base_length|
  print "黄金比 @@@base=",base_length,":result=",RatioCalculator.calculate_ratio(base_length,GoldenRatio),"\n"
  print "白銀比 @@@base=",base_length,":result=",RatioCalculator.calculate_ratio(base_length,SilverRatio),"\n"
}

出力(共通)

黄金比 @@@base=1:result=1.618
白銀比 @@@base=1:result=1.4142
黄金比 @@@base=2:result=3.236
白銀比 @@@base=2:result=2.8284
補足

▼ダック・タイピング
ダック・タイピングとは同じインタフェースを実装するオブジェクト同士は継承階層やインターフェースの実装と関係なしに
交換可能であること。Rubyなど動的言語で可能。Javaは不可。
上記のサンプルコードがそのままダック・タイピングの例になります。

デーブ・トーマスの

"If it walks like a duck and quacks like a duck, it must be a duck"
(もしもそれがアヒルのように歩き、アヒルのように鳴くのなら、それはアヒルである)

が語源