Originally posted by Marilyn de Queiroz:
I prefer option 1 for the same reason that Ilja prefers option 2.
That's interesting - could you please elaborate on what you find easier to parse about option 1?
Here is what happens to me:
Option 1: "OK, there is some synchronized block. After that, iter gets returned. What is iter? Ah, iter gets assigned to in the synchronized block. What's that line above. Duh, it's just the declaration of iter. Let's double check that it's really the same variable. Yes, seems to be. So let's summarize: it returns an iterator for the listeners, wrapped by a new ArrayList."
Option 2: "OK, just a synchronized block with a return in it. Seems to return an iterator of listeners, wrapped by a new ArrayList."
The difference really is just a couple of seconds. Still, I find option 1 to be unnecessarily complex. It's also more likely that it contains a bug - just let's also have a field called itera, and return that one instead...
Also, I think that returning in the middle of a method rather than at the end, particularly if there is more than one return in the method, makes it more difficult to refactor later.
That's true, though I don't see how it's true in this case.
On the other hand I find that early returns can make methods easier to *understand*, which is a prerequisite for refactoring.
Often when I have to refactor a big method, one of the very first things I do is introducing
Guard Clauses. After that, it's much easier to understand which steps the method can be separated into. Refactoring the method so that, for example, it's easy to extract methods, isn't too hard, even with the guard clauses present.
Your mileage may vary, of course.