How to write clean, readable and maintainable code

How to write clean, readable and maintainable code

Everybody has different styles of writing code. The coding style is directly related to readability and maintainability of code. Writing a clean code doesn’t only help other developers but also benefit yourself.

Clean code, off course, takes time and effort. Management team always hurry for shipping which put programmers into pressure. As a result of this, the programmer often misses different things. Those codes make other team members difficult to read. Also, it makes difficult to self to read and understand after some period of time.

In this article, we are going to discuss some of the rules and coding conventions for writing a beautiful code.

Naming Convention

The first thing we must discuss to write clean code is naming convention. We can see names everywhere in our project: classes, functions, arguments, options, variable and like this. We must write names that are understandable. It makes take some time to choose a perfect name but it will save a lot of time later.

Meaningful Names

Naming includes function name, class name, variable name, file name and so on. During declaration, the name should be descriptive and unambiguous names. Variable names are declared and accessed throughout the application. Similarly, each attribute name, function name, class name should make a meaningful distinction and pronounceable.

The following function name is clear and meaningful. Similarly, variable names are also clear and meaningful.

//good practice
public function sendMail()
{
    protected $hotel;
    protected $photo;
}

Comments

Comments are one of the easiest parts of programming but usually neglected. The programmer should always try to explain their code. Along with this, the comments should not be too noisy. Make comments only when it is necessary.

// example of noisy comments

public function createUser(Request $request)
{
    $user        = new User;   //create new user instance
    $user->name  = $request->name;   //assign name
    $user->age   = $request->age;    //assign age
    $user->email = $request->email;    //assign email
    $user->save();  //save user
}

Another common issue faced during programming is that programmers try different attempts to make their code working fast. During this, the programmer often forgets to comment their code. This is a common bad practice. The unnecessary commented code should be removed from the application as the commented code will decrease the readability of code.

// example of commented code in project

public function store(Request $request)
{
    //check if file exist
    /**
    if ($request->hasFile('default_image')) {

        $default_image = $request->default_image;
        .....
    }
    **/

    $this->saveImage();
}

Indentation of Code

Another feature I really love about clean programming is the indentation of code. Indentation helps to write clean code. Writing code on the same indentation makes it clean and readable.

// example of bad indentation
public function index()
{
    $data = [];
    $data['checkIn'] = $checkIn;
    $data['checkOut'] = $checkOut;
    $data['adults'] = $adults;
    $data['children'] = $children;
    $data['hotel'] = $hotel;
    $data['relatedHotels'] = $relatedHotels;
    $data['wishlist'] = $wishlist;
}

// example of good indentation
public function index()
{
    $data                  = [];
    $data['checkIn']       = $checkIn;
    $data['checkOut']      = $checkOut;
    $data['adults']        = $adults;
    $data['children']      = $children;
    $data['hotel']         = $hotel;
    $data['relatedHotels'] = $relatedHotels;
    $data['wishlist']      = $wishlist;
}

Functions

New programmer often try to write different tasks into one function. This makes a function bulky and unclean. To overcome this problem, Uncle Bob states in his book that “Functions should DO ONLY ONE THING”.

small function with one function one thing

The only two golden rules for writing clean functions are:

  • Function should be small.
  • Function should do only one thing and they should do it well.

The above rule implies that blocks inside function should be small. Function with conditions inside it also should be small. For this, the function may need to call another function.

The second rule implies that one function should do one single task. A single function with multiple task can lead to unmanageable code and confusing over time. For example, a createUser() function should only create a new user. It should not do other than that.

Fewer Arguments

The function name should be descriptive. The programmer should avoid unrelated names for function. Similarly, a function should have fewer arguments. Suppose you are building a function that accepts too arguments. Then, when you call it from different places, you need to remember the order of parameters. It is painful. Isn’t it? So, it’s good to have fewer parameter as possible.

// bad practice
public function createUser($name, $age, $address, $phone, .....)
{
    #code
}

// good practice
$data            = [];
$data['name']    = 'myName';
$data['age']     = 'myAge';
$data['address'] = 'myAddress';
createUser($data);  // function call
.....

public function createUser($data)
{
    #code
}

Get rid of deads

During working on a project for a long time left unused codes. These can be variables, functions, or any others. They must be removed from the project. Removing such dead variables, functions make our code much cleaner. Moreover, modern IDEs has searching functionality for dead codes.

Try Catch First

Error handling is a must in programming. Every programmer should be aware of possible errors and a way to handle those errors. Errors may be due to input errors or during the execution of scripts. These errors must be handled correctly else you are gonna pay a lot for it.

Among various ways of error handling, try-catch is one. It helps to catch the exception when something goes wrong in the code. When something goes wrong, we can simply catch the exception and display properly to the user.

function myFunction()
{
    try {
        #code
    } catch( Exception $e) {
        #do whatever with exception
    }
}

Classes

As like function class should be small. The class name should be clear and pronounceable. More small the classes, cleaner, readable and maintainable. Also, it doesn’t mean that few lines in class make it good because there may be more responsibilities. So, the main point here is that a class should have the single responsibility.

If you already have a project or starting a new project, identifying the responsibilities helps to write clean and refactored code. Most of the time, we focus on “make it working” but forget to make it clean.

Conclusion

We all know that writing code is easy but writing clean and maintainable code is hard. It takes time and effort. As we keep on following writing clean code, it becomes easy. When working on a large project for a longer period of time, maintaining code becomes a serious issue. Thus, following guidelines makes it easy. Besides these, if you are programming in PHP, you can also follow the latest version of PHP guidelines to write clean code.

So, what do you think about writing clean, readable and maintainable code? Please drop your comment or feedback in the comment field below.

Read More Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here