 |
Account Login
|
 |
 |
Latest Articles
|
 |
 |
IRC Channel
|
 |
 |
Associates
|
 |
 |
Associates
|
 |
|
 |
 |
|
 |
05-06-2009, 06:18 AM
|
#1 (permalink)
|
|
The Contributor
Join Date: May 2009
Location: West Midlands
Posts: 26
Thanks: 2
|
Curly brackets!
Hi all
I have just completed my first useful script (not completely functional yet but that's for another thread!) and I am boggled by the number of curly brackets i have ended up with lol!
I basically had to go through using comments to number them and check they were all opened and closed correctly.
Funds do not allow the purchase of coda yet (which i presume has a clever gismo to prompt me on this) so I wondered what basic methods you more experienced coders use to keep track of these slippery little blighters!
Thanks :)
|
|
|
05-06-2009, 07:10 AM
|
#2 (permalink)
|
|
The Contributor
Join Date: May 2009
Location: West Midlands
Posts: 26
Thanks: 2
|
Ok Iknow - double posting but found something I didn't know about. Smultron (open source text editor for macs) does do something just never realised!
When you make a bracket (square, curly, round) it flashes the coressponding one, of beeps if it can't find one. Yey!
Would still ike to hear tips tho as I don't always hear the beep! :)
|
|
|
05-06-2009, 12:00 PM
|
#3 (permalink)
|
|
The Gregarious
Join Date: Feb 2009
Location: New York
Posts: 645
Thanks: 64
|
You can try to do things short handed, so if you have a quick conditional, you don't have to use brackets like so:
if($a) {
echo "hello";
}
That's 2 brackets you have to worry about. But you can just do this:
if($a) echo "hello";
|
|
|
|
05-06-2009, 12:10 PM
|
#4 (permalink)
|
|
The Contributor
Join Date: May 2009
Location: West Midlands
Posts: 26
Thanks: 2
|
Would this work if i have lots of if elses inside a main if else?
|
|
|
05-06-2009, 12:23 PM
|
#5 (permalink)
|
|
The Gregarious
Join Date: Feb 2009
Location: New York
Posts: 645
Thanks: 64
|
Quote:
Originally Posted by Guezala
Would this work if i have lots of if elses inside a main if else?
|
Yeah..you can do this....
if($var) echo "Hello";
elseif ($var == "something") echo "Hello 2";
else echo "Hello 3";
Just don't get too carried away I guess....
If you really have a lot of conditionals, it might be faster to use switch function.....
|
|
|
|
05-06-2009, 12:45 PM
|
#6 (permalink)
|
|
Moderateur
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
|
Whilst removing curly braces where they're not strictly necessary might seem like a good idea, in practice it's all too easy run into problems as a result. I guess my most practical advice would be to use good indentation in your code.
For example:
PHP Code:
if (condition) {
if (condition)
// do something
else
// do something else
} else {
// do something else entirely
}
Compared to:
PHP Code:
if (condition)
{
if (condition)
{
// do something
}
else
{
// do something else
}
}
else
{
// do something else entirely
}
Also, don't try to nest things too deeply. If there are lots of nested blocks it can quickly get confusing as to what the current block does and when. Code can often be rewritten to keep the nesting fairly shallow and clear as to what is going on. If there are 200 lines (just an arbitrary number) between opening and closing braces of an if statement, perhaps it's time to rethink the structure.
|
|
|
|
05-06-2009, 12:53 PM
|
#7 (permalink)
|
|
The Contributor
Join Date: May 2009
Location: West Midlands
Posts: 26
Thanks: 2
|
Yeah i'm thinking i might try the switch function. Thanks for that both :)
Ya never know i might post some code later... a bit too ashamed of my teensy weensy effort to show it yet lol :D
|
|
|
05-06-2009, 01:12 PM
|
#8 (permalink)
|
|
The Gregarious
Join Date: Feb 2009
Location: New York
Posts: 645
Thanks: 64
|
Quote:
Originally Posted by Guezala
Yeah i'm thinking i might try the switch function. Thanks for that both :)
Ya never know i might post some code later... a bit too ashamed of my teensy weensy effort to show it yet lol :D
|
Don't be ashamed. I have so many posts with questions, it's really the best way to go about it.
Just do yourself some justice and try to code as much as possible and then ask for help unless you have a "theoretical" question about how something works...
I think what irks a lot of people here and on other message boards are people who don't even bother to try and they just want someone to provide code for them...
|
|
|
|
05-06-2009, 01:15 PM
|
#9 (permalink)
|
|
Wizard
Join Date: Sep 2007
Posts: 1,299
Thanks: 17
|
Quote:
Originally Posted by allworknoplay
You can try to do things short handed, so if you have a quick conditional, you don't have to use brackets like so:
if($a) {
echo "hello";
}
That's 2 brackets you have to worry about. But you can just do this:
if($a) echo "hello";
|
While it may seem like wisdom at the time to this, it is bad practice and can lead to bugs more easily.
Always indent your code, without indents code is half impossible to read. That should take care of half your problems right there.
|
|
|
|
05-06-2009, 01:21 PM
|
#10 (permalink)
|
|
The Gregarious
Join Date: Feb 2009
Location: New York
Posts: 645
Thanks: 64
|
Quote:
Originally Posted by Village Idiot
While it may seem like wisdom at the time to this, it is bad practice and can lead to bugs more easily.
Always indent your code, without indents code is half impossible to read. That should take care of half your problems right there.
|
Right, I can see that...is it really bad practice though to do it for a quick line like in my example, as long as it doesn't get too nested like Salathe mentioned...??
I just feel, if I need to check something, and echo it, I'd rather save the trouble of using brackets, but if I have to use multiple else/if statements, then I would use brackets...
Here's an example if I want to do a quick exit...
$a = 10;
if($a == 10) exit;
|
|
|
|
05-06-2009, 01:43 PM
|
#11 (permalink)
|
|
La Vida es Sueño
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
|
Salathe said it right when he said don't indent too deeply. I always avoid that whenever I can. I dislike even having an if within an if; sometimes it's unavoidable. Nor do I like adding else statements, again, sometimes it cannot be helped!
For instance, to give a simple example, instead of adding an else for a return statement, I would aim to return that within the if statement, and knowing that if, as below, it did evaluate to true then it wouldn't reach the second return, and thus saving us an else.
php Code:
function doThisAndThat($bTrueOrFalse) { if ($bTrueOrFalse) { return 'It is true'; } /* If the above is true we can be sure it's NOT true here. */ return 'It is false'; }
In addendum to this, I also like to make good use of continue in loops. For example:
php Code:
foreach ($aMember as $pMember) { if ($pMember->isNotLoggedIn()) { continue; } /* Again, if the above evaluates to true then it wouldn't get here. */ $aLoggedIn[] = $pMember; }
That also saves us an else, and makes our code, at least in my eyes, much easier to read.
I don't know if I can explain this awfully well, but I like to exclude all the items we don't want in the subsequent code first, instead of deciding what we need to include, and then placing an else at the bottom to handle the exclusions.
This is the way I wouldn't do it (I wish to save the good way for the end so your mind retains it!)
php Code:
if ($bTrueOrFalse) { /* The bad way: Handle the stuff we want to include and process. This is the main chunk of our code and so likely to contain many loops and conditionals. */ } else { /* Handle the exclusions. Likely to contain many else statements. */ }
Last but not least, the way I would do it, as in the first two examples, is like so:
php Code:
if ($bTrueOrFalse) { /* This stuff is not required by the below code as it has an undesirable attribute/property. */ continue; /* Therefore we exclude it and continue. */ }
/* Continue with the stuff that we really do need to include, now that we've filtered out all the bad stuff. Instead of handling what we need first and then adding an else at the bottom to handle the exclusions. */
In simple form it could be shown as the following:
(I found this UML diagram creator yesterday via Reddit. Seems quite useful! Seems it can also be used for lovely flow charts.)
The underlining assumption behind this way of working is that the chunk of code required for processing exclusions will be smaller than the code for processing inclusions. Inclusions being the items we want to work with. This saves us having huge chunks of code for processing inclusions, and then having lots of isolated else statements at the bottom handling exclusions.
Hopefully this more real-life example will crystallise this in your mind:
php Code:
if ($pMember->isInactive()) { /* Member is not active, so we don't want to deal with this. It becomes an excluded item. Perhaps we want to also send an email to inactive members to remind them to activate their accounts. */ $pMember->sendReminder(); return; }
if ($pMember->isAdministrator()) { /* Member is an administrator, and we don't wish to work with administrators in this scenario, again, exclude this item. */ return; }
/* We now have a list of members who are active and are not administrators. Perfect! Let's begin work on processing that now. These are what I call "inclusions", whereas the above two process the "exclusions" -- items we don't require in this process. */
/* This is likely to be the epicentre of the code... */
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Last edited by Wildhoney : 05-06-2009 at 03:24 PM.
|
|
|
05-06-2009, 01:57 PM
|
#12 (permalink)
|
|
The Gregarious
Join Date: Feb 2009
Location: New York
Posts: 645
Thanks: 64
|
wow WH:
You are quite thorough....you and Salathe...
Anyways, do you think there are any performance benefits of including the inclusions first?
Or is this just simply just a preferable method that utilizes "continue" which I normally don't use in my everyday tasks...but I can see how it is useful in your example..
Also, it's probably just preference with a mixture of good coding practice, but in your other example you have this:
PHP Code:
function doThisAndThat($bTrueOrFalse) { if ($bTrueOrFalse) { return 'It is true'; } /* If the above is true we can be sure it's NOT true here. */ return 'It is false'; }
Would you ever do this or think this looks cleaner?
I know how much you hate using "else"...
PHP Code:
function doThisAndThat($bTrueOrFalse) { if ($bTrueOrFalse) return 'It is true'; else return 'It is false'; }
EDIT: I see you added more after I posted which kinda answers my question.
Quote:
|
The underlining assumption behind this way of working is that the chunk of code required for processing exclusions will be smaller than the code for processing inclusions.
|
|
|
|
|
05-06-2009, 02:16 PM
|
#13 (permalink)
|
|
La Vida es Sueño
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
|
In your example, you really don't need that else for the return because it's going to happen irrespective of anything else. In those examples where it either is or isn't, then check for an is, and the isn't will be the default.
Think of it in binary terms, yes/no, true/false, 0/1. If you check for the yes (true, 1), then the no (false, 0) is the resulting value, and can be returned as such.
It's when you introduce more complicated conditionals that it requires more thinking on your behalf, such as with hexadecimal (base-16), and even our base-10 counting system. Anything other than base-2 (binary), where we only have the possibility of 2 outcomes, which is fundamentally how computers work (and many more things, too), and so tends to be used quite commonly in everyday life, and to keep the topic relevant, in programming also.
I don't think there is any such performance gain, it's personal preference for readability, really.
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
|
|
|
05-06-2009, 02:28 PM
|
#14 (permalink)
|
|
The Gregarious
Join Date: Feb 2009
Location: New York
Posts: 645
Thanks: 64
|
Quote:
Originally Posted by Wildhoney
In your example, you really don't need that else for the return because it's going to happen irrespective of anything else. In those examples where it either is or isn't, then check for an is, and the isn't will be the default.
Think of it in binary terms, yes/no, true/false, 0/1. If you check for the yes (true, 1), then the no (false, 0) is the resulting value, and can be returned as such.
It's when you introduce more complicated conditionals that it requires more thinking on your behalf, such as with hexadecimal (base-16), and even our base-10 counting system. Anything other than base-2 (binary), where we only have the possibility of 2 outcomes, which is fundamentally how computers work (and many more things, too), and so tends to be used quite commonly in everyday life, and to keep the topic relevant, in programming also.
I don't think there is any such performance gain, it's personal preference for readability, really.
|
Thanks, so this would work....
PHP Code:
function doThisAndThat($bTrueOrFalse)
{
if ($bTrueOrFalse) return 'It is true';
return 'It is false';
}
But I can see how that would look confusing so I wouldn't want to do it that way either....
I think for advanced programmers like yourselves, there becomes a thin line between preference and proper coding...although I tend to see more on the latter....
I've seen debates in the past on just where to place the brackets...
ex:
if() {
or
if()
{
Stuff like that when at the end of the day it's just preference...
|
|
|
|
05-06-2009, 03:36 PM
|
#15 (permalink)
|
|
The Contributor
Join Date: May 2009
Location: West Midlands
Posts: 26
Thanks: 2
|
Blimey!
Well I need some chocolate now and a brain transplant. I'd hate to see your advanced section!
Since we have veered a bit i will take this opportunity to ask a more specific question.
Basically the if elses i was talking about would do this:
Firstly check if all my variables (answers to questionnaire) were not set. If not set, prompt to fill in.
Then progressing to validating some user info using some simple regexes (5 variables in total), then to print out a thankyou message and format an email to myself with all the inputed info.
I have all the code.... just not sure how I am going to join it.
If I use switch then can i ask first if the variables are set, then that each of the user info variables are valid then print thankyou and send mail? I don't think I can use foreach because they are diff regexes for each input.
I really thought I had this but brain is mush now :(
|
|
|
05-06-2009, 03:57 PM
|
#16 (permalink)
|
|
The Gregarious
Join Date: Feb 2009
Location: New York
Posts: 645
Thanks: 64
|
Quote:
Originally Posted by Guezala
Blimey!
Well I need some chocolate now and a brain transplant. I'd hate to see your advanced section!
Since we have veered a bit i will take this opportunity to ask a more specific question.
Basically the if elses i was talking about would do this:
Firstly check if all my variables (answers to questionnaire) were not set. If not set, prompt to fill in.
Then progressing to validating some user info using some simple regexes (5 variables in total), then to print out a thankyou message and format an email to myself with all the inputed info.
I have all the code.... just not sure how I am going to join it.
If I use switch then can i ask first if the variables are set, then that each of the user info variables are valid then print thankyou and send mail? I don't think I can use foreach because they are diff regexes for each input.
I really thought I had this but brain is mush now :(
|
Can't you do a loop for the majority of the inputs and then for the 5 variables do those using regex?
I'll try to come up with a quick example unless someone comes up with one before I do....
|
|
|
|
05-06-2009, 04:23 PM
|
#17 (permalink)
|
|
The Gregarious
Join Date: Feb 2009
Location: New York
Posts: 645
Thanks: 64
|
Ok this is a really bad example but it does work somewhat and perhaps you can pick some stuff out of it. I personally am trying to code everything in OO now, but I just wanted to provide you with something.
Again, this is pretty bad...but it works...if anything, maybe you can learn not to do it this way...LOL...
PHP Code:
//CHECK YOUR POST VARIABLES FOR ANYTHING EMPTY
if(in_array("",$_POST)) {
//some variable is empty so set $check01 = false;
$check01 = false;
}else {
$check01 = true;
}
//do your other checks here
//lets just say it passes, so $check02 = true
$check02 = true;
if($check01 == true && $check02 == true) {
//input data and send email
echo "everything checks! send email.";
}else{
echo "You need to enter all fields.";
}
|
|
|
|
05-06-2009, 05:37 PM
|
#18 (permalink)
|
|
La Vida es Sueño
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
|
This may seem quite complex and superfluous, and it probably is just that for an example. However, I've tried to keep it as modular as possible (No use of exceptions, classes, et cetera...) as I remember what I was like when I first began learning PHP. Didn't know a damn thing!
The theory for the script is as follows:
- Notify the script of what we require from the form: required fields, and regular expressions (regex);
- Weed out all the bad items and return those immediately if they fail the validation process;
- If all is well with the items in the form data then
return true;
php Code:
function TalkPHP_Is_This_Form_Valid (array $aFormData){ /* Set a default return that will be returned if validation fails. */ $aValidatedForm = array('status' => false); /* The validation rules, specifying an optional regular expression to validate that field. Fields without expressions will be ignored. */ $aValidationRules = array('Username' => null, 'Name' => null, 'Age' => '\d', 'DoB' => '\d{2}-\d{2}-\d{4}'); /* Loop through the validation rules specified above. We're going to be working in the fashion of: exclude, include. Check all the exclusions first (those that return false). If all is well at the end of the loop, return true as it passed! */ foreach ($aValidationRules as $szKey => $szRegex) { /* Check to see if the item even exists in the form data. */ if (! array_key_exists($szKey, $aFormData)) { /* Specify a message so that the user knows what he or she did wrong. */ $aValidatedForm[ 'message'] = $szKey . ' does not exist'; return $aValidatedForm; } /* Check to see if the item is simply empty (null, blank). */ if (empty($aFormData[ $szKey] )) { /* Do the same as above to inform the individual. */ $aValidatedForm[ 'message'] = $szKey . ' cannot be empty'; return $aValidatedForm; } /* Check to see if we have specified a regular expression for this field. */ if (is_null($aValidationRules[ $szKey] )) { /* Continue the loop if not. This item passed validation if it got this far. */ continue; } /* Validate the value against the regular expression specified for this field at the top of the function. */ if (! preg_match('~' . $aValidationRules[ $szKey] . '~i', $aFormData[ $szKey] )) { /* Set the message as usual to notify them of this error. */ $aValidatedForm[ 'message'] = $szKey . ' syntax is invalid'; return $aValidatedForm; } } /* Everything passed and validated as we expected and so we can return true knowing that if something failed in the form data, our script wouldn't have gotten this far. */ $aValidatedForm[ 'status'] = true; return $aValidatedForm; }
php Code:
/* Our array that contains all the form data. Such form data fields can be constructed using either PHP (Looping through _GET/_POST) or by naming your form items as like: name="my_form[Name]" */$aVariables = array( 'Username' => 'Wildhoney', 'Name' => 'Adam', 'Age' => 23, 'DoB' => '10-10-1985'); /* Validate the form using the values above. */$aValidatedForm = TalkPHP_Is_This_Form_Valid ($aVariables); if (! $aValidatedForm[ 'status'] ){ /* If the validation failed then display the message to the user. */ echo 'Oops: ' . $aValidatedForm[ 'message']; }else{ /* Otherwise... voila! */ echo 'Thank you.'; }
I apologise, as it does look confusing to begin with, even to me! However, you'll begin to understand it, I am sure, after a few glances, and after a few questions.
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
|
|
|
|
The Following User Says Thank You to Wildhoney For This Useful Post:
|
|
05-06-2009, 05:50 PM
|
#19 (permalink)
|
|
The Gregarious
Join Date: Feb 2009
Location: New York
Posts: 645
Thanks: 64
|
Quote:
Originally Posted by Wildhoney
I remember what I was like when I first began learning PHP. Didn't know a damn thing! 
|
That must have been so long ago.....hard for me to even imagine...

|
|
|
|
05-06-2009, 08:25 PM
|
#20 (permalink)
|
|
The Contributor
Join Date: May 2009
Location: West Midlands
Posts: 26
Thanks: 2
|
Ah ok i will have a play tomorrow. Thanks. Might post a link once i have fiddled some more. :) Thanks all for your eager responses :D
|
|
|
|
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
|
|
|
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Linear Mode
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|