A method can have more than one return statement but no two statements must be in the same block.
The below snippet is incorrect because both the return statements come under the same block of code. In this case, JVM complains saying "unreachable ...". But the code that Mihai wrote is valid.
Any many others . It is generaly considered that have anything but a single return statement at the very end of the method is, while perfectly correct, bad style as it makes the code more difficult to read and easier to misinterpret.
SCJD, SCEA
Mihai Radulescu
Ranch Hand
Joined: Sep 18, 2003
Posts: 912
posted
0
I agree with you Jon, if the code has more exit points is more difficut to read and interpret, BUT , this is not always.
Most of the time I try to avoid this kind of "multiple return" but when the solution seams to get to complex,I just make it easy with an extra retun.
My question is still : Is this a valid technique (for the developer exam and general) ?
Jon Entwistle
Ranch Hand
Joined: Feb 20, 2003
Posts: 118
posted
0
I would say that you really shouldn't - if you feel the need, reconsider your algorithm. Remember the three golden guidelines from the cover of 'The practice of programming' by Kernigan and Pike - 'Simplicity, Clarity, Generality' (the first two apply here)
Cheers,
Jon [ May 27, 2004: Message edited by: Jon Entwistle ]
This is when I relook at my code and see how I can further break it apart into more methods, if the method is complex then it is probably doing more than one thing. If you try to keep it simple and take the approach of "A method should do one thing and one thing only, then you will find that you will have very little if never chances of needing more than one return.
It is clues like these that help in seeing where to refactor. Clues like needing more than one return.
Good Luck.
Mark
Mihai Radulescu
Ranch Hand
Joined: Sep 18, 2003
Posts: 912
posted
0
Yes Mark, you are right, the best way is to break the "mammoth" methods in to small "mammoth" methods with (clear)specific task. I know about, I read about(all the develop. exam book mention this) but .... TahnX.
Have only one return, 98% of the time. and you are guaranteed not to lose points. If you have more than one return, you also might not lose points (85% chance*), but you also might lose points (15% chance*).
Mark
* chance percentages are based on a poll by Associated Press and CNN, there is a 15-85% margin of error.