Introduce Explaining Variable(説明用変数の導入)

Product Codeがちょっと読みやすくなったか。Test codeの改善はあまり期待できなさそう。
◯ Product code(ruby)

# before
class Order
  attr_accessor :quantity
  attr_accessor :item_price

  def initialize (quantity, item_price)
    @quantity = quantity
    @item_price = item_price
  end

  def price
    return @quantity * @item_price -
      [0, @quantity - 500].max * @item_price * 0.05 +
      [@quantity * @item_price * 0.1, 100.0].min
  end
end

# after
class Order
  attr_accessor :quantity
  attr_accessor :item_price

  def initialize (quantity, item_price)
    @quantity = quantity
    @item_price = item_price
  end

  def price
    base_price = @quantity * @item_price
    quantity_discount = [0, @quantity - 500].max * @item_price * 0.05
    shipping = [base_price * 0.1, 100.0].min
    return base_price - quantity_discount + shipping
  end
end


◯ test code(rspec)

# before
describe Order do
  let(:order){ Order.new(quantity, item_price) }

  describe 'price' do
    subject{ order.price }

    context 'quantity < 500' do
      let(:quantity){ 499 }
      context 'quantity * item_price * 0.1 < 100.0' do
        let(:item_price){ 2 }
        it{ should == 1097.8 }
      end
      context 'quantity * item_price * 0.1 >= 100.0' do
        let(:item_price){ 3 }
        it{ should == 1597.0 }
      end
    end

    context 'quantity == 500' do
      let(:quantity){ 500 }
      context 'quantity * item_price * 0.1 < 100.0' do
        let(:item_price){ 1 }
        it{ should == 550.0 }
      end
      context 'quantity * item_price * 0.1 >= 100.0' do
        let(:item_price){ 2 }
        it{ should == 1100.0 }
      end
    end

    context 'quantity > 500' do
      let(:quantity){ 501 }
      context 'quantity * item_price * 0.1 < 100.0' do
        let(:item_price){ 1 }
        it{ should == 551.05 }
      end
      context 'quantity * item_price * 0.1 >= 100.0' do
        let(:item_price){ 2 }
        it{ should == 1101.9 }
      end
    end
  end
end

# after
# 同上

※ 参考資料
 リファクタリング:Rubyエディション6.6 説明用変数の導入(p.143〜146)