Coding best practices - Part 2

Coding best practices
Coding best practices

Published Version: 1.0

To check the 1st part click the below link;

Coding best practices - Part 1

Avoid Obvious Comments

Commenting your code is fantastic; however, it can be overdone or just be plain redundant.


Take this example:




Fig 1: Incorrect example with Avoid Obvious Comments
Fig 1: Incorrect example with Avoid Obvious Comments

When the text is that obvious, it's really not productive to repeat it within comments. If you must comment on that code, you can simply combine it to a single line instead:

Fig 2: Correct example with Avoid Obvious Comments
Fig 2: Correct example with Avoid Obvious Comments


Note: If you have to write more than a one-line comment to explain what the code is doing, you should consider rewriting the code to be more readable.

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:

Fig 3: Example with Code Grouping
Fig 3: Example with Code Grouping

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

Avoid Deep Nesting

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

Here is a simplified example:

Fig 4: Incorrect example with Avoid Deep Nesting
Fig 4: Incorrect example with Avoid Deep Nesting

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

Fig 5: Correct example with Avoid Deep Nesting
Fig 5: Correct example with Avoid Deep Nesting

Limit Line Length

Our eyes are more comfortable when reading tall and narrow columns of text. This is precisely the reason why newspaper articles look like this:


Fig 6: Example with Newspaper Articles for Limit Line Length
Fig 6: Example with Newspaper Articles for Limit Line Length

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

Also, if anyone intends to read the code from a terminal window, such as Vim users, it is a good idea to limit the line length to around 80 characters.

// bad practice

$my_email->set_from('test@email.com')->add_to('programming@gmail.com')->set_subject('Methods Chained')->set_body('Some long message')->send();

// good practice

$my_email

->set_from('test@email.com')

->add_to('programming@gmail.com')

->set_subject('Methods Chained')

->set_body('Some long message')

->send();


// bad practice

$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 practice

$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'";


Consistent Temporary Names

Normally, the variables should be descriptive and contain one or more words. But this doesn't necessarily apply to temporary variables. They can be as short as a single character.

It is a good practice to use consistent names for your temporary variables that have the same kind of role.


Here are a few examples;


Fig 7: Example with Consistent Temporary Names
Fig 7: Example with Consistent Temporary Names


Fig 8: Example with Consistent Temporary Names
Fig 8: Example with Consistent Temporary Names

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.

Fig 9: Example with Capitalize SQL Special Words
Fig 9: Example with Capitalize SQL Special Words

Avoid Using Magic Numbers

The concept of magic numbers in programming refers to the use of hard-coded numerical values in your code. Using such numbers might make sense to you while you are writing the code. However, you or someone else will most probably have a hard time figuring out what that number was supposed to do when they look at the same piece of code in future.


For example:

// bad practice

while($egg_count > 400) {

  // do something

}

// good practice

$container_capacity = 400;

while($egg_count > $container_capacity) {

  // do something

}

Considering the code above, in the first case, we have no idea what the 400 signifies. Is it the count of people who will be served eggs, or is it something else? On the other hand, we know very clearly in the second case that we are checking if our egg count is over the container capacity.


It is also easier to update the $container_capacity by changing its value in one place. This will not be possible when using magic numbers as you will have to go through the whole code.


Separation of Code and Data

This is another principle that applies to almost all programming languages in all environments. In the case of web development, the "data" usually implies HTML output.


When PHP was first released many years ago, it was primarily seen as a template engine. It was common to have big HTML files with a few lines of PHP code in between. However, things have changed over the years, and websites have become more and more dynamic and functional. The code is now a huge part of web applications, and it is no longer a good practice to combine it with the HTML.


You can either apply the principle to your application by yourself, or you can use a third-party tool (template engines, frameworks, or CMSs) and follow their conventions.


Alternate Syntax Inside Templates

You may choose not to use a fancy template engine, and instead go with plain inline PHP in your template files. This does not necessarily violate the "Separation of Code and Data," as long as the inline code is directly related to the output and is readable. In this case, you should consider using the alternate syntax for control structures.


Here is an example:

<div class="user_controls"> <?php if ($user = Current_User::user()): ?> Hello, <em><?php echo $user->username; ?></em> <br/> <?php echo anchor('logout', 'Logout'); ?> <?php else: ?> <?php echo anchor('login','Login'); ?> | <?php echo anchor('signup', 'Register'); ?> <?php endif; ?> </div> <h1>My Message Board</h1> <?php foreach($categories as $category): ?> <div class="category"> <h2><?php echo $category->title; ?></h2> <?php foreach($category->Forums as $forum): ?> <div class="forum"> <h3> <?php echo anchor('forums/'.$forum->id, $forum->title) ?> (<?php echo $forum->Threads->count(); ?> threads) </h3> <div class="description"> <?php echo $forum->description; ?> </div> </div> <?php endforeach; ?> </div> <?php endforeach; ?>


This lets you avoid lots of curly braces. Also, the code looks and feels similar to the way HTML is structured and indented.


File and Folder Organization

Technically, we could write an entire application's code within a single file. But that would be a nightmare to read and maintain.


During our first programming projects, most of us knew about the idea of creating "include files". We have created an inc folder, with two files in it: db.php and functions.php. But. as the applications grew, the functions file also became huge and unmaintainable.


So keep in mind at the number of lines in your file which you have currently working on and think how we can break it in a logical and organized manner that we can reuse the same file later and maintain the scalability  as well.


We will discuss few more about Reusability and Scalability in our next post.


Few other points to remember

To make the code more simple and readable, few more practices we should follow at the time of writing code.

  • Don’t use lengthy functions. Ideally, a single function should carry out a single task.

  • Classes should not have too many methods. Instead, break the class into subclasses.

  • Sections of code should not be commented out, rather remove them.

  • Unused variables should be removed. In other words, do not declare any variable which is not being used further by the code.

We can use SonarLint to minify or nullify such kind of issues.

To be continued...

"Remember, Learning is a journey, not a destination." - Prasun Das

Comments

Popular posts from this blog

Coding best practices - Part 3

Coding best practices - Part 1