Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio says 'Local variable is redundant' [closed]

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?

like image 850
TheLettuceMaster Avatar asked Apr 18 '14 17:04

TheLettuceMaster


People also ask

What does it mean local variable is redundant?

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.

What is redundant initializer?

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.

What is redundancy in Java?

In computer programming, redundant code is source code or compiled code in a computer program that is unnecessary.


1 Answers

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.

like image 95
Simon Dorociak Avatar answered Sep 19 '22 16:09

Simon Dorociak