简体   繁体   中英

Programming conventions in java

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 .....
}

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.

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);

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM