Alex Rivera | Logout

Using function arguments as local variables

Asked 2010-05-02T12:53:32.137
17

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?

Edit
Report

1 Answer

19
  1. 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 a remainingBalance local processing variable in lieu of modifying the num parameter as part of local processing - just seems clearer to me.

  2. Sometimes, I will modify a local parameter at the beginning of a method to normalize the parameter:

    void saveName(String name) {
      name = (name != null ? name.trim() : "");
      ...
    }
    

    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 like final):

    void saveName(final String name) {
      final String normalizedName = (name != null ? name.trim() : "");
      ...
    }
    
  3. If, 99% of the ti

answered 2010-05-02T14:29:47.927

Your Answer