パンくず
リファクタリング-プログラマーの体質改善テクニック
データの再編成
サブクラスによるタイプコードの置き換え
内容
リファクタリング名
サブクラスによるタイプコードの置き換え
適用ケース要約
クラスのふるまいに影響を与えるタイプコードが使われている
適用内容要約
タイプコードをクラスに書き換える。タイプコードの値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