パンくず
リファクタリング-プログラマーの体質改善テクニック
メソッド呼び出しの単純化
問い合わせと更新の分離
内容
リファクタリング名
問い合わせと更新の分離
適用ケース要約
1つのメソッドが値を返すと同時にオブジェクトの状態を変更している
適用内容要約
問い合わせようと更新用の2つのメソッドをそれぞれ作成する
適用詳細
副作用のないメソッドはシンプルになり、他の処理からも利用しやすくなる。
サンプル
セキュリティシステムに不審者の名前を通知して警報を発するシステムを実装。
不審者が2名いても、警報を鳴らすのは1回のみとする。
サンプルコード
# encoding: Shift_JIS def found_miscreant(people) people.each {|person| if person=="Don" send_alert_message return "Don" end if person=="John/" send_alert_message return "John" end } return "" end def check_security(people) found=found_miscreant people some_later_code found end def send_alert_message() puts "alert!!" end def some_later_code(found) puts found end people=["Tanaka","Suzuki","Don","John"] check_security people
# encoding: Shift_JIS def send_alert(people) send_alert_message unless (found_person(people)=="") end def found_person(people) people.each {|person| return "Don" if person=="Don" return "John" if person=="John/" } return "" end def check_security(people) send_alert people some_later_code found_person(people) end def send_alert_message() puts "alert!!" end def some_later_code(found) puts found end people=["Tanaka","Suzuki","Don","John"] check_security people
出力(共通)
alert!! Don