Forum Moderators: coopster

Message Too Old, No Replies

How do you format your IF/ELSE constructs and why?

         

JAB Creations

1:05 am on Jun 22, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A thought crossed my mind of two approaches to handling if/else constructs.

Here are the two examples I've thought about and I'm curious about the pros and cons when using both. In example does one promote better practices in the long term? What about possible influences on security? Over the long term does either one of these approaches pull ahead in performance compared to the other?

- John

if (!isset($_SESSION['signed-in-variable'])) {echo 'you must be signed in to do that!';}
else if (!isset($_SESSION['signed-in-permission'])) {echo 'you do not have permission to do that!';}
else if (!isset($_POST['required'])) {echo 'you are missing form data!';}
else if (strlen($_POST['title'])<16) {echo 'your title is too short';}
else
{
//do the intended actions here
}


...or...

if (isset($_SESSION['signed-in-variable']))
{
if ($_SESSION['signed-in-permission']<128)
{
if (isset($_POST['required']))
{
if (strlen($_POST['title'])<16)
{
//do the intended actions here
}
else {echo 'your title is too short';}
}
else {echo 'you are missing form data!';}
}
else {echo 'you do not have permission to do that!';}
}
else {echo 'you must be signed in to do that!';}

eelixduppy

1:18 am on Jun 22, 2010 (gmt 0)



I hate having to embed the main function of the code in if statements all over the place. Make it very difficult to read, and later when a modification needs to be made you have to pay close attention to the bracket placements. My scripts (or functions) follow this format most of the time:


#check args/assertions/etc..
#if not met, return/exit/etc...

#do useful work here


Notice that the script will return/exit if the conditions aren't met, long before the "meat" of the script is reached. So for example:


$required_args = array(
"func1" => array("param1", "param2", "param3"),
"func2 => array("param1", "param3")
);

$diff = array_diff($required_args[$func], $arguments);
if(!empty($diff))
{
printf("You are missing the following required arguments: %s", implode(',',$diff))
exit; //or return, whichever
}

// do useful code here


Makes it easier to handle if everything isn't embedded.

astupidname

3:07 am on Jun 22, 2010 (gmt 0)

10+ Year Member



if (!isset($_SESSION['signed-in-variable'])) {echo 'you must be signed in to do that!';}
else if (!isset($_SESSION['signed-in-permission'])) {echo 'you do not have permission to do that!';}
else if (!isset($_POST['required'])) {echo 'you are missing form data!';}
else if (strlen($_POST['title'])<16) {echo 'your title is too short';}
else
{
//do the intended actions here
}



...or...

if (isset($_SESSION['signed-in-variable']))
{
if ($_SESSION['signed-in-permission']<128)
{
if (isset($_POST['required']))
{
if (strlen($_POST['title'])<16)
{
//do the intended actions here
}
else {echo 'your title is too short';}
}
else {echo 'you are missing form data!';}
}
else {echo 'you do not have permission to do that!';}
}
else {echo 'you must be signed in to do that!';}



Both of those formats would be wrong, and rather sloppy looking to me. Contents of a code block {} (always, always, always use brackets! sloppy and unprofessional without) should not be on same line as the 'if' or 'else' or 'else if' statement, though the first bracket should be, seperated by a single space from the last paren ), and a single space between the 'if' or whichever and the first paren (. Plus, indentation must be used, and units of indentation should always be 4 spaces. Furthermore, when 'if' or 'else if' are followed by other 'else if' or 'else' statements, they should be placed immediately after a single space after the previous statements closing bracket, which should be on a seperate line. The most prominent, readable format is:

if (!isset($_SESSION['signed-in-variable'])) {
echo 'you must be signed in to do that!';
} else if (!isset($_SESSION['signed-in-permission'])) {
echo 'you do not have permission to do that!';
} else if (!isset($_POST['required'])) {
echo 'you are missing form data!';
} else if (strlen($_POST['title'])<16) {
echo 'your title is too short';
} else {
//do the intended actions here
}



Nesting is o.k. and can reduce overall amount of code needed at times, though I do try to avoid too much of it also. But in that case, it would be:

if (isset($_SESSION['signed-in-variable'])) {
if ($_SESSION['signed-in-permission']<128) {
if (isset($_POST['required'])) {
if (strlen($_POST['title'])<16) {
//do the intended actions here
} else {
echo 'your title is too short';
}
} else {
echo 'you are missing form data!';
}
} else {
echo 'you do not have permission to do that!';
}
} else {
echo 'you must be signed in to do that!';
}


Security? Don't believe there is any difference which would come from formatting. As for performance, any differences I suspect will be next to none. My main point here being the actual code formatting, as opposed to code layout.

Note that formatting is an area of some debate, some people or languages have other preferences such as using 2 spaces for indenting (I believe that's wrong, 4 is just right and most readable). I take my influence from when I learned javascript, taking my code convention influences from Douglas Crockford of Yahoo Code Conventions for the JavaScript Programming Language [javascript.crockford.com]
The format I show above is also most widely accepted and used in other languages such as Java and Actionscript.
I see brackets on individual lines (where not necessary to be on seperate line) as a beginners trait and big waste of space/lines, especially when you get in to bigger programs it's hideous.

If anybody's wondering, how to post formatted code on webmasterworld [webmasterworld.com]
Do not copy formatted code on webmasterworld from IE, use other browser such as Firefox.

penders

11:18 pm on Jun 22, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



if (!isset($_SESSION['signed-in-variable'])) { 
echo 'you must be signed in to do that!';
} else if (!iss.....


Yes, I tend to favour the same indentation style (I believe it's called "One True Brace Style" - 1TBS), although a 2 space indent is my preference, not 4. :)

I see brackets on individual lines (where not necessary to be on seperate line) as a beginners trait and big waste of space/lines, especially when you get in to bigger programs it's hideous.


I wouldn't have said this was necessarily a beginners trait. May be if they have come from other languages - yes. There are several well established indentation styles. I believe this is called 'Allman style' (there are other names) and is common in Java as well. My book on Java is full of examples in this style. It does offer the advantage over 1TBS that you can easily comment out (or replace) the control statement and leave the code block as is.

Wikipedia - Indent Style [en.wikipedia.org]

We seem to be discussing code layout / indentation style - I'm not even sure that that is the topic of this thread? Are we talking syntactical arrangement of the code here? In which case I think version 1 of your code is far easier to read and maintain than version 2?

Just another little thing that bugs me a bit, and I think it is more down to personal preference these days is... 'else if' and 'elseif' - I notice 'else if' is being used above, I would always use 'elseif' in this situation. They are not actually identical, although I believe with PHP5 they are as near as dammit the same thing. However, I'm sure 'elseif' was reported in the past (PHP4?) as being more efficient ie. quicker. Some languages don't have 'elseif' (no space) - PHP does.

JAB Creations

6:35 pm on Jul 14, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I've been AFK from online in general for far too long of late hence my late reply.

Sane indentation is what I prefer, two spaces is okay. My biggest preference though is to have curely brackets on their own line...

function func_name()
{

}


As it's a vertical alignment issue my eyes look up and down the code, not side to side. Some people may think that's too nit picky but I don't have split seconds to waste. ;)

I prefer a single space of indentation as I prefer to keep "finished" code clean and don't mind since it's "finished" to have a long horizontal scrollbar because I'm used to that in the application I use to code. However when I'm constructing something such as let's say a MySQL query I'll break it down to multiple lines until I'm getting the exact output I need.

Going back to the main purpose of my post I have spent time re-visioning chunks of my code to reduce the indentation and to reject things up front rather then rejecting things with else statements as I am finding it makes it more difficult to work around certain conditions and thus seems to greatly reduce the subjectivity of undesirable user input from wrecking havoc. :)

- John