August 10, 2016


Coding Standard – Single Entry & Exit

Imagine a road where we have only one entry and one return, how simple and how easy it would be to manage the traffic and chaos. Now, replace the same scenario in the world of software coding, and replace the entry and exit statement in the function with cars on the road. Similar to the road with multiple entry and exit points, the software code with multiple entry and return will also become tough to manage and lead to much chaos, and the only way to avoid the chaos is to use a single entry and exit in a function.

A code written with multiple returns is often called "spaghetti code" and a code written with a single return is often called "structured code". A function should have only a single return, but along with a single return, we should also keep a check on the single entry for a function. Many people will get confused to hear single entry in a function, but yes, a few legacy programming languages like Assembly language and C allow user to create multiple entry points.

To state how single return functions are better than multiple return functions, a few examples are quoted below, which will show how a function with multiple returns make the function flow into a spaghetti like pattern and hence tough to understand and debug.

Remember that any code that is tough to understand and debug, is also tough to manage and is prone to introduce more defects.

In the example above, there is a comparison between single return function and multiple return function line with line. Though we have one extra variable allocated for return code, but still the function with single return is much simple to understand and debug the flow and the return code.

For C and C++ code, where the user can allocate Memory, with multiple exits you need to remember to free the allocated memory at every exit and a miss at one place will lead to a memory leak. In the code above, I have, for example, added only one memory allocation. Now, just imagine a big function with multiple allocation and the complexity involved to free the memory with multiple exit points, and it might lead to a humongous memory leak.

There are multiple ways in which code can be designed to avoid the multiple exits and use only one single exit in a function. There is no standard way and it all depends on the requirement on how and what is developing/coding and what Language is being used to code in.

One point to make here is many people argue that Single Exit point is no longer valid as there are IDEs that compile/recompile code at every keystrokes and analyze the issue there and then only, but still one thing we must remember is that a single exit code is easy to understand and hence, simple to debug and manage.