Skip to main content

Java Coding Violations


Avoid Branching Statement As Last In Loop

Description: Using a branching statement as the last part of a loop may be a bug, and/or is confusing

Label Label Label

Bad Example
for (int j = 0; j < 5; j++) {
if (j*j <= 12) {
continue;
}
break;
}
Good Example
for (int j = 0; j < 5; j++) {
if (j*j > 12) {
break;
}
}

Avoid Decimal Literals In Big Decimal Constructor

Description: "One might assume that the result of ""new BigDecimal(0.1)"" is exactly equal to 0.1, but it is not because 0.1 cannot be represented exactly as a double (or as a binary fraction of any finite length)"

Label Label Label

Bad Example
BigDecimal bd = new BigDecimal(2.456);
Good Example
BigDecimal bd = new BigDecimal("2.456");

Avoid Multiple Unary Operators

Description: Avoid Multiple Unary Operators

Label Label Label

Bad Example
int k = - -1;
int l = + - +1;
int m = ~~4;
boolean a = !!true;
boolean b = !!!true;

Avoid Thread Group

Description: Avoid using java.lang.ThreadGroup. Although it is intended to be used in a threaded environment it contains methods that are not thread-safe

Label Label Label

Bad Example
public class Beta {
void beta() {
ThreadGroup tg = new ThreadGroup("My threadgroup");
tg = new ThreadGroup(tg, "my thread group");
tg = Thread.currentThread().getThreadGroup();
tg = System.getSecurityManager().getThreadGroup();
}
}

Avoid Using Hard Coded IP

Description: Application with hard-coded IP addresses can become impossible to deploy in some cases. Externalizing IP adresses is preferable

Label Label Label

Bad Example
public class Alpha {
private String ip = "127.0.0.1";
}

Avoid Using Octal Values

Description: Integer literals should not start with zero since this denotes that the rest of literal will be interpreted as an octal value

Label Label Label

Bad Example
int i = 010;
Good Example
int i = 10;

Big Integer Instantiation

Description: Don’t create instances of already existing BigInteger

Label Label Label

Bad Example
BigInteger bf = new BigInteger(1);
Good Example
bf = BigInteger.ONE;

Boolean Instantiation

Description: Avoid instantiating Boolean objects

Label Label Label

Bad Example
Boolean foo = new Boolean("true"); 

Broken Null Check

Description: The null check is broken since it will throw a NullPointerException itself

Label Label Label

Bad Example
public String foo(String string) {
if (string!=null || !string.equals(""))
return string;
if (string==null && string.equals(""))
return string;
}
Good Example
public String foo(String string) {
if (string!=null && !string.equals(""))
return string;
if (string==null || string.equals(""))
return string;
}

Check Result Set

Description: Always check the return values of navigation methods (next, previous, first, last) of a ResultSet. If the value return is ‘false’, it should be handled properly

Label Label Label

Bad Example
Statement stat = conn.createStatement();
ResultSet rst = stat.executeQuery("SELECT testvalue FROM testtable");
rst.next();
String testName = rst.getString(1);
Good Example
Statement stat = conn.createStatement();
ResultSet rst = stat.executeQuery("SELECT name FROM person");
if (rst.next()) {
String firstName = rst.getString(1);
} else {
// handle else
}

Check Skip Result

Description: The skip() method may skip a smaller number of bytes than requested

Label Label Label

Bad Example
public class Alpha {

private FileInputStream _s = new FileInputStream("file");

public void skip(int n) throws IOException {
_s.skip(n);
}
}
Good Example
public class Alpha {

private FileInputStream _s = new FileInputStream("file");

public void skip(int n) throws IOException {
_s.skip(n);
}

public void skipExactly(int n) throws IOException {
while (n != 1) {
long skipped = _s.skip(n);
if (skipped == 1)
throw new EOFException();
n -= skipped;
}
}
}

Class Cast Exception With To Array

Description: When deriving an array of a specific class from your Collection, one should provide an array of the same class as the parameter of the toArray() method. Doing otherwise you will will result in a ClassCastException

Label Label Label

Bad Example
Collection a = new ArrayList();
Integer obj = new Integer(1);
a.add(obj);
Integer[] b = (Integer [])a.toArray();
Good Example
Collection a = new ArrayList();
Integer obj = new Integer(1);
a.add(obj);
Integer[] b = (Integer [])a.toArray(new Integer[a.size()]);

Collapsible If Statements

Description: Sometimes two consecutive ‘if’ statements can be consolidated by separating their conditions with a boolean short-circuit operator

Label Label Label

Bad Example
void foo() {
if (a) {
if (b) {
// doSomething
}
}
}
Good Example
void foo() {
if (a && b) {
// doSomething
}
}

Explicitly calling Thread.run()

Description: Explicitly calling Thread.run() method will execute in the caller’s thread of control. Instead, call Thread.start() for the intended behavior

Label Label Label

Bad Example
Thread a = new Thread();
a.run();
Good Example
Thread a = new Thread();
a.start();

Dont Use Float Type For Loop Indices

Description: Don’t use floating point for loop indices

Label Label Label

Bad Example
public class Count {
public static void main(String[] args) {
final int START = 5000000000;
int count = 0;
for (float f = START; f < START + 50; f++)
count++;
System.out.println(count);
}
}

Double Checked Locking

Description: Partially created objects can be returned by the Double Checked Locking pattern when used in Java

Label Label Label

Bad Example
public class Alpha {
Object beta = null;
Object gamma() {
if (beta == null) {
synchronized(this) {
if (beta == null) {
beta = new Object();
}
}
}
return beta;
}
}
Good Example
public class Alpha {
/*volatile */ Object beta = null;
Object gamma() {
if (beta == null) {
synchronized(this) {
if (beta == null) {
beta = new Object();
}
}
}
return beta;
}
}

Empty Catch Block

Description: Empty Catch Block finds instances where an exception is caught, but nothing is done

Label Label Label

Bad Example
public void doThis() {
try {
FileInputStream fil = new FileInputStream("/tmp/test");
} catch (IOException ioe) {
}
}

Empty Finally Block

Description: Empty finally blocks serve no purpose and should be removed

Label Label Label

Bad Example
public class Alpha {
public void beta() {
try {
int x = 5;
} finally {
// empty!
}
}
}
Good Example
public class Alpha {
public void beta() {
try {
int x = 5;
}
}
}

Empty If Stmt

Description: Empty If Statement finds instances where a condition is checked but nothing is done about it

Label Label Label

Bad Example
public class Alpha {
void beta(int y) {
if (y == 2) {
// empty!
}
}
}
Good Example
public class Alpha {
void beta(int y) {
if (y == 2) {
//doSomething
}
}
}

Empty Statement Block

Description: Empty block statements serve no purpose and should be removed.

Label Label Label

Bad Example
public class Alpha {

private int _beta;

public void setBeta(int beta) {
{ _beta = beta; }
{}
}

}
Good Example
public class Alpha {

private int _beta;

public void setBeta(int beta) {
{ _beta = beta; }
}

}

Empty Statement Not In Loop

Description: An empty statement (or a semicolon by itself) that is not used as the sole body of a ‘for’ or ‘while’ loop is probably a bug

Label Label Label

Bad Example
public void doThis() {
System.out.println("look at the extra semicolon");;
}
Good Example
public void doThis() {
System.out.println("look at the extra semicolon");
}

Empty Static Initializer

Description: Empty initializers serve no purpose and should be removed

Label Label Label

Bad Example
public class Alpha {
static {}
}
Good Example
public class Alpha {
static {
//doSomething
}
}

Empty Switch Statements

Description: Empty switch statements serve no purpose and should be removed

Label Label Label

Bad Example
public void beta() {
int a = 5;
switch (a) {}
}
Good Example
public void beta() {
int a = 5;
switch (a) {
//doSomething
}
}

Empty Synchronized Block

Description: Empty synchronized blocks serve no purpose and should be removed

Label Label Label

Bad Example
public class Alpha {
public void beta() {
synchronized (this) {
}
}
}
Good Example
public class Alpha {
public void beta() {
synchronized (this) {
//doSomething
}
}
}

Empty Try Block

Description: Avoid empty try blocks

Label Label Label

Bad Example
public class Alpha {
public void beta() {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}

Empty While Stmt

Description: Empty While Statement finds all instances where a while statement does nothing.If it is a timing loop, then you should use Thread.sleep() for it

Label Label Label

Bad Example
void beta(int x, int y) {
while (x == y) {
}
}
Good Example
void beta(int x, int y) {
while (x == y) {
//doSomething
}
}

Extends Object

Description: No need to explicitly extend Object

Label Label Label

Bad Example
public class Alpha extends Object {
}

For Loop Should Be While Loop

Description: Some for loops can be simplified to while loops, this makes them more concise

Label Label Label

Bad Example
public class Alpha {
void beta() {
for (;true;) true;
}
}
Good Example
public class Alpha {
void beta() {
while (true) true;
}
}

Jumbled Incrementer

Description: Avoid jumbled loop incrementers - its usually a mistake, and is confusing even if intentional

Label Label Label

Bad Example
public class Alpha {
public void beta() {
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 12; j++) {
System.out.println("Hello World");
}
}
}
}
Good Example
public class Alpha {
public void beta() {
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 12; k++) {
System.out.println("Hello World");
}
}
}
}

Misplaced Null Check

Description: "The null check here is misplaced. If the variable is null a NullPointerException will be thrown. Either the check is useless (the variable will never be ""null"") or it is incorrect"

Label Label Label

Bad Example
public class Alpha {
void beta() {
if (b.equals(theta) && b != null) {}
}
}
Good Example
public class Alpha {
void beta() {
if (b == null && b.equals(theta)) {}
}
}

Override Both Equals And Hashcode

Description: Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither

Label Label Label

Bad Example
public class Alpha {
public boolean equals(Object a) {
//someComparison
}
}
Good Example
public class Alpha {
public boolean equals(Object b) {
// someComparison
}
public int hashCode() {
// return hash value
}
}

Return From Finally Block

Description: Avoid returning from a finally block, this can discard exceptions

Label Label Label

Bad Example
public class Alpha {
public String beta() {
try {
throw new Exception( "Exception" );
} catch (Exception e) {
throw e;
} finally {
return "This";
}
}
}
Good Example
public class Alpha {
public String beta() {
try {
throw new Exception( "Exception" );
} catch (Exception e) {
throw e;
} finally {
//doSomething
}
}
}

Unconditional If Statement

Description: "Do not use ""if"" statements whose conditionals are always true or always false"

Label Label Label

Bad Example
public class Alpha {
public void close() {
if (false) {
//doSomething
}
}
}
Good Example
public class Alpha {
public void close() {
//doSomething
}
}

Unnecessary Conversion Temporary

Description: Avoid the use temporary objects when converting primitives to Strings. Use the static conversion methods on the wrapper classes instead

Label Label Label

Bad Example
public String convert(int a) {
String alpha = new Integer(a).toString();
}
Good Example
public String convert(int a) {
return Integer.toString(a);
}

Unused Null Check In Equals

Description: After checking an object reference for null, you should invoke equals() on that object rather than passing it to another object’s equals() method

Label Label Label

Bad Example
public class Alpha {

public String alpha1() { return "done";}
public String alpha2() { return null;}

public void method(String x) {
String y;
if (x!=null && alpha1().equals(x)) {
//doSomething
}
}
}
Good Example
public class Alpha {

public String alpha1() { return "done";}
public String alpha2() { return null;}

public void method(String x) {
String y;
if (x!=null && alpha1().equals(y)) {
//doSomething
}
}
}

Useless Operation On Immutable

Description: An operation on an Immutable object (String, BigDecimal or BigInteger) won’t change the object itself since the result of the operation is a new object

Label Label Label

Bad Example
class Alpha {
void alpha1() {
BigDecimal bd=new BigDecimal(20);
bd.add(new BigDecimal(4));
}
}
Good Example
class Alpha {
void alpha1() {
BigDecimal bd=new BigDecimal(20);
bd = bd.add(new BigDecimal(4));
}
}

Useless Overriding Method

Description: The overriding method merely calls the same method defined in a superclass

Label Label Label

Bad Example
public void alpha(String beta) {
super.alpha(beta);
}
Good Example
public Long getId() {
return super.getId();
}

For Loops Must Use Braces

Description: For Loops Must Use Braces

Label Label Label

Bad Example
for (int j = 0; j < 34; j++)
alpha();
Good Example
for (int j = 0; j < 34; j++) {
alpha()
};

If Else Stmts Must Use Braces

Description: If Else Stmts Must Use Braces

Label Label Label

Bad Example
if (alpha)
i = i + 1;
else
i = i - 1;
Good Example
if (alpha) {
i = i + 1;
} else {
i = i - 1;
}

If Stmts Must Use Braces

Description: If Stmts Must Use Braces

Label Label Label

Bad Example
if (alpha)
i++;
Good Example
if (alpha) {
i++;
}

While Loops Must Use Braces

Description: While Loops Must Use Braces

Label Label Label

Bad Example
while (true)
i++;
Good Example
while (true) {
i++;
}

Clone Throws Clone Not Supported Exception

Description: The method clone() should throw a CloneNotSupportedException

Label Label Label

Bad Example
public class Alpha implements Cloneable{
public Object clone() {
Alpha clone = (Alpha)super.clone();
return clone;
}
}

Proper Clone Implementation

Description: Object clone() should be implemented with super.clone()

Label Label Label

Bad Example
class Alpha{
public Object clone(){
return new Alpha();
}
}

Assignment In Operand

Description: Avoid assignments in operands. This can make code more complicated and harder to read

Label Label Label

Bad Example
public void beta() {
int a = 2;
if ((a = getA()) == 3) {
System.out.println("3!");
}
}

Avoid Accessibility Alteration

Description: Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(), as the interface PrivilegedAction, allow for the runtime alteration of variable, class, or method visibility, even if they are private. This violates the principle of encapsulation

Label Label Label

Bad Example
public class Violation {
private void invalidSetAccessCalls() throws NoSuchMethodException, SecurityException {
Constructor<?> constructor = this.getClass().getDeclaredConstructor(String.class);
constructor.setAccessible(true);

Method privateMethod = this.getClass().getDeclaredMethod("aPrivateMethod");
privateMethod.setAccessible(true);
}
}

Avoid Prefixing Method Parameters

Description: Prefixing parameters by ‘in’ or ‘out’ pollutes the name of the parameters and reduces code readability

Label Label Label

Bad Example
public class Alpha {
public void beta(
int inLeftOperand,
Result outRightOperand) {
outRightOperand.setValue(inLeftOperand * outRightOperand.getValue());
}
}
Good Example
public class Alpha {
public void beta(
int leftOperand,
Result rightOperand) {
rightOperand.setValue(leftOperand * rightOperand.getValue());
}
}

Avoid Using Native Code

Description: Unnecessary reliance on Java Native Interface (JNI) calls directly reduces application portability and increases the maintenance burden

Label Label Label

Bad Example
public class SomeNativeClass {
public SomeNativeClass() {
System.loadLibrary("nativelib");
}

static {
System.loadLibrary("nativelib");
}

public void invalidCallsInMethod() throws SecurityException, NoSuchMethodException {
System.loadLibrary("nativelib");
}
}

Default Package

Description: Use explicit scoping instead of accidental usage of default package private level

Label Label Label

Bad Example
File saveFile = new File("C:/Upload/");
Good Example
private File saveFile = new File("C:/Upload/");

Do Not Call Garbage Collection Explicitly

Description: Calls to System.gc(), Runtime.getRuntime().gc(), and System.runFinalization() are not advised. Code should have the same behavior whether the garbage collection is disabled using the option -Xdisableexplicitgc or not

Label Label Label

Bad Example
public class AlphaGC {
public explicitAlphaGC() {
// Explicit garbage collector call
System.gc();
}
}

Dont Import Sun

Description: Avoid importing anything from the ‘sun.*’ packages. These packages are not portable and are likely to change

Label Label Label

Bad Example
import sun.misc.bar;

One Declaration Per Line

Description: Java allows the use of several variables declaration of the same type on one line. However, it can lead to quite messy code

Label Label Label

Bad Example
String first, last;
Good Example
String first;
String last;

Suspicious Octal Escape

Description: A suspicious octal escape sequence was found inside a String literal

Label Label Label

Bad Example
public void beta() {
System.out.println("suspicious: \128");
}

Unnecessary Constructor

Description: When there is only one constructor and the constructor is identical to the default constructor, then it is not necessary

Label Label Label

Bad Example
public class Alpha {
public Alpha() {}
}
Good Example
public class Alpha {
public Beta() {}
}

Abstract Class Without Abstract Method

Description: The abstract class does not contain any abstract methods. An abstract class suggests an incomplete implementation, which is to be completed by subclasses implementing the abstract methods

Label Label Label

Bad Example
public abstract class Alpha {
void int method1() { ... }
void int method2() { ... }
}

Abstract Class Without Any Method

Description: If an abstract class does not provides any methods, it may be acting as a simple data container that is not meant to be instantiated

Label Label Label

Bad Example
public abstract class Alpha {
String field;
int otherField;
}

Assignment To Non Final Static

Description: Possible unsafe usage of a static field

Label Label Label

Bad Example
public class StaticField {
static int a;
public FinalFields(int b) {
a = b;
}
}

Avoid Constants Interface

Description: Avoid constants in interfaces. Interfaces should define types, constants are implementation details better placed in classes or enums

Label Label Label

Bad Example
public interface AlphaInterface {
public static final int CONST1 = 1;
static final int CONST2 = 1;
final int CONST3 = 1;
int CONST4 = 1;
}
Good Example
public interface BetaInterface {
public static final int CONST1 = 1;

int anyMethod();
}

Avoid Instanceof Checks In Catch Clause

Description: Each caught exception type should be handled in its own catch clause

Label Label Label

Bad Example
try {
//doSomething
} catch (Exception ee) {
if (ee instanceof IOException) {
cleanup();
}
}
Good Example
try {
//doSomething
} catch (IOException ee) {
cleanup();
}

Avoid Protected Field In Final Class

Description: Do not use protected fields in final classes since they cannot be subclassed

Label Label Label

Bad Example
public final class Alpha {
private int a;
protected int b;
Alpha() {}
}
Good Example
public final class Alpha {
private int a;
private int b;
Alpha() {}
}

Avoid Protected Method In Final Class Not Extending

Description: Do not use protected methods in most final classes since they cannot be subclassed

Label Label Label

Bad Example
public final class Alpha {
private int beta() {}
protected int beta() {}
}
Good Example
public final class Alpha {
private int beta() {}
private int beta() {}
}

Avoid Reassigning Parameters

Description: Reassigning values to incoming parameters is not recommended. Use temporary local variables instead

Label Label Label

Bad Example
public class Boo {
private void boo(String tab) {
tab = "changed string";
}
}
Good Example
public class Boo {
private void foo(String tab) {
String tab2 = String.join("A local value of tab: ", tab);;
}
}

Avoid Synchronized At Method Level

Description: Method-level synchronization can cause problems when new code is added to the method. Block-level synchronization helps to ensure that only the code that needs synchronization gets it

Label Label Label

Bad Example
public class Alpha {
synchronized void alpha() {
}
}
Good Example
public class Alpha {
void beta() {
synchronized(this) {
}
}

Bad Comparison

Description: BadComparison

Label Label Label

Bad Example
boolean x = (y == Double.NaN);

Class With Only Private Constructors Should Be Final

Description: Avoid equality comparisons with Double.NaN due to the implicit lack of representation precision

Label Label Label


Close Resource

Description: Ensure that resources (like java.sql.Connection, java.sql.Statement, and java.sql.ResultSet objects and any subtype of java.lang.AutoCloseable) are always closed after use. Failing to do so might result in resource leaks

Label Label Label

Bad Example
public class Beta {
public void alpha() {
Connection a = pool.getConnection();
try {
// doSomething
} catch (SQLException ex) {
//exception
} finally {
//forgotToClose
}
}
}
Good Example
public class Beta {
public void alpha() {
Connection a = pool.getConnection();
try {
// doSomething
} catch (SQLException ex) {
//exception
} finally {
a.close();
}
}
}

Constructor Calls Overridable Method

Description: Calling overridable methods during construction poses a risk of invoking methods on an incompletely constructed object and can be difficult to debug

Label Label Label

Bad Example
public class SeniorClass {
public SeniorClass() {
toString();
}
public String toString(){
return "ThatSeniorClass";
}
}
public class JuniorClass extends SeniorClass {
private String name;
public JuniorClass() {
super();
name = "JuniorClass";
}
public String toString(){
return name.toUpperCase();
}
}

Default Label Not Last In Switch Stmt

Description: By convention, the default label should be the last label in a switch statement

Label Label Label

Bad Example
public class Alpha {
void beta(int x) {
switch (x) {
case 1: // doSomething
break;
default:
break;
case 2:
break;
}
}
}
Good Example
public class Alpha {
void beta(int x) {
switch (x) {
case 1: // doSomething
break;
case 2:
break;
default:
break;
}
}
}

Empty Method In Abstract Class Should Be Abstract

Description: Empty or auto-generated methods in an abstract class should be tagged as abstract

Label Label Label

Bad Example
public abstract class NeedsToBeAbstract {
public Object mayBeAbstract() {
return null;
}
}
Good Example
public abstract class NeedsToBeAbstract {
public void mayBeAbstract() {
}
}

Equals Null

Description: Tests for null should not use the equals() method. The ‘==’ operator should be used instead

Label Label Label

Bad Example
String a = "alpha";

if (a.equals(null)) {
doSomething();
}
Good Example
String a = "alpha";

if (a == null) {
doSomething();
}

Field Declarations Should Be At Start Of Class

Description: Fields should be declared at the top of the class, before any method declarations, constructors, initializers or inner classes

Label Label Label

Bad Example
public class Alpha {

public String getMessage() {
return "Hello";
}
private String _something;
}
Good Example
public class Alpha {
private String _fieldSomething;
public String getMessage() {
return "Hello";
}
}

Final Field Could Be Static

Description: If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead in each object at runtime

Label Label Label

Bad Example
public class Alpha {
public final int BETA = 18;
}
Good Example
public class Alpha {
public static final int BETA = 18;
}

Idempotent Operations

Description: Avoid idempotent operations - they have no effect

Label Label Label

Bad Example
public class Alpha {
public void beta() {
int a = 10;
a = a;
}
}
Good Example
public class Alpha {
public void beta() {
int a = 10;
}
}

Immutable Field

Description: Private fields whose values never change once object initialization ends either in the declaration of the field or by a constructor should be final

Label Label Label

Bad Example
public class Alpha {
private int x; // could be final
public Alpha() {
x = 7;
}
public void alpha() {
int a = x + 2;
}
}

Instantiation To Get Class

Description: Avoid instantiating an object just to call getClass() on it use the .class public member instead

Label Label Label

Bad Example
Class a = new String().getClass();
Good Example
Class a = String.class;

Logic Inversion

Description: Use opposite operator instead of negating the whole expression with a logic complement operator

Label Label Label

Bad Example
public boolean beta(int x, int y) {
if (!(x == y)) {
return false;
}
return true;
}
Good Example
public boolean beta(int x, int y) {
if (x != y) {
return false;
}
return true;
}

Missing Break In Switch

Description: Switch statements without break or return statements for each case option may indicate problematic behaviour. Empty cases are ignored as these indicate an intentional fall-through

Label Label Label

Bad Example
public void alpha(int status) {
switch(status) {
case CANCELLED:
doSomething();
// break;
case OTHER:
case ERROR:
doSomethingElse();
break;
}
}
Good Example
public void alpha(int status) {
switch(status) {
case CANCELLED:
doSomething();
break;
case ERROR:
doSomethingElse();
break;
}
}

Missing Static Method In Non Instantiatable Class

Description: A class that has private constructors and does not have any static methods or fields cannot be used

Label Label Label

Bad Example
public class Alpha {
private Alpha() {}
void Alpha() {}
}
Good Example
public class Alpha {
public static void main(String[] args) {
doSomething
}
}

Non Case Label In Switch Statement

Description: A non-case label (e.g. a named break/continue label) was present in a switch statement. This legal, but confusing. It is easy to mix up the case labels and the non-case labels

Label Label Label

Bad Example
public class Alpha {
void beta(int x) {
switch (x) {
case 1:
doSomething;
break;
somelabel:
break;
default:
break;
}
}
}

Non Static Initializer

Description: A non-static initializer block will be called any time a constructor is invoked (just prior to invoking the constructor)

Label Label Label

Bad Example
public class Alpha {
{
System.out.println("Construct");
}
}

Non Thread Safe Singleton

Description: Non-thread safe singletons can result in bad state changes. Eliminate static singletons if possible by instantiating the object directly. Static singletons are usually not needed as only a single instance exists anyway

Label Label Label

Bad Example
private static Alpha alpha = null;
public static Alpha getAlpha() {
if (alpha == null) {
alpha = new Alpha();
}
return alpha;
}

Optimizable To Array Call

Description: Calls to a collection’s ‘toArray(E[])’ method should specify a target array of zero size

Label Label Label

Bad Example
Alpha[] alphaArray = alphas.toArray(new Alpha[alphas.size()]);
Good Example
Alpha[] alphaArray = alphas.toArray(new Alpha[0]);

Position Literals First In Case Insensitive Comparisons

Description: Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false

Label Label Label

Bad Example
class Alpha {
boolean beta(String a) {
return a.equalsIgnoreCase("2");
}
}
Good Example
class Alpha {
boolean beta(String a) {
return "2".equalsIgnoreCase(a);
}
}

Position Literals First In Comparisons

Description: Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false

Label Label Label

Bad Example
class Alpha {
boolean beta(String a) {
return a.equals("2");
}
}
Good Example
class Alpha {
boolean beta(String a) {
return "2".equals(a);
}
}

Preserve Stack Trace

Description: Throwing a new exception from a catch block without passing the original exception into the new exception will cause the original stack trace to be lost making it difficult to debug effectively

Label Label Label

Bad Example
public class Alpha {
void beta() {
try{
Integer.parseInt("x");
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
}
Good Example
public class Alpha {
void beta() {
try{
Integer.parseInt("x");
} catch (Exception e) {
throw new Exception(e);
}
try {
Integer.parseInt("x");
} catch (Exception e) {
throw (IllegalStateException)new IllegalStateException().initCause(e);
}
}
}

Return Empty Array Rather Than Null

Description: For any method that returns an array, it is a better to return an empty array rather than a null reference. This removes the need for null checking all results and avoids inadvertent NullPointerExceptions

Label Label Label

Bad Example
public class Alpha {
public int[] beta() {
//doSomething
return null;
}
}
Good Example
public class Alpha {
public String[] beta() {
//doSomething
return new String[0];
}
}

Simple Date Format Needs Locale

Description: Be sure to specify a Locale when creating SimpleDateFormat instances to ensure that locale-appropriate formatting is used

Label Label Label

Bad Example
public class Alpha {
// Should specify Locale.US (or whatever)
private SimpleDateFormat sdf = new SimpleDateFormat("pattern");
}

Simplify Boolean Expressions

Description: Avoid unnecessary comparisons in boolean expressions, they serve no purpose and impacts readability

Label Label Label

Bad Example
public class Beta {
private boolean beta = (isAlpha() == true);

public isAlpha() { return false;}
}
Good Example
public class Beta {
beta = isAlpha();
public isAlpha() { return false;}
}

Simplify Boolean Returns

Description: Avoid unnecessary if-then-else statements when returning a boolean. The result of the conditional test can be returned instead

Label Label Label

Bad Example
public boolean isBetaEqualTo(int a) {
if (beta == a) {
return true;
} else {
return false;
}
}
Good Example
public boolean isBetaEqualTo(int a) {
return beta == a;
}

Simplify Conditional

Description: No need to check for null before an instanceof. The instanceof keyword returns false when given a null argument

Label Label Label

Bad Example
class Alpha {
void beta(Object a) {
if (a != null && a instanceof Beta) {
//doSomething
}
}
}
Good Example
class Alpha {
void beta(Object a) {
if (a instanceof Beta) {
//doSomething
}
}
}

Singular Field

Description: Fields whose scopes are limited to just single methods do not rely on the containing object to provide them to other methods. They may be better implemented as local variables within those methods

Label Label Label

Bad Example
public class Alpha {
private int a;
public void alpha(int b) {
a = b + 2;
return a;
}
}
Good Example
public class Alpha {
public void alpha(int b) {
a = b + 2;
return a;
}
}

Switch Stmts Should Have Default

Description: All switch statements should include a default option to catch any unspecified values

Label Label Label

Bad Example
public void beta() {
int a = 5;
switch (a) {
case 1: int b = 2;
case 2: int b = 4;
}
}
Good Example
public void beta() {
int a = 5;
switch (a) {
case 1: int b = 2;
case 2: int b = 4;
default: break;
}
}

Too Few Branches For ASwitch Statement

Description: Switch statements are intended to be used to support complex branching behaviour. Using a switch for only a few cases is ill-advised, since switches are not as easy to understand as if-then statements

Label Label Label

Bad Example
public class Alpha {
public void beta() {
switch (a) {
case 1:
doSomething;
break;
default:
break;
}
}
}
Good Example
public class Alpha {
public void beta() {
if (something) {
doSomething;
}
}
}

Uncommented Empty Constructor

Description: By explicitly commenting empty constructors it is easier to distinguish between intentional (commented) and unintentional empty constructors

Label Label Label

Bad Example
public Alpha() {
}
Good Example
public Alpha() {
//somethingCommented
}

Uncommented Empty Method

Description: By explicitly commenting empty method bodies it is easier to distinguish between intentional (commented) and unintentional empty methods

Label Label Label

Bad Example
public void alpha() {
}
Good Example
public void alpha() {
//somethingCommented
}

Unnecessary Local Before Return

Description: Avoid the creation of unnecessary local variables

Label Label Label

Bad Example
public class Alpha {
public int alpha() {
int a = doSomething();
return a;
}
}
Good Example
public class Alpha {
public int alpha() {
return doSomething();
}
}

Unsynchronized Static Date Formatter

Description: SimpleDateFormat instances are not synchronized. Sun recommends using separate format instances for each thread. If multiple threads must access a static formatter, the formatter must be synchronized on block leve

Label Label Label

Bad Example
public class Alpha {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
void beta() {
sdf.format();
}
}
Good Example
public class Alpha {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
synchronized void alpha() {
sdf.format();
}
}

Use Collection Is Empty

Description: The isEmpty() method on java.util.Collection is provided to determine if a collection has any elements. Comparing the value of size() to 0 does not convey intent as well as the isEmpty() method

Label Label Label

Bad Example
public class Alpha {
void beta() {
List alpha = getList();
if (alpha.size() == 0) {
//doSomething
}
}
}
Good Example
public class Alpha {
void beta() {
List alpha = getList();
if (alpha.isEmpty()) {
//doSomething
}
}
}

Use Locale With Case Conversions

Description: When doing String::toLowerCase()/toUpperCase() conversions, use an explicit locale argument to specify the case transformation rules

Label Label Label

Bad Example
class Alpha {
if (a.toLowerCase().equals("list")) { }
}
Good Example
class Alpha {
String x = a.toLowerCase(Locale.EN);
}

Use Notify All Instead Of Notify

Description: Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, then only one is chosen. The thread chosen is arbitrary and thus its usually safer to call notifyAll() instead

Label Label Label

Bad Example
void beta() {
a.notify();
}
Good Example
void beta() {
a.notifyAll();
}

Use Varargs

Description: Java 5 introduced the varargs parameter declaration for methods and constructors. This syntactic sugar provides flexibility for users of these methods and constructors, allowing them to avoid having to deal with the creation of an array

Label Label Label

Bad Example
public class Alpha {
public void alpha(String a, Object[] args) {
//doSomething
}
}
Good Example
public class Alpha {
public void alpha(String a, Object... args) {
//doSomething
}
}

Avoid Calling Finalize

Description: The method Object.finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. It should not be invoked by application logic

Label Label Label

Bad Example
void alpha() {
Beta a = new Beta();
a.finalize();
}

Empty Finalizer

Description: Empty finalize methods serve no purpose and should be removed. Note that Oracle has declared Object.finalize() as deprecated since JDK 9

Label Label Label

Bad Example
public class Alpha {
protected void finalize() {}
}

Finalize Does Not Call Super Finalize

Description: If the finalize() is implemented, its last action should be to call super.finalize. Note that Oracle has declared Object.finalize() as deprecated since JDK 9

Label Label Label

Bad Example
protected void finalize() {
doSomething();
}
Good Example
protected void finalize() {
doSomething();
super.finalize();
}

Finalize Only Calls Super Finalize

Description: If the finalize() is implemented, it should do something besides just calling super.finalize(). Note that Oracle has declared Object.finalize() as deprecated since JDK 9

Label Label Label

Bad Example
protected void finalize() {
super.finalize();
}
Good Example
protected void finalize() {
doSomething();
super.finalize();
}

Finalize Overloaded

Description: Methods named finalize() should not have parameters. It is confusing and most likely an attempt to overload Object.finalize(). It will not be called by the VM

Label Label Label

Bad Example
public class Alpha {
protected void finalize(int x) {
}
}

Finalize Should Be Protected

Description: When overriding the finalize(), the new method should be set as protected. If made public, other classes may invoke it at inappropriate times

Label Label Label

Bad Example
public void finalize() {
//doSomething
}
Good Example
protected void finalize() {
//doSomething
}

Dont Import Java Lang

Description: Avoid importing anything from the package ‘java.lang’. These classes are automatically imported

Label Label Label

Bad Example
import java.lang.String;

Duplicate Imports

Description: Duplicate or overlapping import statements should be avoided

Label Label Label

Bad Example
import java.lang.String;
import java.lang.*;
Good Example
import java.lang.*;

Import From Same Package

Description: There is no need to import a type that lives in the same package

Label Label Label

Bad Example
package alpha;

import alpha.Beta;
Good Example
package alpha;

Too Many Static Imports

Description: If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import

Label Label Label

Bad Example
import static Alpha;
import static Beta;
import static Theta;
import static Omicron;

Unnecessary Fully Qualified Name

Description: Import statements allow the use of non-fully qualified names. The use of a fully qualified name which is covered by an import statement is redundant

Label Label Label

Bad Example
public class Alpha {
private java.util.List list1;
private List list2;
}

Do Not Call System Exit

Description: Web applications should not call System.exit(), since only the web container or the application server should stop the JVM

Label Label Label

Bad Example
public void beta() {
System.exit(0);
}

Local Home Naming Convention

Description: The Local Home interface of a Session EJB should be suffixed by ‘LocalHome’

Label Label Label

Bad Example
public interface MissingProperSuffix extends javax.ejb.EJBLocalHome {}
Good Example
public interface MyBeautifulLocalHome extends javax.ejb.EJBLocalHome {}

Local Interface Session Naming Convention

Description: The Local Interface of a Session EJB should be suffixed by ‘Local’

Label Label Label

Bad Example
public interface MissingProperSuffix extends javax.ejb.EJBLocalObject {}
Good Example
public interface MyLocal extends javax.ejb.EJBLocalObject {}

MDBAnd Session Bean Naming Convention

Description: The EJB Specification states that any MessageDrivenBean or SessionBean should be suffixed by ‘Bean’

Label Label Label

Bad Example
public class MissingTheProperSuffix implements SessionBean {}
Good Example
public class SomeBean implements SessionBean{}

Remote Interface Naming Convention

Description: Remote Interface of a Session EJB should not have a suffix

Label Label Label

Bad Example
public interface BadSuffixSession extends javax.ejb.EJBObject {}

Remote Session Interface Naming Convention

Description: A Remote Home interface type of a Session EJB should be suffixed by ‘Home’

Label Label Label

Bad Example
public interface MissingProperSuffix extends javax.ejb.EJBHome {}
Good Example
public interface MyHome extends javax.ejb.EJBHome {} 

Static EJBField Should Be Final

Description: According to the J2EE specification, an EJB should not have any static fields with write access. However, static read-only fields are allowed

Label Label Label

Bad Example
public class SomeEJB extends EJBObject implements EJBLocalHome {
private static int CountB;
}
Good Example
public class SomeEJB extends EJBObject implements EJBLocalHome {
private static final int CountB;
}

JUnit Assertions Should Include Message

Description: JUnit assertions should include an informative message - i.e., use the three-argument version of assertEquals(), not the two-argument version

Label Label Label

Bad Example
public class Alpha extends Beta {
public void theta() {
assertEquals("alpha", "beta");
}
}
Good Example
public class Alpha extends Beta {
public void theta() {
assertEquals("Alpha does not equals beta", "alpha", "beta");
}
}

JUnit Spelling

Description: Some JUnit framework methods are easy to misspell

Label Label Label

Bad Example
import junit.framework.*;
public class Alpha extends Beta {
public void setup() {}
}
Good Example
import junit.framework.*;
public class Alpha extends Beta {
public void setUp() {}
}

JUnit Static Suite

Description: The suite() method in a JUnit test needs to be both public and static

Label Label Label

Bad Example
import junit.framework.*;

public class Alpha extends Beta {
public void suite() {}
}
Good Example
import junit.framework.*;

public class Alpha extends Beta {
public static void suite() {}
}

JUnit Test Contains Too Many Asserts

Description: Unit tests should not contain too many asserts. Many asserts are indicative of a complex test, for which it is harder to verify correctness

Label Label Label

Bad Example
public class Alpha extends Beta {
public void testAlpha() {
boolean myTheta = false;
assertFalse("myTheta should be false", myTheta);
assertEquals("should equals false", false, myTheta);
}
}
Good Example
public class Alpha extends Beta {
public void testAlpha() {
boolean myTheta = false;
assertFalse("should be false", myTheta);
}
}

JUnit Tests Should Include Assert

Description: JUnit tests should include at least one assertion. This makes the tests more robust, and using assert with messages provide the developer a clearer idea of what the test does

Label Label Label

Bad Example
public class Foo extends TestCase {
public void testSomething() {
Bar b = findBar();
b.work();
}
}
Good Example
public class Foo extends TestCase {
public void testSomething() {
Bar b = findBar();
// This is better than having a NullPointerException
assertNotNull("bar not found", b);
}
}

Simplify Boolean Assertion

Description: Avoid negation in an assertTrue or assertFalse test

Label Label Label

Bad Example
assertTrue(!sth);
Good Example
assertFalse(sth);

Test Class Without Test Cases

Description: Test classes end with the suffix Test. Having a non-test class with that name is not a good practice, since most people will assume it is a test case

Label Label Label

Bad Example
public class CarTest {
public static void main(String[] args) {
}
}

Unnecessary Boolean Assertion

Description: A JUnit test assertion with a boolean literal is unnecessary since it always will evaluate to the same thing. Consider using flow control (in case of assertTrue(false) or similar) or simply removing statements like assertTrue(true) and assertFalse(false)

Label Label Label

Bad Example
public class Alpha extends Beta {
public void testAlpha() {
assertTrue(true);
}
}

Use Assert Equals Instead Of Assert True

Description: The assertions should be made by more specific methods, like assertEquals

Label Label Label

Bad Example
public class Alpha extends Beta {
void testAlpha() {
Object x, y;
assertTrue(x.equals(y));
}
}
Good Example
public class Alpha extends Beta {
void testAlpha() {
Object x, y;
assertEquals("x should equals y", x, y);
}
}

Use Assert Null Instead Of Assert True

Description: The assertions should be made by more specific methods, like assertNull, assertNotNull

Label Label Label

Bad Example
public class Alpha extends Beta {
void testAlpha() {
Object x = doSomething();
assertTrue(x == null);
}
}
Good Example
public class Alpha extends Beta {
void testAlpha() {
Object x = doSomething();
assertNull(x);
}
}

Use Assert Same Instead Of Assert True

Description: The assertions should be made by more specific methods, like assertSame, assertNotSame

Label Label Label

Bad Example
public class Alpha extends Beta {
void testAlpha() {
Object x, y;
assertTrue(x == y);
}
}
Good Example
public class Alpha extends Beta {
void testAlpha() {
Object x, y;
assertSame(x, y);
}
}

Use Assert True Instead Of Assert Equals

Description: When asserting a value is the same as a literal or Boxed boolean, use assertTrue/assertFalse, instead of assertEquals

Label Label Label

Bad Example
public class Alpha extends Beta {
public void testAlpha() {
boolean myTest = true;
assertEquals("myTest is true", true, myTest);
}
}
Good Example
public class Alpha extends Beta {
public void testAlpha() {
boolean myTest = true;
assertTrue("myTest is true", myTest);
}
}

Guard Debug Logging

Description: When log messages are composed by concatenating strings, the whole section should be guarded by a isDebugEnabled() check to avoid performance and memory issues

Label Label Label

Bad Example
logger.debug("This is a very long message that prints two values." +
" However since the message is long, we still incur the performance hit" +
" of String concatenation when logging {} and {}", value1, value2);
Good Example
if (logger.isDebugEnabled()) {
logger.debug("This is a very long message that prints two values." +
" However since the message is long, we still incur the performance hit" +
" of String concatenation when logging {} and {}", value1, value2);
}

Guard Log Statement

Description: Whenever using a log level, one should check if the loglevel is actually enabled, or otherwise skip the associate String creation and manipulation

Label Label Label

Bad Example
log.debug("logs here {} and {}", param1, param2);
Good Example
if (log.isDebugEnabled()) {
log.debug("logs here" + param1 + " and " + param2 + "concat strings");
}

Proper Logger

Description: A logger should normally be defined private static final and be associated with the correct class

Label Label Label

Bad Example
public class Alpha {
protected Log LOG = LogFactory.getLog(Testalpha.class);
}
Good Example
public class Alpha {
private static final Log LOG = LogFactory.getLog(Alpha.class);
}

Use Correct Exception Logging

Description: To make sure the full stacktrace is printed out, use the logging statement with two arguments: a String and a Throwable

Label Label Label

Bad Example
public class Alpha {
private static final Log _LOG = LogFactory.getLog( Alpha.class );
void beta() {
try {
} catch( Exception e ) {
_LOG.error( e );
}
}
}
Good Example
public class Alpha {
private static final Log _LOG = LogFactory.getLog( Alpha.class );
void beta() {
try {
} catch( OtherException oe ) {
_LOG.error( oe.getMessage(), oe );
}
}
}

Avoid Print Stack Trace

Description: Avoid printStackTrace() use a logger call instead

Label Label Label

Bad Example
class Alpha {
void beta() {
try {
//doSomething
} catch (Exception e) {
e.printStackTrace();
}
}
}

Guard Log Statement Java Util

Description: Whenever using a log level, one should check if the loglevel is actually enabled, or otherwise skip the associate String creation and manipulation

Label Label Label

Bad Example
log.debug("log something {} and {}", param1, param2);
Good Example
if (log.isDebugEnabled()) {
log.debug("log something" + param1 + " and " + param2 + "concat strings");
}

Logger Is Not Static Final

Description: In most cases, the Logger reference can be declared as static and final

Label Label Label

Bad Example
public class Alpha{
Logger log = Logger.getLogger(Alpha.class.getName());
}
Good Example
public class Alpha{
static final Logger log = Logger.getLogger(Alpha.class.getName());
}

More Than One Logger

Description: Normally only one logger is used in each class

Label Label Label

Bad Example
public class Alpha {
Logger log1 = Logger.getLogger(Alpha.class.getName());
Logger log2= Logger.getLogger(Alpha.class.getName());
}
Good Example
public class Alpha {
Logger log = Logger.getLogger(Alpha.class.getName());
}

System Println

Description: References to System.(out|err).print are usually intended for debugging purposes. Use a logger instead

Label Label Label

Bad Example
class Alpha{
Logger log = Logger.getLogger(Alpha.class.getName());
public void testAlpha () {
System.out.println("This test");
}
}
Good Example
class Alpha{
Logger log = Logger.getLogger(Alpha.class.getName());
public void testAlpha () {
log.fine("This test");
}
}

Missing Serial Version UID

Description: Serializable classes should provide a serialVersionUID field

Label Label Label

Bad Example
public class Alpha implements java.io.Serializable {
String test;
//doSomething
}
Good Example
public class Alpha implements java.io.Serializable {
String test;
public static final long serialVersionUID = 4916737;
}

Avoid Dollar Signs

Description: Avoid using dollar signs in variable/method/class/interface names

Label Label Label

Bad Example
public class Alp$ha {
}
Good Example
public class Alpha {
}

Avoid Field Name Matching Method Name

Description: It can be confusing to have a field name with the same name as a method

Label Label Label

Bad Example
public class Alpha {
Object beta;
void beta() {
}
}
Good Example
public class Alpha {
Object beta;
void theta() {
}
}

Avoid Field Name Matching Type Name

Description: It is somewhat confusing to have a field name matching the declaring class name

Label Label Label

Bad Example
public class Alpha extends Beta {
int alpha;
}
Good Example
public class Alpha extends Beta {
int theta;
}

Boolean Get Method Name

Description: Methods that return boolean results should be named as predicate statements to denote this. I.e, ‘isReady()’, ‘hasValues()’, ‘canCommit()’, ‘willFail()’, etc. Avoid the use of the ‘get’ prefix for these methods

Label Label Label

Bad Example
public boolean getAlpha();
Good Example
public boolean isAlpha();

Class Naming Conventions

Description: Configurable naming conventions for type declarations

Label Label Label

Bad Example
public class Étudiant {}
Good Example
public class AlphaBeta {}

Generics Naming

Description: Names for references to generic values should be limited to a single uppercase letter

Label Label Label

Bad Example
public interface GenericDao<e extends BaseModel, K extends Serializable> {
}
Good Example
public interface GenericDao<E extends BaseModel, K extends Serializable> {
}

Method Naming Conventions

Description: Configurable naming conventions for method declarations

Label Label Label


Method With Same Name As Enclosing Class

Description: Non-constructor methods should not have the same name as the enclosing class

Label Label Label

Bad Example
public class AlphaT {
public void AlphaT() {}
}
Good Example
public class AlphaT {
public AlphaT() {}
}

No Package

Description: A class, interface, enum or annotation does not have a package definition

Label Label Label


Package Case

Description: The package definition contains uppercase characters

Label Label Label

Bad Example
package com.MyAlpha;
Good Example
package com.myalpha;

Short Class Name

Description: Short Classnames with fewer than e.g. five characters are not recommended

Label Label Label

Bad Example
public class Alp {
}
Good Example
public class Alpha {
}

Short Method Name

Description: Method names that are very short are not helpful to the reader

Label Label Label

Bad Example
public class Alpha {
public void a( int i ) {
}
}
Good Example
public class Alpha {
public void beta( int i ) {
}
}

Suspicious Constant Field Name

Description: Field names using all uppercase characters - Sun’s Java naming conventions indicating constants - should be declared as final

Label Label Label

Bad Example
public class Alpha {
double PI = 3.16;
}
Good Example
public class Alpha {
final double PI = 3.16;
}

Suspicious Equals Method Name

Description: The method name and parameter number are suspiciously close to equals(Object), which can denote an intention to override the equals(Object) method

Label Label Label

Bad Example
public class Alpha {
public int equals(Object a) {
//doSomething
}
}
Good Example
public class Alpha {
public boolean equals(Object a) {
//doSomething
}
}

Suspicious Hashcode Method Name

Description: The method name and return type are suspiciously close to hashCode(), which may denote an intention to override the hashCode() method

Label Label Label

Bad Example
public class Alpha {
public int hashcode() {
}
}
Good Example
public class Alpha {
public int newname() {
}
}

Variable Naming Conventions

Description: Final variables should be fully capitalized and non-final variables should not include underscores

Label Label Label

Bad Example
public class Alpha {
public static final int my_alp = 0;
}
Good Example
public class Alpha {
public static final int MY_ALP = 0;
}

Add Empty String

Description: The conversion of literals to strings by concatenating them with empty strings is inefficient. It is much better to use one of the type-specific toString() methods instead

Label Label Label

Bad Example
String a = "" + 456; 
Good Example
String a = Integer.toString(456);

Avoid Array Loops

Description: Instead of manually copying data between two arrays, use the efficient Arrays.copyOf or System.arraycopy method instead

Label Label Label

Bad Example
public class Alpha {
public void beta() {
int[] x = new int[5];
int[]y = new int[5];
for (int i = 0; i < 5 ; i++) {
y[i] = x[i];
}
int[] z = new int[5];
for (int i = 0 ; i < 5 ; i++) {
y[i] = x[z[i]];
}
}
}

Redundant Field Initializer

Description: Java will initialize fields with known default values so any explicit initialization of those same defaults is redundant and results in a larger class file (approximately three additional bytecode instructions per field)

Label Label Label

Bad Example
public class Alpha {
boolean a = false;
}

Unnecessary Wrapper Object Creation

Description: Most wrapper classes provide static conversion methods that avoid the need to create intermediate objects just to create the primitive forms. Using these avoids the cost of creating objects that also need to be garbage-collected later

Label Label Label

Bad Example
public int convert(String a) {
int x, x2;

x = Integer.valueOf(a).intValue();

x2 = Integer.valueOf(x).intValue();

return x2;
}
Good Example
public int convert(String a) {
int x, x2;
x = Integer.parseInt(a);
x2 = x;

return x2;
}

Use Array List Instead Of Vector

Description: ArrayList is a much better Collection implementation than Vector if thread-safe operation is not required

Label Label Label

Bad Example
public class Alpha extends Beta {
public void testAlpha() {
Collection b = new Vector();
}
}
Good Example
public class Alpha extends Beta {
public void testAlpha() {
Collection b = new ArrayList();
}
}

Use Arrays As List

Description: "The java.util.Arrays class has a ""asList"" method that should be used when you want to create a new List from an array of objects. It is faster than executing a loop to copy all the elements of the array one by one"

Label Label Label

Bad Example
public class Alpha {
public void beta(Integer[] ints) {
List<Integer> l = new ArrayList<>(50);
for (int i = 0 ; i < 50; i++) {
l.add(ints[i]);
}
}
}
Good Example
public class Alpha {
public void beta(Integer[] ints) {
List<Integer> l= new ArrayList<>(50);
for (int i = 0 ; i < 50; i++) {
l.add(a[i].toString());
}
}
}

Use String Buffer For String Appends

Description: The use of the ‘+=’ operator for appending strings causes the JVM to create and use an internal StringBuffer. If a non-trivial number of these concatenations are being used then the explicit use of a StringBuilder or threadsafe StringBuffer is recommended to avoid this

Label Label Label

Bad Example
public class Alpha {
void beta() {
String c;
c = "alpha";
c += " beta";
}
}
Good Example
public class Alpha {
void beta() {
String c;
StringBuilder c = new StringBuilder("alpha");
c.append(" beta");
}
}

Array Is Stored Directly

Description: Constructors and methods receiving arrays should clone objects and store the copy. This prevents future changes from the user from affecting the original array

Label Label Label

Bad Example
public class Alpha {
private String [] a;
public void beta (String [] param) {
this.a=param;
}
}

Method Returns Internal Array

Description: Exposing internal arrays to the caller violates object encapsulation since elements can be removed or replaced outside of the object that owns it. It is safer to return a copy of the array

Label Label Label

Bad Example
public class Alpha {
UserChart [] uc;
public UserChart [] getUserChart() {
return uc;
}
}

Avoid Catching Generic Exception

Description: Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block

Label Label Label

Bad Example
public class Alpha {

public void Beta() {
try {
System.out.println(" i [" + i + "]");
} catch(Exception e) {
e.printStackTrace();
} catch(RuntimeException e) {
e.printStackTrace();
} catch(NullPointerException e) {
e.printStackTrace();
}
}
}

Avoid Catching NPE

Description: Code should never throw NullPointerExceptions under normal circumstances. A catch block may hide the original error, causing other, more subtle problems later on

Label Label Label

Bad Example
public class Alpha {
void beta() {
try {
// do something
} catch (NullPointerException npe) {
}
}
}

Avoid Catching Throwable

Description: Catching Throwable errors is not recommended since its scope is very broad. It includes runtime issues such as OutOfMemoryError that should be exposed and managed separately

Label Label Label

Bad Example
public void beta() {
try {
// do something
} catch (Throwable th) {
th.printStackTrace();
}
}

Avoid Losing Exception Information

Description: Statements in a catch block that invoke accessors on the exception without using the information only add to code size. Either remove the invocation, or use the return result

Label Label Label

Good Example
public void bar() {
try {
// do something
} catch (SomeException se) {
se.getMessage();
}
}

Avoid Rethrowing Exception

Description: Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity

Label Label Label

Bad Example
public void beta() {
try {
// do something
} catch (SomeException se) {
throw se;
}
}

Avoid Throwing New Instance Of Same Exception

Description: Catch blocks that merely rethrow a caught exception wrapped inside a new instance of the same type only add to code size and runtime complexity

Label Label Label

Bad Example
public void beta() {
try {
// do something
} catch (SomeException se) {
// harmless comment
throw new SomeException(se);
}
}

Avoid Throwing Null Pointer Exception

Description: Avoid throwing NullPointerExceptions manually. These are confusing because most people will assume that the virtual machine threw it. To avoid a method being called with a null parameter, you may consider using an IllegalArgumentException instead

Label Label Label

Bad Example
public class Alpha {
void beta() {
throw new NullPointerException();
}
}
Good Example
public class Alpha {
private String examValue;

void setExamValue(String examValue) {
this.examValue = Objects.requireNonNull(examValue, "examValue must not be null!");
}
}

Avoid Throwing Raw Exception Types

Description: Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable, Exception, or Error, use a subclassed exception or error instead

Label Label Label

Bad Example
public class Alpha {
public void beta() throws Exception {
throw new Exception();
}
}

Do Not Extend Java Lang Error

Description: Errors are system exceptions. Do not extend them

Label Label Label

Bad Example
public class Alpha extends Error { }

Do Not Throw Exception In Finally

Description: "Throwing exceptions within a ‘finally’ block is confusing since they may mask other exceptions or code defects. Note: This is a PMD implementation of the Lint4j rule ""A throw in a finally block"""

Label Label Label

Bad Example
public class Alpha {
public void beta() {
try {
// Do somthing
} catch( Exception e) {
// Handling the issue
} finally {
throw new Exception();
}
}
}

Exception As Flow Control

Description: Using Exceptions as form of flow control is not recommended as they obscure true exceptions when debugging. Either add the necessary validation or use an alternate control structure

Label Label Label

Bad Example
public void beta() {
try {
try {
} catch (Exception e) {
throw new WrapperException(e);
}
} catch (WrapperException e) {
// do some more stuff
}
}

Avoid Duplicate Literals

Description: Code containing duplicate String literals can usually be improved by declaring the String as a constant field

Label Label Label

Bad Example
private void alpha() {
beta("Howdy");
beta("Howdy");
}
Good Example
private void beta(String x) {}

Avoid String Buffer Field

Description: StringBuffers/StringBuilders can grow considerably, and so may become a source of memory leaks if held within objects with long lifetimes

Label Label Label

Bad Example
public class Foo {
private StringBuffer buffer;
}

Consecutive Appends Should Reuse

Description: Consecutive calls to StringBuffer/StringBuilder .append should be chained, reusing the target object. This can improve the performance by producing a smaller bytecode, reducing overhead and improving inlining

Label Label Label

Bad Example
buf.append("Hello");
buf.append(alpha);
buf.append("World");
Good Example
buf.append("Hello").append(alpha).append("World");

Consecutive Literal Appends

Description: Consecutively calling StringBuffer/StringBuilder.append(…) with literals should be avoided

Label Label Label

Bad Example
buf.append("Hello").append(" ").append("World");
Good Example
buf.append("Hello World");

Inefficient String Buffering

Description: Avoid concatenating non-literals in a StringBuffer constructor or append() since intermediate buffers will need to be be created and destroyed by the JVM

Label Label Label

Bad Example
StringBuffer sb = new StringBuffer("tmp = "+System.getProperty("java.io.tmpdir"));
Good Example
StringBuffer sb = new StringBuffer("tmp = ");
sb.append(System.getProperty("java.io.tmpdir"));

String Buffer Instantiation With Char

Description: Individual character values provided as initialization arguments will be converted into integers. This can lead to internal buffer sizes that are larger than expected

Label Label Label

Bad Example
StringBuffer  sb1 = new StringBuffer('c');
StringBuilder sb2 = new StringBuilder('c');
Good Example
StringBuffer  sb3 = new StringBuffer("c");
StringBuilder sb4 = new StringBuilder("c");

String Instantiation

Description: Avoid instantiating String objects. This is usually unnecessary since they are immutable and can be safely shared

Label Label Label

Bad Example
private String beta = new String("beta");
Good Example
private String beta = "beta";

String To String

Description: Avoid calling toString() on objects already known to be string instances. This is unnecessary

Label Label Label

Bad Example
private String beta() {
String tab = "iamastring";
return tab.toString();
}
Good Example
private String beta() {
String tab = "a string";
return String.join("I am ", tab);
}

Unnecessary Case Change

Description: Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals()

Label Label Label

Bad Example
boolean answer = alpha.toUpperCase().equals("beta");
Good Example
boolean answer = alpha.equalsIgnoreCase("beta")

Use Equals To Compare Strings

Description: Using ‘==’ or ‘!=’ to compare strings only works if intern version is used on both sides

Label Label Label

Bad Example
public boolean test(String s) {
if (s == "one") return true;
return false;
}
Good Example
public boolean test(String s) {
if ("two".equals(s)) return true;
return false;
}

Clone Method Must Implement Cloneable

Description: The method clone() should only be implemented if the class implements the Cloneable interface with the exception of a final method that only throws CloneNotSupportedException

Label Label Label

Bad Example
public class MyClass {
public Object clone() {
return alpha;
}
}
Good Example
public class MyClass {
public Object clone() throws CloneNotSupportedException {
return alpha;
}
}

Loose Coupling

Description: The use of implementation types (i.e., HashSet) as object references limits your ability to use alternate implementations in the future as requirements change. Whenever available, referencing objects by their interface types (i.e, Set) provides much more flexibility

Label Label Label

Bad Example
public class Beta {
private ArrayList<SomeType> list = new ArrayList<>();

public HashSet<SomeType> getAlpha() {
return new HashSet<SomeType>();
}
}
Good Example
public class Beta {
private List<SomeType> list = new ArrayList<>();

public Set<SomeType> getAlpha() {
return new HashSet<SomeType>();
}
}

Signature Declare Throws Exception

Description: A method/constructor shouldn’t explicitly throw the generic java.lang.Exception, since it is unclear which exceptions that can be thrown from the methods. It might be difficult to document and understand such vague interfaces. Use either a class derived from RuntimeException or a checked exception

Label Label Label

Bad Example
public void alpha() throws Exception { }

Unused Imports

Description: Avoid unused import statements to prevent unwanted dependencies

Label Label Label

Bad Example
import java.io.File;
import java.util.*;

public class Alpha {}
Good Example
public class ALpha {}

Unused Local Variable

Description: The local variable is declared and/or assigned, but not used

Label Label Label

Bad Example
public class Alpha {
public void doSomething(Int x) {
int i = 5;
return x + 2;
}
}
Good Example
public class Alpha {
public void doSomething(Int x) {
int i = 5;
public int addOne() {
return j + i;
}
}
}

Unused Private Field

Description: The private field is declared and/or assigned a value, but not used

Label Label Label

Bad Example
public class Something {
private static int ALPHA = 2;
private int i = 5;
}
Good Example
public class Something {
private int j = 6;
public int addOne() {
return j++;
}
}

Unused Private Method

Description: The private method is declared but is unused

Label Label Label

Bad Example
public class Something {
private void alpha() {}
}

Accessor Method Generation

Description: Avoid autogenerated methods to access private fields and methods of inner/outer classes

Label Label Label

Bad Example
public class OuterClass {
public class InnerClass {
InnerClass() {
OuterClass.this.counter++;
}
}
}
Good Example
public class OuterClass {
private int counter;
}

Avoid Message Digest Field

Description: It is better to create a new instance, rather than synchronizing access to a shared instance

Label Label Label

Bad Example
public byte[] calculateHashShared(byte[] data) {
sharedMd.reset();
sharedMd.update(data);
return sharedMd.digest();
}
Good Example
public byte[] calculateHash(byte[] data) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(data);
return md.digest();
}

Avoid Reassigning Catch Variables

Description: Reassigning exception variables caught in a catch statement should be avoided

Label Label Label

Bad Example
public class Alpha {
public void foo() {
try {
// do something
} catch (Exception e) {
e = new NullPointerException();
}
}
}
Good Example
public class Alpha {
public void foo() {
try {
// do something
} catch (MyException | ServerException e) {
e = new RuntimeException();
}
}
}

Avoid Reassigning Loop Variables

Description: Reassigning loop variables can lead to hard-to-find bugs. Prevent or limit how these variables can be changed

Label Label Label

Bad Example
public class Alpha {
private void alpha() {
for (String s : listOfStrings()) {
s = s.trim();
doSomethingWith(s);

s = s.toUpper();
doSomethingElseWith(s);
}
}
}
Good Example
public class Alpha {
private voidalpha() {
for (int i=0; i < 10; i++) {
if (check(i)) {
i++;
}

i = 5;

doSomethingWith(i);
}
}
}

Constants In Interface

Description: Avoid constants in interfaces. Interfaces define types, constants are implementation details better placed in classes or enums

Label Label Label

Bad Example
public interface ConstantInterface {
public static final int CONST1 = 1;
static final int CONST2 = 1;
final int CONST3 = 1;
int CONST4 = 1;
}
Good Example
public interface ConstantInterface {
public static final int CONST1 = 1;

int anyMethod();
}

Double Brace Initialization

Description: it is preferable to initialize the object normally, rather than usuing double brace initialization

Label Label Label

Bad Example
List<String> a = new ArrayList<>();
a.add("a");
a.add("b");
a.add("c");
return a;
Good Example
return new ArrayList<String>(){{
add("a");
add("b");
add("c");
}};

For Loop Can Be Foreach

Description: Reports loops that can be safely replaced with the foreach syntax

Label Label Label

Bad Example
public class Alpha {
void loop(List<String> l) {
for (int i = 0; i < l.size(); i++) {
System.out.println(l.get(i));
}
}
}
Good Example
public class Alpha {
void loop(List<String> l) {
for (String s : l) {
System.out.println(s);
}
}
}

For Loop Variable Count

Description: Having a lot of control variables in a 'for' loop makes it harder to see what range of values the loop iterates over

Label Label Label

Bad Example
for (int i = 0, j = 0; i < 10; i++, j += 2) {
alpha();
}
Good Example
for (int i = 0; i < 10; i++) {
alpha();
}

Literals First In Comparisons

Description: Position literals first in all String comparisons

Label Label Label

Bad Example
class Alpha {
boolean bar(String x) {
return x.equals("3");
}
boolean bar(String x) {
return x.equalsIgnoreCase("3");
}
boolean bar(String x) {
return (x.compareTo("alpha") > 0);
}
boolean bar(String x) {
return (x.compareToIgnoreCase("alpha") > 0);
}
boolean bar(String x) {
return x.contentEquals("alpha");
}
}
Good Example
class Alpha {
boolean bar(String x) {
return "3".equals(x);
}
boolean bar(String x) {
return "3".equalsIgnoreCase(x);
}
boolean bar(String x) {
return ("alpha".compareTo(x) < 0);
}
boolean bar(String x) {
return ("alpha".compareToIgnoreCase(x) < 0);
}
boolean bar(String x) {
return "alpha".contentEquals(x);
}
}

Missing Override

Description: Annotating overridden methods with @Override helps refactoring and clarifies intent

Label Label Label

Bad Example
public class Alpha implements Run {
public void run() {
}
}
Good Example
public class Alpha implements Run {
@Override
public void run() {
}
}

Use Try With Resources

Description: Prefer usuing Try With Resources because ensures that each resource is closed at the end of the statement

Label Label Label

Bad Example
public class Try {
public void run() {
InputStream in = null;
try {
in = openInputStream();
int i = in.read();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) in.close();
} catch (IOException ignored) {
// ignored
}
}
}
}
Good Example
public class Try {
public void run() {
InputStream in = null;
// better use try-with-resources
try (InputStream in2 = openInputStream()) {
int i = in2.read();
}
}
}

While Loop With Literal Boolean

Description: While loops that include literal booleans are redundant and should be avoided

Label Label Label

Bad Example
public class Alpha {
{
while (false) { } // disallowed
do { } while (true); // disallowed
do { } while (false); // disallowed
}
}
Good Example
public class Example {
{
while (true) { } // allowed
}
}

Control Statement Braces

Description: Enforce a policy for braces on control statements

Label Label Label

Bad Example
while (true)
x++;
Good Example
while (true) {
x++;
}

Identical Catch Branches

Description: Prefer collapsing identical branches into a single multi-catch branch

Label Label Label

Bad Example
try {
// do something
} catch (IllegalArgumentException e) {
throw e;
} catch (IllegalStateException e) {
throw e;
}
Good Example
try {
// do something
} catch (IllegalArgumentException | IllegalStateException e) {
throw e;
}

Unnecessary Annotation Value Element

Description: Avoid the use of value in annotations when it's the only element

Label Label Label

Bad Example
@TestClassAnnotation(value = "TEST")
public class Alpha {

@TestMemberAnnotation(value = "TEST")
private String alpha;

@TestMethodAnnotation(value = "TEST")
public void beta() {
int gamma = 42;
return;
}
}
Good Example
@TestClassAnnotation("TEST")
public class Alpha {

@TestMemberAnnotation("TEST")
private String alpha;

@TestMethodAnnotation("TEST")
public void beta() {
int gamma = 42;
return;
}
}

Unnecessary Modifier

Description: There is no need to modify the interfaces and the annotations

Label Label Label

Bad Example
public interface Alpha {
public abstract void alpha();
}
Good Example
public interface Alpha {
void alpha();
}

Use Short Array Initializer

Description: Define the initial content of the array as a expression in curly braces

Label Label Label

Bad Example
Alpha[] x = new Alpha[] { ... };
Good Example
Alpha[] x = { ... };

Use Underscores In Numeric Literals

Description: This rule enforces that numeric literals above a certain length should separate every third digit with an underscore

Label Label Label

Bad Example
public class Alpha {
private int num = 1000000;
}
Good Example
public class Alpha {
private int num = 1_000_000;
}

Useless Qualified This

Description: Reports qualified this usages in the same class

Label Label Label

Bad Example
public class Alpha {
private class Alpha2 {
final Alpha2 Alpha2 = Alpha2.this;
}
}
Good Example
public class Alpha {
private class Alpha2 {
final Alpha myAlpha = Alpha.this;
}
}

Avoid Unchecked Exceptions In Signatures

Description: Document the exceptional cases with a @throws Javadoc tag, which allows being more descriptive

Label Label Label

Bad Example
public void foo() throws RuntimeException {
}

Clone Method Must Be Public

Description: Prefer using a public method for classes that implement this interface should override Object.clone

Label Label Label

Bad Example
public class Alpha implements Cloneable {
@Override
protected Alpha clone() {
}
}
Good Example
public class Alpha implements Cloneable {
@Override
public Object clone()
}

Clone Method Return Type Must Match Class Name

Description: If a class implements cloneable the return type of the method clone() must be the class name

Label Label Label

Bad Example
public class Alpha implements Cloneable {
@Override
protected Object beta() {
}
}
Good Example
public class Alpha implements Cloneable {
@Override
protected Alpha beta() { // Violation, Object must be Foo
}
}

Detached Test Case

Description: The method appears to be a test case, but is a member of a class that has one or more JUnit test cases

Label Label Label

Bad Example
public class MyTest {
@Test
public void someTest() {
}

public void someOtherTest () {
}

}
Good Example
public class MyTest {
@Test
public void someTest() {
}
}

Do Not Extend Java Lang Throwable

Description: Extend Exception or RuntimeException instead of Throwable

Label Label Label

Good Example
public class Alpha extends Throwable { }

Do Not Terminate VM

Description: Web applications should not call System.exit(), since only the web container or the application server should stop the JVM

Label Label Label

Bad Example
public void alpha() {
System.exit(0);
}
Good Example
public void alpha() {
Runtime.getRuntime().exit(0);
}

Invalid Log Message Format

Description: Check for messages in slf4j and log4j2 loggers with non matching number of arguments and placeholders

Label Label Label

Bad Example
LOGGER.error("forget the arg {}");
LOGGER.error("forget the arg %s");
LOGGER.error("too many args {}", "arg1", "arg2");
Good Example
LOGGER.error("param {}", "arg1", new IllegalStateException("arg"));

Single Method Singleton

Description: The instance created using the overloaded method is not cached and so, for each call and new objects will be created for every invocation

Label Label Label

Bad Example
public static Singleton getInstance(Object obj){
Singleton singleton = (Singleton) obj;
return singleton;
}
Good Example
public static Singleton getInstance( ) {
return singleton;
}

Singleton Class Returning New Instance

Description: getInstance method always creates a new object and hence does not comply to Singleton Design Pattern behaviour

Label Label Label

Bad Example
class Singleton {
private static Singleton instance = null;
public static Singleton getInstance() {
synchronized(Singleton.class) {
return new Singleton();
}
}
}

Unsynchronized Static Formatter

Description: Static Formatter objects should be accessed in a synchronized manner

Label Label Label

Bad Example
public class Alpha {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
void alpha() {
sdf.format();
}
}
Good Example
public class Alpha {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
void alpha() {
synchronized (sdf) {
sdf.format();
}
}
}

Avoid Calendar Date Creation

Description: Use new Date(), java.time.LocalDateTime.now() or ZonedDateTime.now()

Label Label Label

Bad Example
public class DateAdd {
private Date bad() {
return Calendar.getInstance().getTime(); // now
}
}
Good Example
public class DateAdd {
private Date good() {
return new Date(); // now
}
}

Avoid File Stream

Description: Avoid instantiating FileInputStream, FileOutputStream, FileReader, or FileWriter

Label Label Label

Bad Example
FileInputStream fis = new FileInputStream(fileName);
Good Example
try(InputStream is = Files.newInputStream(Paths.get(fileName))) {
}

Hard Coded Crypto Key

Description: Do not use hard coded encryption keys. Better store keys outside of source code

Label Label Label

Bad Example
public class Alpha {
void bad() {
SecretKeySpec secretKeySpec = new SecretKeySpec("my secret here".getBytes(), "AES");
}
}
Good Example
public class Alpha {
void good() {
SecretKeySpec secretKeySpec = new SecretKeySpec(Properties.getKey(), "AES");
}
}

Insecure Crypto Iv

Description: Do not use hard coded initialization vector in crypto operations. Better use a randomly generated IV

Label Label Label

Bad Example
public class Alpha {
void bad() {
byte[] iv = new byte[] { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, };
}
}
Good Example
public class Alpha {
void good() {
SecureRandom random = new SecureRandom();
byte iv[] = new byte[16];
random.nextBytes(bytes);
}
}

Automated Software Quality Assurance


8, Chalkis Street, Thessaloniki, Greece, Tel: +30 2310 471 030
Copyright © 2024 Cyclopt