Clean code – Java: how to achieve it?

The spring season is coming, when nature renews its beauty. We can take inspiration and work on the aesthetic side of our source codes. Right now is a good time to start cleaning up and cleaning out your code, because clean code is not just a trendy concept, but a necessity for program quality.

Clean code is similar to dental care in many ways. If we don’t take care of the source code, we neglect the architecture and new functionality of the so-called “topping up”, over time the unnecessary costs and time needed to remediate it will start to grow. Similarly with teeth. Bacteria (program bugs in the IT world) love a dirty, unkempt (program) environment.

Writing clean code is no longer about personal preference, but there are many recommendations and tips proven by years of practice that help us write such code. In our article, we will look at a series of rules and recommendations for writing clean code in Java. These principles will help us create code that is not only functional, but also elegant and easy to understand for us and other developers.

May our code bloom as beautifully as nature blooms in spring. Let’s do it!

What is clean code?

Clean code can be defined as code that is relatively simple to read and understand, while being easy to modify and maintain. It should be well organized and consistent in the rules used, free of errors.

Properties of pure code

When writing source code, we try to make it have the following properties:

  1. Simplicity – the code should be as simple as possible to make it easy to understand. A lot of unnecessary errors in a program occur if the developers doesn’t fully understand what the code is doing.
  2. Maintainability – the code should be maintainable in the long term so that it can be easily modified and extended with new functionality. Many different developers may work on the code, so it is important to make sure that they work together and follow the agreed rules.
  3. Testability – the code should be relatively easy to test, this will also make it less error prone. It’s ideal to focus on automated testing to ensure that when programming new functionality, we don’t break the existing one.

Clean code contains no code duplication, is less prone to errors, and it is also easier to isolate and fix problems in the code. Also, there is no need to write so many comments explaining complex code points.

Properties of “dirty” code

On the contrary, if your code contains any of the following features, it’s worth considering how they can be eliminated. So-called “dirty” code can be fully functional and the compiler doesn’t really care how the code is written, but there may be problems in the future, especially if it is modified. Characteristics of dirty code include: chaos, complexity, difficult to read and understand, extensibility issues, difficult to locate and fix bugs, duplication, time consuming.

Clean Java code

Project structure

The first step towards clean code is a suitable project structure, which specifies how to organize source files, resources, configurations, tests, etc. The goal is to create an intuitive project structure that would reduce the time of searching between files.

Although Java doesn’t force us to use any particular project structure, it is always a good idea to follow proven community standards. Maven, a tool for automated project builds, recommends a standardized layout of folders in a project according to the following structure:

src/main/java Resource files and libraries
src/main/resources Other sources such as. models, …
src/test/java Test source files
src/test/resources Other resources for testing

Files in this type of project structure are primarily divided into application and test files. These are then subdivided into source files and other sources. The source code is then organized into packages at a lower level.

Correct naming

One of the most important principles of clean code is the use of clear and meaningful names for variables, functions, classes, and other identifiers. Therefore, we should always give them a name that is related to their functionality. for example it should be clear from the name of the method, without studying it in detail, what the method does. This makes it easier for other developers to understand what your code is doing. Also, variables must be named in such a way that it is immediately obvious what is being stored in them and what data type it is. While it is certainly more convenient to abbreviate identifier names (e.g. c instead of count, or calc instead of calculate) in order to write code faster, the readability of the code will ultimately suffer. Code readability and understandability helps in maintaining the code in the long run.

Source file structure

The source code file contains many different elements. The Java compiler leaves developers quite a lot of freedom to choose the order of elements that suits them, and requires sticking only to the basic structure of the source file. As with project structure, several recommendations have been made, but a typical arrangement of elements in source code looks like this:

  • Package
  • Imports
    • all static imports,
    • all non-static imports,
  • Class
    • variables,
    • instances,
    • constructors,
    • methods.
The first step to clean code is an appropriate project structure
The first step towards clean code is choosing an appropriate project structure.

Parameters of the method

Although method parameters are necessary in most cases, the amount of parameters in a method can make the code less understandable and readable. Therefore, we should strive to optimize the number of parameters in a method to achieve a certain compromise. Most of the time a good choice is to have about 3 parameters and if there are far more parameters, the method is usually longer and more complicated. In this case, the related parameters can be merged into a common data object and used as a method parameter. for example We can use an object type “address” instead of parameters (name, surname, street, city, state, phone number).

In any case, this needs to be considered on a case-by-case basis and not try to create unnecessarily new data types to link unrelated parameters together. We’re trying to improve the readability of the code, not complicate it.

Inflexible code

Hardcoded values in the program make it quite difficult to change such values, especially if the same values are scattered throughout the program. This often leads to errors if we forget to change it to a new value at some point.
Therefore, we try to make the code react to changes dynamically by hard-coded values, e.g.:

  • replace with a constant or enumeration class,
  • replace the value read from the configuration file or environment.

Comments in code

When it comes to comments, it’s important to be cautious and use them sparingly. Meaningful comments in the code can be helpful for understanding non-trivial aspects of the program, but at the same time they should not describe obvious parts of the code, as bloated comments can make the code less readable. In principle, we try to follow the following recommendations:

  • Comments are an addition to the code, their purpose is not to explain poorly written, hard to understand code.
  • Comments must be properly formatted to be readable.
  • It is recommended to use JavaDoc comments, especially if our code will be used by someone else.
  • We mainly use one-line comments. Block comments should only be used to explain unconventional decisions or solutions.

Logging code

As with comments, the importance of code logging cannot be disputed. However, if we overdo it with logging data, it can lead to reduced program performance and code clutter. We can use various libraries and frameworks to log messages in Java. I will mention for example Apache Log4J. When logging messages, we try to follow the following advice:

  • We need to make the log message very clear and descriptive.
  • If the code is running in production, we need to choose an appropriate logging level.
  • We need to avoid logging everything, instead think about what information can really help us.

Tools

There are several tools available in the Java ecosystem that help in writing clean code. We can use code formatting and code analysis tools such as SonarQube, SpotBugs, Veracode, Checkstyle, Codacy, FindBugs, Coverity, PMD, etc.

Most popular Java code editors, such as Eclipse and IntelliJ, allow automatic code formatting. We can easily customize or replace the default formatting rules with our own formatting rules.

Conclusion

In this article, we’ve covered basic recommendations and practices that can help you write clean Java code. Remember that writing clean Java code is the key to developing good software.

If you’re looking for a job and you’re a Java developer, check out our employee benefits and respond to our job offers.

About the author

Jozef Wagner

Java Developer Senior

Viac ako 10 rokov programujem v Jave, momentálne pracujem v msg life Slovakia ako Java programátor senior a pomáham zákazníkom implementovať ich požiadavky do poistného softvéru Life Factory. Vo voľnom čase si rád oddýchnem v lese, prípadne si zahrám nejakú dobrú počítačovú hru.

Let us know about you