I am getting a warning on many methods that local variable is redundant
.
Here is a sample method:
public MyObject getMSListItem(int pos) {
MyObject li = getItem(pos);
return li;
}
Now it SEEMS, I suppose, I can do this to fix it:
public MyObject getMSListItem(int pos) {
return getItem(pos);
}
Another example:
public String getTeacher(int pos) {
ffTeacherListItem t = getItem(pos);
String teacher = t.teacher;
return teacher;
}
Seems this could be:
public String getTeacher(int pos) {
ffTeacherListItem t = getItem(pos);
return t.teacher;
}
OR as recommended below, even better!
public String getTeacher(int pos) {
return getItem(pos).teacher;
}
Is there really a "best practice" for this? Is one way better than the other? Or is it just about code readability and nothing more?
Code Inspection: Redundant local variablea 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.
The variable's value is assigned but never used, making it a dead store. This variable's initial value is not used. After initialization, the variable is either assigned another value or goes out of scope. Example: The following code excerpt assigns to the variable r and then overwrites the value without using it.
In computer programming, redundant code is source code or compiled code in a computer program that is unnecessary.
Is there really a "best practice" for this? Is one way better than the other? Or is it just about code readability and nothing more?
Simplified said: In your scenario it's useless. It's not incorrect but why you would you do this:
ffTeacherListItem t = getItem(pos);
String teacher = t.teacher;
return teacher;
when you can do same thing with:
ffTeacherListItem t = getItem(pos);
return t.teacher;
or also you can do:
return getItem(pos).teacher;
All above do same but second and third code is cleaner and you should always try to write clean code without useless lines and references1. There is also unwritten rule - Less code, less errors.
1This is "advantage" of languages like C++ which don't have garbage collector and you are responsible for all objects and instances you'll create (their releasing from memory etc.). So you are thinking more before you'll decide to create new instance of some Object.
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