Best Code structure?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
J0kerz
Forum Commoner
Posts: 37
Joined: Fri May 29, 2009 2:51 pm

Best Code structure?

Post 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!
;)
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Best Code structure?

Post by pickle »

I generally go deeper and deeper. Having multiple exit/return points can make a function difficult to debug.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Best Code structure?

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Best Code structure?

Post 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.
(#10850)
thinsoldier
Forum Contributor
Posts: 367
Joined: Fri Jul 20, 2007 11:29 am
Contact:

Re: Best Code structure?

Post 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.
Warning: I have no idea what I'm talking about.
Post Reply