Why is the following giving me a "local variable is redundant error"?
public double depreciationAmount() {
double depreciationAmount = (cost * percentDepreciated);
return depreciationAmount;
}
Code Inspection: Redundant local variablea local variable that is immediately returned. a local variable that is immediately assigned to another variable and is not used anymore. a local variable that always has the same value as another local variable or parameter.
In computer programming, redundant code is source code or compiled code in a computer program that is unnecessary.
Local variables are the workhorse of Java. They allow methods to compute significant results by cheaply storing intermediate values. Unlike a field, a local variable is declared, initialized, and used in the same block.
Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block. Access modifiers cannot be used for local variables. Local variables are visible only within the declared method, constructor, or block.
Why is the following giving me a "local variable is redundant error"?
Because you can trivially write this without using a local variable.
public double depreciationAmount() {
return cost * percentDepreciated;
}
Hence the local variable is deemed to be unnecessary / redundant by the checker.
However, I surmise that this is not a compiler error. It might be a compiler warning, or more likely it is a style checker or bug checker warning. It is something you could ignore without any risk to the correctness of your code ... as written.
Also, I would predict that once that the code has been JIT compiled (by a modern Hotspot JIT compiler ...) there would be no performance difference between the two versions.
I won't attempt to address the issue as to whether the warning is appropriate1. If you feel it is inappropriate, then "Local variable is redundant" using Java explains how to suppress it.
1 - Except to say that it is too much to expect current generation style checkers to know when so-called explaining variables are needed. First you'd need to get a statistically significant2 group of developers to agree on measurable3 criteria for when the variables are needed, and when they aren't.
2 - Yea, I know. Abuse of terminology.
3 - They must be measurable, and there needs to be consensus on what the thresholds should be if this is to be implemented by a checker.
Although not the case here, if having a redundant local variable is desired (I've had one time where this was the case - without getting into specifics), here's how to suppress this specific warning.
@SuppressWarnings("UnnecessaryLocalVariable")
public double depreciationAmount() {
double depreciationAmount = (cost * percentDepreciated);
return depreciationAmount;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With