Replace Temp with Query(問い合わせによる一時変数の置き換え)


HOME > プログラミング > リファクタリング > Replace Temp with Query リファクタリング プログラムの体質改善テクニック

Replace Temp with Queryとは、テンポラリ変数(一時変数)をメソッドに置き換えるというリファクタリングです。
テンポラリ変数で計算している式を他のクラスなどからアクセスできるようにする効果と、長いメソッドを整理する効果があります。

リファクタリング前:

public int GetTotalAmountOfItemsWithDiscount(Items[] items)
{

	int totalValue = 0;
	  
	foreach(Item item in items)
	{
		totalValue += item.value;
	}


	if(totalValue > 1000)
	{
		return totalValue * 0.9;
	}

	return totalValue;
}
 

リファクタリング後:

public int GetTotalAmountOfItemsWithDiscount(Items[] items)
{
	if(GetTotalAmountOfItems(items) > 1000)
	{
		return GetTotalAmountOfItems(items) * 0.9;
	}

	return GetTotalAmountOfItems(items);
}  

public int GetTotalAmountOfItems(Items[] item)
{
	int totalValue = 0;
	  
	foreach(Item item in items)
	{
		totalValue += item.value;
	}
	
	return totalValue;
}
	  

Copyright(c) 2012 WoodenSoldier Software