Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single-entry/single-exit rule [closed]

I have read a rule somewhere to:

Follow the single-entry/single-exit rule. Never write multiple return statements in the same function.

Is this statement true? If that so, could you please give more detail as to why we should follow this rule?

like image 973
Nayana Adassuriya Avatar asked Oct 05 '12 11:10

Nayana Adassuriya


1 Answers

Is this true?

That's what the rule says, in places where it's used and enforced. Is it a good rule? I fight against its adoption tooth and nail. I think its a stupid rule. Worse than stupid: It's a harmful rule for C++.

I do agree with the first part of the rule, "single entry". The Fortran entry statement causes a lot more problems than it solves. This first part of the rule does not pertain to C or C++ for the simple reason that neither language provides a multiple entry point mechanism. "Single entry" is a no-op in C and C++.

So what about "single exit"? Early return does not necessarily cause problems. Failing to deal with allocated resources prior to returning is what causes problems. The right rule is "clean up your mess", or don't leave dangling resources. Single exit does not solve this problem because it doesn't say a thing about cleaning up your mess.

In C, the single entry / single exit rule typically goes hand in hand with allowing (and even encouraging) the use of goto for error handling. I can see the place for goto as used for error handling in the Linux kernel code. But not in C++. This is why I wrote that single entry / single exit is harmful in C++. This rule discourages the use of RAII and exception-safe programming and encourages the use of goto.

like image 149
David Hammen Avatar answered Oct 06 '22 00:10

David Hammen