Checklists are always helpful! They provide a quick check to ensure consistency and completeness in carrying out a task efficiently and effectively.
Here, I've consolidated a basic 20 points checklist for Java Beginners to review the code. It'll help them to ensure code quality and consistency.
Without further ado... Let's go through it...
1. Null Checks
We know NullPointerException is the most common exception in Java and can cause big problems.
So, as a general practice, always do a null check on a variable before any operation.
2. Exception Handling
The try-catch block should be used for exception handling with proper logging in the catch block.
Also, make sure to close the resources properly in the finally block.
3. Code Indentation and Formatting
For a cleaner and readable code, use code indentation thoroughly (with Tab or Spaces anything).
It can be done automatically with the built-in editor of the IDE. For instance, use Ctrl-Shift-F in Eclipse. Similarly, Ctrl-Alt-L in IntelliJ.
Make use of Java formatting rules!
4. Optimize Imports
Always optimize imports in the Java class.
5. Static Code Review Tools
Use static code review tools like Sonar, PMD, and FindBugs to review the code.
6. Constants
Create a constant file for static values that are needed at multiple places
Use Database-driven values for dynamic values
Use ENUMs for a group of constants
7. Naming Conventions
Always check if the name of a variable/method/class truly covers the subject
Package names should be in all lower cases that start with reversed Internet domain name followed by application name. For example, org/companyname/appname
Class names should start with Capitals. For instance, Animal, Employee, and User
Variable/Method names should be in CamelCase. For instance animalInstanceList, calculateAmount, and displaySummary()
Try to avoid abbreviations in class/method/variable names. Prefer domainCode over dmnCd
8. Not All One-Liners
It's good to keep the code clean and readable. So, it's a better idea to not always go with one-liners. Especially, when we initialize and operate the variable in one line.
For example, write:
out.write(attrs.get("offset") + "-" + Math.min(attrs.get("count"), attrs.get("offset") + attrs.get("max")) + " " + title + " " + attrs.get("count"));
as:
int start = attrs.get("offset")
int total = attrs.get("count"))
int end = Math.min(total, start + attrs.get("max"))
out.write(start + "-" + end + " " + title + " " + total)
9. White-Spaces
Use white-spaces to separate combined statements to make code more readable.
For example, write:
Integer.valueOf(params.offset?params.offset:attrs.offset)
as:
Integer.valueOf(params.offset ? params.offset : attrs.offset)
10. Spaces Before and After Brackets
In general, we don't use white spaces in the brackets.
For example, write:
if ( params )
if ( total > 0 )
if ( end < begin )
as:
if (params)
if (total > 0)
if (end < begin)
11. Curly Braces
Use curly braces for one-liners also.
For example, write:
if ( end < begin )
end = begin
as:
if (end < begin) {
end = begin
}
12. Comments
Always put comments (if any) defining the purpose.
For example, Javadoc on a class:
/**
* General convenience tags for layout - header, body and footer
* @author – Name
* @dateCreated - Date
*/
class LayoutTagLib {
}
Javadoc on a method:
/**
* Gets the user for specified code and role.
* @param code :- The code, either username or email address
* @param role :- The role identification e.g. A, B or C. Default is A.
* @return the user or null if not found
*/
User findUser(String code, String role = "A")
Make sure the code is self-explanatory and comments are really useful in very specific cases.
13. Clean Up
Remove console print Statements (SOPs), use logging instead (never log personal information)
Remove obsolete comments
Use the @deprecated annotation on the method/variable, if it is not meant for future use or going to be removed
Remove hardcoded variable values
14. Business Logic
Avoid redundant code by using reusable components like utilities and service methods.
15. StringBuilder or StringBuffer in Place of String
When performing a lot of operations on the String, use StringBuilder or StringBuffer
For example, Java creates a new String object for every concatenation operation. In this case, a better idea is to use a StringBuffer.
16. switch-case Over Multiple if-else
It's a good practice to use switch-case in place of multiple if-else conditions.
It optimizes the code execution and also makes code cleaner and more readable.
17. Objects Creation in a Loop
It is usually better to create the object inside the loop (If object is not required outside loop). Java optimizes memory usage for short-lived objects.
For example, write:
Person person;
for (int i=0; i<namesList.size(); i++) {
person = new Person();
person.setName(namesList.get(i));
person.display();
}
as:
for (int i=0; i<namesList.size(); i++) {
Person person = new Person();
person.setName(namesList.get(i));
person.display();
}
Also, create a new object only if required.
For example, write:
ArrayList<Person> personList = new ArrayList<Person>();
for (int i=0; i<namesList.size(); i++) {
Person person = new Person();
if (null != namesList.get(i)) {
person.setName(namesList.get(i));
personList.add(person);
}
}
as:
ArrayList<Person> personList = new ArrayList<Person>();
for (int i=0; i<namesList.size(); i++) {
if (null != namesList.get(i)) {
Person person = new Person();
person.setName(namesList.get(i));
personList.add(person);
}
}
18. Code Commit
Group the files and commit together (don't commit files in separate commits)
Don't commit the code which has the actual Password. Make sure to use a system/configuration variable to replace the password
Commit messages should contain the task information. For example, JIRA issue number, a meaningful comment on code implementation
Commit .class files (from the build, out, target directories), only if required
19. Use equals over ==
equals perform the actual comparison of two strings, whereas == compares object references.
20. Keep It Simple!
Maintain simplicity and readability of code.
Please let me know your thoughts on it.
Thanks for reading.
Top comments (17)
Id suggest that constants files only be used if needed in multiple places and apart from reference to a single class. It the usage will always be in regards to a single class (or within a single class) then put the constants in that class.
Thanks for pointing it out. I totally agree with you. Will update the article.
Great article and guidelines.
I just don't agree with number 12 as I believe self-documented code is better code.
I think comments are really useful in very specific cases, where your code can't explain what you want to achieve. About the author and date, the VCS covers that part of the comment.
In number 16 I would just add a default case to every switch case for enums, it is a good practice and helps developers when they add a new value to the enum.
Keep going!
Thanks @pedroduarten9 for pointing it out. I agree with you on both points.
However, on number 12 it is advised for Java beginners to add comments on class/method which helps in Javadoc, not on the code to explain. As you say - comments are really useful in very specific cases. I'll update the article to mitigate this confusion.
Cheers!
Thanks for the guide.
Regarding the number 17, I feel like the example looks not very valid eventhough the point is valid.
Thanks for pointing it out. I've fixed it in the article.
Please have a look.
The code example is wrong.
In both cases new Person is executed and there is no object reuse. Except that the second example obfuscates escape analysis, so I'd argue that its inferior.
Thanks for pointing it out. I've fixed it in the article.
Please have a look.
I still don't get what you're trying to show here.
Java won't optimize anything in these cases because you're adding the person object to a list, so its not a short lived object.
My bad. I didn't give it much thought.
Thanks for help!
Great post!
In Intellij the default formatting rules (point 3) make 4,9 and 10 redundant because it does them automatically.
In addition, in Intellij you can set the flags "Add unambiguous imports on the fly" & "Optimize imports on the fly" to save you some typing even before the formatting is pressed.
:)
Thanks.
I totally agree with you. IDE (IntelliJ, Eclipse) provides built-in features for automatic formatting and cleanup.
Good suggestion on One-liners, one-liner code is difficult to debug.
8 looks more like C++ to me than Java.. Am I missing something?
It is actually Groovy. May be I should add simple Java code as an example.
But this article is called checklist for JAVA beginners. Groovy is not Java.
It is my bad. I code both in Java and Groovy. And I missed to change the example code before adding it to the article. However, I've updated it to Java already.
Thanks for pointing it out.