RuleDescriptionExampleKPI
Return Empty Array Or Collection Instead Of Null Returning null value instead of an empty array or collection can lead to denial-of-service vulnerabilities when the client code fails to explicitly handle the null return value. For methods that return a set of values using an array or collection, returning an empty array or collection is an excellent alternative to returning a null value.

More Info
MET55-J - Return an empty array or collection instead of a null value for methods that return an array or collection

MSC19-C - For functions that return an array, prefer returning an empty array over a null value
Non-compliant code:
class Demo {
public static List getList() {
return null; // Non-compliant code
}

public static void main(String[] args) {
List results = getList();
for (Result result: results) { } // Need to add Nullity check to prevent NPE
}
}


Compliant code:
class Demo {
public static List getList() {
return Collections.emptyList(); // Compliant code
}

public static void main(String[] args) {
List results = getList();
for (Result result: results) { } // No need to add Nullity check to prevent NPE
}
}
Robustness
Preserve Stack Trace In LogsPreserve stack trace in logs. This will help to analyse the logs in case of any exception. Non-compliant code:
class Demo {
public void process1() {
try{
//some statements
} catch(Exception e) {
logger.error("Error while processing");
}
}
}


Compliant code:
class Demo {
public void process2() {
try {
//some statements
} catch(Exception e) {
logger.error("Error while processing",e);
}
}
}

Analyzability
Read Only TransactionSpring components support database transactions using "@Transactional" annotation. If readOnly attribute is not explicitly set to true, we will have read/write transactions for select queries. Hence, it is always recommended to explicitly specify the readOnly attribute.Non-Compliant Code:
class Demo {
public class UserRepository {
@Query("select username from users")
public List getAllUsers() {
}
}
}


Compliant Code:
class Demo {
@Transactional(readOnly=true)
public class UserRepository {
@Query("select username from users")
public List getAllUsers() {
}
}
//Compliant Code
public class UserRepository {
@Transactional(readOnly=true)
@Query("select username from users")
public List getAllUsers() {
}
}
}
Robustness
Unusual REST PracticeThe best practices while creating REST API's are :
1. URL should contain resources (E.g. nouns) only; not actions or verbs.

2. Singular and plural noun should not be mixed together.

3. Use plural noun only for all the resources.

4. Use GET method, instead of the POST method to fetch the data.

5. Use PUT, POST and DELETE methods to alter the state.
Non-compliant code
class Demo {
@RequestMapping("/users")
public class UserController{

@RequestMapping(value="/getUser")
public void getUser(){
}
}
}


Compliant code
class Demo {
@RequestMapping("/users")
public class UserController{

@RequestMapping(value="/{user}")
public void getUser() {
}
}
}
Maintainability
Variables Should Not Be Self AssignedSelf-assignment of the variables can be confusing and leads to bugs; however, one should not assign a variable to itself. Hence, this statement can be redundant and removed.Non-compliant code
class Demo {
public void demo(String name, String surName) {
String surName = surName;
name = name;
}
}


Compliant code
class Demo {
public void setName(String name) {
this.name = name;
}
}
Functionality
Externalizable Must Have No Arguments ConstructorExternalizable interface cannot be deserialized without a non-argument constructor,so non-argument constructor must be implemented.Non-compliant code
public class Car implements Externalizable {
public Car(String color,String model,int avg){
}
}


Compliant code
public class Car implements Externalizable {
public Car() {}
public Car (String color,String model,int avg){
}
Efficiency
Getters And Setters Should Access The Expected FieldsGetter and Setter methods must access the expected fields. For each instance variable, a getter method returns its value, while a setter method sets or updates its value.
For example, 'active' is an instance variable and 'setActive' (boolean value) is a setter method. Instead of unexpectedly updating any field, it must update or set the active variable.
Non-compliant code
class Demo {
// Non-compliant code
private boolean active;
public void setActive(boolean b)
{
this.Y = b;
}


Compliant code
private boolean active;
public void setActive(boolean b)
{
this.active = b;
}
}
Functionality
RunFinalizersOnExit Should Not Be CalledRemove Runtime::runFinalizersOnExit and System::runFinalizersOnExit methods. It can be enabled with "System.runFinalizersOnExit" and "Runtime.runFinalizersOnExit".It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in unexpected behavior or deadlock.

- [CWE-586]- Explicit Call to Finalize()
Non-compliant code
public static void main(String [] args) {

System.runFinalizersOnExit(true); // Noncompliant

}


Compliant code
public static void main(String [] args) {
Runtime.addShutdownHook(new Runnable() {
public void run(){
doSomething();
}
});
Efficiency
Big Integer InstantiationUse already existing BigIntegers (BigInteger.ZERO, BigInteger.ONE, BigInteger.TEN).Instead of creating a new object with new BigInteger better use one static object which is created once when the BigInteger class is loaded. It is likely to yield significantly better space and time performance. Zero and One is probably the most fundamental number in mathematics. Using static objects avoids the allocation about 48 bytes and the need to collect them back later in a tight loop that can matter. Non-compliant code
BigInteger bigInteger = new BigInteger("1");
int n=4;
for (int i = 2; i <=n ; i++){
bigInteger = bigInteger.multiply(BigInteger.valueOf(i));
}
System.out.println("Factorial of 4 : "+bigInteger);


Compliant code
BigInteger bigInteger = BigInteger.ONE;
int n=4;
for (int i = 2; i <=n ; i++){
bigInteger = bigInteger.multiply(BigInteger.valueOf(i));
}
System.out.println("Factorial of 4 : "+bigInteger);

Efficiency
Maps With Enum Values Replace With EnumMapIf Map has all the key values from the same Enum then Map should be replaced with EnumMap because the underlying data structure is a simple array so it will be more efficient than other sets.Non-compliant code
public class MyClass {
public enum CITY {
PUNE, MUMBAI, GOA, NAGPUR;
}
public void mapMood() {
Map moodMap = new HashMap ();
}
}


Compliant code
public class MyClass {
public enum CITY {
PUNE, MUMBAI, GOA, NAGPUR;
}
public void mapMood() {
EnumMap moodMap = new EnumMap<> (CITY.class);
}
}
Functionality
Mismatch Regex Boundaries Should Not Be UsedIn the regular expression by switching $ and ^ boundaries it will never match and it can be misused.Noncompliant Code

pattern.compile("$[a-z]+^");

Compliant Code

pattern.compile("^[a-z]+$");
Functionality
Avoid Concatenating Char As StringAvoid concatenating characters as strings because using string rather than char creates unnecessarily space accommodation in heap space. Appending a character as a char will always be faster than appending it as a String.Noncompliant Code

class Demo {
StringBuffer sb = new StringBuffer("Hi ");
sb.append("i");
System.out.println(sb);
}


Compliant Code

class Demo {
StringBuffer sb = new StringBuffer("Hi ");
sb.append('i');
System.out.println(sb);
}

Functionality
Empty String Should Not Be UsedConcatenating empty string with literals during conversion is inefficient.Noncompliant Code

String s = "" + 456;

Compliant Code

String t = Integer.toString(456);
Functionality
Exceptions Should Not Be Thrown In Finally BlockException that is thrown in finally block will mask any previous exception in try or catch block and the stack trace and exception message will be lost. Noncompliant Code

try {
throw new IllegalArgumentException();
} finally {
throw new RuntimeException();
}


Compliant Code

try {
throw new IllegalArgumentException();
} finally {

}

Functionality