Page 1 of 1

Best Code structure?

Posted: Mon May 30, 2011 11:45 am
by J0kerz
Hi,

I have a quick question regarding the best PHP Code structure.

What is better to do:

EXAMPLE 1

Code: Select all

if( STATEMENT 1 ){


		if( STATEMENT 2 ){

			//EXECUTE CODE HERE

		}else{

			exit;

		}

	}else{

		exit;

	}

Or EXAMPLE 2

Code: Select all

if (! STATEMENT 1){
	
		exit;
	
	}
	
	
	if (! STATEMENT 2){
	
		exit;
	
	}
	
	//EXECUTE CODE HERE


Is it better to code using a technique where you go deeper and deeper in the code following only if statement is met or is it better to do simple error check and just always stays "out" of the if statements?

I bet theres not much of a difference, but overall, which way should I choose?

Thanks guys!
;)

Re: Best Code structure?

Posted: Mon May 30, 2011 2:29 pm
by pickle
I generally go deeper and deeper. Having multiple exit/return points can make a function difficult to debug.

Re: Best Code structure?

Posted: Tue May 31, 2011 3:24 am
by Eran
Nested if .. else statements can be just as hard to debug as they can become unwieldy. Many times conditions can be combined or written differently to reduce the number of if .. else statements. Your first example could've been easily re-written as -

Code: Select all

if( STATEMENT 1 && STATEMENT 2 ){
    //EXECUTE CODE HERE
}else{
     exit;
}
Further, if you're using any kind of abstraction (which you should) such as classes or functions, then I would advise returning early with simple error checking since it make the code more readable than nested if .. else statements.

Re: Best Code structure?

Posted: Tue May 31, 2011 6:48 pm
by Christopher
I would also point out that using exit should be limited. It is essentially a goto and therefore defeats the organization of structured programming constructs like if's.

Re: Best Code structure?

Posted: Mon Jun 06, 2011 3:03 pm
by thinsoldier
It depends.

Just the other day I wrote some code like example one and today I read it and got lost and rewrote it as example 2.
Also today I had some code like example 2 that wasn't working exactly as I needed in all cases and the fix wound up looking like example 1.