문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top