パンくず
リファクタリング-プログラマーの体質改善テクニック
メソッド呼び出しの単純化
オブジェクトそのものの受け渡し
内容
リファクタリング名
オブジェクトそのものの受け渡し
適用内容要約
代わりにオブジェクトそのものを渡す
適用詳細
あるオブジェクトの複数のフィールドを引数で渡すような場合。オブジェクトそのものを渡すことで
拡張が容易になります。
サンプル
肥満度(BMI)を計測する機能を実装します
肥満度(BMI)=体重(kg)÷身長(m)÷身長(m)
サンプルとして以下の2名を計測対象とします
氏名 | 身長 | 体重 |
---|---|---|
田中卓志さん | 187 | 59 |
石塚英彦さん | 175 | 130 |
サンプルコード
# encoding: Shift_JIS class BmiCalculator def self.calculate_bmi(height,weight) return weight/height/height end end class Person attr_reader:height,:weight def initialize(height,weight) @height=height @weight=weight end end tanaka=Person.new(1.87,59) ishiduka=Person.new(1.75,130) puts "tanakaのBMI:#{BmiCalculator::calculate_bmi(tanaka.height,tanaka.weight)}" puts "ishidukaのBMI:#{BmiCalculator::calculate_bmi(ishiduka.height,ishiduka.weight)}"
# encoding: Shift_JIS class BmiCalculator def self.calculate_bmi(person) return person.weight/person.height/person.height end end class Person attr_reader:height,:weight def initialize(height,weight) @height=height @weight=weight end end tanaka=Person.new(1.87,59) ishiduka=Person.new(1.75,130) puts "tanakaのBMI:#{BmiCalculator::calculate_bmi(tanaka)}" puts "ishidukaのBMI:#{BmiCalculator::calculate_bmi(ishiduka)}"
出力(共通)
tanakaのBMI:16.872086705367607 ishidukaのBMI:42.44897959183674