Guidelines for Java code reviews

Having another pair of eyes scan your code is always useful and helps you spot mistakes before you break production. You need not be an expert to review someone's code. Some experience with the programming language and a review checklist should help you get started. We've put together a list of things you should keep in mind when you're reviewing Java code. Read on!

1. Follow Java code conventions

Following language conventions helps quickly skim through the code and make sense of it, thereby improving readability. For instance, all package names in Java are written in lowercase, constants in all caps, variable names in CamelCase, etc. Find the complete list of conventions here .

Some teams develop their own conventions, so be flexible in such cases!

2. Replace imperative code with lambdas and streams

If you're using Java 8+, replacing loops and extremely verbose methods with streams and lambdas makes the code look cleaner. Lambdas and streams allow you to write functional code in Java. The following snippet filters odd numbers in the traditional imperative way:

This is the functional way of filtering odd numbers:

3. Beware of the NullPointerException

When writing new methods, try to avoid returning nulls if possible. It could lead to null pointer exceptions. In the snippet below, the highest method returns a null if the list has no integers.

Before directly calling a method on an object I recommend checking for nulls as shown below.

It can be pretty cumbersome to have null checks everywhere in your code though. If you are using Java 8+, consider using the Optional class to represent values that may not have valid states. It allows you to easily define alternate behavior and is useful for chaining methods.

In the snippet below, we are using Java Stream API to find the highest number with a method which returns an Optional . Note that we are using Stream.reduce , which returns an Optional value.

‍ Alte rnatively, you could also use annotations such as @Nullable or @NonNull which will result in warnings if there is a null conflict while building the code. For instance, passing a @Nullable argument to a method that accepts @NonNull parameters.

4. Directly assigning references from client code to a field

References exposed to the client code can be manipulated even if the field is final. Let's understand this better with an example.

In the above snippet, we directly assign a reference from the client code to a field. The client can easily mutate the contents of the list and manipulate our code as shown below.

Instead, consider cloning the reference or creating a new reference and then assigning it to the field as shown below:

The same rule applies while returning references. You need to be cautious so as not to expose internal mutable state.

5. Handle exceptions with care

While catching exceptions, if you have multiple catch blocks, ensure that the sequence of catch blocks is most specific to least. In the snippet below, the exception will never be caught in the second block since the Exception class is the mother of all exceptions.

If the situation is recoverable and can be handled by the client (the consumer of your library or code) then it is good to use checked exceptions. e. g. IOException is a checked exception that forces the client to handle the scenario and in case the client chooses to re-throw the exception then it should be a conscious call to disregard the exception.

6. Ponder over the choice of data structures

Java collections provide ArrayList , LinkedList , Vector , Stack , HashSet , HashMap , Hashtable . It's important to understand the pros and cons of each to use them in the correct context. A few hints to help you make the right choice:

  • Map : Useful if you have unordered items in the form of key, value pairs and require efficient retrieval, insertion, and deletion operations. HashMap , Hashtable , LinkedHashMap are all implementations of the Map interface.
  • List : Very commonly used to create an ordered list of items. This list may contain duplicates. ArrayList is an implementation of the List interface. A list can be made thread-safe using Collections.synchronizedList thus removing the need for using Vector . Here 's some more info on why Vector is essentially obsolete.
  • Set : Similar to list but does not allow duplicates. HashSet implements the Set interface.

7. Think twice before you expose

There are quite a few access modifiers to choose from in Java — public , protected , private . Unless you want to expose a method to the client code, you might want to keep everything private by default. Once you expose an API, there's no going back.

For instance, you have a class Library that has the following method to checkout a book by name:

If you do not keep the searchByTitle method private by default and it ends up being exposed, other classes could start using it and building logic on top of it that you may have wanted to be part of the Library class. It could break the encapsulation of the Library class or it may be impossible to revert/modify later without breaking someone else's code. Expose consciously!

8. Code to interfaces

If you have concrete implementations of certain interfaces (e. g. ArrayList or LinkedList ) and if you use them directly in your code, then it can lead to high coupling. Sticking with the List interface enables you to switch over the implementation any time in the future without breaking any code.

In the above snippet, using the Printer interface allows the developer to move to another concrete class HTMLPrinter .

9. Don't force fit interfaces

Take a look at the following interface:

interface BookService {        List<Book> fetchBooks();    void saveBooks(List<Book> books);    void order(OrderDetails orderDetails) throws BookNotFoundException, BookUnavailableException; } class BookServiceImpl implements BookService { ...

Is there a benefit of creating such an interface? Is there a scope for this interface being implemented by another class? Is this interface generic enough to be implemented by another class? If the answer to all these questions is no, then I'd definitely recommend avoiding this unnecessary interface that you'll have to maintain in the future. Martin Fowler explains this really well in his blog .

Well then, what's a good use case for an interface? Let's say we have a class Rectangle and a class Circle that has behavior to calculate perimeter. If there is a requirement, to sum up, the perimeter of all shapes — a use case for polymorphism, then having the interface would make more sense, as shown below.

10. Override hashCode when overriding equals

Objects that are equal because of their values are called value objects . e. g. money, time. Such classes must override the equals method to return true if the values are the same. The equals method is usually used by other libraries for comparison and equality checks; hence overriding equals is necessary. Each Java object also has a hash code value that differentiates it from another object.

In the above example, we have overridden only the equals method of Object .

We would expect coinCount to update the number of 1 rupee coins to 7 since we override equals. But HashMap internally checks if the hash code for 2 objects is equal and only then proceeds to test equality via the equals method. Two different objects may or may not have the same hash code but two equal objects must always have the same hash code, as defined by the contract of the hashCode method. So checking for hash code first is an early exit condition. This implies that both equals and hashCode methods must be overridden to express equality.

If you write or review Java code, DeepSource can help you with automating the code reviews and save you a ton of time. Just add a .deepsource.toml file in the root of the repository and DeepSource will pick it up for scanning right away. The scan will find scope for improvements across your code and help you fix them with helpful descriptions.

Sign up and see for yourself!

More from DeepSource

Get started with deepsource.

DeepSource is free forever for small teams and open-source projects. Start analyzing your code in less than 2 minutes.

Read product updates, company announcements, how we build DeepSource, what we think about good code, and more.

how to do code review java

How to Make Good Code Reviews Better

Article hero image

I have been doing day-to-day code reviews for over a decade now. The benefits of code reviews are plenty: someone spot checks your work for errors, they get to learn from your solution, and the collaboration helps to improve the organization’s overall approach to tooling and automation. If you’re not currently doing code reviews in your organization, start now. It’ll make everyone a better engineer. Plenty of people and organizations have shared their code review best practices and what the definition of good code reviews mean to them. Guides from Google , the SmartBear team , and engineer Philipp Hauer are all excellent reads. Below is my personal take on what good code reviews look like and how to make them even better at the team and organizational level. This is in the context of the tech environment I have been working at - currently at Uber, and before that at Skype/Microsoft and Skyscanner. Good code reviews are the bar that all of us should strive for. They cover common and easy to follow best practices that any team can get started with, while ensuring high-quality and helpful reviews for the long term. Better code reviews are where engineers keep improving how they do code reviews. These code reviews look at the code change in the context of the codebase, of who is requesting it and in what situation. These reviews adjust their approach based on the context and situation. The goal not only being a high-quality review, but also to help the developers and teams requesting the review to be more productive.

Areas Covered by the Code Review

Good code reviews look at the change itself and how it fits into the codebase. They will look through the clarity of the title and description and "why" of the change . They cover the correctness of the code, test coverage, functionality changes, and confirm that they follow the coding guides and best practices. They will point out obvious improvements, such as hard to understand code, unclear names, commented out code, untested code, or unhandled edge cases. They will also note when too many changes are crammed into one review, and suggest keeping code changes single-purposed or breaking the change into more focused parts. Better code reviews look at the change in the context of the larger system, as well as check that changes are easy to maintain. They might ask questions about the necessity of the change or how it impacts other parts of the system. They look at abstractions introduced and how these fit into the existing software architecture. They note maintainability observations, such as complex logic that could be simplified, improving test structure, removing duplications, and other possible improvements. Engineer Joel Kemp describes great code reviews as a contextual pass following an initial, light pass .

Tone of the Review

The tone of code reviews can greatly influence morale within teams. Reviews with a harsh tone contribute to a feeling of a hostile environment with their microaggressions. Opinionated language can turn people defensive, sparking heated discussions. At the same time, a professional and positive tone can contribute to a more inclusive environment. People in these environments are open to constructive feedback and code reviews can instead trigger healthy and lively discussions. Good code reviews ask open-ended questions instead of making strong or opinionated statements. They offer alternatives and possible workarounds that might work better for the situation without insisting those solutions are the best or only way to proceed. These reviews assume the reviewer might be missing something and ask for clarification instead of correction. Better code reviews are also empathetic. They know that the person writing the code spent a lot of time and effort on this change. These code reviews are kind and unassuming. They applaud nice solutions and are all-round positive.

how to do code review java

Approving vs Requesting Changes

Once a reviewer completes their review, they can either mark it approved, block the review with change requests, or not set a specific status, leaving it in a “not yet approved” state. How reviewers use the approve and request changes statuses is telling of the code reviews. Good code reviews don't approve changes while there are open-ended questions. However, they make it clear which questions or comments are non-blocking or unimportant, marking them distinctively. They are explicit when approving a change - e.g. adding a thumbs up comment like “looks good!”. Some places use acronyms like LGTM —these also work, but be aware that newcomers could misinterpret these insider acronyms for something else. Good code reviews are equally explicit when they are requesting a follow-up, using the code review tool or team convention to communicate this. Better code reviews are firm on the principle but flexible on the practice: sometimes, certain comments are addressed by the author with a separate, follow-up code change. For changes that are more urgent than others, reviewers try to make themselves available for quicker reviews.

From Code Reviews to Talking to Each Other

Code reviews are usually done asynchronously and in writing through a code review tool. This is usually out of convenience, to enable remote code reviews, and to allow multiple people to review the same code change. But when is it time to stop using the tool—however good it might be—and start talking face to face about the code? Good code reviews leave as many comments and questions as are needed. If the revision does not address all of them, they will note those as well. When the conversation gets into a long back-and-forth, reviewers will try to switch to talking to the author in-person instead of burning more time using the code review tool. Better code reviews will proactively reach out to the person making the change after they do a first pass on the code and have lots of comments and questions. These people have learned that they save a lot of time, misunderstandings, and hard feelings this way. The fact that there are many comments on the code indicates that there is likely some misunderstanding on either side. These kinds of misunderstandings are easier identified and resolved by talking things through.

Nitpicks are are unimportant comments, where the code could be merged without even addressing these. These could be things like variable declarations being in alphabetical order, unit tests following a certain structure, or brackets being on the same line. Good code reviews make it clear when changes are unimportant nitpicks. They usually mark comments like these distinctively, adding the “nit:” prefix to them. Too many of these can become frustrating and take the attention away from the more important parts of the review, so reviewers aim to not go overboard with these. Better code reviews realize that too many nitpicks are a sign of lack of tooling or a lack of standards. Reviewers who come across these frequently will look at solving this problem outside the code review process. For example, many of the common nitpick comments can be solved via automated linting. Those that cannot can usually be resolved by the team agreeing to certain standards and following them—perhaps even automating them, eventually.

Code Reviews for New Joiners

Starting at a new company is overwhelming for most people. The codebase is new, the style of programming is different than before, and people review your code very differently. So should code reviews be gentler for new starters, to get them used to the new environment, or should they keep the bar just as high, as it is for everyone else? Good code reviews use the same quality bar and approach for everyone, regardless of their job title, level or when they joined the company. Following the above, code reviews have a kind tone, request changes where needed, and will reach out to talk to reviewers when they have many comments. Better code reviews pay additional attention to making the first few reviews for new joiners a great experience. Reviewers are empathetic to the fact that the recent joiner might not be aware of all the coding guidelines and might be unfamiliar with parts of the code. These reviews put additional effort into explaining alternative approaches and pointing to guides. They are also very positive in tone, celebrating the first few changes to the codebase that the author is suggesting.

Cross-Office, Cross-Time Zone Reviews

Code reviews get more difficult when reviewers are not in the same location. They are especially challenging when reviewers are sitting in very different time zones. I have had my fair share of these reviews over the years, modifying code owned by teams in the US and Asia, while being based in Europe. Good code reviews account for the time zone difference when they can. Reviewers aim to review the code in the overlapping working hours between offices. For reviews with many comments, reviewers will offer to chat directly or do a video call to talk through changes. Better code reviews notice when code reviews repeatedly run into timezone issues and look for a systemic solution, outside the code review framework. Let's say a team from Europe is frequently changing a service that triggers code reviews from the US-based owner of this service. The system-level question is why these changes are happening so frequently. Are the changes done in the right codebase or should another system be changed? Will the frequency of changes be the same or go down over time? Assuming the changes are done in the right codebase and the frequency will not go down, can the cross-office dependency be broken in some way? Solutions to these kinds of problems are often not simple and could involve refactoring, creating of new services/interfaces or tooling improvements. But solving dependencies like this will make the life of both teams easier and their progress more efficient for the long term, meaning the return on investment is often quite impressive.

Organizational Support

The way companies and their engineering organizations approach code reviews is a big element of how efficient they can be. Organizations that view them as unimportant and trivial end up investing little in making reviews easier. In cultures like this, it might be tempting to just do away with code reviews entirely. Engineers advocating for doing better code reviews might feel isolated, without support from above and eventually give up. The result is an organization where problems continue to repeat and compound upon themselves. Organizations with good code reviews ensure that all engineers take part in the code review process—even those that might be working on solo projects. They encourage raising the quality bar, and teams facilitate healthy discussions on code review approaches both at the team and org level. These companies often have code review guides for larger codebases that engineers initiated and wrote. Organizations like this recognise that code reviews take up a good chunk of engineers' time. Many of these companies will add code reviews as expectations to the developer job competencies, expecting senior engineers to spend a larger chunk of their time reviewing the code of others. Organizations with better code reviews have hard rules around no code making it to production without a code review—just as business logic changes don't make it to production without automated tests. These organizations have learned that the cost of cutting corners is not worth it; instead, they have processes for expedited reviews for urgent cases. These organizations invest in developer productivity, including working continually to develop more efficient code reviews and tooling improvements. Helpful engineering executives don't need convincing on the benefits of code reviews and other engineering best practices. Instead, they support initiatives on better tooling or more efficient code review processes that come from teams. When people come across reviews that feel hostile, they feel they can speak up and have support all-round to resolve the issue. Senior engineers and managers consider code reviews that are not up to the bar just as much of an issue as sloppy code or poor behavior. Both engineers and engineering managers feel empowered to improve how code reviews are done.

Start With Good, Make it Better

Good code reviews already have lots of good effort going into them. They do a thorough review of the change itself, avoid being opinionated with the tone of comments, and make nitpicks clear. They maintain a consistent bar, regardless of who is requesting the review and try to make cross-time zone reviews less painful by paying additional attention to these. Organizations that have good reviews ensure that every developer regularly receives and does code reviews. This is already a high bar—but if you get here, don’t stop. Code reviews are one of the best ways to improve your skills, mentor others, and learn how to be a more efficient communicator. Get to better code reviews by continuously improving on the details, but also start looking at changes at a high level as well. Be empathetic in the tone of comments and think of ways outside the code review process to eliminate frequent nitpicks. Make code reviews especially welcoming for new starters and look for systemic solutions for painful cross-time zone reviews. Organizations that are forward-looking encourage investing in tooling and process improvements to make code reviews better, reaping more of the benefits. ------- Gergely is currently an engineering lead in Amsterdam. This blog post originally appeared on Gergely’s blog, The Pragmatic Engineer . If you’d like to read more from Gergely, you can subscribe to his monthly newsletter for his articles on engineering, tech leadership and distributed systems. If you would like to contribute articles to the Stack Overflow blog, send an email to [email protected].

DZone

  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
  • Manage My Drafts

Modernizing APIs : Share your thoughts on GraphQL, AI, microservices, automation , and more for our April report (+ enter a raffle for $250!).

DZone Research Report : A look at our developer audience, their tech stacks, and topics and tools they're exploring.

Getting Started With Large Language Models : A guide for both novices and seasoned practitioners to unlock the power of language models.

Managing API integrations : Assess your use case and needs — plus learn patterns for the design, build, and maintenance of your integrations.

  • Be Punctual! Avoiding Kotlin’s lateinit In Spring Boot Testing
  • Scaling Java Microservices to Extreme Performance Using NCache
  • Leveraging Java's Fork/Join Framework for Efficient Parallel Programming: Part 1
  • Achieving Inheritance in NoSQL Databases With Java Using Eclipse JNoSQL
  • How To Implement Code Reviews Into Your DevOps Practice
  • Understanding Status Page Aggregation: Inside the Technology of a Typical Status Page Aggregator
  • Applying CI/CD to Java Apps Using Spring Boot
  • Requirements, Code, and Tests: How Venn Diagrams Can Explain It All

Guidelines for Java Code Reviews

Get a jump-start on your next code review session with this list..

Meenakshi Dhanani user avatar

Join the DZone community and get the full member experience.

Having another pair of eyes scan your code is always useful and helps you spot mistakes before you break production. You need not be an expert to review someone’s code. Some experience with the programming language and a review checklist should help you get started. We’ve put together a list of things you should keep in mind when you’re reviewing Java code. Read on!

1. Follow Java Code Conventions

Following language conventions helps quickly skim through the code and make sense of it, thereby improving readability. For instance, all package names in Java are written in lowercase, constants in all caps, variable names in CamelCase, etc. Find the complete list of conventions here .

Some teams develop their own conventions, so be flexible in such cases!

2. Replace Imperative Code With Lambdas and Streams

If you’re using Java 8+, replacing loops and extremely verbose methods with streams and lambdas makes the code look cleaner. Lambdas and streams allow you to write functional code in Java. The following snippet filters odd numbers in the traditional imperative way:

This is the functional way of filtering odd numbers:

3. Beware of the NullPointerException

When writing new methods, try to avoid returning nulls if possible. It could lead to null pointer exceptions. In the snippet below, the highest method returns a null if the list has no integers.

Before directly calling a method on an object I recommend checking for nulls as shown below.

It can be pretty cumbersome to have null checks everywhere in your code though. If you are using Java 8+, consider using the Optional class to represent values that may not have valid states. It allows you to easily define alternate behavior and is useful for chaining methods.

In the snippet below, we are using Java Stream API to find the highest number with a method which returns an Optional . Note that we are using Stream.reduce , which returns an Optional value.

Alternatively, you could also use annotations such as @Nullable or @NonNull which will result in warnings if there is a null conflict while building the code. For instance, passing a @Nullable argument to a method that accepts @NonNull parameters.

4. Directly Assigning References From Client Code to a Field

References exposed to the client code can be manipulated even if the field is final. Let’s understand this better with an example.

In the above snippet, we directly assign a reference from the client code to a field. The client can easily mutate the contents of the list and manipulate our code as shown below.

Instead, consider cloning the reference or creating a new reference and then assigning it to the field as shown below:

The same rule applies while returning references. You need to be cautious so as not to expose internal mutable state.

5. Handle Exceptions With Care

While catching exceptions, if you have multiple catch blocks, ensure that the sequence of catch blocks is most specific to least. In the snippet below, the exception will never be caught in the second block since the Exception class is the mother of all exceptions.

If the situation is recoverable and can be handled by the client (the consumer of your library or code) then it is good to use checked exceptions. e. g. IOException is a checked exception that forces the client to handle the scenario and in case the client chooses to re-throw the exception then it should be a conscious call to disregard the exception.

6. Ponder Over the Choice of Data Structures

Java collections provide ArrayList , LinkedList , Vector , Stack , HashSet , HashMap , Hashtable . It’s important to understand the pros and cons of each to use them in the correct context. A few hints to help you make the right choice:

Map : Useful if you have unordered items in the form of key, value pairs and require efficient retrieval, insertion, and deletion operations. HashMap , Hashtable , LinkedHashMap are all implementations of the Map interface.

List : Very commonly used to create an ordered list of items. This list may contain duplicates. ArrayList is an implementation of the List interface. A list can be made thread-safe using Collections.synchronizedList thus removing the need for using Vector . Here ’s some more info on why Vector is essentially obsolete.

Set : Similar to list but does not allow duplicates. HashSet implements the Set interface.

7. Think Twice Before You Expose

There are quite a few access modifiers to choose from in Java — public , protected , private . Unless you want to expose a method to the client code, you might want to keep everything private by default. Once you expose an API, there’s no going back.

For instance, you have a class Library that has the following method to checkout a book by name:

If you do not keep the searchByTitle method private by default and it ends up being exposed, other classes could start using it and building logic on top of it that you may have wanted to be part of the Library class. It could break the encapsulation of the Library class or it may be impossible to revert/modify later without breaking someone else’s code. Expose consciously!

8. Code to Interfaces

If you have concrete implementations of certain interfaces (e. g. ArrayList or LinkedList ) and if you use them directly in your code, then it can lead to high coupling. Sticking with the List interface enables you to switch over the implementation any time in the future without breaking any code.

In the above snippet, using the Printer interface allows the developer to move to another concrete class HTMLPrinter .

9. Don’t Force Fit Interfaces

Take a look at the following interface:

Is there a benefit of creating such an interface? Is there a scope for this interface being implemented by another class? Is this interface generic enough to be implemented by another class? If the answer to all these questions is no, then I’d definitely recommend avoiding this unnecessary interface that you’ll have to maintain in the future. Martin Fowler explains this really well in his blog .

Well then, what’s a good use case for an interface? Let’s say we have a class Rectangle and a class Circle that has behavior to calculate perimeter. If there is a requirement, to sum up, the perimeter of all shapes — a use case for polymorphism, then having the interface would make more sense, as shown below.

10. Override hashCode When Overriding Equals

Objects that are equal because of their values are called value objects . e. g. money, time. Such classes must override the equals method to return true if the values are the same. The equals method is usually used by other libraries for comparison and equality checks; hence overriding equals is necessary. Each Java object also has a hash code value that differentiates it from another object.

In the above example, we have overridden only the equals method of Object .

We would expect coinCount to update the number of 1 rupee coins to 7 since we override equals. But HashMap internally checks if the hash code for 2 objects is equal and only then proceeds to test equality via the equals method. Two different objects may or may not have the same hash code but two equal objects must always have the same hash code, as defined by the contract of the hashCode method. So checking for hash code first is an early exit condition. This implies that both equals and hashCode methods must be overridden to express equality.

Published at DZone with permission of Meenakshi Dhanani . See the original article here.

Opinions expressed by DZone contributors are their own.

Partner Resources

  • About DZone
  • Send feedback
  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone
  • Terms of Service
  • Privacy Policy
  • 3343 Perimeter Hill Drive
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

Code review checklist: how to tackle issues with Java concurrency

by Roman Leventov

GzQlMvHCGYcEKGRtS5pZxvzPyXHKTZPHf6cr

At the Apache Druid community, we are currently preparing a detailed checklist to be used during code reviews. I decided to publish parts of the checklist as posts on Medium to gather more ideas for checklist items. Hopefully, somebody will find it useful in practice.

By the way, it seems me that creating project-specific checklists for code reviews should be a powerful idea, yet I don’t see any existing examples among large open source projects.

This post contains checklist items about problems that arise with the multithreaded Java code.

Thanks to Marko Topolnik , Matko Medenjak , Chris Vest , Simon Willnauer , Ben Manes , Gleb Smirnov , Andrey Satarin , Benedict Jin , and Petr Janeček for reviews and contributions to this post. The checklist is not considered complete, comments and suggestions are welcome!

Update: this checklist is now available on Github .

1.1. If the patch introduces a new subsystem with concurrent code, is the necessity for concurrency rationalized in the patch description ? Is there a discussion of alternative design approaches that could simplify the concurrency model of the code (see the next item)?

1.2. Is it possible to apply one or several design patterns (some of them are listed below) to significantly simplify the concurrency model of the code, while not considerably compromising other quality aspects , such as overall simplicity, efficiency, testability, extensibility, etc?

Immutability/Snapshotting. When some state should be updated, a new immutable object (or a snapshot within a mutable object) is created, published and used, while some concurrent threads may still use older copies or snapshots. See [EJ Item 17], [JCIP 3.4], items 4.5 and 9.2 in this checklist, CopyOnWriteArrayList , CopyOnWriteArraySet , persistent data structures .

Divide and conquer. Work is split into several parts that are processed independently, each part in a single thread. Then the results of processing are combined. Parallel Streams (see section 14) or ForkJoinPool (see items 10.4 and 10.5) can be used to apply this pattern.

Producer-consumer. Pieces of work are transmitted between worker threads via queues. See [JCIP 5.3], item 6.1 in this checklist, CSP , SEDA .

Instance confinement. Objects of some root type encapsulate some complex hierarchical child state. Root objects are solitarily responsible for the safety of accesses and modifications to the child state from multiple threads. In other words, composed objects are synchronized rather than synchronized objects are composed. See [JCIP 4.2, 10.1.3, 10.1.4].

Thread/Task/Serial thread confinement. Some state is made local to a thread using top-down pass-through parameters or ThreadLocal . See [JCIP 3.3]. Task confinement is a variation of the idea of thread confinement that is used in conjunction with the divide-and-conquer pattern. It usually comes in the form of lambda-captured “context” parameters or fields in the per-thread task objects. Serial thread confinement is an extension of the idea of thread confinement for the producer-consumer pattern, see [JCIP 5.3.2].

2. Documentation

2.1. For every class, method, and field that has signs of being thread-safe, such as the synchronized keyword, volatile modifiers on fields, use of any classes from java.util.concurrent.* , or third-party concurrency primitives, or concurrent collections: do their Javadoc comments include

  • The justification for thread safety : is it explained why a particular class, method or field has to be thread-safe?
  • Concurrent control flow documentation : is it enumerated from what methods and in contexts of what threads (executors, thread pools) each specific method of a thread-safe class is called?

Wherever some logic is parallelized or the execution is delegated to another thread, are there comments explaining why it’s worse or inappropriate to execute the logic sequentially or in the same thread? See also item 14.1 in this checklist about parallel Stream use.

2.2. If the patch introduces a new subsystem that uses threads or thread pools, are there high-level descriptions of the threading model, the concurrent control flow (or the data flow) of the subsystem somewhere, e. g. in the Javadoc comment for the package in package-info.java or for the main class of the subsystem? Are these descriptions kept up-to-date when new threads or thread pools are added or some old ones deleted from the system?

Description of the threading model includes the enumeration of threads and thread pools created and managed in the subsystem, and external pools used in the subsystem (such as ForkJoinPool.commonPool() ), their sizes and other important characteristics such as thread priorities, and the lifecycle of the managed threads and thread pools.

A high-level description of concurrent control flow should be an overview and tie together concurrent control flow documentation for individual classes, see the previous item. If the producer-consumer pattern is used, the concurrent control flow is trivial and the data flow should be documented instead.

Describing threading models and control/data flow greatly improves the maintainability of the system, because in the absence of descriptions or diagrams developers spend a lot of time and effort to create and refresh these models in their minds. Putting the models down also helps to discover bottlenecks and the ways to simplify the design (see item 1.2).

2.3. For classes and methods that are parts of the public API or the extensions API of the project: is it specified in their Javadoc comments whether they are (or in case of interfaces and abstract classes designed for subclassing in extensions, should they be implemented as) immutable, thread-safe or not thread-safe ? For classes and methods that are (or should be implemented as) thread-safe, is it documented precisely with what other methods (or themselves) they may be called concurrently from multiple threads? See also [EJ Item 82] and [JCIP 4.5].

If the @com.google.errorprone.annotations.Immutable annotation is used to mark immutable classes, Error Prone static analysis tool is capable to detect when a class is not actually immutable (see the relevant bug pattern ).

2.4. For subsystems, classes, methods, and fields that use some concurrency design patterns, either high-level (such as those mentioned in item 1.2 in this checklist) or low-level (such as double-checked locking, see section 8 in this checklist): are the used concurrency patterns pronounced in the design or implementation comments for the respective subsystems, classes, methods, and fields? This helps readers to make sense out of the code quicker.

2.5. Are ConcurrentHashMap and ConcurrentSkipListMap objects stored in fields and variables of ConcurrentHashMap or ConcurrentSkipListMap or ConcurrentMap type , but not just Map ?

This is important, because in code like the following:

It should be pretty obvious that there might be a race condition because an entity may be put into the map by a concurrent thread between the calls to containsKey() and put() (see item 4.1 about this type of race conditions). While if the type of the entities variable was just Map<String, Enti ty> it would be less obvious and readers might think this is only slightly suboptimal code and pass by.

It’s possible to turn this advice into an inspection in IntelliJ IDEA.

2.6. An extension of the previous item: are ConcurrentHashMaps on which compute() , computeIfAbsent() , computeIfPresent() , or merge() methods are called stored in fields and variables of ConcurrentHashMap type rather than ConcurrentMap ? This is because ConcurrentHashMap (unlike the generic ConcurrentMap interface) guarantees that the lambdas passed into compute() -like methods are performed atomically per key, and the thread safety of the class may depend on that guarantee.

This advice may seem to be overly pedantic, but if used in conjunction with a static analysis rule that prohibits calling compute() -like methods on ConcurrentMap -typed objects that are not ConcurrentHashMaps (it’s possible to create such inspection in IntelliJ IDEA too) it could prevent some bugs: e. g. calling compute() on a ConcurrentSkipListMap might be a race condition and it’s easy to overlook that for somebody who is used to rely on the strong semantics of compute() in ConcurrentHashMap .

2.7. Is @GuardedBy annotation used ? If accesses to some fields should be protected by some lock, are those fields annotated with @GuardedBy ? Are private methods that are called from within critical sections in other methods annotated with @GuardedBy ? If the project doesn’t depend on any library containing this annotation (it’s provided by jcip-annotations , error_prone_annotations , jsr305 and other libraries) and for some reason it’s undesirable to add such dependency, it should be mentioned in Javadoc comments for the respective fields and methods that accesses and calls to them should be protected by some specified locks.

See [JCIP 2.4] for more information about @GuardedBy .

Using GuardedBy is especially beneficial in together with Error Prone, which is able to statically check for unguarded accesses to fields and methods with @GuardedBy annotations .

2.8. If in a thread-safe class some fields are accessed both from within critical sections and outside of critical sections , is it explained in comments why this is safe? For example, unprotected read-only access to a reference to an immutable object might be benignly racy (see item 4.5).

2.9. Regarding every field with a volatile modifier: does it really need to be volatile ? Does the Javadoc comment for the field explain why the semantics of volatile field reads and writes (as defined in the Java Memory Model ) are required for the field?

2.10. Is it explained in the Javadoc comment for each mutable field in a thread-safe class that is neither volatile nor annotated with @GuardedBy , why that is safe? Perhaps, the field is only accessed and mutated from a single method or a set of methods that are specified to be called only from a single thread sequentially (as described in item 2.1). This recommendation also applies to final fields that store objects of non-thread-safe classes when those objects could be mutated from the methods of the enclosing thread-safe class. See items 4.2–4.4 in this checklist about what could go wrong with such code.

3. Excessive thread safety

3.1. An example of excessive thread safety is a class where every modifiable field is volatile or an AtomicReference or other atomic, and every collection field stores a concurrent collection (e. g. ConcurrentHashMap ), although all accesses to those fields are synchronized.

There shouldn’t be any “extra” thread safety in code, there should be just enough of it. Duplication of thread safety confuses readers because they might think the extra thread safety precautions are (or used to be) needed for something but will fail to find the purpose.

The exception from this principle is the volatile modifier on the lazily initialized field in the safe local double-checked locking pattern which is the recommended way to implement double-checked locking, despite that volatile is excessive for correctness when the lazily initialized object has all final fields * . Without that volatile modifier the thread safety of the double-checked locking could easily be broken by a change (addition of a non- final field) in the class of lazily initialized objects, though that class should not be aware of subtle concurrency implications. If the class of lazily initialized objects is specified to be immutable (see item 2.3) the volatile is still unnecessary and the UnsafeLocalDCL pattern could be used safely, but the fact that some class has all final fields doesn’t necessarily mean that it’s immutable.

See also section 8 in this post about double-checked locking.

3.2. Aren’t there AtomicReference , AtomicBoolean , AtomicInteger or AtomicLong fields on which only get() and set() methods are called? Simple fields with volatile modifiers can be used instead, but volatile might not be needed too; see item 2.9.

4. Race conditions

4.1. Aren’t ConcurrentHashMaps updated with multiple separate containsKey() , get() , put() and remove() calls instead of a single call to compute() / computeIfAbsent() / computeIfPresent() / replace() ?

4.2. Aren’t there point read accesses such as Map.get() , containsKey() or List.get() outside of critical sections to a non-thread-safe collection such as HashMap or ArrayList , while new entries can be added to the collection concurrently, even though there is a happens-before edge between the moment when some entry is put into the collection and the moment when the same entry is point-queried outside of a critical section?

The problem is that when new entries can be added to a collection, it grows and changes its internal structure from time to time ( HashMap rehashes the hash table, ArrayList reallocates the internal array). At such moments races might happen and unprotected point read accesses might fail with NullPointerException , ArrayIndexOutOfBoundsException , or return null or some random entry.

Note that this concern applies to ArrayList even when elements are only added to the end of the list. However, a small change in ArrayList ’s implementation in OpenJDK could have disallowed data races in such cases at very little cost. If you are subscribed to the concurrency-interest mailing list, you could help to bring attention to this problem by reviving this thread .

4.3. A variation of the previous item: isn’t a non-thread-safe collection such as HashMap or ArrayList iterated outside of a critical section , while it can be modified concurrently? This could happen by accident when an Iterable , Iterator or Stream over a collection is returned from a method of a thread-safe class, even though the iterator or stream is created within a critical section.

Like the previous item, this one applies to growing ArrayLists too.

4.4. More generally, aren’t non-trivial objects that can be mutated concurrently returned from getters on a thread-safe class?

4.5. If there are multiple variables in a thread-safe class that are updated at once but have individual getters , isn’t there a race condition in the code that calls those getters? If there is, the variables should be made final fields in a dedicated POJO, that serves as a snapshot of the updated state. The POJO is stored in a field of the thread-safe class, directly or as an AtomicReference . Multiple getters to individual fields should be replaced with a single getter that returns the POJO. This allows avoiding a race condition in the client code by reading a consistent snapshot of the state at once.

This pattern is also very useful for crafting safe and reasonably simple non-blocking code: see item 9.2 in this checklist and [JCIP 15.3.1].

4.6. If some logic within some critical section depends on some data that principally is part of the internal mutable state of the class, but was read outside of the critical section or in a different critical section, isn’t there a race condition because the local copy of the data may become out of sync with the internal state by the time when the critical section is entered ? This is a typical variant of check-then-act race condition, see [JCIP 2.2.1].

4.7. Aren’t there race conditions between the code (i. e. program runtime actions) and some actions in the outside world or actions performed by some other programs running on the machine? For example, if some configurations or credentials are hot reloaded from some file or external registry, reading separate configuration parameters or separate credentials (such as username and password) in separate transactions with the file or the registry may be racing with a system operator updating those configurations or credentials.

Another example is checking that a file exists (or not exists) and then reading, deleting, or creating it, respectively, while another program or a user may delete or create the file between the check and the act. It’s not always possible to cope with such race conditions, but it’s useful to keep such possibilities in mind. Prefer static methods from java.nio.file.Files class instead of methods from the old java.io.File for file system operations. Methods from Files are more sensitive to file system race conditions and tend to throw exceptions in adverse cases, while methods on File swallow errors and make it hard even to detect race conditions.

5. Replacing locks with concurrency utilities

5.1. Is it possible to use concurrent collections and/or utilities from java.util.concurrent.* and avoid using locks with Object.wait() / notify() / notifyAll() ? Code redesigned around concurrent collections and utilities is often both clearer and less error-prone than code implementing the equivalent logic with intrinsic locks, Object.wait() and notify() ( Lock objects with await() and signal() are not different in this regard). See [EJ Item 81] for more information.

5.2. Is it possible to simplify code that uses intrinsic locks or Lock objects with conditional waits by using Guava’s Monitor instead ?

6. Avoiding deadlocks

6.1. If a thread-safe class is implemented so that there are nested critical sections protected by different locks, is it possible to redesign the code to get rid of nested critical sections ? Sometimes a class could be split into several distinct classes, or some work that is done within a single thread could be split between several threads or tasks which communicate via concurrent queues. See [JCIP 5.3] for more information about the producer-consumer pattern.

6.2. If restructuring a thread-safe class to avoid nested critical sections is not reasonable, was it deliberately checked that the locks are acquired in the same order throughout the code of the class? Is the locking order documented in the Javadoc comments for the fields where the lock objects are stored?

6.3. If there are nested critical sections protected by several (potentially different) dynamically determined locks (for example, associated with some business logic entities), are the locks ordered before the acquisition ? See [JCIP 10.1.2] for more information.

6.4. Aren’t there calls to some callbacks (listeners, etc.) that can be configured through public API or extension interface calls within critical sections of a class? With such calls, the system might be inherently prone to deadlocks because the external logic executed within a critical section might be unaware of the locking considerations and call back into the logic of the project, where some more locks may be acquired, potentially forming a locking cycle that might lead to deadlock. Let alone the external logic could just perform some time-consuming operation and by that harm the efficiency of the system (see the next item). See [JCIP 10.1.3] and [EJ Item 79] for more information.

7. Improving scalability

7.1. Are critical sections as small as possible? For every critical section: can’t some statements in the beginning and the end of the section be moved out of it? Not only minimizing critical sections improves scalability, but also makes it easier to review them and spot race conditions and deadlocks.

This advice equally applies to lambdas passed into ConcurrentHashMap ’s compute() -like methods.

See also [JCIP 11.4.1] and [EJ Item 79].

7.2. Is it possible to increase locking granularity ? If a thread-safe class encapsulates accesses to map, is it possible to turn critical sections into lambdas passed into ConcurrentHashMap.compute() or computeIfAbsent() or computeIfPresent() methods to enjoy effective per-key locking granularity? Otherwise, is it possible to use Guava’s Striped or an equivalent? See [JCIP 11.4.3] for more information about lock striping.

7.3. Is it possible to use non-blocking collections instead of blocking ones? Here are some possible replacements within JDK:

  • Collections.synchronizedMap(HashMap) , Hashtable → ConcurrentHashMap
  • Collections.synchronizedSet(HashSet) → ConcurrentHashMap.newKeySet()
  • Collections.synchronizedMap(TreeMap) → ConcurrentSkipListMap . By the way, ConcurrentSkipListMap is not the state of the art concurrent sorted dictionary implementation. SnapTree is more efficient than ConcurrentSkipListMap and there have been some research papers presenting algorithms that are claimed to be more efficient than SnapTree.
  • Collections.synchronizedSet(TreeSet) → ConcurrentSkipListSet
  • Collections.synchronizedList(ArrayList) , Vector → CopyOnWriteArrayList
  • LinkedBlockingQueue → ConcurrentLinkedQueue
  • LinkedBlockingDeque → ConcurrentLinkedDeque

Was it considered to use one of the array-based queues from the JCTools library instead of ArrayBlockingQueue ? Those queues from JCTools are classified as blocking, but they avoid lock acquisition in many cases and are generally much faster than ArrayBlockingQueue .

7.4. Is it possible to use ClassValue instead of ConcurrentHashMap<Class, . . .>? Note, however, that u nlike ConcurrentH ashMap wit h its computeIfAb sent() m ethod Clas sValue doesn’t guarantee that per-class value is computed only once, i. e. ClassValue.computeV alue() might be executed by multiple concurrent threads. So if the computation i nside computeV alue() is not thread-safe, it should be synchronized separately. On the other hand, Clas sValue does guarantee that the same value is always returned from ClassValue .get() (u nless re move() is called).

7.5. Was it considered to replace a simple lock with a ReadWriteLock ? Beware, however, that it’s more expensive to acquire and release a ReentrantReadWriteLock than a simple intrinsic lock, so the increase in scalability comes at the cost of reduced throughput. If the operations to be performed under a lock are short, or if a lock is already striped (see item 7.2) and therefore very lightly contended, replacing a simple lock with a ReadWriteLock might have a net negative effect on the application performance. See this comment for more details.

7.6. Is it possible to use a StampedLock instead of a ReentrantReadWriteLock when reentrancy is not needed?

7.7. Is it possible to use LongAdder for “hot fields” (see [JCIP 11.4.4]) instead of AtomicLong or AtomicInteger on which only methods like incrementAndGet() , decrementAndGet() , addAndGet() and (rarely) get() is called, but not set() and compareAndSet() ?

8. Lazy initialization and double-checked locking

8.1. For every lazily initialized field: is the initialization code thread-safe and might it be called from multiple threads concurrently? If the answers are “no” and “yes”, either double-checked locking should be used or the initialization should be eager.

8.2. If a field is initialized lazily under a simple lock, is it possible to use double-checked locking instead to improve performance?

8.3. Does double-checked locking follow the SafeLocalDCL pattern, as noted in item 3.1 in this checklist?

If the initialized objects are immutable a more efficient UnsafeLocalDCL pattern might also be used. However, if the lazily-initialized field is not volatile and there are accesses to the field that bypass the initialization path, the value of the field must be carefully cached in a local variable . For example, the following code is buggy:

It might result in a NullPointerException , because although a non-null value is observed when the field is read the first time at line 1, the second read at line 2 could observe null.

The above code could be fixed as follows:

See “ Wishful Thinking: Happens-Before Is The Actual Ordering ” for more information.

8.4. In each particular case, doesn’t the net impact of double-checked locking and lazy field initialization on performance and complexity overweight the benefits of lazy initialization? Isn’t it ultimately better to initialize the field eagerly?

8.5. If a field is initialized lazily under a simple lock or using double-checked locking, does it really need locking? If nothing bad may happen if two threads do the initialization at the same time and use different copies of the initialized state, a benign race could be allowed. The initialized field should still be volatile (unless the initialized objects are immutable) to ensure there is a happens-before edge between threads doing the initialization and reading the field.

See also [EJ Item 83] and “ Safe Publication this and Safe Initialization in Java ”.

9. Non-blocking and partially blocking code

9.1. If there is some non-blocking or semi-symmetrically blocking code that mutates the state of a thread-safe class, was it deliberately checked that if a thread on a non-blocking mutation path is preempted after each statement, the object is still in a valid state ? Are there enough comments, perhaps before almost every statement where the state is changed, to make it relatively easy for readers of the code to repeat and verify the check?

9.2. Is it possible to simplify some non-blocking code by confining all mutable state in an immutable POJO and update it via compare-and-swap operations ? This pattern is also mentioned in item 4.5. Instead of a POJO, a single long value could be used if all parts of the state are integers that can together fit 64 bits. See also [JCIP 15.3.1].

10. Threads and Executors

10.1. Are Threads given names when created? Are ExecutorServices created with thread factories that name threads?

It appears that different projects have different policies regarding other aspects of Thread creation: whether to make them daemon with setDaemon() , whether to set thread priorities and whether a ThreadGroup should be specified. Many of such rules can be effectively enforced with forbidden-apis .

10.2. Aren’t there threads created and started, but not stored in fields, a-la new Thread(...).start() , in some methods that may be called repeatedly? Is it possible to delegate the work to a cached or a shared ExecutorService instead?

10.3. Aren’t some network I/O operations performed in an Executors.newCachedThreadPool() -created ExecutorService ? If a machine that runs the application has network problems or the network bandwidth is exhausted due to increased load, CachedThreadPools that perform network I/O might begin to create new threads uncontrollably.

10.4. Aren’t there blocking or I/O operations performed in tasks scheduled to a ForkJoinPool (except those performed via a managedBlock() call)? Parallel Stream operations are executed in the common ForkJoinPool implicitly, as well as the lambdas passed into CompletableFuture ’s methods whose names end with “Async”.

This advice should not be taken too far: occasional transient IO (such as that may happen during logging) and operations that may rarely block (such as ConcurrentHashMap.put() calls) usually shouldn’t disqualify all their callers from execution in a ForkJoinPool or in a parallel Stream . See Parallel Stream Guidance for the more detailed discussion of those tradeoffs.

See also section 14 in this checklist about parallel Streams.

10.5. Opposite of the previous item: can non-blocking computations be parallelized or executed asynchronously by submitting tasks to ForkJoinPool.commonPool() or via parallel Streams instead of using a custom thread pool (e. g. created by one of the static factory methods from ExecutorServices )? Unless the custom thread pool is configured with a ThreadFactory that specifies a non-default priority for threads or a custom exception handler (see item 10.1) there is little reason to create more threads in the system instead of reusing threads of the common ForkJoinPool .

11. Thread interruption and Future cancellation

11.1. If some code propagates InterruptedException wrapped into another exception (e. g. RuntimeException ), is the interruption status of the current thread restored before the wrapping exception is thrown?

Propagating InterruptedException wrapped into another exception is a controversial practice (especially in libraries) and it may be prohibited in some projects completely, or in specific subsystems.

11.2. If some method returns normally after catching an InterruptedException , is this coherent with the (documented) semantics of the method? Returning normally after catching an InterruptedException usually makes sense only in two types of methods:

  • Runnable.run() or Callable.call() themselves, or methods that are intended to be submitted as tasks to some Executors as method references. Thread.currentThread().interrupt() should still be called before returning from the method, assuming that the interruption policy of the threads in the Executor is unknown.
  • Methods with “try” or “best effort” semantics. Documentation for such methods should be clear that they stop attempting to do something when the thread is interrupted, restore the interruption status of the thread and return.

If a method doesn’t fall into either of these categories, it should propagate InterruptedException directly or wrapped into another exception (see the previous item), or it should not return normally after catching an InterruptedException , but rather continue execution in some sort of retry loop, saving the interruption status and restoring it before returning (see an example from JCIP). Fortunately, in most situations, it’s not needed to write such boilerplate code: one of the methods from Uninterruptibles utility class from Guava can be used.

11.3. If an InterruptedException or a TimeoutException is caught on a Future.get() call and the task behind the future doesn’t have side effects, i. e. get() is called only to obtain and use the result in the context of the current thread rather than achieve some side effect, is the future canceled ?

See [JCIP 7.1] for more information about thread interruption and task cancellation.

12.1. Are values returned from System.nanoTime() compared in an overflow-aware manner , as described in the documentation for this method?

12.2. Does the code that compares values returned from System.currentTimeMillis() have precautions against “time going backward” ? This might happen due to time correction on a server. Values that are returned from currentTimeMillis() that are less than some other values that have already been seen should be ignored. Otherwise, there should be comments explaining why this issue is not relevant for the code.

Alternatively, System.nanoTime() could be used instead of currentTimeMillis() . Values returned from nanoTime() never decrease (but may overflow — see the previous item). Warning: nanoTime() didn’t always uphold to this guarantee in OpenJDK until 8u192 (see JDK-8184271 ). Make sure to use the freshest distribution.

In distributed systems, the leap second adjustment causes similar issues.

12.3. Do variables that store time limits and periods have suffixes identifying their units , for example, “timeoutMillis” (also -Seconds, -Micros, -Nanos) rather than just “timeout”? In method and constructor parameters, an alternative is providing a TimeUnit parameter next to a “timeout” parameter. This is the preferred option for public APIs.

12.4. Do methods that have “timeout” and “delay” parameters treat negative arguments as zeros? This is to obey the principle of least astonishment because all timed blocking methods in classes from java.util.concurrent.* follow this convention.

13. Thread safety of Cleaners and native code

13.1. If a class manages native resources and employs java.lang.ref.Cleaner (or sun.misc.Cleaner ; or overrides Object.finalize() ) to ensure that resources are freed when objects of the class are garbage collected, and the class implements Closeable with the same cleanup logic executed from close() directly rather than through Cleanable.clean() (or sun.misc.Cleaner.clean() ) to be able to distinguish between explicit close() and cleanup through a cleaner (for example, clean() can log a warning about the object not being closed explicitly before freeing the resources), is it ensured that even if the cleanup logic is called concurrently from multiple threads, the actual cleanup is performed only once ? The cleanup logic in such classes should obviously be idempotent because it’s usually expected to be called twice: the first time from the close() method and the second time from the cleaner or finalize() . The catch is that the cleanup must be concurrently idempotent, even if close() is never called concurrently on objects of the class . That’s because the garbage collector may consider the object to become unreachable before the end of a close() call and initiate cleanup through the cleaner or finalize() while close() is still being executed.

Alternatively, close() could simply delegate to Cleanable.clean() ( sun.misc.Cleaner.clean() ) which is thread-safe. But then it’s impossible to distinguish between explicit and automatic cleanup.

See also JLS 12.6.2 .

13.2. In a class with some native state that has a cleaner or overrides finalize() , are bodies of all methods that interact with the native state wrapped with try { ... } finally { Reference.reachabilityFence(this); } , including constructors and the close() method, but excluding finalize() ? This is needed because an object could become unreachable and the native memory might be freed from the cleaner while the method that interacts with the native state is being executed, that might lead to use-after-free or JVM memory corruption.

reachabilityFence() in close() also eliminates the race between close() and the cleanup executed through the cleaner or finalize() (see the previous item), but it may be a good idea to retain the thread safety precautions in the cleanup procedure, especially if the class in question belongs to the public API of the project because otherwise if close() is accidentally or maliciously called concurrently from multiple threads, the JVM might crash due to double memory free or, worse, memory might be silently corrupted, while the promise of the Java platform is that whatever buggy some code is, as long as it passes bytecode verification, thrown exceptions should be the worst possible outcome, but the virtual machine shouldn’t crash. Item 13.4 also stresses on this principle.

Reference.reachabilityFence() has been added in JDK 9. If the project targets JDK 8 and Hotspot JVM, any method with an empty body is an effective emulation of reachabilityFence() .

See the documentation for Reference.reachabilityFence() and this discussion in the concurrency-interest mailing list for more information.

13.3. Aren’t there classes that have cleaners or override finalize() not to free native resources , but merely to return heap objects to some pools, or merely to report that some heap objects are not returned to some pools? This is an antipattern because of the tremendous complexity of using cleaners and finalize() correctly (see the previous two items) and the negative impact on performance (especially of finalize() ), that might be even larger than the impact of not returning objects back to some pool and thus slightly increasing the garbage allocation rate in the application. If the latter issue arises to be any important, it should better be diagnosed with async-profiler in the allocation profiling mode ( -e alloc ) than by registering cleaners or overriding finalize() .

This advice also applies when pooled objects are direct ByteBuffers or other Java wrappers of native memory chunks. async-profiler -e malloc could be used in such cases to detect direct memory leaks.

13.4. If some classes have some state in native memory and are used actively in concurrent code, or belong to the public API of the project, was it considered making them thread-safe ? As described in item 13.2, if objects of such classes are inadvertently accessed from multiple threads without proper synchronization, memory corruption and JVM crashes might result. This is why classes in the JDK such as java.util.zip.Deflater use synchronization internally despite Deflater objects are not intended to be used concurrently from multiple threads.

Note that making classes with some state in native memory thread-safe also implies that the native state should be safely published in constructors . This means that either the native state should be stored exclusively in final fields, or VarHandle.storeStoreFence() should be called in constructors after full initialization of the native state. If the project targets JDK 9 and VarHandle is not available, the same effect could be achieved by wrapping constructors’ bodies in synchronized (this) { ... } .

14. Parallel Streams

14.1. For every use of parallel Streams via Collection.parallelStream() or Stream.parallel() : is it explained why parallel Stream is used in a comment preceding the stream operation? Are there back-of-the-envelope calculations or references to benchmarks showing that the total CPU time cost of the parallelized computation exceeds 100 microseconds ?

Is there a note in the comment that parallelized operations are generally I/O-free and non-blocking, as per item 10.4? The latter might be obvious momentary, but as codebase evolves the logic that is called from the parallel stream operation might become blocking accidentally. Without comment, it’s harder to notice the discrepancy and the fact that the computation is no longer a good fit for parallel Streams. It can be fixed by calling the non-blocking version of the logic again or by using a simple sequential Stream instead of a parallel Stream .

Bonus: is forbidden-apis configured for the project and are java.util.StringBuffer , java.util.Random and Math.random() prohibited? StringBuffer and Random are thread-safe and all their methods are synchronized , which is never useful in practice and only inhibits the performance. In OpenJDK, Math.random() delegates to a global static Random instance. StringBuilder should be used instead of StringBuffer , ThreadLocalRandom or SplittableRandom should be used instead of Random .

Reading List

  • [JLS] Java Language Specification, Memory Model and final field semantics .
  • [EJ] “Effective Java” by Joshua Bloch, Chapter 11. Concurrency.
  • [JCIP] “Java Concurrency in Practice” by Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, and Doug Lea.
  • Posts by Aleksey Shipilёv: Safe Publication and Safe Initialization in Java Java Memory Model Pragmatics Close Encounters of The Java Memory Model Kind
  • When to use parallel streams written by Doug Lea, with the help of Brian Goetz, Paul Sandoz, Aleksey Shipilev, Heinz Kabutz, Joe Bowbeer, …

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

how to do code review java

  • Developer Blog
  • Software Development

Java Code Review Checklist – What to Include?

Java Code Review Checklist

Faiza Khalid

Are you looking for a Java code review checklist?

According to a survey, developers spend 45% of their time fixing bugs rather than writing new code. Strict code reviews allow developers to spend less time resolving bugs and delivering new features.

Developing a Java application requires a deep understanding of object-oriented programming, Java language, tools like Eclipse IDE , Java Standard Library, Git version control, and frameworks like Hibernate, Spring Boot, etc. You also require skills in database management, like JDBC (Java Database Connectivity) and ORM (object-relational mapping), application security practices, performance optimization, etc.

If you don’t have a professional team with this relevant expertise to take on the task, then submit a request for a complimentary discovery call, and one of our tech account managers who managed similar projects will contact you shortly.

Let’s discuss Java code review checklist items to ensure a well-written, functional, and maintainable software application.

Java Code Review Checklist

Check off the following when performing a Java code review:

Functional Check

Functional checks ensure the software works as intended. Review the following:

  • The code logic correctly implements the required functionality.
  • Check input validation and output accuracy. The code should validate input values to avert unexpected behavior, data corruption, etc., and verify the actual output matches the expected outcome.
  • There are no functional regressions or inconsistencies in case of changes to the existing code.
  • DRY (Don’t Repeat Yourself), SOLID (Single-responsibility Principle, Open-closed Principle, Liskov Substitution Principle, Interface Segregation Principle, and Dependency Inversion Principle), etc.
  • Observe object-oriented principles of Abstraction, Polymorphism, Inheritance, and Encapsulation.

You should check for the following to ensure a clean code:

Hire expert software developers for your next project

Naming Conventions

  • Follow Java code conventions to enhance code readability. All package names in Java are written in lower case, all constants in upper case, variables in CamelCase, etc.
  • Use meaningful and descriptive names instead of relying on comments to understand code. 
  • For example, calculateTax(BigDecimal amount).

No Duplication

  • There should be no code duplication. Classes and methods should focus on one functionality.
  • Declare variables with the smallest scope. E.g., if a variable is used inside a loop, declare it inside the loop.
  • Developers should follow a single code formatting template.

No One-Liners

  • Minimize using one-liners, especially with variable initialization and operation in the same line.

For instance, write the following code:

No White-Spaces

Use white spaces to separate code for better readability. For example, write this:

  • Generally, white spaces are not added in parentheses. E.g., if (total > 0) instead of if ( total > 0 )

Consider the following for a clean code:

  • Remove unnecessary comments or obsolete code.
  • Use @deprecated annotation for variables or methods that are to be removed and will not be used in the future.
  • Remove hard-coded variables.
  • Use switch case instead of multiple if else conditions.
  • Use logging instead of console print statements (SOPs).

Java Fundamental Code Practices

These include the following:

Using Immutable Classes

Make objects immutable where possible. Immutable objects are thread-safe and more secure. 

  • Declare classes as final to prevent their modification after initialization.
  • There are no setter methods that allow modification of its internal states.
  • Mutable objects in a class are deep copied to maintain immutable properties.
  • All mutable objects are initialized within the constructor.
  • Immutable variants are used from java.util package in case a class contains collections.
  • Immutability is maintained in subclasses.

Use mutable objects when they serve the purpose better. For example, instead of creating a new string object for every concatenation operation, use a mutable object.

Protected Accessibility

Review that a field or a member is accessible within its own class, subclass, and classes within the same package. Ensure the following for protected accessibility:

  • Use of a protected modifier when required by code design.
  • Protected members are used for polymorphism and inheritance purposes for code reusability.
  • The use of protected members does not introduce tight coupling.
  • Keep everything private by default and only expose methods to a client code when necessary.
  • Exposing classes or methods, for instance, via a public modifier, can affect code encapsulation. Another dev team could add functionality that you do not want, etc.

Code to Interfaces

The principle of code to interfaces avoids concrete implementations and supports programming against interfaces. Consider the following when verifying the code-to-interface principle in your code:

  • Classes are referencing interfaces, e.g., List, Map, etc., instead of ArrayList, HashMap, etc., as they introduce tight coupling.
  • Interfaces allow different implementations interchangeably (polymorphism).
  • Dependency injections make it easier to modify implementations.
  • There is easier integration of third-party libraries or new components.
  • Interfaces adhere to interface segregation principle (ISP).

Overriding Hashcode

Objects that are equal due to their values should override the equals methods to return true in case of the same values. The equals method is usually used for comparison and equality checks. Therefore, overriding the equals method is essential. 

Each Java object has a hash code value. Two equal objects must have the same hash code. Ensure the two objects are equal if they override both hashcode and equality methods.

Direct References

Carefully review direct references to fields in the client code. Direct references can be manipulated even if you use ‘final’. Instead, clone a reference or create a new reference and then assign it to the field.

Consider the following example:

Although the field is declared final, the reference to an ImmutablePerson object can be reassigned to another object. It indicates the reference is mutable.

In the modifyReference method, a new ImmoytablePerson object is created and assigned to the person reference. This does not modify the original ImmutablePerson object referenced by the person reference in the main method.

Exception Handling

  • Stay clear of NULL pointer exceptions. Avoid returning null values when possible. A good practice is to check for null values before calling a method to avoid NULL pointer exceptions. Consider the following code: 
  • Consider using the OPTIONAL class for variables that may have invalid states, like this:
  • @NULL and @NonNull annotations also show NULL warnings to developers while building the code. 
  • Ensure closing all resources, such as database connections, in the Finally block of try-catch exception handling.
  • Consider throwing custom exceptions instead of generic ones, which makes it easier to handle and debug code.
  • Use checked exceptions for recoverable operations and runtime exceptions for programming errors.

Security Checks

Consider the following security checks when reviewing Java code:

  • Do not log sensitive information;
  • Use immutable objects;
  • Release resources after use, such as streams, connections, etc., to prevent issues like resource leaks, denial of service, etc.
  • Include sensitive information in exception blocks, like file paths, server names, etc.
  • Implement security practices like authorization, authentication, SSL encryption, etc.

General Programming Checks

Using frameworks and libraries.

Leverage ready-to-use frameworks and libraries instead of writing all the code from scratch. 

Some popular Java libraries and frameworks include:

  • Apache Commons;
  • Hibernate Validator;
  • Spring Boot;
  • Apache Struts, etc.

Choice of Data Structures

Use appropriate data structures. Java programming language provides collections like ArrayList, LinkedList, Vector, Stack, HashSet, HashMap, etc. Your developers should know the pros and cons of using each. For example:

  • Map data structures are useful for unordered items that require efficient retrieval, insertion, etc.
  • The list structure is commonly used for ordered items that could contain duplicate values.
  • The set is similar to the List but without duplicates.

Also, ensure the use of the appropriate data types in your code. For example, use BigDecimal instead of float or double, enums for int constants, etc. Use static values, dynamic values, database-driven values, etc., appropriately.

Unit Testing

Testing code modules form an essential part of a Java code review checklist.

  • Review the use of unit testing. Developers should use unit test cases with mock objects for easy and repetitive testing.
  • Unit test cases should run independently of each other.
  • Do not include external services, such as data retrieval from a database, in unit testing.

Implementing Non-Functional Requirements

Ensure non-functional requirements, such as performance, scalability, monitoring , etc., are met. Consider the following:

  • Check for potential bottlenecks, excessive resource utilization, etc.
  • Review caching mechanisms for performance.
  • Check if the code is adjustable for future scalability requirements, like a surge in user traffic.
  • Ensure the application handles failures gracefully with proper recovery processes in place.
  • Check if the code is modular without excessive complexity for easy maintainability in the future.

Separation of Concerns

Assess if your Java code follows the separation of concerns principle, which confirms that a program divides into separate sections, each responsible for a specific functionality. Consider the following under separation of concerns:

  • Single responsibility principle in which each class or method has a single well-defined responsibility.
  • The layered architecture ensures the separation of presentation, business logic, data access, etc.
  • Ensure modules follow loose coupling, where a change in one component does not affect others.
  • Aspect-oriented programming is where cross-cutting aspects of an application, such as security, logging, etc., are separate from core features.

Planning for a Java Code Review?

These Java code review checklist items will help you deliver high-quality code that meets all the functional and non-functional requirements. 

Code review is a critical process as it ensures the successful deployment of software. Expert developers conduct successful code review processes. You need exceptional Java developers to plan Java application design, development, testing, and deployment. 

If you do not find high-quality Java developers on your team, DevTeam.Space can help you via field-expert software developers.

These developers can help you with smooth product development and comprehensive code reviews owing to their extensive experience building cutting-edge software solutions using the latest technologies and tools.

If you wish to know more about how we can help you with Java application development and code reviewing, send us your initial project specifications via this quick form . One of our account managers will contact you shortly for further discussion.

FAQs on Java Code Review Checklists

A good Java code review process ensures adherence to the standards, code quality, performance, etc. Check for programming errors, code modularity, functionality, code conventions, security practices, runtime exceptions, unit tests, etc.

Developers can check Java code quality through manual code reviews, code metrics (complexity, number of lines, etc.), established programming guidelines, dependency management, code refactoring, etc.

Some tools to review Java code include SonarQube, CheckStyle, ESLint with Java Plugin, Lint4j, etc. You need expert developers to use these tools and conduct static code analysis. Find experienced developers at DevTeam.Space for detailed code reviews.

Alexey

Alexey Semeney

Founder of DevTeam.Space

Hire Alexey and His Team To Build a Great Product

Alexey is the founder of DevTeam.Space. He is among the Top 26 mentors of FI’s ‘Global Startup Mentor Awards’ and is a Band Of Angels Technology Expert.

Some of our projects

Management Center of Telecommunication Information

Backend, Communication, DevOps, Java, Software

Management Center of Telecommunication Information

Development Team

Cryptocurrency Exchange

Blockchain, Ethereum, Fintech, Javascript, React, Smart Contracts, Solidity, Trading, Truffle, Web

Cryptocurrency Exchange

DDKoin

Blockchain, Ethereum, Fintech, Node.js, Smart Contracts, Solidity, Trading, Truffle

Read about DevTeamSpace:

New Internet Unicorns Will Be Built Remotely

DevTeam.Space’s goal is to be the most well-organized solution for outsourcing

The Tricks To Hiring and Managing a Virtual Work Force

Business Insider

DevTeam.Space Explains How to Structure Remote Team Management

With love from Florida 🌴

Tell us about your challenge & get a free strategy session, get a complimentary discovery call and a free ballpark estimate for your project.

Hundreds of startups and companies like Samsung , Airbus , NEC , and Disney rely on us to build great software products. We can help you too, by enabling you to hire and effortlessly manage expert developers.

By continuing to use this website you agree to our Cookie Policy

Get a printable version of all questions and answers & bring it as a cheat sheet to your next interview.

Hire vetted developers with devteam.space to build and scale your software products.

Trusted by 100x of startups and enterprise companies like

DEV Community

DEV Community

DeepSource profile image

Posted on Apr 12, 2021 • Updated on Apr 29, 2021 • Originally published at deepsource.io

Guidelines for Java code reviews

Having another pair of eyes scan your code is always useful and helps you spot mistakes before you break production. You need not be an expert to review someone’s code. Some experience with the programming language and a review checklist should help you get started. We’ve put together a list of things you should keep in mind when you’re reviewing Java code. Read on!

1. Follow Java code conventions

Following language conventions helps quickly skim through the code and make sense of it, thereby improving readability. For instance, all package names in Java are written in lowercase, constants in all caps, variable names in CamelCase, etc. Find the complete list of conventions here .

Some teams develop their own conventions, so be flexible in such cases!

2. Replace imperative code with lambdas and streams

If you’re using Java 8+, replacing loops and extremely verbose methods with streams and lambdas makes the code look cleaner. Lambdas and streams allow you to write functional code in Java. The following snippet filters odd numbers in the traditional imperative way:

This is the functional way of filtering odd numbers:

3. Beware of the NullPointerException

When writing new methods, try to avoid returning nulls if possible. It could lead to null pointer exceptions. In the snippet below, the highest method returns a null if the list has no integers.

Before directly calling a method on an object I recommend checking for nulls as shown below.

It can be pretty cumbersome to have null checks everywhere in your code though. If you are using Java 8+, consider using the Optional class to represent values that may not have valid states. It allows you to easily define alternate behavior and is useful for chaining methods.

In the snippet below, we are using Java Stream API to find the highest number with a method which returns an Optional . Note that we are using Stream.reduce , which returns an Optional value.

Alternatively, you could also use annotations such as @Nullable or @NonNull which will result in warnings if there is a null conflict while building the code. For instance, passing a @Nullable argument to a method that accepts @NonNull parameters.

4. Directly assigning references from client code to a field

References exposed to the client code can be manipulated even if the field is final. Let’s understand this better with an example.

In the above snippet, we directly assign a reference from the client code to a field. The client can easily mutate the contents of the list and manipulate our code as shown below.

Instead, consider cloning the reference or creating a new reference and then assigning it to the field as shown below:

The same rule applies while returning references. You need to be cautious so as not to expose internal mutable state.

5. Handle exceptions with care

While catching exceptions, if you have multiple catch blocks, ensure that the sequence of catch blocks is most specific to least. In the snippet below, the exception will never be caught in the second block since the Exception class is the mother of all exceptions.

If the situation is recoverable and can be handled by the client (the consumer of your library or code) then it is good to use checked exceptions. e. g. IOException is a checked exception that forces the client to handle the scenario and in case the client chooses to re-throw the exception then it should be a conscious call to disregard the exception.

6. Ponder over the choice of data structures

Java collections provide ArrayList , LinkedList , Vector , Stack , HashSet , HashMap , Hashtable . It’s important to understand the pros and cons of each to use them in the correct context. A few hints to help you make the right choice:

Map : Useful if you have unordered items in the form of key, value pairs and require efficient retrieval, insertion, and deletion operations. HashMap , Hashtable , LinkedHashMap are all implementations of the Map interface.

List : Very commonly used to create an ordered list of items. This list may contain duplicates. ArrayList is an implementation of the List interface. A list can be made thread-safe using Collections.synchronizedList thus removing the need for using Vector . Here ’s some more info on why Vector is essentially obsolete.

Set : Similar to list but does not allow duplicates. HashSet implements the Set interface.

7. Think twice before you expose

There are quite a few access modifiers to choose from in Java — public , protected , private . Unless you want to expose a method to the client code, you might want to keep everything private by default. Once you expose an API, there’s no going back.

For instance, you have a class Library that has the following method to checkout a book by name:

If you do not keep the searchByTitle method private by default and it ends up being exposed, other classes could start using it and building logic on top of it that you may have wanted to be part of the Library class. It could break the encapsulation of the Library class or it may be impossible to revert/modify later without breaking someone else’s code. Expose consciously!

8. Code to interfaces

If you have concrete implementations of certain interfaces (e. g. ArrayList or LinkedList ) and if you use them directly in your code, then it can lead to high coupling. Sticking with the List interface enables you to switch over the implementation any time in the future without breaking any code.

In the above snippet, using the Printer interface allows the developer to move to another concrete class HTMLPrinter .

9. Don’t force fit interfaces

Take a look at the following interface:

Is there a benefit of creating such an interface? Is there a scope for this interface being implemented by another class? Is this interface generic enough to be implemented by another class? If the answer to all these questions is no, then I’d definitely recommend avoiding this unnecessary interface that you’ll have to maintain in the future. Martin Fowler explains this really well in his blog .

Well then, what’s a good use case for an interface? Let’s say we have a class Rectangle and a class Circle that has behavior to calculate perimeter. If there is a requirement, to sum up, the perimeter of all shapes — a use case for polymorphism, then having the interface would make more sense, as shown below.

10. Override hashCode when overriding equals

Objects that are equal because of their values are called value objects . e. g. money, time. Such classes must override the equals method to return true if the values are the same. The equals method is usually used by other libraries for comparison and equality checks; hence overriding equals is necessary. Each Java object also has a hash code value that differentiates it from another object.

In the above example, we have overridden only the equals method of Object .

We would expect coinCount to update the number of 1 rupee coins to 7 since we override equals. But HashMap internally checks if the hash code for 2 objects is equal and only then proceeds to test equality via the equals method. Two different objects may or may not have the same hash code but two equal objects must always have the same hash code, as defined by the contract of the hashCode method. So checking for hash code first is an early exit condition. This implies that both equals and hashCode methods must be overridden to express equality.

If you write or review Java code, DeepSource can help you with automating the code reviews and save you a ton of time. Just add a .deepsource.toml file in the root of the repository and DeepSource will pick it up for scanning right away. The scan will find scope for improvements across your code and help you fix them with helpful descriptions.

Sign up and see for yourself!

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

tlayach profile image

Using Strings in Python

Paulo GP - Feb 17

Exploring the Random Library in Python

scofieldidehen profile image

Building a Decentralized Todo List DApp in React and Solidity

Scofield Idehen - Feb 17

devasservice profile image

Elevating Python Data Structures with `namedtuple`

Developer Service - Feb 15

Once suspended, deepsource will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, deepsource will be able to comment and publish posts again.

Once unpublished, all posts by deepsource will become hidden and only accessible to themselves.

If deepsource is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Saif Sadiq.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag deepsource:

deepsource consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.

Unflagging deepsource will restore default visibility to their posts.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Java Code Review Checklist

Follow the checklist with the top 10 steps for java code review in order to deliver quality code that enables a great customer experience..

how to do code review java

Code reviews, or peer reviews, can sometimes feel like an unnecessary chore, especially when there is a backlog of features to work on, leaving very little time for these reviews. However, manual or automated reviews are essential to delivering quality code that provides a great customer experience.

This guide covers some of the most common items to check in a Java code review to ensure your code is reliable and easy to read, maintain and scale.

1. Ensure the code follows standard naming conventions

Meaningful naming conventions help ensure the readability and maintainability of the application.

As such, ensure variable, method, and class names convey the subject:

addPerson()

Could be clarified to:

addEmployee()

Use all lower cases for package names and use reversed Internet domain naming conventions:

org/companyname/appname

Class names should start with Capitals:

Employee, Student,

Variable and method names should use CamelCase:

employeeList, studentName, displayEmployees()

2. Make sure it handles constants efficiently

Constants help improve memory as they are cached by the JVM. For values that are reused across multiple places, create a constant file that holds static values.

Favor database-driven values over dynamic values. Also, use ENUMs to group constants.

3. Check for proper clean Up

It is common during development to use procedures that help with your coding and debugging (hard coded variables, for example). It is good practice to remove these items and others such as:

  • Console print statements
  • Unnecessary comments
  • Use @deprecated on method/variable names that aren’t meant for future use

4. Handle strings appropriately

If you need to perform a lot of operations on a String , use StringBuilder or StringBuffer.

Strings are immutable, whereas StringBuilder and StringBuffer are mutable and can be changed. Additionally, a new String object is created for every concatenation operation.

Rather than creating multiple items, using a mutable object is preferred.

5. Optimize to use switch-case over multiple If-Else statements

Rather than using multiple if-else conditions, use the cleaner and more readable switch-case.

Doing so makes the logic cleaner and optimizes the app's performance.

switch(expression) {

// code block

  // code block

   // code block

6. Ensure the code follows appropriate error handling procedures

The NullPointerException is one of the most common and frustrating exceptions.

However, they can be avoided by performing a null check on a variable before operating on it.

The best practice is to use checked exceptions for recoverable operations and use runtime exceptions for programming errors.

Another area to evaluate during a Java code review is to ensure all exceptions are wrapped in custom exceptions.

In this way, the stack trace is preserved, making it easier to debug when things go wrong.

Also, it should declare specific checked exceptions that the method throws rather than generic ones. Doing so doesn’t give you the option to handle and debug the issue appropriately.

Avoid this:

public void hello() throws Exception { //Incorrect way

Try this instead:

public void hello() throws SpecificException1, SpecificException2 { //Correct way

Use the try-catch block for exception handling with appropriate actions taken in the catch block.

Also, use a finally block to release resources, such as database connections, in the finally block. This allows you to close the resource gracefully.

7. Avoid unnecessary comments in code?

Comments should not be used to explain code. If the logic is not intuitive, it should be rewritten. Use comments to answer a question that the code can’t.

Another way to state it is that the comment should explain the “why” versus “what” it does.

8. Validate that the code follows separation of concerns

Ensure there is no duplication. Each class or method should be small and focus on one thing.

For example:

EmployeeDao.java - Data access logic

Employee.java - Domain Logic

EmployeerService.java - Business Logic

EmployeeValidator.java - Validating Input Fields

9. Does the code rely on frameworks rather than custom logic when possible?

When time is of the essence, reinventing the wheel is time wasted. There are plenty of proven frameworks and libraries available for the most common use cases you may need.

Examples include Apache Commons libraries, Spring libraries, and XML/JSON libraries.

10. Make sure variables don’t cause memory leaks

Creating a bunch of unnecessary variables can overwhelm the heap and lead to memory leaks and cause performance problems. This occurs when an object is present in the heap but is no longer used, and the garbage collection cannot remove it from memory.

boolean removed = myItems.remove(item); return removed;

Try This Instead

return myItems.remove(item);

Performing regular Java code reviews can help identify issues before the application makes it to production.

The more thorough you are about the process, the less chance you’ll miss anything that could be added to your backlog.

How Adservio can help

We hope this blog post provides some valuable insight into what to check for in your review process. If your business needs assistance with defining a Java code review process, our team can help.

Reach out to our team of professionals and learn how we can help you accomplish your goals for quality application delivery.

 alt=

Industry insights you won’t delete. Delivered to your inbox weekly.

Other posts.

Digital Quality

Java Performance Tuning, Profiling, and Memory Management

Digital Delivery

Microservice Patterns and Best Practices

Digital Analytics

TOP 5 Open Source Workflow Engines

ELS: Identifying technical debts and reducing it by 80%

Success Story

ELS: Identifying technical debts and reducing it by 80%

RATP: Co-building an excellence center to ensure digital performance

RATP: Co-building an excellence center to ensure digital performance

GRDF: Shifting to SAP Fiori and giving customers a better digital experience

GRDF: Shifting to SAP Fiori and giving customers a better digital experience

Want to join us , let’s talk about your next project.

For companies of all sizes, Adservio provides the agility and flexibility to match market demand.

Our Company

  • News & Insights
  • Privacy & GDPR
  • Commitments
  • Tour Franklin 100-101, Terrasse Boieldieu 92800 Puteaux France ‍
  • [email protected]

how to do code review java

Code Review Best Practices

blog details

Code Review is one of the most important components in ensuring great Code Quality in your projects. How do you ensure that code reviews in your projects yield expected results?

You will learn

  • What is code review?
  • Why do you do code reviews?
  • When should you do a code review?
  • How can you become a good code reviewer?
  • What are the things to look for in a code review?
  • What are the code review best practices?

Article Series

This is the fifth article in a series of eight articles on Code Quality

  • 1 - Introduction To Code Quality
  • 2 - Introduction To Coding Standards - Java examples
  • 3 - Five Important Coding Standards
  • 4 - Best Practices in Static Code Analysis with SonarQube
  • 5 - Code Review Best Practices
  • 6 - What Are Code Smells?
  • 7 - What Is Refactoring?
  • 8 - Continuous Integration - 5 Important Questions or Tips

Why Code Reviews

What could be the reason for doing a code review?

image info

Remember that a code review is not a tool to find fault with others efforts.

Here are a couple of important goals:

  • A code review is done to add value to the system and the people in the team.
  • It also adds to a list of best practices that team members can follow.

Adding Value To The System

Code reviews add value to your system. Aim of the code review is to make the system more maintainable. Your aim is to check for bugs in adhering to functional and non functional requirements - scalablity, performance, security etc.

Adding Value To The People

Code reviews should be used as a way to enhance the knowledge of the developers involved and a way to spread the best practices.

Adding To Best Practices

An important step of code review should be to identify best practices. Common error patterns can be identified and documented.

When Should You Do Code Reviews?

image info

Review As Early As Possible

It is preferable to do code reviews as early as possible .

Review with Normal Focus

Normal focus refers to typical code review done during the course of a sprint for a run of the mill user story.

Review with High Focus

There are times during development when peer reviews need to be done with high focus.

New Developers Joining In

A good example is when a new developer joins a team. A new developer takes time to get familiar and start implementing code that meets the team’s coding standards. An effort should be made to encourage them to learn from code reviews.

New Methodology Or Technology Implemented

When a new methodology is being adopted, or a new technology is being brought into the code base, it is important to have focused code reviews.

Building A Vertical Slice

In the initial stages of the project, you generally build a vertical slice. Vertical slice helps in solving technical challenges.

Vertical slice becomes a reference for the project. It is important to have focused code reviews for the vertical slice.

How To Do Code Reviews?

image info

Encourage Pair Programming

Ideally, I would love to have pair programming reviews. A lot of times, it is much easier to refactor code almost immediately during the review, than at a later point in time.

Let’s quickly review a few other best practices related to code review.

Use Static Analysis Tools

Make use of static analysis tool such as SonarQube.

  • Check the components in code, their sizes, and their interactions with other components in the code.
  • Large classes
  • Complex methods
  • Large components
  • Lot of dependencies
  • Uncovered code

Review Junits

Review the Junits for complex method and classes, and see how readable the code actually is.

Junits are often a very good signal of the readability of code. If the code is difficult to test, the code is definitely difficult to understand.

Check Readability Of Code

Look at the readability of the code, by focusing on the Four Principles Of Simple Design.

What do you look for in a code review?

There are various aspects to be considered while doing a review of the code.

image info

Review The Architecture

Have a look at various points, such as:

  • The choice of frameworks in the code base
  • The way the code components communicate with other systems
  • How testable the code is?
  • The architecture of the components themselves
  • The extent of code reuse - Are common components are identified and abstracted away for use in other places?

Review The Design

image info

Review the following aspects:

  • What is the nature of the interaction between the various classes? How loosely are the classes coupled, and what is the cohesion between them?
  • Have a look at the layer responsibilities, and see if the layers are clearly demarcated, and do not overlap in functionality.
  • How well are the core object oriented principles followed in the code design?
  • What is the nature of the unit tests? How easy or difficult is it to unit test the code under review?

Review The Code

image info

  • Make sure the code follows the Four Principles Of Simple Design
  • Ensure the code got the basics right

image info

  • Will the code be scalable and performant?

image info

  • How does the code handle important security concerns?
  • How well are the unit tests written, and are they readable?
  • Are language specific standards being adhered to? In Java foe example, the following language constructs have certain purposes:

image info

For example, Enums are preferred to strings wherever possible, and this makes the code more readable.

Review Engineering Practices

image info

The quality of code in an application depends greatly on the kind of engineering practices followed in the team. You can check

  • How often the code is committed?
  • Review how often builds are broken
  • Review the entire continuous integration process

image info

In this article, we had a good overview of code review best practices for a team, or organization. The core principle behind doing code reviews is to add value - to the system, to the people involved, and to the best practices as a whole.

Just Released

ad banner

Related Articles

author

Code Quality Basics - What Is Refactoring?

Code quality basics - what are code smells, code quality basics - five important coding standards, introduction to code quality, introduction to coding standards with java examples, code quality basics - best practices in static code analysis with sonarqube, code quality basics - what is technical debt, code quality basics - what is readability of code, code quality basics - what is legacy code, code quality basics - what is code duplication, code quality basics - what is code coverage, code quality basics - what is code complexity, related courses.

ad banner

Javarevisited

Learn Java, Programming, Spring, Hibernate throw tutorials, examples, and interview questions

Topics and Categories

  • collections
  • multithreading
  • design patterns
  • interview questions
  • data structure
  • Java Certifications
  • jsp-servlet
  • online resources
  • jvm-internals

Saturday, August 7, 2021

  • Code Review Checklist and Best practices in Java

10 points checklist on Code Review

how to do code review java

1) Functional Requirement

code review checklist, code review best practices

2) Side effect on existing code

3) concurrency, 4) readability and maintenance, 5) consistency, 6) performance, 7) error and  exception handling, 8) simplicity, 9) reuse of existing code, 10) unit tests.

how to do code review java

6 comments :

Thanks for your comment itoctopus, I agree Concurrency issues are more subtle and most of the time only shows in production due to high volume and different real world, one way to deal with this is load testing which reveals some concurrency issues.

I am big fan of Code reviews and spend more time convincing people to do Code reviews than actually doing them :). While I am here, I would like to share couple of benefits of Code review, which I have personally seen. 1) Code review can be a real team building exercise, It increase and improves communication between team members. Though Code review must be given only keeping positives in mind, instead of criticizing other developer. 2) Code review also increase knowledge sharing between team, which means, whole team remains in same page and ready to backup each other. This can be a huge plus for Manager, who needs to manage leaves and resources. 3) Ultimately benefit of Code review is better code quality, reduce testing time and less number of bugs. There is no substitute of Code review. Now What can go wrong with Code review: Like anything else Code review also has two sides of Coin, if not done properly it can harm the team. feedback must always be constructive, It's responsibility of Senior develop to educate team and encourage them learn and think through. Code reviewer should never think that he has to find flaws, he can also appreciate fellow developer. Keeping things simple and normal is key to success.

Along the lines of "Readability and maintenance" I would include clean code changes like suggested by Robert C Martin in his book, "Clean Code". These are all good tips to keep in mind when we do a code review.

It is good to mention about tools that help to automate codereview: checkstyle , pmd, findbug, sonar.

if concern then security

Majority of times the code reviews are made without a proper explanation what could go wrong and which will not help peer developers to write better and quality code. I start with java docs provided in the code and think if any other developer can really understand it without knowing the end to feature of the API.

Post a Comment

Search this blog, interview questions.

  • core java interview question (182)
  • interview questions (115)
  • data structure and algorithm (91)
  • Coding Interview Question (81)
  • spring interview questions (48)
  • design patterns (47)
  • object oriented programming (39)
  • SQL Interview Questions (36)
  • thread interview questions (30)
  • collections interview questions (26)
  • database interview questions (16)
  • servlet interview questions (15)
  • hibernate interview questions (7)
  • Programming interview question (6)

Java Tutorials

  • date and time tutorial (25)
  • FIX protocol tutorial (17)
  • Java Certification OCPJP SCJP (35)
  • java collection tutorial (91)
  • java IO tutorial (30)
  • Java JSON tutorial (19)
  • Java multithreading Tutorials (64)
  • Java Programming Tutorials (21)
  • Java xml tutorial (17)
  • jsp-servlet (37)
  • online resources (245)

Get New Blog Posts on Your Email

Get new posts by email:.

  • courses (448)
  • database (56)
  • Eclipse (36)
  • general (29)
  • JVM Internals (26)
  • JQuery (23)
  • Testing (23)

Blog Archive

  • ►  February (5)
  • ►  January (85)
  • ►  December (35)
  • ►  November (13)
  • ►  October (15)
  • ►  September (189)
  • ►  August (60)
  • ►  July (54)
  • ►  June (6)
  • ►  May (281)
  • ►  April (200)
  • ►  March (45)
  • ►  February (13)
  • ►  January (12)
  • ►  December (6)
  • ►  November (1)
  • ►  September (2)
  • ►  August (25)
  • ►  July (59)
  • ►  June (53)
  • ►  May (24)
  • ►  April (87)
  • ►  March (20)
  • ►  February (38)
  • ►  January (37)
  • ►  December (105)
  • ►  November (51)
  • ►  October (25)
  • ►  September (46)
  • 5 ways to add multiple JAR in to Classpath in Java...
  • How to implement Post Order Traversal of Binary Tr...
  • Java Enum Tutorial: 10 Examples of Enum in Java
  • Top 10 Excuses Programmers Gives to Avoid Unit Tes...
  • How to Solve java.lang.ClassNotFoundException: org...
  • How to Implement Binary Search Tree in Java? Example
  • What is @SuppressWarnings annotation in Java? Unch...
  • Spring @Transactional Annotation Example - How to ...
  • How to Code in Dart Programing language? Dart Hell...
  • Inner class and nested Static Class in Java with E...
  • How to Attach Source Code in Eclipse to JAR Files ...
  • How to Compare Arrays in Java – Equals vs deepEqua...
  • How to add, subtract days, months, years, hours fr...
  • Difference between equals method and "==" operator...
  • What is final in Java? Final variable , Method and...
  • What is Type Casting in Java? Casting one Class to...
  • Recursion in Java with Example – Programming Tutor...
  • Observer design Pattern in Java with Real world co...
  • How to get current date, month, year and day of we...
  • How to convert milliseconds to Date in Java - Tuto...
  • 3 Examples to Print Array Elements/Values in Java ...
  • How to check if String contains another SubString ...
  • Difference between mvn install, release and deploy...
  • How to check if a String is numeric in Java? Use i...
  • How to use instanceof operator in Java with example
  • How to remove duplicates elements from ArrayList i...
  • How to read input from command line in Java using ...
  • Constructor Chaining in Java Example - Calling one...
  • How to Escape String Literal in Java Using Eclipse...
  • 9 Things about null keyword and reference in Java
  • How to configure Log4j in Java program without XML...
  • What is Constructor in Java with Example – Constru...
  • How to sort HashMap by key and value in Java - Has...
  • How to comment uncomment single line and block of ...
  • Java TreeMap Tutorial: 15 Example of TreeMap in Java
  • How to parse String to Enum in Java | Convert Enum...
  • How to split String in Java by WhiteSpace or tabs?...
  • 3 ways to get number of months and year between tw...
  • Iterative QuickSort Example in Java - without Recu...
  • How to do static import in Eclipse - Java Example ...
  • What is Object in Java and Object Oriented Program...
  • Where is Java used in Real World?
  • Why getter and setter are better than public field...
  • How to use BlockingQueue in Java? ArrayBlockingQue...
  • Top 10 JDBC Interview questions answers for Java p...
  • Top 20 Core Java Interview Questions and Answers f...
  • What is Factory method Design Pattern in Java with...
  • Top 10 Struts Framework Interview Questions and An...
  • How to Create File and Directory in Java Example -...
  • Open Closed Design Principle in Java - Benefits an...
  • How to Create and Run a batch file in Windows - .b...
  • 4 Ways to Search Java Array to Find an Element or ...
  • How to setup Java Environment and run Java Program...
  • Java String Replace Example Tutorial
  • Top 25 Java Collection Framework Interview Questio...
  • What is Static Variable Class method and keyword i...
  • What is static import in Java with Example
  • How to use Class in Java Programming - Example
  • How to use Iterator and ListIterator in Java? Exam...
  • How SubString method works in Java - Memory Leak F...
  • How to build Java Projects using Apache ANT ? Beg...
  • Eclipse shortcut to Type System.out.println in Jav...
  • What is Dart Programming language? how to use Dart...
  • Top 10 Java Serialization Interview Questions and ...
  • How to override compareTo method in Java - Example...
  • How to check if a String is Number in Java - Regul...
  • How to Convert String to Double in Java Program wi...
  • How to convert decimal to binary, octal and hex St...
  • How to write build.xml and run build in Apache ANT...
  • How to Set Path for Java Unix Linux and Windows
  • What is PriorityQueue or priority queue in Java wi...
  • What is Inheritance in Java and OOP Tutorial - Exa...
  • How to use ARM- Automatic resource management in J...
  • Variable argument and Varargs methods in Java with...
  • How to loop over two dimensional array in Java? Ex...
  • What is EnumMap in Java – Example Tutorial
  • How to use String in switch case in Java with Example
  • How to override hashcode in Java example - Tutorial
  • 10 Tips to override toString() method in Java - To...
  • How to work with transient variable in java (an ex...
  • How to String Split Example in Java - Tutorial
  • 2 Examples to Convert Byte[] Array to String in Java
  • How to use multiple JQuery UI Date Picker or Datep...
  • 2 Ways to Parse CSV Files in Java - BufferedReader...
  • How to use CopyOnWriteArraySet in Java with Example
  • How to download jQuery into Web Page from CDN? 3 E...
  • How to convert String or char to ASCII values in J...
  • 5 Reasons to Use Composition over Inheritance in J...
  • How to read file line by line in Java - BufferedRe...
  • How to join three tables in SQL query – MySQL Example
  • 5 Entertaining Posts from StackOverFlow - Must Read
  • How to Convert Collection to String in Java - Spri...
  • 10 Equals and HashCode Interview Questions in Java
  • Top 10 JDBC Best Practices for Java Programmers
  • Java 8 - Journey of for loop in Java - for() to f...
  • Why use SLF4J over Log4J for logging in Java? Example
  • SQL Query to Find All Table Names on a Database Wi...
  • What is polymorphism in Java? Method overloading ...
  • How to Fix Arithmetic overflow error converting nu...
  • ►  July (244)
  • ►  June (2)
  • ►  May (2)
  • ►  April (7)
  • ►  March (8)
  • ►  February (3)
  • ►  January (3)
  • ►  December (4)
  • ►  October (2)
  • ►  August (2)
  • ►  July (3)
  • ►  June (1)
  • ►  May (6)
  • ►  April (13)
  • ►  March (6)
  • ►  February (4)
  • ►  November (6)
  • ►  October (4)
  • ►  August (1)
  • ►  July (2)
  • ►  May (1)
  • ►  April (1)
  • ►  January (1)
  • ►  December (1)
  • ►  November (2)
  • ►  October (6)
  • ►  September (1)
  • ►  August (4)
  • ►  March (2)
  • ►  February (1)
  • ►  July (1)
  • ►  December (2)
  • ►  October (1)
  • Privacy Policy
  • Terms and Conditions

eng-practices

Introduction.

A code review is a process where someone other than the author(s) of a piece of code examines that code.

At Google, we use code review to maintain the quality of our code and products.

This documentation is the canonical description of Google’s code review processes and policies.

This page is an overview of our code review process. There are two other large documents that are a part of this guide:

  • How To Do A Code Review : A detailed guide for code reviewers.
  • The CL Author’s Guide : A detailed guide for developers whose CLs are going through review.

What Do Code Reviewers Look For?

Code reviews should look at:

  • Design : Is the code well-designed and appropriate for your system?
  • Functionality : Does the code behave as the author likely intended? Is the way the code behaves good for its users?
  • Complexity : Could the code be made simpler? Would another developer be able to easily understand and use this code when they come across it in the future?
  • Tests : Does the code have correct and well-designed automated tests?
  • Naming : Did the developer choose clear names for variables, classes, methods, etc.?
  • Comments : Are the comments clear and useful?
  • Style : Does the code follow our style guides ?
  • Documentation : Did the developer also update relevant documentation?

See How To Do A Code Review for more information.

Picking the Best Reviewers

In general, you want to find the best reviewers you can who are capable of responding to your review within a reasonable period of time.

The best reviewer is the person who will be able to give you the most thorough and correct review for the piece of code you are writing. This usually means the owner(s) of the code, who may or may not be the people in the OWNERS file. Sometimes this means asking different people to review different parts of the CL.

If you find an ideal reviewer but they are not available, you should at least CC them on your change.

In-Person Reviews (and Pair Programming)

If you pair-programmed a piece of code with somebody who was qualified to do a good code review on it, then that code is considered reviewed.

You can also do in-person code reviews where the reviewer asks questions and the developer of the change speaks only when spoken to.

Code Security

In this section

Related articles

8 proven code review best practices for developers

Want to try it for yourself?

One of the best ways to improve the quality and security of software is to implement a formal process for manual code reviews. Given the potential errors during code writing, using several fresh eyes with complementary expertise can uncover mistakes the original programmer may never notice. Moreover, while humans are prone to error on their own, a group of experts may catch a bug or security flaw within the code that automated code review tools may miss.

For all the benefits of having a peer code review, it is sometimes challenging to have a peer group convene and rapidly execute the task at hand. To address that point, defining code review practices can help guide the process to get to the desired result: high-quality, secure code. Here are eight code review guidelines that you can implement into your company's software development process.

1. Add comments during source code during creation

The first practice is for developers to use non-functional comments in sections of the code to tell reviewers the intent of a code block. Comments help communicate why the developer made the decision or change they did without the review team having to guess. When executed well, experienced reviewers should be able to use comments to understand the purpose and methodology of the entire code sequence. Moreover, having a style guide and enforcing it ensures readability for the whole team.

2. Don't assume something works without testing

Developing code requires iterations of trial and error. A developer writes some lines, compiles the code, and it doesn't work. Testing the functionality and output of the new code sections can drastically reduce review time later. In addition, it is much easier to correct a small portion of code knowing the rest of the code functions appropriately. One tactic called test driven development (TDD) is to write unit tests before you implement the code. This approach serves as a preliminary check for specific function blocks, leaving the reviewers to focus on integrating these functions in the remainder of the code.

3. Run test suites on proposed code

One approach to validating a specified set of procedures is to use automated test suites to write unit tests for each code block. The test suite presents a collection of known functions and evaluates the code against a known positive result. Another tool to assess how the code performs specific actions, test suites accelerate the validation of sections of code that perform one or more tasks that the test suite prescribes. A failure can point the developer to a specific area they need to modify.

4. Ensure pull requests are small and with a singular purpose

Pull requests (PRs) refer to a standardized process for requesting peer code reviews. When the developer completes the initial code change, the PR triggers the review process. The developer should create PRs with specific instructions for the reviewers to increase the efficiency and speed of the manual code review. The more elaborate the PR, the longer the review can take, which risks the reviewer missing the PR's primary objective. In fact, the ideal size of a PR is less than 250 lines because reviewers can discover 70-90% of defects in under an hour.

Live Hack: Exploiting AI-Generated Code

Gain insights into best practices for utilizing generative AI coding tools securely in our upcoming live hacking session.

5. Always run automated code checkers

Before the peer review, the developer can employ code review tools like scanners, automated code checkers , or static code analyzers to evaluate the quality of a codebase after changes were made. These tools cover overt formatting mistakes like errors in function names or spacing issues. Scanners or linters have defined guardrails and operate like spellcheck for the code to find errors quickly. Employing these tools removes this work from the manual peer review process, allowing the code review team to focus on stylistic or interpretive errors.

For example, Java code review tools can find bugs and security issues within Java code and offer actionable advice that enable developers to quickly remediate them. Snyk Code offers code quality recommendations directly from your IDE, providing a frictionless developer experience.

6. Review all code and PRs

As the code is sequential, reviewers need to assess the entire code and PR set for cohesiveness. Changing one section can drastically affect downstream subroutines, so the code peer review team needs to consider the whole code and all PRs when evaluating it. Larger, more substantial PRs naturally garner more attention, however, an error in a small PR can have effects even more devastating than that of a set of flaws with an extensive PR.

7.Set limits for review time and code lines checked

Reviewing code is a time-consuming and tedious (though critical) process. To that end, it is essential to limit the amount of time a reviewer or team spends on the details of each line of code. A few examples of best practices in this area include ensuring the team members don't spend more than an hour on code reviews or that the team does not review more than several hundred lines in a given number of hours. This philosophy sets expectations for the code review team and ensures that they meticulously check the part of the code tied to the PR. By organizing code reviews in an efficient way for the whole team, developers can get valuable feedback and quickly improve the quality of their code.

8. Conduct a security code review

Another best practice for code reviews is to conduct a secure code review . While automated tools check the code for spacing or naming errors and compare it with known standard functions, manual reviews assess the code's style, intent, and functional output. The third type of assessment is a security code review, which reviews the developer's code for security robustness.

The code can have inherent vulnerabilities that compromise the application or surrounding code blocks. A secure code review can identify these vulnerabilities and also aid in identifying errors in logic tied to how an application works. The developer must be able to write the code in an environment that guards it against external attacks that can have effects ranging from intellectual property theft to revenue loss to data loss

The good news is that there are existing static application security testing (SAST) tools   — like Snyk Code — that can catch vulnerabilities before they hit code review, as well as  secure coding best practices that can protect the source code and enable an efficient secure code review. Examples include limiting access to the code, enforcing strong encryption, and implementing Secrets Management to protect passwords and hardcode from broad sharing.

Final takeaway for how to do a code review

Developers can continue refining and optimizing their code indefinitely, but they still may not catch every error or security flaw. By implementing a peer code review process, development teams can ensure their software is properly tested before pushing code to production. Conducting a code review with a combination of an automated code review, manual peer review steps, and secure code review practices is the most efficient way to ship high-quality, secure code quickly.

Code review FAQ

What is a secure code review.

security code review is a process for checking code for how well it guards against external threats. The code can have inherent security weaknesses that compromise the application or surrounding code blocks. Peer reviews are a manual process that complement automated testing methods for comprehensive security coverage.

What are the benefits of a secure code review?

A secure code review can identify security weaknesses and help to identify errors in the code logic tied to how an application works. This type of review protects the application from data and intellectual property loss, which could impact the company’s revenue and reputation.

Visit our Security Resources page to learn about Snyk's options and tools to help developers create accurate, secure code.

Securing Source Code in Repositories is Essential: How To Get Started

Keeping your source code secure helps safeguard it against data breaches, maintains user trust, and helps to prevent potential financial losses or reputational damage; learn why it's important and how to get started.

Patch Logo Segment

Snyk is a developer security platform. Integrating directly into development tools, workflows, and automation pipelines, Snyk makes it easy for teams to find, prioritize, and fix security vulnerabilities in code, dependencies, containers, and infrastructure as code. Supported by industry-leading application and security intelligence, Snyk puts security expertise in any developer’s toolkit.

© 2024 Snyk Limited Registered in England and Wales

How to do Automated Code Review on Java

Andriy Sokolov

Audio Version Of This Article

"What's so good about automated reviews? These computerized strategies effortlessly locate the inaccuracies and minor faults, which you might ignore during manual code inspections."

Irrespective of operating inside an “ Open Source ” or Industrial programming region, software program builders employ analysis ways to research and examine source code. We recognize that it's their prime task to overcome flaws or safety problems inside the program to ensure that it meets excellent standards. Developers can perform this operation manually or mechanically through Automated Code Review .

The custom of automatically evaluating source code using predetermined coding regulations to discover wasteful or suboptimal programming is called Automated code review.

By automating, the special programs designed help to make bad code detection easier. Let’s make it easier to understand. The evaluated software or device regularly offers ai alarming instances or breaches of coding benchmarks. Review software may additionally equip you with a mechanical process of solving detected errors as well.

WHAT DISTINGUISHES COMPUTERIZED CODE OVERVIEW FROM MANUAL CODE CRITIQUES?

Automatic review tools save time spent in reviewing the software. Although they have a shorter release time; but, they do not do it very well examine. In addition, there are certain limitations of Automatic Code Review software. Consequently, for instant and effective software improvement, teams have to mix manual and automatic opinions preferably.

Learn more about Secure Coding Practices.

Manual code reviews include a developer's peers manually evaluating code to find out any potential flaws.

The substantial advantages of automatic code overview over manual code evaluation are:

1. Time efficiency

The best part is that an automated code overview tool might, without delay, spot errors while the developer is writing.

2. The absence of human mistake

Automatic code evaluation structures, not like human beings, are excluded from manual errors. But, as an alternative, they execute ideal policies-based audits: they'll do so if they may be designed to locate well-defined inaccuracies.

3. The absence of bias

Unlike manual code reviews, automated code reviews don't contain biases in the evaluation. Evaluators' personal preferences and inclinations don't reflect in the automatic code reviews. Then again, relying entirely on computerized code reviews no longer ensures the detection of all bugs or protection flaws. For instance, some security flaws, including authentication issues, getting the right to manipulate points, and inappropriate cryptography use, are difficult to stumble on mechanically.

CAN AUTOMATED CODE REVIEWS BE USED INSTEAD OF MANUAL CODE REVIEWS?

No. Guide code reviews lower high-hazard high-degree decisions like using inefficient architectures. In addition, they inspire a collaborative environment and peer grievance. Even as automated ones are superior over the other type, they're not always preferred over manual code reviews.

But there is a possibility of them making manual code opinions more excellent green because they relieve human reviewers of the weight of checking for minor mistakes, which include character naming, space, or style.

The automated code evaluation gear assists builders in finding flaws and identifying capacity dangers. In the code evaluation method, these tools frequently gift caution flags to decide if the code satisfies the company's requirements. An automated code evaluation tool may also automatically restore troubles or help customers by fixing them.

WHAT ISSUES DOES AUTOMATED CODE REVIEW SOLVE?

The following are some of the issues that automated code overview technology take a look at:

  • Mistakes-inclined code safety
  • Compatibility
  • Unused codes
  • Code execution performance

No surprise, an automation software program can scan thousands of traces of code in a matter of seconds. But, they cannot parent the developer's commercial enterprise logic and targets.

It purposefully hides the pathways by using far extra advanced automation techniques. Computerized code review can also overlook the objectives at the back of them.

But what's so good about Automated reviews? These computerized strategies effortlessly locate the inaccuracies and minor faults you might ignore during manual code inspections.

However, this automation can't pass past a certain degree of reviewing. You can do that through manual code evaluation.

It is not required for reviewers to have all of the relevant statistics and abilities. The automation software is set up to provide indicators while feasible issues are detected.

Reviewing trend is currently going closer to computerized code review to save time, cash, and attempt, but many groups still need a human touch.

AUTOMATED CODE REVIEW TOOLS:

In our studies on the challenge, we explained why code critiques are critical. First, automated code evaluations automate quantities of the code assessment procedure. Second, it is substantial because code evaluations are finished by builders and their managers, who are a few of the high-quality-paid organizations in a firm primarily based on their location of forte.

Computerized code overview answers are often connected with offerings that host relaxed Git-based repositories, including

  • Code commit

These evaluate the code in a slightly different way and determine if the code fulfills the wanted necessities. But, of course, these standards vary based on the software program's utility.

A number of those software solutions enable programmers to set their coding standards. Similarly, some equipment moves past a guidelines-based code analysis.

WHAT FACTORS MUST BE CONSIDERED AS DECIDING ON AUTOMATIC CODE EVALUATION TOOLS?

Cutting-edge software program development exceptional practices include automated code review. The following are the vital elements to keep in mind even as deciding on code review tools:

Support for code language and IDE:

The maximum essential standard is that the tool should help the code's language. Therefore, it is crucial to decide whether the gear under consideration endorses the application's programming languages and the programming languages that the group intends to employ.

Frequently used: popular tools have fewer troubles, quicker support, and higher documentation.

Cloud-hosted:

Cloud-based help is essential for diverse groups seeking to collaborate. However, a cloud-hosted gadget, alternatively, can also cause safety and connection issues. Consequently, the team ought to weigh the benefits and drawbacks of a cloud solution.

Well documented and supported:

Better documentation facilitates the understanding of the latest team members. In addition, developers might advantage from technical assistance as they discover ways to use the automated code evaluate equipment.

Static code analysis uses an extensive list of policies: automatic code reviews are guided by predefined guidelines. Therefore, it is tremendous to have various pieces of regulations within the auto code checking device.

Talents of machine Learning:

Machine learning is a part of auto code review structures. Therefore, a device with machine learning abilities is a better option than the other one.

HO TO DO AUTOMATED CODE EVALUATION ON JAVA?

One of the maximum tedious components of a Java mission that builders forever pull away from is the code evaluation. Checking thousands of strains of somebody else's code for such things as block braces, code indenting, Javadoc comments, and naming conventions can be an actual pain.

To make matters worse, code reviews are typically restricted with the aid of unforgiving and tight task schedules. There may never be sufficient time for a detailed code evaluation, so code critiques regularly become simply exercising in code beautification. Regardless of the first-rate intentions of the reviewer, optimization and logic checking retake a seat.

Java code analyzers ease the ache

In the face of such troubles, Java code analyzers are simply what the client ordered. Those tools are meant to automate as maximum code evaluation procedures as possible. The most straightforward part of the assessment left to the human reviewer is checking for any flaws within the good middle judgment of the class and identifying viable optimizations.

Optimizations can make a massive difference in the performance of any code. When programmers assess various code analyzers, they find many primary characteristics. The most important one being commonly used IDEs like NetBeans , Eclipse , jEdit , and JDeveloper .

Some code-checking tools are fantastic at locating code errors; however, expect to apply the incorrect line variety as a reference and manually hunt down the error. Such gadgets are too strenuous to be adopted in projects.

WHAT ABOUT THE IDE INTEGRATED TOOLS?

Tools integrated with IDEs greatly simplify this System because the code-checking outcomes are displayed inside the IDE getting used. You need to double-click the mistake to pick the corresponding line of code on your Java editor.

Although the list of automated code review tools for Java is so long, we have presented top tools below:

  • SonarQube .
  • Eclipse. Jenkins.
  • Visual Studio

Three automated code review tools for Java have been sufficiently compelling and met the IDE help criterion. These are PMD , Checkstyle , and Jalopy .

PMD and Checkstyle

According to the PMD documentation, the tool checks for the following things in your code;

PMD looks for these things:

  • Duplicate import statements
  • local components that are not used
  • Empty trap blocks
  • Unused parameters
  • Empty if statements
  • Unused non-public strategies
  • Probable singleton classes
  • brief/lengthy variable and approach names

Checkstyle looks for these things:

  • Naming conventions
  • Size violations
  • White space
  • Miscellaneous tests (which includes some valuable tests like a pointless gadget. Out and printstackTrace)

How do they work?

In contrast to PMD, Checkstyle can capture Javadoc commenting; however, PMD gives a helpful CPD , which contains copied coding. While using PMD, the mistakes programmers regularly discover are unused imports, unused non-public variables, and the occasional replica literal.

Checkstyle found many more significant errors.

Along with detecting lacking Javadoc comments, it catches line width past 80 characters, variable names not following conventions, and tab utilization in preference to areas, among other matters. Both types of equipment come up with the way of making your guidelines.

Jalopy is an easily configurable supply code formatted that may detect, and attach, several code convention flaws that would appear in Java code. Thus, Jalopy is extra of a code fixer than a code checker. Nevertheless, jalopy plug-ins are a gift for most IDEs, and, in most instances, they get pretty seamlessly with the IDE.

Many developers thin Jalopy to be a robust tool, capable of doing several significant matters. For example, it could restore code indentation, brace alignment, line wrapping past a positive character duration, add valuable Javadoc feedback, and refer to kind imports.

The enjoyable part is that Jalopy is superbly configurable. It has a easy to use user interface that allows to perform all basic functions. You don’t need to tweak with XML configuration files.

Which one is better?

Checkstyle appears a better option. It tests for top things that enterprise code conventions expect. So PMD is a way to go if improving code first-class is your primary purpose. But in case you wish to head similarly and want a device to do the fixing job, take a look at Jalopy.

BOTTOM LINE:

Instead of struggling with your code reviews and losing treasured resources on work that regularly does not attain a great deal, it's better to go with one of these automated code review tools.

As soon as the tools have made code-checking an enormously easy assignment, you can make code assessment a typical hobby. Automated code review no more remains to be finished at the quiet of a task while cut-off dates are already making existence miserable.

The equipment also offers integration with Apache Ant, so you ought to very well run the code checker daily while a construct is being taken or while your unit exams are executed. As a result, stay on top of things of your code and deliver code which you, in reality, consider is high exceptional.

Browse By Tags

Don’t Miss It

What Is Code Review – How It Helps Professional Developers Deliver Quality Software

20 April 2022

What is Code Refactoring?

06 December 2021

Ten Best SonarQube alternatives in 2021

27 October 2021

Metric Based Code Complexity Analysis - How Effective Is It?

04 October 2021

right-icon

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus convallis sem tellus, vitae egestas felis vestibule ut.

Error message details.

Reuse Permissions

Request permission to republish or redistribute SHRM content and materials.

The Performance Review Problem

As the arcane annual assessment earns a failing grade, employers struggle to create a better system to measure and motivate their workers.

​After an annual review that lasted about 10 minutes, a New Jersey-based account coordinator knew it was time to leave the public relations agency where he had worked for almost a year. 

The 25-year-old, who requested anonymity, asked for the meeting because his boss had not mentioned any formal assessment process, nor had his manager ever critiqued his work. The coordinator says he sat with a trio of senior executives who did not ask him any questions beyond how he would rate himself. He says they ignored his requests for guidance on how to advance at the agency. 

Screen Shot 2023-03-15 at 85749 AM.png

This example also illustrates one of the common failures in performance management: limiting reviews to once or twice a year without having any other meaningful career discussions in between. Nearly half (49 percent) of companies give annual or semiannual reviews, according to a study of 1,000 full-time U.S. employees released late last year by software company Workhuman. 

The only situation that is worse than doing one review per year is doing none at all, experts say. The good news is that only 7 percent of companies are keeping employees in the dark about their performance, and 28 percent of organizations are conducting assessments quarterly, the Workhuman study found.  

A Pervasive Problem

Reviews generally do not work.

That doesn’t mean that more-frequent formal meetings or casual sit-downs between supervisors and their direct reports are solving the performance review quandary, either. Only about 1 in 4 companies in North America (26 percent) said their performance management systems were effective, according to a survey of 837 companies conducted last fall by consulting firm WTW. And only one-third of the organizations said employees felt their efforts were evaluated fairly. 

Meanwhile, a Gallup survey conducted last year found that 95 percent of managers are dissatisfied with their organization’s review system.

The problem is not new, though it is taking on greater importance, experts say. Millennials and members of Generation Z crave feedback and are focused on career development. Meanwhile, the tight labor market has companies searching for ways to keep high-performing employees in the fold. Fewer than 20 percent of employees feel inspired by their reviews, and disengaged employees cost U.S. companies a collective $1.6 trillion a year, according to Gallup.

Lesli Jennings, a senior director at WTW, says part of the issue is that reviews are now so much more than a discussion of past performance. They include conversations about career development, employee experience and compensation. 

“The performance management design itself is not evolving as quickly as the objectives and the purpose that we have set out for what we want it to do,” Jennings says. 

Screen Shot 2023-03-15 at 84340 AM.png

Poor Review Practices

Some argue that means it’s time to completely scrap annual reviews and stop using scales composed of numbers or adjectives to rate employees. 

“Every single human alive today is a horribly unreliable rater of other human beings,” says Marcus Buckingham, head of people and performance research at the Roseland, N.J.-based ADP Research Institute. He says people bring their own backgrounds and personalities to bear in the reviews in what is called the “idiosyncratic rating effect.” He says the ratings managers bestow on others are more a reflection of themselves than of those they’re reviewing.

Buckingham adds that very few positions have quantifiable outcomes that can be considered a measure of competence, talent or success. It’s possible to tally a salesperson’s results or test someone’s knowledge of a computer program, he says, but he’s baffled by attempts to measure attributes such as “leadership potential.”

“I’m going to rate you on a theoretical construct like ‘strategic thinking’? Everybody knows that’s rubbish,” Buckingham says. He adds that performance reviews that offer rankings give “data that’s just bad” and insists that companies rely on data analytics because they don’t trust their managers’ judgment. But instead of working on improving their managers’ skills, he says, they put data systems in place. 

“Because we don’t educate our managers on how to have some of these conversations, we’ve decided that the solution is to give them really bad ratings systems or really bad categorization systems,” Buckingham says. 

R eviewing the Data

A mong North American employers:

  • More than 9 in 10 (93 percent) cited driving organizational performance as a key objective for performance management, yet less than half (44 percent) said their performance management program is ­meeting that objective.
  • Nearly 3 in 4 (72 percent) said ­supporting the career development of their employees is a primary objective, but only 31 percent said their performance management program was meeting that objective.
  • Less than half (49 percent) agreed that managers at their organization are ­effective at assessing the performance of their direct reports. 
  • Only 1 in 3 indicated that employees feel their performance is evaluated fairly. 
  • Just 1 in 6 (16 percent) reported having altered their performance management approach to align with remote and hybrid work models, which are rapidly becoming more prevalent.

Source: WTW 2022 Performance Reset Survey of 837 organizations worldwide, including 150 North American employers.

Data Lovers

Ratings aren’t likely to disappear anytime soon, however. “Data-driven” has become a rallying cry for companies as they seek to operate more efficiently. Organizations are trying to measure everything from sales to productivity, though such efforts can cause turmoil and hurt some individuals’ careers.

A June 2022 study of nearly 30,000 workers at an unnamed North American retail chain found that women were more likely to receive higher overall ratings than men, though women were ranked lower on “potential.” 

In that study, women were 12 percent more likely to be given the lowest rating for potential, as well as 15 percent and 28 percent less likely to receive the middle and highest potential ratings, respectively, according to the professors who conducted the study, Alan Benson of the University of Minnesota, Danielle Li of MIT and Kelly Shue of Yale. The authors also said women were 14 percent less likely to get promoted than men. “Because potential is not directly observed,” they noted, “these assessments can be highly subjective, leaving room for bias.” 

Screen Shot 2023-03-15 at 85749 AM.png

Birmingham left abruptly one afternoon and did not go in to work the next day, which he says Blizzard interpreted as his resignation. Blizzard did not respond to requests for comment.

Stack ranking became popular in the 1980s after it was embraced by General Electric. Its adoption has waned, though several tech companies continue to use it. Google and Twitter relied on stack ranking to decide who to let go in their recent rounds of layoffs, according to published reports.

Birmingham says that the system can cause anxiety and competition, which can kill team cohesion, and that arbitrary lower ratings adversely affect compensation and promotion potential. These systems can also suggest that a manager is ineffective, he says. “It implies that as managers, we basically have not done our job to hire them and train them appropriately or terminate them if they really aren’t working out.”

Birmingham says he is not opposed to ranking systems but doesn’t think they’re necessary. “I feel like the conversation about how to improve your career, what the expectations are for your job and what it will take to get to the next level are all things you can do without a rating,” he says.

Measurements Matter

Grant Pruitt, president and co-founder of Whitebox Real Estate, does not give any type of rating in his performance reviews, though he believes in using data to track his employees’ performance. “What isn’t measured can’t be managed,” says Pruitt, whose company has about 20 employees in several offices across Texas. 

At the beginning of the year, Whitebox employees set goals with their managers. Discussions are held about what benchmarks are reasonable, and these targets can be changed if there is a meaningful shift in business conditions. Team leaders hold weekly department meetings with their direct reports to discuss what’s happening and track progress. Managers hold quarterly private reviews with individuals to dig deeper into whether they’re meeting their goals and if not, why.

“Was it an achievable goal? Realistic? If it was, then what do we need to do to make sure we don’t miss it the next time?” Pruitt says. Whitebox switched to quarterly reviews about four years ago to address problems earlier and avoid having issues fester, Pruitt adds.

It’s easier to set goals for people in sales than for those in other departments, Pruitt concedes. However, he adds that executives need to brainstorm about targets they can use for other roles. For example, administrative employees can be rated on how quickly and efficiently they handle requests.

Pruitt maintains that the goal system makes it easier to respond when an employee disagrees with their manager about their performance review because there are quantitative measures to examine. The data also helps eliminate any unconscious bias a manager may have and helps ensure that a leader isn’t just giving an employee a good rating because they work out at the same gym or their children go to school together.

“I think that’s really where the numbers and the data are important,” Pruitt says. “The data doesn’t know whose kids play on the same sports team.”

Whitebox employees are also judged on how well they embrace the company’s core values, such as integrity, tenacity and coachability. Some of those values may require more-subjective judgments that can be more important than hitting quantifiable goals. 

Pruitt admits that there were occasions when he looked the other way with a few individuals who were “hitting it out of the park,” even though he believed they lacked integrity. But eventually, he had to let them go and the company lost money.

“They really came back to bite me,” Pruitt says.

Screen Shot 2023-03-15 at 84352 AM.png

Grades Are Good

Diane Dooley, CHRO of Iselin, N.J.-based World Insurance Associates LLC, also believes establishing quantitative methods to gauge employees’ performance is essential. “We are living in a world of data analytics,” she says. The broker’s roughly 2,000 employees are rated on a scale of 1 to 5.

World Insurance has taken numerous steps to remove bias from reviews. For example, last year the company conducted unconscious-bias training to help managers separate personal feelings from performance reviews. And all people managers convene to go over the reviews they’ve conducted. Dooley says that process gives everyone a chance to discuss why an employee was given a certain rank and to question some decisions. “We want to make sure we’re using the same standards,” she explains.

Currently, World Insurance conducts reviews only once a year because it has been on an acquisition binge and there hasn’t been time to institute a more frequent schedule. That will change eventually, says Dooley, who adds that she wants to introduce department grids that show how an employee’s rank compares to others’ on the team. 

“It’s just a tool that helps the department or the division understand where their people are and how we can help them collectively,” says Dooley, who has used the system at other companies. 

Dooley says she isn’t worried about World Insurance holding reviews only annually, because good managers regularly check in with their employees regardless of how frequently reviews are mandated.

Such conversations can easily fall through the cracks, however. “Managers want to manage the employees, but they get so caught up in the company’s KPIs [key performance indicators] and making sure that they’re doing everything that they need to do,” says Jennifer Currence, SHRM-SCP, CEO of WithIn Leadership, a leadership development and coaching firm in Tampa, Fla. “It’s hard to set aside the time.” 

WTW’s Jennings adds that managers sometimes avoid initiating conversations with employees who are not performing well. Such discussions are often difficult, and managers may not feel equipped to conduct them. 

“Having to address underperformers is hard work,” Jennings says. 

Additionally, experts say, coaching managers to engage in such sensitive discourse can be expensive and time-consuming.

Improve Your Performance Reviews

H ere’s how to make the review process more ­palatable for both managers and their direct reports:

  • Don’t limit conversations to once or twice per year. Every team is different, so leaders should decide what schedule is most appropriate for their departments. However, it’s important to deal with any problems as they arise; don’t let them fester.
  • Set performance goals and expectations at the beginning of the year so employees understand their responsibilities. This helps lend objectivity to the process by introducing measurable targets. However, the goals should be adjusted if there are major changes to the business or an employee’s circumstances. 
  • Explain how each employee’s position, as well as each department, fits into the company’s overall ­strategy. This will help employees understand why their job matters and why it’s important.
  • Simplify the process. There’s no need for a ­double-digit number of steps or numerous
  • questions that require long-winded answers. 
  • Consider a 360-degree approach. Input from employees’ colleagues or from other managers can help give a fuller picture of employees’ capabilities and contributions.
  • Eliminate proximity bias. You may not see some employees as often as others, especially if they work remotely, but that doesn’t mean they’re not working hard. 
  • End recency bias, which is basing a review on an employee’s most recent performance while ignoring earlier efforts. Don’t let recent mistakes overshadow the employee’s other impressive accomplishments.
  • Solicit feedback from employees. Reviews should be a two-way conversation, not a lecture.
  • Train managers to give advice calmly and helpfully. This is especially important when leaders must call out an employee’s subpar performance. 
  • Don’t discuss compensation during reviews. Employees are likely to be so focused on learning about a raise or bonus that they won’t pay much attention to anything else.

Increase Conversations

Finding the right formula for performance reviews is tricky. The company’s size, values, industry and age all play a role. Currence says businesses need to think about the frequency and purpose of these meetings. Some managers may have weekly discussions with their direct reports, but the conversations might center on status updates as opposed to performance. 

“We need to have more regular conversations,” Currence says. “There has to be a happy balance.”

San Jose, Calif.-based software maker Adobe Inc. was a pioneer when it eliminated annual reviews in 2012 after employees said assessments that look backward weren’t useful and managers lamented how time-consuming they were. Instead, Adobe introduced quarterly check-ins and did away with its numerical ratings system, even though the company is “data-driven,” according to Arden Madsen, senior director of talent management.

Screen Shot 2023-03-15 at 85749 AM.png

Adobe’s system has changed over the years as the company grew from about 11,000 employees in 2012 to around 28,000 today. In the beginning, employees were not asked a universal set of questions and the information gathered was not stored in a central place accessible to all. In 2020, Adobe instituted three or four questions that must be asked at each quarterly meeting, one of which is whether the employee has feedback for the manager. Other topics covered depend on the employee, their role and their goals.

Madsen says asking consistent questions and making reviews easily accessible are important, as internal mobility within the company has grown. 

Adobe, like many businesses, separates conversations about performance from discussions about raises and bonuses, even though they’re intertwined. 

“Money is so emotionally charged,” says WithIn Leadership’s Currence. “When we tie performance review conversations with money, we as human beings do not hear anything about performance. We only focus on the money.”    

Theresa Agovino is the workplace editor for SHRM.

Illustrations by Neil Jamieson.

Related Articles

how to do code review java

Rising Demand for Workforce AI Skills Leads to Calls for Upskilling

As artificial intelligence technology continues to develop, the demand for workers with the ability to work alongside and manage AI systems will increase. This means that workers who are not able to adapt and learn these new skills will be left behind in the job market.

A vast majority of U.S. professionals  think students should be prepared to use AI upon entering the workforce.

Employers Want New Grads with AI Experience, Knowledge

A vast majority of U.S. professionals say students entering the workforce should have experience using AI and be prepared to use it in the workplace, and they expect higher education to play a critical role in that preparation.

HR Daily Newsletter

New, trends and analysis, as well as breaking news alerts, to help HR professionals do their jobs better each business day.

Success title

Success caption

  • Newsletters

Google’s Gemini is now in everything. Here’s how you can try it out.

Gmail, Docs, and more will now come with Gemini baked in. But Europeans will have to wait before they can download the app.

  • Will Douglas Heaven archive page

In the biggest mass-market AI launch yet, Google is rolling out Gemini , its family of large language models, across almost all its products, from Android to the iOS Google app to Gmail to Docs and more. You can also now get your hands on Gemini Ultra, the most powerful version of the model, for the first time.  

With this launch, Google is sunsetting Bard , the company's answer to ChatGPT. Bard, which has been powered by a version of Gemini since December, will now be known as Gemini too.  

ChatGPT , released by Microsoft-backed OpenAI just 14 months ago, changed people’s expectations of what computers could do. Google, which has been racing to catch up ever since, unveiled its Gemini family of models in December. They are multimodal large language models that can interact with you via voice, image, and text. Google claimed that its own benchmarking showed that Gemini could outperform OpenAI's multimodal model, GPT-4, on a range of standard tests. But the margins were slim. 

By baking Gemini into its ubiquitous products, Google is hoping to make up lost ground. “Every launch is big, but this one is the biggest yet,” Sissie Hsiao, Google vice president and general manager of Google Assistant and Bard (now Gemini), said in a press conference yesterday. “We think this is one of the most profound ways that we’re going to advance our company’s mission.”

But some will have to wait longer than others to play with Google’s new toys. The company has announced rollouts in the US and East Asia but said nothing about when the Android and iOS apps will come to the UK or the rest of Europe. This may be because the company is waiting for the EU’s new AI Act to be set in stone, says Dragoș Tudorache, a Romanian politician and member of the European Parliament, who was a key negotiator on the law.

“We’re working with local regulators to make sure that we’re abiding by local regime requirements before we can expand,” Hsiao said. “Rest assured, we are absolutely working on it and I hope we’ll be able to announce expansion very, very soon.”

How can you get it? Gemini Pro, Google’s middle-tier model that has been available via Bard since December, will continue to be available for free on the web at gemini.google.com (rather than bard.google.com). But now there is a mobile app as well.

If you have an Android device, you can either download the Gemini app or opt in to an upgrade in Google Assistant. This will let you call up Gemini in the same way that you use Google Assistant: by pressing the power button, swiping from the corner of the screen, or saying “Hey, Google!” iOS users can download the Google app, which will now include Gemini.

Gemini will pop up as an overlay on your screen, where you can ask it questions or give it instructions about whatever’s on your phone at the time, such as summarizing an article or generating a caption for a photo.  

Finally, Google is launching a paid-for service called Gemini Advanced. This comes bundled in a subscription costing $19.99 a month that the company is calling the Google One Premium AI Plan. It combines the perks of the existing Google One Premium Plan, such as 2TB of extra storage, with access to Google's most powerful model, Gemini Ultra, for the first time. This will compete with OpenAI’s paid-for service, ChatGPT Plus, which buys you access to the more powerful GPT-4 (rather than the default GPT-3.5) for $20 a month.

At some point soon (Google didn't say exactly when) this subscription will also unlock Gemini across Google’s Workspace apps like Docs, Sheets, and Slides, where it works as a smart assistant similar to the GPT-4-powered Copilot that Microsoft is trialing in Office 365.

When can you get it? The free Gemini app (powered by Gemini Pro) is available from today in English in the US. Starting next week, you’ll be able to access it across the Asia Pacific region in English and in Japanese and Korean. But there is no word on when the app will come to the UK, countries in the EU, or Switzerland.

Gemini Advanced (the paid-for service that gives access to Gemini Ultra) is available in English in more than 150 countries, including the UK and EU (but not France). Google says it is analyzing local requirements and fine-tuning Gemini for cultural nuance in different countries. But the company promises that more languages and regions are coming.

What can you do with it? Google says it has developed its Gemini products with the help of more than 100 testers and power users. At the press conference yesterday, Google execs outlined a handful of use cases, such as getting Gemini to help write a cover letter for a job application. “This can help you come across as more professional and increase your relevance to recruiters,” said Google’s vice president for product management, Kristina Behr.

Or you could take a picture of your flat tire and ask Gemini how to fix it. A more elaborate example involved Gemini managing a snack rota for the parents of kids on a soccer team. Gemini would come up with a schedule for who should bring snacks and when, help you email other parents, and then field their replies. In future versions, Gemini will be able to draw on data in your Google Drive that could help manage carpooling around game schedules, Behr said.   

But we should expect people to come up with a lot more uses themselves. “I’m really excited to see how people around the world are going to push the envelope on this AI,” Hsaio said.

Is it safe? Google has been working hard to make sure its products are safe to use. But no amount of testing can anticipate all the ways that tech will get used and misused once it is released. In the last few months, Meta saw people use its image-making app to produce pictures of Mickey Mouse with guns and SpongeBob SquarePants flying a jet into two towers. Others used Microsoft’s image-making software to create fake pornographic images of Taylor Swift .

The AI Act aims to mitigate some—but not all—of these problems. For example, it requires the makers of powerful AI like Gemini to build in safeguards, such as watermarking for generated images and steps to avoid reproducing copyrighted material. Google says that all images generated by its products will include its SynthID watermarks. 

Like most companies, Google was knocked onto the back foot when ChatGPT arrived. Microsoft’s partnership with OpenAI has given it a boost over its old rival. But with Gemini, Google has come back strong: this is the slickest packaging of this generation’s tech yet. 

Artificial intelligence

Ai for everything: 10 breakthrough technologies 2024.

Generative AI tools like ChatGPT reached mass adoption in record time, and reset the course of an entire industry.

What’s next for AI in 2024

Our writers look at the four hot trends to watch out for this year

  • Melissa Heikkilä archive page

These six questions will dictate the future of generative AI

Generative AI took the world by storm in 2023. Its future—and ours—will be shaped by what we do next.

OpenAI teases an amazing new generative video model called Sora

The firm is sharing Sora with a small group of safety testers but the rest of us will have to wait to learn more.

Stay connected

Get the latest updates from mit technology review.

Discover special offers, top stories, upcoming events, and more.

Thank you for submitting your email!

It looks like something went wrong.

We’re having trouble saving your preferences. Try refreshing this page and updating them one more time. If you continue to get this message, reach out to us at [email protected] with a list of newsletters you’d like to receive.

IMAGES

  1. Code Reviews in Java Lab

    how to do code review java

  2. Code Review: Java using PostMethod multiple times (3 Solutions!!)

    how to do code review java

  3. Code Review Template

    how to do code review java

  4. Code Review Template

    how to do code review java

  5. Code Review: Java Manual-Reference-Counting (4 Solutions!!)

    how to do code review java

  6. Code Review: Java 2d array nested loops

    how to do code review java

VIDEO

  1. DRY makes your code 500% better · intermediate Java code review

  2. java code conventions: Пустые строки и пробелы, урок 8!

  3. java code conventions: Введение, урок 1!

  4. How to learn java coding easily?

  5. PW Java course review

  6. ⬅️ program java codes 😎📒📒📒📔📔

COMMENTS

  1. Java Code Review: Best Practices Guide

    Introduction Code reviews are an essential part of the software development process, especially in Java, a language known for its resilience and cross-platform capabilities. Effective code...

  2. Guidelines for Java code reviews

    Guidelines for Java code reviews Having another pair of eyes scan your code is always useful and helps you spot mistakes before you break production. You need not be an expert to review someone's code. Some experience with the programming language and a review checklist should help you get started.

  3. How to Make Good Code Reviews Better

    Good code reviews ask open-ended questions instead of making strong or opinionated statements. They offer alternatives and possible workarounds that might work better for the situation without insisting those solutions are the best or only way to proceed.

  4. Java Code Review Checklist

    1 1 * Reference: http://techbus.safaribooksonline.com/book/programming/java/9780137150021 Static Code Analysis code style Java (programming language) Opinions expressed by DZone...

  5. How to Become Better Java Code Reviewer

    Follow Published in Javarevisited · 5 min read · Apr 10, 2021 -- Photo by Thirdman from Pexels Code review impacts software quality.³ Participation in code reviews reduces the risk of...

  6. How to do a code review

    eng-practices How to do a code review The pages in this section contain recommendations on the best way to do code reviews, based on long experience. All together they represent one complete document, broken up into many separate sections.

  7. Guidelines for Java Code Reviews

    1. Follow Java Code Conventions. Following language conventions helps quickly skim through the code and make sense of it, thereby improving readability. For instance, all package names in Java are ...

  8. Code Review Checklist for Java Beginners

    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.

  9. Top Best Practices for Code Review in Java: Tips and Examples

    Below are some best practices for code review in Java: Follow coding standards: Make sure that the code follows the project's coding standards, such as naming conventions and formatting...

  10. Top 7 Java code review tools 2023

    5. SonarLint. SonarLint is another free open source Java code review tool that checks the code against standards to evaluate the code quality. This analyzer is adept at locating security vulnerabilities and provides reports to show duplicate code, complexity, and comparison with code standards.

  11. Code review checklist: how to tackle issues with Java concurrency

    2. Documentation. 2.1. For every class, method, and field that has signs of being thread-safe, such as the synchronized keyword, volatile modifiers on fields, use of any classes from java.util.concurrent.*, or third-party concurrency primitives, or concurrent collections: do their Javadoc comments include.

  12. Java Code Review Checklist

    Review the following: The code logic correctly implements the required functionality. Check input validation and output accuracy. The code should validate input values to avert unexpected behavior, data corruption, etc., and verify the actual output matches the expected outcome.

  13. Guidelines for Java code reviews

    1. Follow Java code conventions Following language conventions helps quickly skim through the code and make sense of it, thereby improving readability. For instance, all package names in Java are written in lowercase, constants in all caps, variable names in CamelCase, etc. Find the complete list of conventions here.

  14. How To Review Someone Else's Code: Tips and Best Practices

    A code review is a collaborative process where other members of your development team look over your code to give you: Critiques Potential improvements A list of outstanding questions In practice, this means that your fellow developers will either add comments within your code or send you a list of questions to answer.

  15. Java Code Review Checklist

    This guide covers some of the most common items to check in a Java code review to ensure your code is reliable and easy to read, maintain and scale. 1. Ensure the code follows standard naming conventions. Meaningful naming conventions help ensure the readability and maintainability of the application. As such, ensure variable, method, and class ...

  16. Code Review Best Practices

    You will learn What is code review? Why do you do code reviews? When should you do a code review? How can you become a good code reviewer? What are the things to look for in a code review? What are the code review best practices? Article Series This is the fifth article in a series of eight articles on Code Quality 1 - Introduction To Code Quality

  17. Code Review Checklist and Best practices in Java

    1) Functional Requirement Does Code meet the functional requirement: first and foremost does code meets all requirements which it should meet, point out if anything has been left out. 2) Side effect on existing code

  18. Introduction {#intro}

    eng-practices A code review is a process where someone other than the author (s) of a piece of code examines that code. At Google, we use code review to maintain the quality of our code and products. This documentation is the canonical description of Google's code review processes and policies. This page is an overview of our code review process.

  19. 8 Proven Code Review Best Practices for Developers

    By organizing code reviews in an efficient way for the whole team, developers can get valuable feedback and quickly improve the quality of their code. 8. Conduct a security code review. Another best practice for code reviews is to conduct a secure code review. While automated tools check the code for spacing or naming errors and compare it with ...

  20. DueCode Blog

    How to do Automated Code Review on Java Andriy Sokolov / 27 October 2021 7 min read Audio Version Of This Article "What's so good about automated reviews? These computerized strategies effortlessly locate the inaccuracies and minor faults, which you might ignore during manual code inspections."

  21. Code Review Tips (How I Review Code as a Staff Software Engineer

    As a staff software engineer that has been in the industry for a while, I've done my fair share of code reviews (probably thousands of reviews at this point)...

  22. Code Reviews in Java Lab

    From the Teacher Dashboard, find your CSA section row and select the number listed under the 'Students' column: Select Manage Code Review Groups. Turn on the Enable Code Review toggle. Note that the code review option will disable automatically after a period of time, and you will need to return to this page to turn it back on

  23. How To Do Code Reviews

    Which means we have to do a code review. How should you do such review? What is or isn't im... A user sent in a GitHub pull request for our Google Photos clone. Which means we have to do a code ...

  24. GitHub Copilot overview

    Have you started working on a new code base, then try entering /explain to let Copilot help you understand the code. Depending on your question, Copilot Chat might return source code in a code block. Hovering over the code block presents options to Copy and Insert at Cursor (⌃Enter (Windows, Linux Ctrl+Enter)).

  25. The Performance Review Problem

    Data Lovers. Ratings aren't likely to disappear anytime soon, however. "Data-driven" has become a rallying cry for companies as they seek to operate more efficiently.

  26. Spring AOP: Log Requests and Responses with Annotations

    It combines the aspect code with the application code to create a woven class. Introduction: Introduction allows adding new methods or attributes to existing classes, enhancing the capabilities of a class without modifying its source code. AspectJ: AspectJ is a widely used extension of Java that supports AOP. It provides a rich set of features ...

  27. Navigating NoSQL: Choose the Right Database for Your Needs

    JCGs serve the Java, SOA, Agile and Telecom communities with daily news written by domain experts, articles, tutorials, reviews, announcements, code snippets and open source projects. Disclaimer. All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners. Java is a trademark or registered ...

  28. Google's Gemini is now in everything. Here's how you can try it out

    Gmail, Docs, and more will now come with Gemini baked in. But Europeans will have to wait before they can download the app. In the biggest mass-market AI launch yet, Google is rolling out Gemini ...