1

I have a simple question about one aspect about so called programming conventions in java.

Simply - if I pass a local variable in one method to a another (helper) method - should I keep the name of it to 100 percent or try to rename it slightly?

Look at the example - should I rename the variable totalAmount in the helpermethods signature to something similar (for instance total_amount or theTotalAmount)?

private void myMethod() {

   int totalAmount = 0;
   // calculations where totalAmount is involved.

   myHelperMethod(totalAmount); // send totalAmount to a another method.

}

private void myHelperMethod(int totalAmount) {

    // use totalAmount here .....
}
1
  • 2
    That is your choice; just find a name that best suits what the method does/what you prefer. There is no real convention here other than naming conventions. Commented Jul 12, 2013 at 9:56

4 Answers 4

11

There's absolutely no obligation to keep the same variable name.

Just choose a name that fits the local context.

In your example, your myHelperMethod could potentially receive any amount as a parameter, not necessarily a totalAmount. Let's just name it amount, or anything else that describes its actual role in this method.

Sign up to request clarification or add additional context in comments.

Comments

2

No, you need not. Its like pouring water from one glass to another, the value(water) will remain the same, the glass(holder) will change.

Comments

2

Even in cases when the call is a variable-for-variable (it could be expression-for-variable) the two names represent conceptually different things, so you should not be naming them the same unless they really mean the same thing.

Formal parameters represent variables with names meaningful inside the function, while variables that you pass represent variables with names meaningful outside the function. Here is an example:

// Function definition
static double computeDiscount(double originalPrice, double discountPercentage, double cap) {
    ...
}

// Function calls
double priceClothing = computeDiscount(clothingOrigPrice, discountPercentage, clothingDiscountCap);
double priceAccessories = computeDiscount(accessoriesOrigPrice, discountPercentage, accessoriesDiscountCap);

Comments

0

It's your choice to decide about the names. Conventions don't tell what name you should keep. Use names which reflects the entity the best. And also avoid using the confusing names. In your case if both the 'totalAmount' are actually representing the totalAmount, then you made the right choice. If not, then reconsider changing the names.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.