Standards for Exiting a Function

Possible duplicate:
Why should a function have only one exit point?

As a CS student, it hit me in the head that there should be only one exit point at the end.

eg. It:

function foo() { //do stuff here if($bar) { $out = FALSE; } else { $out = TRUE; } return $out; } 

Not:

 function foo() { //do stuff here if($bar) { return FALSE; } return TRUE; } 

However, I saw that this second type of exit was used quite often in the code of other people in php and even in the main code for some frameworks (for example, Kohana, which I used recently). Is this method of exiting a function considered acceptable in php standards?

Edit: I see why I was told not to do this, since it will be easier to track some problems in a function with one exit point, sometimes I see why this should be resolved, since other problems are better solved or tracked in functions with multiple exit points .

Edit 2: added β€œmake stuff here” comments in the sample code to make people happy

+4
source share
3 answers

I always used the last route, since you need to declare $out and have another variable. But in retrospect, it is just logical - it does no harm. The first route may look cleaner, depending on the context of your code.

It all comes down to consistency . As long as you have a system that determines when it is time to use route 1 or route 2, you feel great.

+2
source

These are six of one, or half a dozen of the other - happiness is consistency.

+2
source

I saw (good) return code in both directions. If you use a framework / codebase that sequentially uses one method, I will follow this. Otherwise, use whatever is convenient for you .: D

+2
source

Source: https://habr.com/ru/post/1415995/


All Articles