Tbpgr Blog

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

書籍 リファクタリング−プログラマーの体質改善 | メソッド呼び出しの単純化 | オブジェクトそのものの受け渡し

内容

リファクタリング

オブジェクトそのものの受け渡し

適用ケース要約

あるオブジェクトから複数の値を取得し、それらの値をメソッド呼び出しの引数として渡している

適用内容要約

代わりにオブジェクトそのものを渡す

適用詳細

あるオブジェクトの複数のフィールドを引数で渡すような場合。オブジェクトそのものを渡すことで
拡張が容易になります。

サンプル

肥満度(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