How to Write Clean Code? Follow These Best Practices

Know the best practices for writing clean code.


Photo by Safar Safarov on Unsplash


Hey folks, this article is not about some java related feature or concept but more than that. Basically, I’m going to explain all mistakes a java developer does while writing the code and hence how you can minimize it and you don’t have to refactor your code. So this article is about the BEST PRACTICES a developer should always follow.


1. What’s There in The Name :

A developer should always try to give a meaningful name to the variables, methods, and classes. It becomes too easy to understand what the method or class or variable is about when someone reads your code while reviewing it or debugging it. Giving names like a,b, and c to the variable does not intend any meaning and becomes less relevant while debugging the code.

1. Always start the name of a class with upper case. Eg.

public class Employee {
}

here Employee is the class name and other developers can easily understand that this class deals with employee-related stuff.

2. Always start a variable name with lowercase. Eg.

private int salary;

here the salary tells about the salary of the employee.

3. Always start the method name with lowercase and do not include And and Or words in the method name. Eg.

public int calculateSalary(int noOfDaysWorked , int baseSalary)

4. Write constants in upper case and separate them with an underscore. Eg.

public final int RETIREMENT_AGE = 58;

Note : do not use special symbols while writing variables ,methods , constants or classes names .


2. Smaller the Methods Better to Manage and Debug:

Writing many things into a single function leads to bad design implementation. Also, it’s not advised to write too big methods as it’s hard to debug if so many things are done in a single function. Hence write your function between 10–15 lines focusing on a single thing that the method does.


3. Be Smart to Reduce Lines of Code :

Always try to think before even you start writing any piece of code. Also, think about if there is any possibility of reducing no of lines that you want to write. Generally, developers check a boolean condition in the if block and then return the value. This isn’t the correct way to write the code. Let me explain the piece of code for better understanding.

boolean isContractor(Employee employee) { 
     if(employee.isCtr) {
        return true;
    } else {
        return false;
    }
}

the above code can be reduced to :

boolean isContractor(Employee employee) {
       return employee.isCtr;
}

Now you can see, we reduced the code to a single line instead of six.


4. Are Comments Necessary?

Yeah, comments do add meaning to complex methods or algorithms but they are not necessary for your code. If you write a piece of code and you think that any developer can understand by just reading the code then there is no need of adding comments to self-explanatory code. But do remember to add comments where you think you have explained or written complex logic or algorithm so that later any developer can understand while debugging the code.


5. Single Task in One Method:

Adding many tasks/things into a single method is not a good design. So developers should always try to maintain different functions for the different tasks to perform. Eg.

public void addUser(String userName , String password) {
//perform user addition operation to DB
}

6. Structure Your Code:

Always write functions in the order they are called. Also, write all variables to the top of all methods, so it becomes easier to locate. If some variables are used only in a single function then try to make those variables locale variables to that function.


7. Reviewers Don’t Like Duplicate Code:

Whenever you start writing code, you can give a look at related functions and classes in the codebase to check whether similar functionality already exists or not. If there is some method that does the same task as you want then reuse it.

If there is a method that has similar code as you want to write then write a single function that will perform the task of both functions, one which is already there in the codebase and the other which you wanted to write. This is the best practice to remove duplicate code.


8. Check Your Code Functionality by Writing Test Cases:

Once you are done with writing your methods and related classes then go ahead and identify test scenarios and corner cases for your code functionality.

Now you can include test cases for all these identified scenarios and check whether your code passes these test cases or not. While doing coding if you had missed some corner cases then try to include them.


9. Don’t Hardcode:

Hard coding is a bad idea which I generally see many developers do while coding. If you are hard coding some strings then it becomes difficult to test the functionality implemented by you. It may introduce bugs to your code if something is changed related to your code.

private static String serverIpAddress =”1.2.3.4”;

Never do this mistake. You can write a function that will fetch the IP address and then you can use it in your code.


10. Logging Makes Code Debugging Easier:

While writing code every developer should try to log necessary points about the functionality to get an idea about the flow or important info. It makes it easier for another developer to read the logs and check the code flow and debug and fix the issue.

Code without logs or improper logs does not help other developers to understand the code easily and the developer himself has to put extra effort to debug the issue.

Also, note that the developer should not log each and every statement results as excessive logging may reduce the performance of the application.


11. Reduce Method Parameters:

Passing many parameters to a single function is not good practice. Instead, you should try to create an object and then pass that object as a parameter to function. This improves code readability and hence improves code quality.

Eg.

public void addUser(String name , String gender , String age ,String userName , String password) {
//perform user addition operation to DB
}

The above code can be reduced by passing the User object to function as a parameter.

public void addUser(User user) {
//perform user addition operation to DB
}
//where user will be a class 
class User {
private String name ;
private String gender ;
private int age ;
private String userName;
private String password;
//here we can have constructors and getters and setters for above instance variables 
}

You can see, how easy it became to read the argument passed to function.


12. Code Reuse:

I have already talked about duplicate code which you should avoid. Basically, you should always look for your functionality before you write them into the code base or related code area and if you find them use it, and if not then go ahead with your own method and write them.


13. END NOTE

In conclusion, writing clean code is an essential aspect of software development that can have a significant impact on the quality, maintainability, and overall success of a project. Clean code is characterized by its readability, simplicity, and clarity, and it follows established coding conventions and best practices.

The ultimate goal of writing clean code is to make it easier for others (and future versions of yourself) to understand and work with, leading to increased efficiency and reduced bugs. Adhering to the principles of clean code requires discipline and a constant effort to improve, but the benefits are well worth the investment.


You can use of SonarLint plugin for Eclipse and IntelliJ IDE for improving your code quality .This plug in suggest you what are best practices while writing code and your code looks more concise, readable and maintainable .


If you liked this blog post, consider following Vikram Gupta.