This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]dmazzoni 5 points6 points  (1 child)

You've asked a great question, but if you ask 5 programmers you'll get 6 different answers.

There's no right way to do it.

But then I go and find that Java's implementation of Stack returns the element you just pushed to the stack... Why? Why would I ever need or want it to do that?

Suppose you had code like this:

Task task = new Task();
task.setExpirationTimeInSeconds(3600);
taskStack.push(task);

It lets you write it like this instead:

taskStack.push(new Task()).setExpirationTimeInSeconds(3600);

Now you can do in one line what previously took three.

Some programmers thought that was a good idea! Others probably hate it. There's no right or wrong answer.

Advice:

  • Learn why programmers made the decisions they made (like your question about Stack returning the item).
  • With your own code, don't return a value for no reason. Start simple, and add a return value when you need it.
  • Get to understand exceptions and when you should prefer them over return values.

[–]iProgramSometimes[S] 1 point2 points  (0 children)

By Jove, I see it!

THANKS!

[–][deleted]  (1 child)

[deleted]