Coding Standards and Best Practices

479
Coding Standards

Most of us assume that coding is the most important part of programming. As we develop more and more systems, mostly large systems, then there comes a situation where coding only is not the solution but the maintainability is. Then, we realize that there are other important aspects of programming than coding.

Programming is not only about writing code, it is an art. It helps us think differently and build a problem-solving techniques within us. A simple program can be written in many ways if given to multiple developers in a same programming language. However, there is always a question of best practices. Thus, following standard coding practices helps us standardize products and help reduce future maintenance cost.

Benefits of Code Standards

Why do we need to follow coding standards and best practices in programming? Well, let’s explain a situation. You are a part of software development team of 10 people. There is no any standards of software developments. You all are programming following your own coding standards.

After you build your software, when you need to check the code to add features or fix bugs, then you will find it very difficult to read and maintain the code. So, it’s best to set standards everybody follows so that you don’t get lost on your own code after few months back.

These are some of the most important benefits of implementing coding standards.

  • Decrease Failure Rate
    When we implement coding standards in our project, it automatically decreases the failure rate. A large number of errors and bugs can be prevented or tracked down in the early stage.
  • Enhanced Development
    When the failure rate is decreased, it automatically increases the efficiency of the development process. Following Coding Standards helps to eliminate the misunderstanding of code as well as helps to gain the trust of clients.
  • Faster Debugging
    We can debug faster when we write clean code. Messy and uncommented code are difficult to debug as well as time consuming. We can go right in the issue instead of wandering and testing here and there for searching the code. Isn’t it?
  • Easy to Maintain and Extend
    Clean code are easier to maintain. Not only clean code helps to maintain easily but also make it efficient to extend feature on existing application. A clean and well documented code helps to extend new features more easily compared to undocumented system.

Coding Techniques

Consistent Indentation

It is always best to give 2 or 4 spaces of indent when coding. Tabs can be used as well but it’s not a best practice to give tabs while indenting. But, please DON’T MIX space and tabs together.

The code should also be structured in a logical way. The unstructured code becomes difficult to read as well as maintain.

public function store(Request $request)
{
    $this->validate($request, [
            'title'=>'required|max:255',
            'status'=> 'required',
        ]
    );
    $post         = new $this->post;
    $post->title  = $request-> title;
    $post->status = $request-> status;
    $post->body   = $request-> body;

    $post->save();

    return redirect()->action('PostController@index')
                    ->with('success', 'Record created.');
}

Consistent Naming Convention

Naming consistency is also very important in programming. The different programmer has different techniques of naming. The most common naming conventions are camelCaseUnderScoressnake_case, and kebab-case. Whatever you follow, follow the same convention throughout the project.

Descriptive names also play an important role in understanding the code. Giving confusing names to class, functions or variables can lead to misunderstanding. For example avoid using variables name like $a$b. Instead, descriptive names such as firstname$email$phone should be used. In addition, we should avoid using spaces and special characters when naming a file.

Code Refactor

Refactoring code is a first step of writing high quality code. For example, instead of writing a large complex function, it should be refactored to smaller chunks to make it readable and track the issue easily. Refactor includes everything that your write such as methods, variables names, type and number arguments .

We should consider refactoring our code when there are lots of nested loops. One solution to avoid multiple nested loops is to return early. Below is a simple example of an early return.

function foo($bar, $baz)
{
    if (!$foo) {
        return null;
    }
   // method logic goes here
    return $some_value;
}

Use DRY Principle

DRY stands for Don’t Repeat Yourself. You get the point; Right? According to Wikipedia, “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.” It means that the same piece of code should not be repeated over and over again.

Let’s take WordPress as an example. While building a theme, we create a separate header.php and footer.php files. We define our header and footer templates on these file respectively. Then, we include them on every pages avoiding the repetition of same code over and over again. Whenever we need to make changes, we can simply edit a single file. Easy! isn’t it?

Let’s look at another example on backend part. Suppose we have a controller ArticleController.php and inside it, we have a private function makeSlugFromTitle which is used to create slug from title of article. Then, we have another controller ForumController.php which also have a private function makeSlugFromTitle which does the same function. So, instead of having two repeated function, we can create a new helper function that is accessible within application.

The main benefits of DRY principle are Maintainability, Readability and Reuse. We will discuss in more depth about DRY principle in another article.

Code Comments and Documentation

Have you ever checked your own code that was written a long time ago? Well, I have checked and surprised to see the code. The reasons are many to make me surprised by quality of my own code :P, but the main point here is I was unable to get what the function does on first sight. Although, I came to know the functionality while checking at the code, but wouldn’t it has been better if I could instantly get the basic information about the function?

Imaging debugging a a legacy application written by other developers. Yes, legacy application code. Well, code comments play an important role. Code should be properly commented and documented. There are various ways of commenting technique. Whatever you follow, it should give basic information about the function, parameter and return types.

Is comment really necessary? Yes but not in all cases. Please avoid obvious code. Don’t overflood your code with comments. When complex calculations are being executed, it’s best to write inline comments.

A simple example of commenting using phpDoc Block Comments:

/**
 * What the function does goes here
 *
 * @param Typehint $a
 * @param Typehint $b
 * @return what the function return
 */

Well, these are some of the techniques of implementing coding standards in programming. As they provide great advantage, following them is essential. Have you been following them? Don’t forget to drop you opinion in the comment below.

Read More Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.