3 ms·
It's strange that many programmers in this topic feel that multiple return points are bad. It is very clear how nesting makes code logic more complex, but why m
by antirez 15y ago
It's strange that many programmers in this topic feel that multiple return points are bad. It is very clear how nesting makes code logic more complex, but why many return points are a problem at all? They don't require you to do extra work while reading or writing the code, actually it is exactly the reverse IMHO, every return point remove some possible future state.
Also many times early return is an exact translation of the way we think in our natural languages: "if that is this way don't continue at all", "if this precondition is meet return that value", and so forth.
- hxa7241 15y agoIt is because it is unstructured -- in the Dijkstra 'structured programming' sense. The flow is no longer nested, so you cannot skim over -- mentally fold -- parts. It also means the effects of transformations are less 'limited'. With structured code, if you put a statement after a block it will be executed (notwithstanding exceptions, but that is a slightly different matter...), no matter what is changed. But if you have returns, breaks, etc. that structural condition is lost. If you have a function with a statement, or block, at the very end, to clear something up or something, but then someone puts an early return in, the clear-up will be missed. There is a certain error-proneness there. The best use of the early-return pattern ('replace nested conditional with guard clauses' in the Refactoring book) is where that is the only thing going on in the function. So you are effectively reading/understanding the whole thing as an 'early-return function'. (And software is very different from natural languages. When you look at software what you see is not language, but a machine. And it has a particular hierarchical structure.)
- Rusky 15y agoMentally folding sections of code is easier with multiple returns- the code that satisfies the conditions established by the early return is just the rest of the function, rather than until the denesting point you have to look for. RAII, GC, and/or try/finally solve the "error-proneness" of early returns, and in a language like C you can simulate that with a simple (good use of) goto.