2

Can you tell me what are the advantages (if there is any advantage) of using getTheLastElement2() instead of getTheLastElement()? I mean why is it necessary to create the reference obj when it is easier just to return the result?

import java.util.ArrayList;
        import java.util.List;

public class Test {
    List list;

    Test(ArrayList list){
        this.list = list;
    }

    public Object getTheLastElement(){
        if (list.isEmpty())
            return null;
        else
            return list.get(list.size()-1);
    }

    public Object getTheLastElement2(){
        Object obj;
        if (list.isEmpty())
            obj = null;
        else
            obj = list.get(list.size()-1);
        return obj;
    }
}
webpersistence
  • 894
  • 3
  • 12
  • 29
  • Neither of these works. – Oliver Charlesworth May 28 '16 at 11:18
  • 1
    You'll have to return the `size - 1`th element, not just `size`. – Kajal May 28 '16 at 11:19
  • You might also like to have a look at http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement which discusses the pros and cons of having a single exit point vs multiple exit points in a function. In your code example I would suggest that `getTheLastElement()` is more readable, and would be even more so without the `else` statement. – mhawke May 28 '16 at 11:31

2 Answers2

2

There is no difference between these two implementations: the obj reference will probably be optimized away.

You do get a slight advantage when debugging the code, because you can set breakpoint on the return statement of getTheLastElement2, and know that it is always going to be hit. This is in contrast with getTheLastElement, where you would need two breakpoints to examine the return value.

Note that else in the first example is redundant:

public Object getTheLastElement(){
    if (list.isEmpty()) {
        return null;
    }
    return list.get(list.size()-1);
}

You could further shrink this to a single ternary expression:

public Object getTheLastElement(){
    return !list.isEmpty() ? list.get(list.size()-1) : null;
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

No, there is no advantage. Also, you should return list.get(list.size()-1)

Priyansh Goel
  • 2,660
  • 1
  • 13
  • 37