10 Tips To Keep Your Code Clean

4 min read

Did you ever look into your or your team members code and think ‘What a hack? Why does this method look like a cat was walking on the keyboard?’. If so, then you definitely need to spend some time to clean your project’s code, because high-quality code is easier to understand, modify and scale.

In this article we are going to talk about 10 tips that will help you to become a better programmer. So enough talking and let’s start…

1. Naming Convention

Nobody forbids you to give a name to your methods or variables in your own way but there is a common convention between developers according to programming language they use. So you need to stick to it in order not to make your colleages become angry because of your naming. In this example I will show you the best naming practice from Java perspectives.

  • All variables, methods and classes should use CamelCase style. The only difference: a first letter of class should be capital:
class UserService {
private String firstName;

public String getFirstName() {
return firstName;
}
}
  • Constants should use all capital letters divided with underscore:
final int MAX_AGE = 20;
  • Try to avoid special characters and numbers:
//This is a BAD practice
User user1 = new User();
User user2$ = new User();
  • Don’t use too much words in the variable/method name. It should be as simple as possible, but also informative.
//This is a BAD practice
public void saveUserIntoMongoDBDatabase(User user);//This is much better
public void saveUser(User user);
  • Use verbs for function names and nouns for classes and attributes.

2. Write What You Mean

When you create a variable don’t be lazy to give it a full name. Never use only one letter in the name. Variable should represent the value it was created for. Even if you know what this variable is made for, doesn’t mean other developers will understand it. Also when you will come back to a certain block of code after some time you will probably forget the meaning of this variable.

Let’s consider the following code snippet:

public boolean check() {
if (a < max) {
return true;
} else {
return false;
}
}

This code is totally unclear, so other developer will definitely not understand what this method does. Let’s make some refactoring and see how it can be written in a better way:

public boolean isAgeAcceptable() {
if (userAge < maxAge) {
return true;
} else {
return false;
}
}

3. Variables/Methods Declaration

All variables in the class should be declared at the top of the class. Using such approach you will always know where to find the declaration of this variable and will not have to scroll over the whole class (which might contains thousands lines of code) to find where it was declared.

If variable is used only in one method then it would be better to declare it as a local variable of this method.

Methods should be declared in the same order as they are used (from top to bottom). For example, if you are calling some method from your current method then that method should be declared below the current one. Also more important methods should be declared at the top of a class and minor methods at the end.

4. Single Responsibility

One method should be responsible only for one action. If your method does two or three different things at a time then you should consider splitting the functionality of this method into other methods.

Such method is easier to understand, scale and reuse in other methods.

For example, you have a method saveUserAndChargeCard() which saves user to database and charges his credit card. This method is definitely bad, because it contains ‘And’ in the name and performs two actions. Avoid using words like ‘and’, ‘or’ etc. in a method name. You should split this function into saveUser() and chargeCard().

5. Small Methods

There is no a standard pattern for method length among the developers. Someone can say that 10 lines is max size, someone can say 5, in some cases even 20 lines of code is okay. So how to choose a correct one? Ectually, there is no a correct answer. Just try to make your methods as small as possible. The best methods are considered to be from 5 to 10 lines of code. But no one will fight you if your method has 12 or 15 lines, just make sure that these 15 lines of code is understandable and high-quality.

Also if you are writing some algorithm that makes some complicated calculations (or something similar) and it cannot be splitted into smaller methods, don’t worry such cases are also acceptable, but again watch your code quality.

6. Minimize Your Code

Don’t write three lines of code if the same thing can be done with only one line. It means that before adding some block of code you need to think about the best approach you can apply to this piece of code.

You might create a great functionality and algorithms, but it will not make sense if your code reviewer will ask to refactor your code because he can write the same thing using in to times less lines of code.

Let’s consider small example:

boolean hasCreditCard(User user) {
if (user.hasCard) {
return true;
} else {
return false;
}
}

At the first look this method seems to be normal, but it can be simplified:

boolean hasCreditCard(User user) {
return user.hasCard;
}

As you can see we have written only one line of code instead of five. So think harder before starting implementation.

7. Duplication Is EVIL

Try to avoid code duplication in your project (unless you get paid for written lines of code ☺). If you cannot reuse a method in other place then probably this method is bad and you should consider a better way to write this method. Your methods must be as universal as possible. This will help your team members to use your method instead of writing their own.

For example, if you have two functions that implement almost the same thing and the only difference is one line then it would be better to extract the same functionality into other method and concat these two functions into one with adding some condition checking.

8. Comments

Some time ago comments were considered as a normal practice and almost everyone was commenting a code. But now is considered if you are adding a comment then your code is not self-explaining and you should choose a better way to implement it.

Another issue related to comments is that often developers modify some block of code but forget to change a comment. For example, you created a function which implement some functionality and left a comment about what this function does. Then you or other developer changes function name or rewrites it at all and forgets to change comment. In such case other team members will be confused because the function and the meaning of this function mismatch.

It’s okay to leave comments if your are writing very complicated algorithm and your comments and noted will help other developers to better understand it.

9. Code checker tools

I would recommend you to use special tools that check your code quality even if you are applying all of the things described above. This tools can scan your code and show you where are some mistakes in your code, because you can miss something doing all of this checks manually.

One of the best tools for this is SonarQubeIt’s the leading product for continuous code quality analysis. But if it’s too complicated for you then you can just install some plugins to your development environment.

10. Best practices

The last thing I want to talk about is using of best practices. No matter what functionality you are working on I pretty sure that someone has already done it (or something similar) before. So it would be great to make some investigation before implementation of this feature.

Also learing best practices will help you to level up your professional skills and you can share your experience with your colleages.

Conclusion

Thank you guys for reading. I hope you enjoyed it and learned some new stuff. Please subscribe and press ‘Clap’ button if you like this. And don’t forget to clean your code!)

Leave a Reply

Your email address will not be published. Required fields are marked *