I thought i would spend a little time writing a bit about how to write clean PHP code (or clean code in general) as a few fellow webdevelopers (including myself) have been complaining about how most new users write horrible code.
Badly written code is bad, that's primordial;
Primo, it's bad for yourself, it is scientifically proved that it makes you depressive and have led several programmers to suicide.
Messy code is an ideal hideout for wild coding errors: they will elegantly fade into the chaos, thus being hard to detect.
(Nota Bene: An error can be a missing semi-colon or a missing parenthesis, etc..)
Secondly, it's bad for the people who devote their time to help you. The main trigger for me writing this is this thread. I would help, but the code is too messy. If you want fellow programmers to be able to help you, you gotta give them a chance to understand the code at first glance. We won't spend our evening deciphering your code, really.
How can you write cleaner code?
First step will be to choose your favorite text editor. This step is important as you will most probably stick to this editor until the rest of your life
Next thing to do, it look into the syntax highlighting settings (depending how personalisable the software is) and the indentation settings.
the what?
..the indentation settings!
That's one of the most important thing to say: INDENT!
indent, tab..whatever you call it.
Why would you do that..?!
Indenting (correctly) will give you an almost godly overview of your code.
In a matter of 1/12th of a second, you'll be able to tell where a chunck of code ends, where a function starts...
an example (from the thread i mentioned above):
bad:
PHP Code:
function isrequired($s, $v) {
global $fields_required;
if (in_array($v, $fields_required)) {
echo $s;
}
}
better:
PHP Code:
function isrequired($s, $v) {
global $fields_required;
if (in_array($v, $fields_required)) {
echo $s;
}
}
Can you see the difference? I hope you can
I can assure you, you would see the difference at larger scales.
Almost every programming, markup, styling language ignores tabs and whitespaces (except whitespace, hehe), so let's take advantage of that.
(
PS:
the above code chunk could have been written like this:
PHP Code:
function isrequired($s, $v) {
global $fields_required;
if (in_array($v, $fields_required)) {
echo $s;
}
}
)
The Curly Braces Idyl:
Curly braces are elegant, fragile beings. Their hearts can easily be broken, so they should be handled with the necessary care.
One thing you should know: They always come in pair! (Failing to provide a fellow curly brace will generate an error, and break their hearts)
If you write flat, dull code, it won't be hard to forget one, see:
PHP Code:
<?php
$dir = "/etc/php5/";
function listdir($dir)
{
if (is_dir($dir))
{
if ($dh = opendir($dir))
{
while (($file = readdir($dh)) !== false)
{
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
}
?>
See! Which curly brace belongs to which?!
How hard would it be to mistype and add or forget one if you already have 3 braces in a row (see last 4 lines in example code above)
I'll now post the readable version of the code for you to see the difference in readability:
PHP Code:
<?php
$dir = "/etc/php5/";
function listdir($dir)
{
if (is_dir($dir))
{
if ($dh = opendir($dir))
{
while (($file = readdir($dh)) !== false)
{
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
}
?>
Now, if you wonder which one belongs to which one just follow a vertical line from any curly braces.
You might have noticed that some people have the opening curly brace on the same line as the function name and the closing one under it:
PHP Code:
function fictional($parameter){
// dream
}
while other people will do:
PHP Code:
function fictional($parameter)
{
// dream
}
That really is a matter of choice! (personally i much prefer the first one)
Spaces and com(ets)as:
As i said previously, use spaces!
e.g.:
PHP Code:
list($drink,$color,$power)=$info;
instead, write:
PHP Code:
list($drink, $color, $power) = $info;
i usually leave one space after a coma, if it gets extra messy and long (for example in an INSERT query) i leave a space before and after the coma.
Additional infos
Don't post "I didn't write it!" as an excuse, if you are using code that you didn't write, need it, but find it awfully written, then correct it!
Add the necessary comments, spaces and tabs!
When creating custom functions, you might want to add a comment line above it, presenting it like the PHP manual:
PHP Code:
bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]] )
bool being the type returned (void, bool, int, resource, str, array, mixed)
mail is obviously the function's name
and the rest are the function's parameters (or pseudo parameter's name) and their respective types.
Those in square brackets designate optional parameters. It is advised that they appear in your comments too.
At last i will show you an example of a custom function
(This is a function i used in an application, so it has quite limited use for you, just look at the structure, and pre-function comments)
PHP Code:
<?php
##############################################################
#
# xml2array()
#
##############################################################
#(Short description)
# xml2array() turn a preformatted XML file into an array
#
##############################################################
# array xml2array(str filename)
function xml2array($xml_file){
# loading file
$xml = simplexml_load_file($xml_file);
if(!$xml){
# could not load file
return false;
}
# reading values from xml
$dvd_list['userid'] = $xml->userid;
The bottom line is this: Each question deserves no more than a certain amount of time and effort from the few stalwart volunteers that answer the majority of the questions posed in this forum. Interesting and unusual questions of course deserve more time than the regular, mundane ones. If one of these volunteers looks at your code and sees that it would require an unreasonable amount of time and effort to correct because you haven't bothered to indent it properly or haven't used the [ PHP][/PHP] tags many of them will just move on to the next thread where the person asking the question has made more effort. I personally have completely stopped answering questions that are not encapsulated within [ PHP][/PHP] tags. If you want your questions to get the maximum coverage from the widest knowledge base take note of the recommendations in this thread; it's in your interest.
This is all good advice for new users. The only problem is that new users will probably never read it, especially if stickied (word?). The sticky zone, it seems, is in almost every new user's blind spot.
Here's a good suggestion for the forum that I think I read somewhere in one of the stickies here:
A user should not be allowed to post until they have read (or at least visited) the "read this first" stickies and should be notified that failing to follow posting guidelines will likely result in an unanswered question.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Its up to the coder to decide which way they want to do it. Personally, I prefer the first method also. The second method requires too many extra lines that just aren't necessary and don't improve readability (IMO).
Its up to the coder to decide which way they want to do it.
Not if you're working for a company that has coding standards which state that you are specifically to do it one way or the other.
Personally, I prefer the first method also. The second method requires too many extra lines that just aren't necessary and don't improve readability (IMO).
--Steve
Personally, I find the method with the opening brace on its own line much easier to read, especially when you start getting complex nestings of loop and if/else blocks - my eyes just seem to see the structure more easily that way. But what works best for me doesn't necessarily work better for anyone else.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
function gadget($gadgets)
{
foreach($gadgets as $gadget)
{
if(false !== $gadget)
{
echo $gadget;
}
}
}
My vote goes to the above method. The whole point of indenting is so it is clear which opening curly brace is paired with which closing curly brace. When separated vertically without any offset I find it very clear.
Bookmarks