Something like this (yes, this doesn’t deal with some edge cases – that’s not the point):
int CountDigits(int num) { int count = 1; while (num >= 10) { count++; num /= 10; } return count; }
What’s your opinion about this? That is, using function arguments as local variables.
Both are placed on the stack, and pretty much identical performance wise, I’m wondering about the best-practices aspects of this.
I feel like an idiot when I add an additional and quite redundant line to that function consisting of int numCopy = num, however it does bug me.
What do you think? Should this be avoided?
As a general rule, I wouldn’t use a function parameter as a local processing variable, i.e. I treat function parameters as read-only.
In my mind, intuitively understandabie code is paramount for maintainability, and modifying a function parameter to use as a local processing variable tends to run counter to that goal. I have come to expect that a parameter will have the same value in the middle and bottom of a method as it does at the top. Plus, an aptly-named local processing variable may improve understandability.
Still, as @Stewart says, this rule is more or less important depending on the length and complexity of the function. For short simple functions like the one you show, simply using the parameter itself may be easier to understand than introducing a new local variable (very subjective).
Nevertheless, if I were to write something as simple as
countDigits(), I’d tend to use aremainingBalancelocal processing variable in lieu of modifying thenumparameter as part of local processing – just seems clearer to me.Sometimes, I will modify a local parameter at the beginning of a method to normalize the parameter:
I rationalize that this is okay because:
a. it is easy to see at the top of the method,
b. the parameter maintains its the original conceptual intent, and
c. the parameter is stable for the rest of the method
Then again, half the time, I’m just as apt to use a local variable anyway, just to get a couple of extra
finals in there (okay, that’s a bad reason, but I likefinal):If, 99% of the time, the code leaves function parameters unmodified (i.e. mutating parameters are unintuitive or unexpected for this code base) , then, during that other 1% of the time, dropping a quick comment about a mutating parameter at the top of a long/complex function could be a big boon to understandability:
P.S. 🙂
parameters vs arguments
http://en.wikipedia.org/wiki/Parameter_(computer_science)#Parameters_and_arguments
So,
baris a parameter.The value of
xis the argument for thebarparameter.