Nested condition against return on unexpected result

Consider the following two coding styles:

Nested Conditions:

if(is_numeric($user_id)) { // .. do stuff if(is_valid_user($user_id)) { return foo($user_id); } else { return FALSE; } } else { return FALSE; } 

vs. just stopping when something is wrong:

 if(!is_numeric($user_id)) { return FALSE; } // .. do stuff if(!is_valid_user($user_id)) { return FALSE; } return foo($user_id); 

This, of course, is at least partially about taste; but what are these two different styles called?

When do you prefer each other?

Are there other, possibly cleaner coding styles?

+4
source share
3 answers

I generally adhere to the idea that least nesting is easier to read. For this reason, I prefer the second style. Of course, no matter what style you use, I would even slightly modify your second example to make it even easier to read.

 if(!is_numeric($user_id)) return FALSE; // .. do stuff if(!is_valid_user($user_id)) return FALSE; return foo($user_id); 

I have inverse expressions on the right that make them stand out. In addition, having everything on one line helps me present statements that are gates, and easily dumps code into sections ... but that's just me.

+1
source

You can completely disable else .

 if (is_numeric($user_id)) { // do stuff if (is_valid_user($user_id)) return foo($user_id); } return false; 

A bit cleaner, less code, still easy to read / understand.

+1
source

Another coding style related to your question has only one return for each method / function.

Schools often teach this principle. I think Martin Fowler was a proponent of this, based on some online searches.

The main reason is probably not related to PHP, but, for example, in C, if you have dynamically allocated memory in a function that needs to be cleared by returning everywhere, or leads to re-code, memory leak, or using goto to get code to free memory.

+1
source

All Articles