Clean Coding Part 1

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:

  1. I’ve seen an abundance of dirty and useless code come up on these forums.
  2. 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 :o

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!

hmm…

Few interesting points there…

But your HTML code isn’t well set-out, you should always have new items on a new line, it isn’t a must, but it makes html a whole lot easyer to use…

As for the php, I would only change a few things such as…

}
else
{

to
}else{
it doesn’t make a darned but of difference but it looks better and means less work.

Anyway, thats my 2 cents… Everyone has there own little ways (hell I like to tab everything, even on my html).

i tab as well. But all i’m trying to do here is help people keep clutter out of their code. Thats why i prefer always putting { in lines of their own, its easier to find out where you’ve closed off your braces, say you lose your spot.

Hey again

The conventions provided by evilcode may look “nice” to some, however they are not standardised. When using PHP, with it being an Open Source programming/language, it is very likely that several people will need to read your code. Code does not only need to be beautiful, it also needs to be readable, that’s the whole point of conventions.

The currently accepted standard revolves around the PEAR coding standards, found here: http://pear.php.net/manual/en/standards.php . I advise that everyone use these conventions… they increase readability, keep your code in a standardised structure and makes it pretty all in one :P.

Some other points such as avoiding shell (#) style comments and treating “Alternative Syntax” as the plague will also improve readability and make your code more accessible to other programmers.

Conventions should not only be used in coding, however you should use them in file/module/table naming as well. This aids in determining the purpose of files as well as their content types. This all makes your life easier… something that we develop applications for in the first place!

If anyone’s interested, here is a very brief list of some conventions, additional to the PEAR Standards, that I try and stick to:

CONVENTIONS

Comments: Single Line (//) for short, specific comments and structure
comments. Blocks (/* … */) for larger comments, documentation
entries, copyright notices etc.

Variable Naming: lowercase, underscores eg $variable_name

Constant Naming: uppercae, underscores eg SOME_CONSTANT

Function Naming: lowercase except first letters of terms eg FunctionName()

Class Naming: uppercase, underscores, OBJ_ prefix eg $OBJ_DATABASE
excepton: System Classes: SYS_ prefix

Table Naming: lowercase, tbl_ prefix eg tbl_name

Database Naming: lowercase, db_ prefix eh db_databasename

File Naming:
includes: .inc.php suffix
config: .cfg.php suffix
classes: .cls.php suffix
setup: _ perfix, .stp.php suffix

HTML Template Tagging: <tpl prefix, /> suffix for non-Smarty engines

Prefixes should be avoided. They might make a self documentation but also make your code senseless. I don’t know about you, but to me, it’s quite obvious that the identifier after a ‘new’ is a class name. No need to mention it in the name itself. Microsoft did something similar by prefixing all classes by a C, it’s plain horrible and an extra caracter to type too often.

As someone who has been coding PHP only since July 29, 2003, I thought that variable names were supposed be of the form: $firstSecondThird. Now I see a comment by camtech that says variable names should be: $first_second_third.

Ninety-plus percent of the PHP code I see is of the form $firstSecond.

What is THE answer. I am trying to learn the correct rules as I enter this (new to me) language.

thanks,
dave

PHP has absolutly no strict rules about this as Java does. There are the PEAR standards, which are applied to everything in the PEAR library and that most seem to apply to their code slowly. They are highly inspired by the Java standards. I personally don’t think having a global standard is needed, you can use one if you like it, as long as you keep the same rules during your entire application, there is no real problem.

Although it is an interesting setup, I do code like that mostly, although though is one little different that I do…

Its just the alignment of brackets and how i look at it, its its my style i have no problem debugging it, but others may?

[php]
function DetermineClass ($class, $birth) {

if ((!$class) || (!$birth)) {
return FALSE;
} else {
return (“Your Charecter of the $class class was born on $birth”);
}

                                                       }

DetermineClass(Jedi, Tattoine);
[/php]

Something like that anyways…

But Hey, thats just my style, and thats how I edit and write it… its not like anyone else edits my stuff anyways.

You don’t seem to be able to locate errors the way you code, there is a missing closing bracket.

I have a missing bracket?? Where? I count 3 open & 3 closed?

If your talking about the functions closing bracket, look straight under the opening one.

On my screen it’s on the oppsosite side of the screen. I align my brackets like you do, but the opening one is not on the same line as the condition/parameters:

function foo($bar)
{
    if( $bar == 'foo' )
    {
        //...
    }
}

It’s quite a standard method. I like it because it spaces the code and makes it very clear.

I code like so:

if($var == '')
{
     if($var == '')
     {
          if($var == '')
          {
                echo 'tada';
          }
     }
}

I tab like a monkey, so its easy for me to remember that there is a } each tab until i get to the left margin. Ex:

          }
     }
}
?>

I’ve also been switching to single quotes instead of double recently… Muche easier i might add :)

Sponsor our Newsletter | Privacy Policy | Terms of Service