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 说:在你的场景中它没用.这并没有错,但您为什么要这样做:
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++ 这样没有垃圾收集器的语言的优势",你负责你将创建的所有对象和实例(它们从内存中释放等).).因此,在决定创建某个对象的新实例之前,您会考虑更多.
这篇关于Android Studio 说“局部变量是多余的"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!