The world is a stage where all of us are artists and constant learning is the foundation of success. So, to improve ourselves here we are going to know more about clean code in Java. We will see why it is important and how to achieve that in Java.
Clean Code
First of all, before knowing how to write a clean code see what is clean code. Honestly, there is not an easy answer for this. Broadly, clean code can be summarized as code that any developer can read and change easily.
Writing clean code is a matter of personal habit as much as it’s a matter of skill. Clean coding principles help us achieve a lot of desirable goals related to the software we intend to produce.
Why to write Clean code
- Maintainable Codebase: Any software that we develop has a productive life so it will require changes and general maintenance. With clean code we can develop software that is easy to change and maintain over time.
- Easier Troubleshooting: Software can exhibit unintended behavior due to a variety of internal or external factors. It may often require a quick turnaround in terms of fixes and availability. Software developed with clean coding principles is easier to troubleshoot for problems.
- Faster Onboarding: Software during its lifetime will see many developers create, update, and maintain it, with developers joining at different points in time. Clean code helps achieve a quicker onboarding to keep productivity high.
Keypoints for Clean code
- Focused: A piece of code should be written to solve a specific problem. It should not do anything strictly not related to solving the given problem.
- Simple: This is by far the most important and often ignored characteristic of clean code. The software design and implementation must be as simple as possible, which can help us achieve the desired outcomes.
- Testable: Clean code, while being simple, must solve the problem at hand. It must be intuitive and easy to test the codebase, preferably in an automated manner.
Writing Clean Code
We’ll categorize them in different buckets and understand how to write clean code.
1. Project Structure
Before even starting to write any code, think about your program: classes, functions, structures, and so forth. Use packages and do not add too many classes to one package unless the classes fit within the same category.
The more you plan, the easier it will be to keep writing your code otherwise, you will have to restructure and refactor your code in the future.
- src/main/java: For source files
- src/main/resources: For resource files, like properties
- src/test/java: For test source files
- src/test/resources: For test resource files, like properties
2. Naming Convention
You may say it’s obvious and everybody knows that good naming of classes, methods, and variables is very important. You can always change RspValidation.java
to ResponseValidation.java
or print()
to printResponse().
Names of variables should have their intents. I hope that I never see String asd
in my programs.
Finding correct names and words for your code helps to avoid additional comments regarding explanations about the code.
Don’t forget to use camel cases for Java code. Class names should start with a capital letter (please).
3. Source File Structure
In Java we can write a code in a specific order in which to place elements in a source file can significantly improve code readability.
- Package statement
- Import statements
- All static imports
- All non-static imports
- Exactly one top-level class
- Class variables
- Instance variables
- Constructors
- Methods
4. Whitespaces
We all know that it is easier to read and understand short paragraphs compared to a large block of text. It is not very different when it comes to reading code as well. Well-placed and consistent whitespaces and blank lines can enhance the readability of the code.
There is no one single rule to adopt here but a general set of guidelines and an inherent intention to keep readability at the center of it:
- Two blank lines before starting static blocks, fields, constructors and inner classes.
- One blank line after a method signature that is multiline.
- A single space separating reserved keywords like if, for, catch from an open parentheses.
- A single space separating reserved keywords like else, catch from a closing parentheses.
5. Method and Method Parameters
Your method has to solve only one problem. Avoid writing big methods, because other developers might find them difficult to read. Decompose your method into a few perfectly named methods it will be easier to test them.
Parameters are essential for methods to work as per specification. But, a long list of parameters can make it difficult for someone to read and understand the code. Let’s understand the best practices which may help us:
- Try to restrict the number of parameters a method accepts, three parameters can be one good choice
- We may consider bundling parameters into custom-types but must be careful not to dump unrelated parameters into a single type
6. Hardcoding
It is so easy to hardcode something when you are in a rush. But heavily hardcoded code is so difficult to maintain and leads to bugs and mistakes. It can lead to duplication, which makes change more difficult. It can often lead to undesirable behavior if the values need to be dynamic. In most cases, hardcoded values can be refactored in one of the following ways:
- Consider replacing with constants or enums defined within Java.
- Or else, replace with constants defined at the class level or in a separate class file.
- If possible, replace with values which can be picked from configuration or environment.
7. Duplication
If two of your methods have repetitive code extract it to the third method or a separate class and use it for all the repetitions.
It may be easier to see everything in one method, but less code, no repetitions, easier to maintain, and avoid bugs.
8. Code Comments
Code comment can be beneficial while reading code to understand the non-trivial aspects. At the same time, care should be taken to not include obvious things in the comments.
Java allows two types of comments: Implementation comments and documentation comments:
- Comments should only complement a code, if we are not able to understand the code without comments, perhaps we need to refactor it
- We should use block comments rarely, possibly to describe non-trivial design decisions.
- We should use JavaDoc comments for most of our classes, interfaces, public and protected methods.
- All comments should be well-formed with a proper indentation for readability.
/*
* This method makes use of the custom implementation of equals
* method to avoid duplication of an employee with same name.
*/
public addEmployee(Employee employee) {
}
9. Logging
The importance of logs can not be over-emphasized in development in general and maintenance in particular.
- Avoid excessive logging, think about what information might be of help in troubleshooting.
- Choose log levels wisely, we may want to enable log levels selectively on production.
- Be very clear and descriptive with contextual data in the log message.
- Use external tools for tracing, aggregation, filtering of log messages for faster analytics.
That’s pretty much it from the article. We will come with 2nd Part in which we will include solid Principles and so.
If you have any feedback or queries, please do let me know in the comments. Also, if you liked the article, please give me a thumbs up and I will keep writing blogs like this for you in the future as well. Keep reading and Keep coding.

2 thoughts on “Functional Java CodeStyle [Part: 1]7 min read”
Comments are closed.