Using an input variable as a working variable is a poor practice. Let’s analyze the code below paying particular attention how its input parameter is being used.
public void Execute(int itemIndex) { for (int item = 0; item < 10; item++) { bool status = ProcessItem(itemIndex); if (!status) { itemIndex++; } else { break; } } }
Let’s suppose we wanted to print the search start index at the end of the method. We can conclude that search starts at input itemIndex. So, we can write:
public void Execute(int itemIndex) { for (int item = 0; item < 10; item++) { bool status = ProcessItem(itemIndex); if (!status) { itemIndex++; } else { break; } } Console.Write("Search start index: " + itemIndex); }
The code is incorrect because the input variable, itemIndex, is being incremented on each iteration if status variable is false. The original input value has been lost. In order to make the code clearer and less error prone we should eliminate use of input variable as working variable:
public void Execute(int itemIndex) { int foundItemIndex = itemIndex; for (int item = 0; item < 10; item++) { bool status = ProcessItem(foundItemIndex); if (!status) { foundItemIndex++; } else { break; } } Console.Write("Search start index: " + itemIndex); }
Conclusion
Keeping the input variable constant makes the code less complex. Unfortunately, C# does not allow explicit constant argument declaration as C++ does. Therefore it is up to the developer to make sure not to modify parameter value in the method.