Java Android Studio 说“局部变量是多余的”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23159351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:07:01  来源:igfitidea点击:

Android Studio says 'Local variable is redundant'

javaandroidandroid-studiorefactoring

提问by TheLettuceMaster

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

我收到了许多方法的警告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?

这真的有“最佳实践”吗?一种方法比另一种更好吗?或者它只是关于代码可读性而仅此而已?

采纳答案by Simon Dorociak

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 scenarioit'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.

以上都是一样的,但第二个和第三个代码更干净,你应该总是尝试编写干净的代码,没有无用的行和引用1。还有一个不成文的规则——更少的代码,更少的错误

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.

1这是像 C++ 这样没有垃圾收集器的语言的“优势”,你负责你将创建的所有对象和实例(它们从内存中释放等)。因此,在决定创建某个对象的新实例之前,您会考虑更多。