Android Studio says: "Local variable redundant"

I get a warning on many methods that local variable is redundant .

Here is an example method:

 public MyObject getMSListItem(int pos) { MyObject li = getItem(pos); return li; } 

Now he is SEEMS, I suppose I can do this to fix this:

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

It seems it 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 any "best practice" for this? Is one way better than the other? Or is it just code readability and nothing more?

+6
source share
1 answer

Is there any "best practice" for this? Is One Way Better Than Others? Or is it just code readability and nothing more?

Simplified: In your scenario, it is useless. This is not true, but why would you do this:

 ffTeacherListItem t = getItem(pos); String teacher = t.teacher; return teacher; 

when you can do the same:

 ffTeacherListItem t = getItem(pos); return t.teacher; 

and also you can:

 return getItem(pos).teacher; 

All of the above does the same, but the second and third codes are cleaner, and you should always try to write clean code without useless lines and links 1 . There is also an unwritten rule - less code, fewer errors.

1 This is an β€œadvantage” of languages ​​such as C ++, which do not have a garbage collector, and you are responsible for all the objects and instances that you create (freeing them from memory, etc.). So, you think more before deciding to create a new instance of an object.

+9
source

All Articles