Simple Tips on How to Start Writing Clean Code

By Simple Tips on How to Start Writing Clean Code

Writing clean code requires trying out different practices and tips. This task is not as easy as it sounds, and the main problem is that there are a couple of tips to write clean code. For this reason, it becomes difficult for programmers, especially new, to select the best practices and follow them. Every programming language has keywords and built-in methods. We do not worry about writing these because, of course, they are already written in the best practice. There are other things that we are required to write, for example, our classes, methods, variables, etc. In this article, we shall discuss the benefits of giving your classes, methods, variables, and so on, speaking words. Then we focus on tips to write clean code.

What are the benefits of writing clean code?

The main reason for writing clean code is saving the time needed to read and understand the code. Maybe new developers have joined your team, and you need to look back at code that you wrote more than one year ago. Well written code will make the process of understanding simpler while messy code will slow down any development work and make the work of programmers harder. Sometimes developers will opt to stop reading the code if it is too dirty and start writing new code, and that is time wastage.

Here is a quick list of the benefits of clean code:

  1. Easier to read and comprehend.
  2. Better for team onboarding.
  3. Easier to follow.

Imagine one of your clients comes back after one or two years and wants additional modules on his/her project. Now assume you did not write code in the best practices. When you look at that project, you will find difficulties adding what your client wants. So you can see how hard it is to understand poorly written code. I have faced this challenge more than once, and I decided to follow the best practices when writing code.

Another scenario is reading your friends' code. If you read it for the first time, you will take the time to understand what is there. The time taken to understand the project depends on how code is written. Sometimes we need to explain to our friends or teammates what our code is all about. This is not necessary since it wastes time explaining our codes now and them. We can avoid it by writing clean code by following the standard practices.

Clean code makes it easier for us and our teammates to understand projects quickly. This is the benefit of a well-written code. We can see that we won't spend hours trying to understand the code. Therefore it is good to write code in a way that is in harmony with the tips we will discuss below.

Tips on writing clean code

Now it is time to see what the tips to help us write clean code are. Clean code follows certain practices, and it is these practices that make our code readable, more straightforward, and more understandable and hence clean. These are the guidelines for choosing the right coding practices. You may implement one or two of them, and you will get positive results.

1. Ensure code is readable for others

Computers will understand the code that has no syntax errors, no matter how poor it is written. Because we shall be working in teams or we shall leave our code to other people to maintain, we should not neglect code readability by humans. Even if nobody else will access our code, we will need to get back to it in the future. This is the reason why we should write clean code that will be easy to understand.

How do I make my code readable?

The easiest way to achieve this is to use whitespace. It is okay to minify our code before we deploy it for faster execution. However, it is not a good practice to write code that seems minified. We use indentation, line breaks, and even empty lines to structure our code in a more readable format. When we follow this practice, our code readability improves significantly. Let's have a look at two examples. First is terrible practice, second is a better practice.

Bad
public static Connection dbconnect() { try {forName("com.mysql.jdbc.Driver").newInstance();
    conn = getConnection("jdbc:mysql://localhost:3306/pos_system", "root", "");return conn;} 
    catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) {
    System.out.println("error " + e); alert.setTitle("An error has occured!"); 
    alert.setHeaderText("Error connecting to database!");alert.setContentText(e.getMessage() +
    "\n" + e.getCause()); alert.showAndWait(); Platform.exit();return null;}}
Better
public static Connection dbconnect() {
    try {
        forName("com.mysql.jdbc.Driver").newInstance();
        conn = getConnection("jdbc:mysql://localhost:3306/pos_system", "root", "");
        return conn;
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) {
        System.out.println("error " + e);
        alert.setTitle("An error has occured!");
        alert.setHeaderText("Error connecting to database!");
        alert.setContentText(e.getMessage()
                + "\n" + e.getCause());
        alert.showAndWait();
        Platform.exit();
        return null;
    }
}

2. Let one function perform only one task

When writing code ensure you separate tasks into methods. This helps you choose the right names and helps understand what happening in that method. When you write long methods, you will end up in a mess because someone else cannot predict what that method does. This practice not only makes code readable but also ensures code reusability.

Side note: this practice of letting every function, or method, perform only one task is called the Single responsibility principle. Robert C. Martin introduced this coding practice as one of the five object-oriented design principles, also known as SOLID. If you want to learn more about it, I recommend reading this article.

Example
public static int multiply(int x, int y){
    return x * y;
}

private String people;
public String getPeople() {
    return people;
}
public void setPeople(String people) {
    this.people = people;
}

3. Use meaningful names for classes, methods and variables

This is the second tip that helps us write clean and comprehensible code. Meaningful names mean names that are self-explanatory and are descriptive that other people can understand the purpose of the class, method, or variable. These names should suggest what the classes, methods, or variables are used for. The following examples show bad and better names for variables, respectively.

Bad
public class abcd {
    public static void xyz(){
        int a = 50;
        int b = 75;
        int c = 66;
        int d = 80;
        int e = 77;
        int total = a + b + c+d+e;
        double avg = total/5;
        System.out.println("Student's average marks is "+avg);
    }
    public static void main(String[] args) {
        xyz();
    }
}
Better
public class CalculateAverage {
    public static void findAverage() {
        int maths = 50;
        int english = 75;
        int swahili = 66;
        int science = 80;
        int socialStudies = 77;
        int totalMarks = maths + english + swahili + science + socialStudies;
        double averageMarks = totalMarks / 5;
        System.out.println("Student's average marks is " + averageMarks);
    }
    public static void main(String[] args) {
        findAverage();
    }
}

Note that using descriptive names doesn't mean we are safe to use as many characters as we want. The best rule is to limit the names to a maximum of four words. When you find yourself using many words, it means you are trying to do many things at one time. At that point, you need to simplify your code.

There are guidelines for choosing the right names for your variables. Different languages encourage different approaches. And in this tutorial am going to use Java-style of naming classes, methods, and variables.

You may be interested to learn Java Naming Conventions.

4. Use comments for clarification

In addition to writing short methods and using meaningful names for our classes, methods, and variables, we should write comments. There are lines in our code that need further explanation. The problem is not that they are not hard to understand or use. But we want to make more sense why coded in that specific way. Comments generally make our code more understandable.

Sometimes we need to explain our reasoning when we solve a specific problem because we have not used the best practice. Hence we need to leave a small explanation for others and even ourselves. So, whenever we find ourselves in a situation where we decide to use some hack, quick fix, or unconventional approach, let's use comments to explain why we did what we did. It is better to use one or two lines for comment with explanation than to force people to guess.

5. Be consistent

When you find that one practice or style that works for you and you like it stick to it. Use this style in all your projects as this will help you understand even the old project whenever you go back to them. Using different styles in different projects is not a good idea and is like not using any coding practice. Going back to your projects will not be easy and quick if you used different styles.

The best thing is to select the best coding practices for you and follow that in all projects. Trying out new styles also is good. This helps find better ways to code. However, practice on different small projects until you learn and master the style. Do not use new practices on your main projects. This could result in problems if you decide to abandon the styles.

6. Review your code regularly

The last tip is to review your code after some time to familiarize yourself with it. You need to maintain your code and improve its readability as much as possible. Code maintenance does not only entail adding new features or fixing bugs. Also, improving the structure of code is maintenance and should be done on a regular basis. If we don't review and update our old code, it will get outdated. Just like our devices, eg, laptops, phones, and vehicles, we need to check on them and ensure they are in good condition.

Conclusion

We have discussed the importance of writing clean code and the tips we can use to get clean code. These six tips may not bring the most significant impact on our projects. However, they are among the most frequently mentioned by experienced programmers. I use these tips in all projects, and I love them.

I hope that they will help you in writing clean code for your next projects. The best thing is to get started. Pick some that suit you and keep rolling.

Happy coding!

Was this article helpful?
Donate with PayPal: https://www.paypal.com/donate

Bessy
Eric Murithi Muchenah

Life is beautiful, time is precious. Make the most out of it.