Android Studio说“局部变量是多余的” [英] Android Studio says 'Local variable is redundant'
问题描述
我收到许多方法的警告本地变量是多余的
。
I am getting a warning on many methods that local variable is redundant
.
这是一个示例方法:
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);
}
另一个例子:
public String getTeacher(int pos) {
ffTeacherListItem t = getItem(pos);
String teacher = t.teacher;
return teacher;
}
似乎这可能是:
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?
推荐答案
真的有最佳实践吗? 为了这?有一种方式比
更好吗?或者只是代码可读性而已?
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;
或者你也可以这样做:
return getItem(pos).teacher;
以上所有相同但第二和第三代码更清晰,你应该总是尝试编写干净的代码而不用无用的行和参考文献 1 。还有不成文的规则 - 更少的代码,更少的错误。
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.
1 这是优势像C ++这样没有垃圾收集器的语言,你负责所有你创建的对象和实例(它们从内存中释放等)。因此,在决定创建某个Object的新实例之前,您会考虑更多。
这篇关于Android Studio说“局部变量是多余的”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!