Making java method arguments as final

2019-01-08 06:59发布

What difference that final makes between the code below. Is there any advantage in declaring the arguments as final.

public String changeTimezone( Timestamp stamp, Timezone fTz, Timezone toTz){  
    return ....
}

public String changeTimezone(final Timestamp stamp, final Timezone fTz, 
        final Timezone toTz){
    return ....
}

9条回答
Bombasti
2楼-- · 2019-01-08 07:36

I'm speaking of marking variables and fields final in general - doesn't just apply to method arguments. (Marking methods/classes final is a whole different thing).

It's a favor to the readers/future maintainers of your code. Together with a sensible name of the variable, it's helpful and reassuring to the reader of your code to see/understand what the variables in question represent - and it's reassuring to the reader that whenever you see the variable in the same scope, the meaning stays the same, so (s)he doesn't have to scratch his head to always figure out what a variable means in every context. We've seen too many abuses of "re-use" of variables, that makes even a short code snippet hard to understand.

查看更多
\"骚年 ilove
3楼-- · 2019-01-08 07:39

It doesn't make a lot of difference. It just means that you can't write:

stamp = null;
fTz = new ...;

but you can still write:

stamp.setXXX(...);
fTz.setXXX(...);

It's mainly a hint to the maintenance programmer that follows you that you aren't going to assign a new value to the parameter somewhere in the middle of your method where it isn't obvious and might therefore cause confusion.

查看更多
Animai°情兽
4楼-- · 2019-01-08 07:40

The final prevents you from assigning a new value to the variable, and this can be helpful in catching typos. Stylistically you might like to keep the parameters received unchanged and assign only to local variables, so final would help to enforce that style.

Must admit I rarely remember to use final for parameters, maybe I should.

public int example(final int basicRate){
    int discountRate;

    discountRate = basicRate - 10;
    // ... lots of code here 
    if ( isGoldCustomer ) {
        basicRate--;  // typo, we intended to say discountRate--, final catches this
    }
    // ... more code here

    return discountRate;
}
查看更多
登录 后发表回答