Hey guys, well i’m at work again and i’m ready to write again…
I’ve decided write a small tutorial on clean coding for 2 reasons:
- I’ve seen an abundance of dirty and useless code come up on these forums.
- Bad code is incredibly hard to debug
So lets get started:
Say i’m making a script that grabs a users input from a form and then reproduces it on the screen. This is an example of dirty code to do this, which is the most common, because its quicker and easier:
<?php if ($submit){
echo $name; }
else {
echo "<form name=user method=post action=$PHP_SELF><input type=text name=name><input type=sumbit name=submit value=submit>"; }
?>
OK now you asking… “Whats wrong with that? I can read it!”. Yeh you can read it, but it isn’t good to look at, its just a jumble of characters. When debugging clean code is essential… This is how the code SHOULD look.
<?php
if ( isset( $submit ) )
{
$Name = $_POST['name'];
echo( "" . $Name . "" );
}
else
{
$Form = "<form name="user" method="post" action="$PHP_SELF"> <input type="text" name="name" /> <input type="submit" name="submit" value="Submit" />"
echo( "" . $Form . "" );
}
?>
Now, you’re thinking… What a waste of time creating a form variable, then calling it, instead of just echoing the form data.
Well, you right, however, what happens if you want to replicate that form later on? You can just echo the variable instead of echoing the wole form again… see… always thinking
OK, the next thing i’ll babble on about is code separating.
Heres a small snippet of dirty coding in an if statement that checks if a file exists:
<?php
$path = "/path/to/files";
if($file != "" && file_exists($path."/".$file.".php"")) {
include("$path/$file.php"); }
else {
include("default.php"); }
?>
This is the same code, properly separated:
<?php
$path = "/path/to/files";
if ( $file <> "" && file_exists( $path . "/" . $file . ".php" ) )
{
include( $path . "/" . $file. ".php" );
}
else
{
include( "default.php" ) ;
}
?>
Now isn’t that nicer and easier to read? OK, so you basically get the point now. double space all your brackets “( (” instead of “((” and “. $variable .” instead of “.$variable.”
I’ve also become very fond of <> as opposed to != for no other reason then it looks nicer.
OK, another thing i want to stress is how to echo variables. Alot of people think that using:
echo( "$variable" );
Is the best way to do it… However, to increase to the speed of your scripts i suggest one of the following ways:
1: echo $variable;
2: echo( "" . $variable . "" );
3: echo( $variable );
All of those work in the same way, but the best performance wise is simply: echo $variable.
Well, that ends part 1 of my clean coding tutorial, i’ll add new coding tips in my next article.
Happy Coding!