Site icon ucdev

Single point of exit

This article is intended for programmers with some experience in embedded device programming who want to improve the quality of their code. What we cover today is the programming practice of implementing a function in such a way that there is only one place in the code to return value and also exit that routine, and usually it is at the and of the function block. This is called a single point of exit. There is a strong belief among experienced developers, confirmed by some standards such as MISRA C, that this approach is much better than having multiple exit points. To answer the question of whether a single exit point is really better than multiple exit points, let’s talk a bit about the pros and cons of each solution and then draw some conclusions.

In the screenshot below you can see two snippets of code. The one on the left shows multiple exit points, and the one on the right does the same but has only one exit point.

Single point of exit pros and cons

Are there any benefits to using multiple exit points?

The final verdict

As you have probably noticed, there are many advantages to using a single exit point, and there are no serious drawbacks to this solution. We can’t say the same for multiple exit points, especially if the function is large and involves dynamic memory allocation. Exiting too early can cause serious problems. However, there are some situations where there is not much difference, and a single exit point is more natural. These situations usually arise when writing simple „if else” logic, so always balance readability and practicality to decide whether a single exit point makes sense for a particular function, but in general this is the recommended solution, especially when:

Usefull links:

Exit mobile version