Java Coding: Best Practises

In today’s article we will focus on proven and useful tips and tricks for creating quality code, which we at msg life like to use and which will help you to improve the formatting, structure, readability and functionality of your Java code. Coding in Java will become enjoyable when we no longer have to worry about how the code looks, but rather about what it does.

Libraries

We use software libraries so that we don’t have to program everything manually.

  • Use third-party libraries only if necessary. If they are not updated, they may be a source of future code vulnerabilities.
  • Use one testing framework, not more. E.g. JUnit or TestNG.
  • We recommend using mockito to simulate functionality in tests.
  • Several libraries offer very similar methods, pick one library and use that one consistently.

Code formatting

Proper code formatting is very important because accurate and consistent indentation along with appropriate spacing can make reading and editing code much easier.

  • Write a single space around the operators on the left and right.
  • Do not use tabs for indentation, but spaces.
  • Split long lines of code into multiple lines by starting the next line with an operator.
  • Follow formatting rules consistently across all Java projects.
  • Take advantage of the features of modern programming environments when formatting code (e.g. automatic formatting).

Packages

Packages are used to organize related and co-related code.

  • Always use lower case in package names.
  • The name of the package must indicate its purpose.
  • Organize the packages logically into a hierarchical project structure.

Annotations

They provide additional information about the code in the form of metadata.

  • We limit the use of annotations to make the code cleaner.
  • When using the @Deprecated annotation, provide both the reason and an alternative in the javadoc comment.
  • Annotations like @Nonnull and @Nullable should be used sparingly and judiciously.
  • Use the @VisibleForTesting annotation only temporarily in tests when you need to extend access rights from private to package private.

Comments

They are intended to help clarify the code, therefore:

  • if the code is written in a simple and understandable style, no comments are necessary,
  • don’t write (or generate) any javadoc for getter(s) and setter(s),
  • for (package) private methods, prefer an implementation note and avoid writing javadoc.

Exceptions

We use them for unexpected situations in code.

  • Use unchecked exceptions to make the code more flexible.
  • Use the predefined JDK exception types and avoid creating your own.

Naming

We try to choose appropriate titles that reflect the purpose and importance of the individual parts of the programme.

  • We generally avoid abbreviations and choose meaningful names.
  • We use adverbs for boolean variables. for example disabled.
  • For other types and variables, we use nouns. for example ArrayList (class), element (variable).
  • For methods, we use verbs. for example add, remove.
  • In the method name, we try to indicate the intention of the method, for example: calculateSpeed.
  • We try to be precise, e.g. instead of the general variable time for storing time in hours, it is better to use timeInHours.
  • We avoid any duplication. for example instead of addElement(element), use add(element).

Methods

Methods form the basic unit of code in Java, so it is important to follow best practices when writing them.

  • The method solves only one problem (we follow the Single Responsibility Principle), but properly.
  • Each method has a clear single purpose.
  • Well-structured code contains short methods and have less than 15 lines. If the method is longer there should be a good reason for it.
  • We avoid repetition.
  • We try not to change the input to the method and calculate the output.
  • If we also need to change the input parameter of the function, we indicate this in the function name. for example the function starts with the prefix update.
  • We use functional programming and modern APIs.

Interfaces

Interfaces are the rules that need to be implemented in the classes that implement a given interface.

  • We don’t use interfaces if we don’t need them.
  • If only one class will use the interface, the use of the interface becomes meaningless.
  • For interfaces, use the Interface Segregation Principle.
  • We design the interface for some specific purpose, avoiding generic interfaces.

Classes

Classes are the basic building blocks of any Java application.

  • Each class should handle only one specific concept or functionality.
  • We avoid creating multi-functional classes that do everything.
  • Decide whether your class will focus on data or on their manipulation. for example the data class maintains the state (e.g., Matrix). A class focused on working with data defines behavior (e.g., MultiplicationService).
  • We primarily use private methods. Public methods only to the extent necessary for the object to interact with the outside world.
  • We do not use the protected approach in our tests. Instead, we use package private.

We hope these tips and tricks will help you write cleaner, clearer, and more efficient Java code. If you’re a Java developer looking for work, 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