A short summary of Java coding best practices

based on coding standards by Oracle, Google, Twitter and Spring Framework

The objective of this article is to give you a quick summary of do and don’ts in other words prefer and avoid based on coding standards from tech giants such as Oracle, Google, Twitter, and Spring Framework.

You might or might not agree with some of the best practices presented here, and that’s absolutely fine as long as there is some coding standard in place.

Why coding standards in the first place? There are many good reasons if you Google it and I will leave you with the following illustration

Coding standards document can be lengthy and boring. This article cherry picks bits and pieces from coding conventions by Google, Oracle, Twitter and Spring and it’s objective is to provide you with an easy to follow and less boring set of practices to make your code easy to read and maintain.

Almost always you will join teams working on existing software and there is a pretty good chance that most of the authors have left or switched to different projects, leaving you stranded with portions of code that make you question humanity.

Let’s dive into best practices from various coding standards.

Java Source File

The following is considered as best practices when it comes to java source files:

  • The source file length is lower than 2,000 lines of code
  • The source file is organized with documentation comment, package declaration, followed by a class comment, imports grouped (static last), class/interface signature and so on as shown below

Naming

Class and interface names are CamelCase and it is recommended to use the whole word and avoid acronyms/abbreviations. For example class Raster or class ImageSprite

  • Package — names com.deepspace over com.deepSpace or com.deep_space
  • File — names are CamelCase and end with .java matching the class name. There is one public class per file with each top-level class in its file
  • Method — names should be verbs in mixed case with each internal word capitalized for example run(); or runFast();
  • Constants — should be uppercase with “_” separating each words for example int MIN_WIDTH = 44; and int MAX_WIDTH = 99;
  • Variable — a name that tells the reader of the program what the variable represents i.e. if you are storing a test grade then pick grade vs var1 . Keep the variable names short avoid including metadata.

Remember — the variable name should be short and easily tell the reader what value it represents. Use your judgment.

Prefer & Avoid

Formatting and indentation are all about organizing your code to make it easy to read, and it includes spacing, line length, wraps and breaks and so on

  • Indentation — Use 2 or 4 spaces or tabs and stay consistent
  • Line length — Up to 70 to 120 characters depending on the effect on readability. It’s important to eliminate the need for horizontal scrolling and place line breaks after a comma and operator.

Methods — Here are a listing of best practices

If-checks — IMO writing well-formatted code makes it easy to spot typos and errors to the author and the code reviewers, see below:

Ternary operator — And below are recommended practices

Switch — When it comes to switch it’s best practice to

  • Always have a default case even without code
  • Use /* falls through */ to indicate the control falls to the next case

Exception messages — When throwing an exception here are samples of good and poorly indented messages.

Iterators and Streams — Streams are becoming more common and at times it can be very complex hence, it’s important to indent for easy to read.

Declarations and Assignments— One declaration per line is recommended since it encourages comments as shown below.

Put declarations only at the beginning of blocks (A block is code surrounded by curly braces { and }). Do not wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.

It’s also important to avoid local declarations that hide declarations of the higher-levels and is to avoid confusions as shown below

Spacing & line breaks — Avoid the temptation of saving 1–2 lines of code at the expense of readability. Here are all the best practices when it comes to spacing and blank lines (A white space does make a difference)

  • One (1) blank line between methods and Spring developers recommends two (2) blank lines after constructors, static block, fields and inner class
  • Space pad operators i.e. Use int foo = a + b + 1; over int foo=a+b+1;
  • Separate all binary operators except “.” from operands using a space
  • Open brace “{” appears at the end of the same line as the declaration statement or method and closing brace “}” starts a line by itself indented

Documentation and Comments

It’s worth mentioning that almost all code goes changes throughout its lifetime and there will be times when you or someone is trying to figure out what a complex block of code, a method, or a class is intended to do unless clearly described. The reality is almost always as follow

There are times that the comment on a complex piece of code, method, class does not add any value or serve its purpose. This usually happens when commenting for the sake of it.

Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Let’s get started. There are two types of comments

Implementation Comments — are meant to comment out code or comment about a particular implementation of the code.

Documentation Comments — are meant to describe the specification of the code from an implementation-free perspective to be read by developers who might not necessarily have the source code at hand.

The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer.

Types of Implementation Comments

There are four (4) types of implementation comments as shown below

  • Block comment — see example below
  • Single line comment — when the comment is not longer than a line
  • Trailing comments — Very short comment moved to the right end
  • End of line comment — begins a comment that continues to the newline. It can comment out a complete line or only a partial line. It shouldn’t be used on consecutive multiple lines for text comments; however, it can be used in consecutive multiple lines for commenting out sections of code.

Documentation comments (i.e. Javadoc)

Javadoc is a tool that generates HTML documentation form your java code using the comments that begin with /** and end with */ — see Wikipedia for more details on how Javadoc works or just read along.

Here is an example of Javadoc

And the above would result in an HTML as follow when javadoc is run against the code that has the above

Here are some key tags that you can use to enhance the quality of the generated java documentation.

For a complete listing and more detailed description see here

Twitter’s coding standard advises against the use of @author tag

Code can change hands numerous times in its lifetime, and quite often the original author of a source file is irrelevant after several iterations. We find it’s better to trust commit history and OWNERS files to determine ownership of a body of code.

Following are examples of how you could write a documentation comment that is insightful as described in Twitter’s coding standard

It’s important to be professional when it comes to writing comments

And it is important to keep in mind not to document overrided method unless the implementation has changed.

And here are a few more points to keep in mind

  • Avoid wildcard imports — as described in Twitter’s coding standards it makes the source of class less clear. I work in a team with a mix of Eclipse and IntelliJ users and I found out that Eclipse removes wildcard imports and IntelliJ introduces them. There probably is an option to turn it off, just wanted to point out the default for the two.
  • Always use @Override annotation when overriding
  • Encourage use of @Nullable when a field or method returns null
  • Make use of special comments for future work and do not forget to leave a reference to yourself so others know who to ask their Y question instead of guessing, removing it or checking git blame to find who added it. Some IDEs like Eclipse and IntelliJ also, help in listing these for easy access as well as a reminder.

The end game is to write code that makes the life of future authors and maintainers easy.

Conclusion

If you enjoyed this article, you might find my other articles useful.

The following article highlights what I wish I knew earlier as a developer and would have greatly helped me down the road. In other words, what would I tell to my student self?

There are many benefits to contributing to Open-source and I have shared my experience and knowledge of contributing to Spring Boot, Spring Security, and Elasticsearch repositories.

In the following article, I have listed 13 important points inspired by Google that any developer could apply to their code reviews

Load testing doesn’t have to be the job of a QA or tester or performance tester, anyone could with some effort load/performance test their piece of code. It’s a great skill to have.

Please follow me on medium and check out my other articles https://medium.com/@rhamedy and feel free to connect with me on LinkedIn.

A Human first • Senior software developer • Loves to write with over 250K views on Medium • Let’s connect on linkedin.com/in/rhamedy

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store