7 Practices for Writing Good Code


Having delved into the world of programming for many years, but only now really taking it seriously on a personal level and a teaching level, I can see how important clean coding and commenting can be.

“Code readability is a universal subject in the world of computer programming. It’s one of the first things we learn as developers.” – Burak Guzel

Adapted and paraphrased from Top 15+ Best Practices for Writing Super Readable Code.

Also see Source Code Comment Styling: Tips and Best Practices.

1 - Commenting and Documentation

1 – Commenting & Documentation

IDE’s (Integrated Development Environment) have come a long way in the past few years. This made commenting your code more useful than ever. Following certain standards in your comments allows IDE’s and other tools to utilize them in different ways.


2 - Consistent Indentation

2 – Consistent Indentation

There is more than one way of indenting code.

Style 1

function foo() {
    if ($maybe) {
        do_it_now();
        again();
    } else {
        abort_mission();
    }
    finalize();
}

Style 2

function foo()
{
    if ($maybe)
    {
        do_it_now();
        again();
    }
    else
    {
        abort_mission();
    }
    finalize();
}

Style 3

function foo()
{   if ($maybe)
    {   do_it_now();
        again();
    }
    else
    {   abort_mission();
    }
    finalize();
}


3 - Code Grouping

3 – Code Grouping

More often than not, certain tasks require a few lines of code. It is a good idea to keep these tasks within separate blocks of code, with some spaces between them.

Here is a simplified example:

// get list of forums
$forums = array();
$r = mysql_query("SELECT id, name, description FROM forums");
while ($d = mysql_fetch_assoc($r)) {
    $forums []= $d;
}
 
// load the templates
load_template('header');
load_template('forum_list',$forums);
load_template('footer');

Adding a comment at the beginning of each block of code also emphasizes the visual separation.


4 - Consistent Naming Conventions

4 – Consistent Naming Conventions

First of all, the names should have word boundaries. There are two popular options:

  • camelCase: First letter of each word is capitalized, except the first word
  • underscores: Underscores between words, like: mysql_real_escape_string()


5 - Avoid Deep Nesting

5 – Avoid Deep Nesting

Too many levels of nesting can make code harder to read and follow.

function do_stuff() {
 
// ...
 
    if (is_writable($folder)) {
 
        if ($fp = fopen($file_path,'w')) {
 
            if ($stuff = get_some_stuff()) {
 
                if (fwrite($fp,$stuff)) {
 
                    // ...
 
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}

For the sake of readability, it is usually possible to make changes to your code to reduce the level of nesting:

function do_stuff() {
 
// ...
 
    if (!is_writable($folder)) {
        return false;
    }
 
    if (!$fp = fopen($file_path,'w')) {
        return false;
    }
 
    if (!$stuff = get_some_stuff()) {
        return false;
    }
 
    if (fwrite($fp,$stuff)) {
        // ...
    } else {
        return false;
    }
}


6 - Limit Line Length

6 – Limit Line Length

It is a good practice to avoid writing horizontally long lines of code.

// bad
$my_email->set_from('test@email.com')->add_to('programming@gmail.com')->set_subject('Methods Chained')->set_body('Some long message')->send();
 
// good
$my_email
    ->set_from('test@email.com')
    ->add_to('programming@gmail.com')
    ->set_subject('Methods Chained')
    ->set_body('Some long message')
    ->send();
 
// bad
$query = "SELECT id, username, first_name, last_name, status FROM users LEFT JOIN user_posts USING(users.id, user_posts.user_id) WHERE post_id = '123'";
 
// good
$query = "SELECT id, username, first_name, last_name, status
    FROM users
    LEFT JOIN user_posts USING(users.id, user_posts.user_id)
    WHERE post_id = '123'";


7 - Capitalise SQL Special Words

7 – Capitalize SQL Special Words

Database interaction is a big part of most web applications. If you are writing raw SQL queries, it is a good idea to keep them readable as well.

Even though SQL special words and function names are case insensitive, it is common practice to capitalize them to distinguish them from your table and column names.

SELECT id, username FROM user;
 
UPDATE user SET last_login = NOW()
WHERE id = '123'
 
SELECT id, username FROM user u
LEFT JOIN user_address ua ON(u.id = ua.user_id)
WHERE ua.state = 'NY'
GROUP BY u.id
ORDER BY u.username
LIMIT 0,20

Similar Posts: