Guidelines for Java Code Reviews
Get a jump-start on your next code review session with this list.
Join the DZone community and get the full member experience.Join For Free
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
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
Alternatively, you could also use annotations such as
@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
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
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.
LinkedHashMapare all implementations of the
List: Very commonly used to create an ordered list of items. This list may contain duplicates.
ArrayListis an implementation of the
Listinterface. A list can be made thread-safe using
Collections.synchronizedListthus removing the need for using
Vector. Here’s some more info on why
Vectoris essentially obsolete.
Set: Similar to list but does not allow duplicates.
7. Think Twice Before You Expose
There are quite a few access modifiers to choose from in Java —
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.
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
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
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
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.