/    Sign up×
Community /Pin to ProfileBookmark

Best Code structure?

Hi,

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

What is better to do:

[B]EXAMPLE 1[/B]

[code=php] if( STATEMENT 1 ){

if( STATEMENT 2 ){

//EXECUTE CODE HERE

}else{

exit;

}

}else{

exit;

}[/code]

Or [B]EXAMPLE 2[/B]

[code=php] if (! STATEMENT 1){

exit;

}

if (! STATEMENT 2){

exit;

}

//EXECUTE CODE HERE
[/code]

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!
?

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@tracknutMay 30.2011 — Personally I try to avoid thinks like "exit" because they tend to be a "surprise!" similar to a "goto". So I would tend to write your example code as:

if (statement1 && statement2)

{

// do stuff

}
Copy linkTweet thisAlerts:
@NogDogMay 31.2011 — You could invert it, too, if you wanted. (I often like to tackle all my "rainy day" scenarios first.)
[code=php]
if(! statement 1 || ! statement 2) {
echo "<p>You idiot, you can't do that!</p>";
}
else {
// rest of code
}
[/code]

(Not necessarily "better" in any way, other than I find I like to work that way.)
Copy linkTweet thisAlerts:
@chrisecclesMay 31.2011 — You could invert it, too, if you wanted. (I often like to tackle all my "rainy day" scenarios first.)
[code=php]
if(! statement 1 || ! statement 2) {
echo "<p>You idiot, you can't do that!</p>";
}
else {
// rest of code
}
[/code]

(Not necessarily "better" in any way, other than I find I like to work that way.)[/QUOTE]


;-)

The error message, I love, NogDog !
-


I set my BBEdit tab expand to 2.

That way, the code is still clearly indented but you don't end

up with the 'staircase' effect driving complex routines off the

page wrap, and it's only 2 key clicks to delete an indent.

Just my 2¢

Chris
×

Success!

Help @J0kerz spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.11,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...