I’m a beginning programmer studying computer science and I’ve been told many times that using a return statement in a loop is not a good programming habit and should be avoided. Nowadays, I read a lot of code in the Java library to learn how everything works and I’m surprised to see that return statements in loop are everywhere.
Does anyone could explain me why using return statements in loops should be avoided?
Thanks!
Most people like to look at a method and assume a single point of exit. When you interpolate returns in the middle of loops it breaks up the flow a bit and jars this assumption. That’s why many will make the “not clean” argument. There’s really nothing dirty about it, but it forces the “human” reader of the program to dig deeper into the method to get a clearer understanding of its flow. Anything you can do to reduce the amount of mental deducing people have to do to understand the flow of your logic is considered a good thing.
If I could glance at a method without reading through its internals while getting an overall general understanding of what it does and where it exits then the author did a good job. Trouble arises when a method, which means well initially, grows over time and forces maintainers to juggle multiple states mentally in an exercise to understand it.
A good example is the classic guard clause which is considered good practice by some. It’s a way of checking the state or a parameter for validity before continuing. If a method is given the wrong stuff then we don’t want to continue. See this fake code:
Somebody comes along and says, “hey cool! We it’s ok to use return statements in the middle of methods!” They make changes and it becomes:
Still not too shabby, but more and more changes go in and you end up with this:
Now you see where this is going. It is difficult to understand where we jump or what’s going on at a single glance.