1. What are code issues?
  2. Vulnerabilities
  3. Code checker configuration
  4. Issue Suppression
  5. Generic module
  6. C/C++
    1. EmboldCXX Issues
      1. Critical issues
      2. High-level issues
      3. Medium level issues
      4. Low level issues
    2. CPP Check Issues
      1. Critical level issues
      2. High level issues
      3. Medium level issues
      4. Low level issues
  7. C#
    1. EmboldCS Issues
      1. Critical level issues
      2. High level issues
      3. Medium level issues
      4. Low level issues
  8. Objective- C
    1. Embold CXX Issues
      1. Critical level issues
      2. High level issues
      3. Medium level issues
      4. Low level issues
  9. Java
    1. Embold Java Issues
      1. Critical level issues
      2. High level issues
      3. Medium level issues
      4. Low level issues
      5. Info level issues
    2. PMD Issues
      1. Critical level issues
      2. High level issues
      3. Medium level issues
      4. Low level issue
      5. Info level issues
    3. SpotBugs code checker
      1. High level issues
      2. Medium level issues
      3. SpotBugs Security: Medium level issues
      4. SpotBugs Security: High level issues
  10. Python
    1. Pylint Code Issues
      1. Critical level issues
      2. High level issues
      3. Medium level issues
      4. Low level issues
    2. Bandit Code Issues
      1. Bandit High Level Issues
      2. Bandit Low Level Issues
  11. JavaScript
    1. JSLint code checker
      1. Critical level issues
      2. High level issues
      3. Medium level issues
      4. Low level issues
    2. ESLint code checker
      1. High level issues
      2. Medium level issues
      3. Low level issues
  12. TypeScript
    1. TSLint code checker
      1. Critical level issue
      2. High level issue
      3. Medium level issue
      4. Low level issue
  13. GO
    1. Go Meta Linter Issues
      1. High level issues
      2. Medium level issues
      3. Low level issues
    2. Gosec Linter Issues
      1. Gosec critical level issues
      2. Gosec high level issues
      3. Gosec medium level issues
      4. Gosec low level issues
    3. Staticcheck Linter Issues
      1. Staticcheck high level issues
      2. Staticcheck medium level issues
      3. Staticcheck low level issues
  14. PHP
    1. PHPMD Code Checker
      1. Critical level issues
      2. High level issues
      3. Medium level issues
      4. Low level issues
    2. PHPCS Code Checker
      1. High level issues
      2. Medium level issues
      3. Low level issues
  15. Kotlin
    1. Detekt code checker
      1. Medium level issues
      2. Low level issues
  16. Solidity
    1. Solium Code Checker
      1. High level issues
      2. Medium level issues
      3. Low level issues
  17. Ruby
    1. Brakeman Code Issues
      1. Brakeman critical level issues
      2. Brakeman high level issues
      3. Brakeman medium level issues
      4. Brakeman low level issues
  18. Apex
    1. Critical level issues
    2. High level issues
    3. Medium level issues
    4. Low level issues
    5. Apex PMD info level issues

What are code issues?

When a system is expected to behave in a certain way and it fails to meet the result, the issue occurs. Similarly, any defect or bug found in the code leads to code issues. BrowserStack Code Quality helps to identify the code issues in your software and provide the solutions for the same. 
There are different languages in which these code checks are written.

Vulnerabilities

The software vulnerability is basically an error or a weakness present in the software code. Those are product-related threats that can hamper your data and gain access to your products and data.

Once, a vulnerability is detected in a code, there is a high risk from a security perspective. External attackers can exploit and trigger the information systems. This may affect the performance of your product.

Vulnerabilities can be caused due to many reasons like design implementation, input validation errors, code injection, complexity in building large systems, and so on.

The most effective way to prevent these vulnerabilities is by enforcing standard security practices. Check here to know more about security standards supported by BrowserStack Code Quality.

Supported languages

Java: Vulnerabilities in Java can be found and BrowserStack Code Quality can help in detecting those.

To get more details about the vulnerability count, refer to this table.

Code checker configuration

Code checker configuration helps you to enable or disable code checkers and their corresponding rules for any repository.

Steps to navigate to code checker configuration
  1. Select the Code checkers configuration option from the repository context menu of the desired repository.
  2. On the Code checkers configuration page, on the left side navigation pane, by default, code issues are enabled except few.
  3. Check or uncheck the radio button to enable or disable a specific rule. If you want the checkers to be disabled, you can disable the code checkers (for example GammaCXX or cppcheck).
  4. For a specific selected checker, rules will be displayed.
  5. Move the cursor on the desired rule to view the More info button. More info will display a detailed description and examples.
  6. Users can search rules manually by typing in the search text box.
  7. On the right side navigation pane, the Filter Rules section can be used to filter the displayed rules based on Criticality or by associated KPI.
  8. To download the file, click Download JSON at the bottom right corner of the code configuration page. This file provides a customized configuration in JSON format and you can change it manually.
  9. To upload the changed file, click Upload JSON Configuration at the top of the code configuration page.

Issue Suppression

Code issues are one of the important assets of BrowserStack Code Quality analysis. Issue suppression is a feature that lists the suppressed code issues within a file/project. Suppression means basically ignoring some parts or a whole parts of the code.

In a few cases, code analysis gives false-positive. Issue suppression is a feature that allows users to suppress these false-positive issue occurrences. This is important because disabling the issue type entirely will not be correct in many cases. If one issue is suppressed, it will be taken off from the code issues panel and will be moved to separate suppressed issues panel.

Steps for suppressing an issue:

1. Go to the Component Explorer present at the top navigation bar next to the duplication tab.
2. Click on the icon on the left side for the issue to be suppressed.
3. Click on Suppress this occurrence” icon.
4. Add comment i.e. the reason for suppression.
5. Click on the Submit button.

Steps for unsuppressing an issue :

  1. Go to the Component Explorer present at the top navigation bar next to the duplication tab.
  2. From the Suppressed Issues tab, click on the unsuppress icon.
Note:
Suppression details can be seen on click of suppressed issue .

Suppression Review Workflow

This feature is only available for enterprise customers.

  1. Select three dots on repository’s page and click on enable suppression approval work flow.

2. When a developer suppresses an issue,  project manager, project admins and super admins will see the list of suppressed issues on newly introduced Suppression Status page.

3. Project manager, project admins and super admins can review – Accept or Reject suppressions.

Suppression history

The suppression history feature allows users to view a comprehensive log of suppression actions taken on certain issues. This log includes details such as the name of the user who initiated the action, the reason for the suppression, the status of the suppression (whether it was pending, approved or rejected), any accompanying reasons for approval or rejection, and the date on which the action occurred. This feature provides transparency and accountability regarding the management of suppression issues within the system.

See screenshot below for reference

Generic module

The generic module is used to import code issues from a file. Regardless of language or combination of languages, if you get your code issues data into the generic format as specified by this module, it will be imported and correctly applied.

Module Name:

gamma_generic

The supported format looks like:

FileSeverityLineDescriptionRuleTag
src/main/java/com/mariten/kanatools/KanaConverter.javaLow26This issue is having low criticality.Custom Rule{"CWE":"146"};{"MISRA":"444"};{"CWE":"123"}
src/main/java/com/mariten/kanatools/KanaConverter.javaHigh33This issue is having High criticality.Rule-01Tag1
src/main/java/com/mariten/kanatools/KanaConverter.javalow45This issue is having low criticality.custom Rule 3{"CWE":"231"};{"CWE":"867"}
src/main/java/com/mariten/kanatools/KanaConverter.javaMedium25This issue is having medium criticality.custom Rule-04{"CWE":"453"}
src/main/java/com/mariten/kanatools/KanaConverter.java Medium39This issue is having medium criticality.custom Rule 5NewTag;TagTest1
src/main/java/com/mariten/kanatools/KanaConverter.javaCritical43Critical custome Rule 8NewTag;TagTest1;Tag_123

Supported severity types :
Critical, High, Medium, Low and Info

Supported input tag formats :

only tag name=   tag1

multiple tag with only name = tag2;tag3

name and value =   “{“CWE”:”330″}”

multiple tag with name and value=  “{“CWE”:”330″};{“CWE”:”200″}”

Usage

There are two ways to run gamma-generic module:

Step 1: Through API

  1. By specifying the path of the CSV file where it is located:
    To specify a path, use the following API:
    POST - api/v1/repositories/{repositoryUid}/config/{moduleType}/{moduleName}
    Refer to this link to get additional information.
  2. By uploading a zip file: Here, the CSV file is zipped and send to API.
    To upload zip use following API:
    POST - api/v1/repositories/{repositoryUid}/upload/{moduleName}
    Refer to this link to get additional information.
  3. Commit CSV files in the source code and then give the relative file path

Step 2: Run scan to get the generic code issues on UI.

  1. Any CSV file name will work

2. By Providing CSV PATH relative to base directory

3. In a remote scan, multiple CSV files can be given with comma-separated paths

Note:
Please refer API documentation to get detailed information on each of these APIs.
Currently, we are supporting this generic module through API and remote scan as well.

C/C++

The section below briefs you about the bugs, vulnerabilities, and code issues in C/C++.


EmboldCXX Issues

Embold comes with a state-of-the-art proprietary analyser. In addition to integrating and building upon great work from the open source space, we have created our own checks and rules to discover code issues that were not sufficiently covered by other tools.


Critical issues

RuleDescriptionExampleKPI
core.DivideZeroCheck for division by zerovoid test(int z) { if (z == 0) int x = 1 / z; // warn }Robustness
core.NonNullParamCheckerCheck for null pointers passed as arguments to a function whose arguments are references or marked with the ‘nonnull’ attributeint f(int *p) __attribute__((nonnull)); void test(int *p) { if (!p) f(p); // warn }Robustness
core.NullDereferenceCheck for dereferences of null pointersvoid test(int *p) { if (p) return; int x = p[0]; // warn }Robustness
core.StackAddressEscapeCheck that addresses to stack memory do not escape the functionchar const *p; void test() { char const str[] = “string”; p = str; // warn }Robustness
core.uninitialized.ArraySubscriptCheck for uninitialized values used as array subscriptsvoid test() { int i, a[10]; int x = a[i]; // warn: array subscript is undefined }Robustness
cplusplus.NewDeleteCheck for double-free and use-after-free problems. Traces memory managed by new/delete.void f(int *p); void testUseMiddleArgAfterDelete(int *p) { delete p; f(p); // warn: use after free }Robustness
cplusplus.NewDeleteLeaksCheck for memory leaks. Traces memory managed by new/delete.void test() { int *p = new int; } // warnResource Utilization
cplusplus.SelfAssignmentChecks C++ copy and move assignment operators for self assignmentResource Utilization
optin.cplusplus.VirtualCallCheck virtual function calls during construction or destructionRobustness
osx.coreFoundation.CFRetainReleaseCheck for null arguments to CFRetain/CFRelease/CFMakeCollectablevoid test(CFTypeRef p) { if (!p) CFRetain(p); // warn }Robustness
osx.coreFoundation.containers.OutOfBoundsChecks for index out-of-bounds when using ‘CFArray’ APIvoid test() { CFArrayRef A = CFArrayCreate(0, 0, 0, &kCFTypeArrayCallBacks); CFArrayGetValueAtIndex(A, 0); // warn }Robustness
osx.coreFoundation.containers.PointerSizedValuesWarns if ‘CFArray’, ‘CFDictionary’, ‘CFSet’ are created with non-pointer-size valuesvoid test() { int x[] = { 1 }; CFArrayRef A = CFArrayCreate(0, (const void **)x, 1, &kCFTypeArrayCallBacks); // warn }Robustness
osx.NumberObjectConversionCheck for erroneous conversions of objects representing numbers into numbersNSNumber *photoCount = [albumDescriptor objectForKey:@”PhotoCount”]; // Warning: Comparing a pointer value of type ‘NSNumber *’ // to a scalar integer value if (photoCount > 0) { [self displayPhotos]; }Robustness
security.FloatLoopCounterWarn on using a floating point value as a loop counter (CERT: FLP30-C, FLP30-CPP)void test() { for (float x = 0.1f; x <= 1.0f; x += 0.1f) {} // warn }Robustness
security.insecureAPI.UncheckedReturnWarn on uses of functions whose return values must be always checkedvoid test() { setuid(1); // warn }Maintainability
unix.MallocCheck for memory leaks, double free, and use-after-free problems. Traces memory managed by malloc()/free().void test() { int *p = malloc(1); free(p); free(p); // warn: attempt to free released memory }Robustness
unix.MismatchedDeallocatorCheck for mismatched deallocators.// C, C++ void test() { int *p = (int *)malloc(sizeof(int)); delete p; // warn }Robustness
alpha.valist.UninitializedExperimental: Check for usages of uninitialized (or already released) va_lists.Robustness
alpha.valist.UnterminatedExperimental: Check for va_lists which are not released by a va_end call.Robustness

High-level issues

RuleDescriptionExampleKPI
alpha.clone.CloneCheckerExperimental: Reports similar pieces of code.void log(); int max(int a, int b) { // warn log(); if (a > b) return a; return b; } int maxClone(int x, int y) { // similar code here log(); if (x > y) return x; return y; }Maintainability
alpha.core.CallAndMessageUnInitRefArgExperimental: Check for logical errors for function calls and Objective-C message expressions (e.g., uninitialized arguments, null function pointers, and pointer to undefined variables)void test(void) { int t; int &p = t; int &s = p; int &q = s; foo(q); // warn }Accuracy
alpha.core.CastSizeExperimental: Check when casting a malloc’ed type T, whether the size is a multiple of the size of Tvoid test() { int *x = (int *)malloc(11); // warn }Accuracy
alpha.core.CastToStructExperimental: Check for cast from non-struct pointer to struct pointerstruct s {}; void test(int *p) { struct s *ps = (struct s *) p; // warn }Accuracy
alpha.core.ConversionExperimental: Loss of sign/precision in implicit conversionsvoid test(unsigned U, signed S) { if (S > 10) { if (U < S) { } } if (S < -10) { if (U < S) { // warn (loss of sign) } } }Accuracy
alpha.core.FixedAddrExperimental: Check for assignment of a fixed address to a pointervoid test() { int *p; p = (int *) 0x10000; // warn }Maintainability
alpha.core.IdenticalExprExperimental: Warn about unintended use of identical expressions in operators// C void test() { int a = 5; int b = a | 4 | a; // warn: identical expr on both sides }Accuracy
alpha.core.PointerArithmExperimental: Check for pointer arithmetic on locations other than array elementsvoid test() { int x; int *p; p = &x + 1; // warn }Maintainability
alpha.core.PointerSubExperimental: Check for pointer subtractions on two pointers pointing to different memory chunksvoid test() { int x, y; int d = &y – &x; // warn }Accuracy
alpha.core.SizeofPtrExperimental: Warn about unintended use of sizeof() on pointer expressionsstruct s {}; int test(struct s *p) { return sizeof(p); // warn: sizeof(ptr) can produce an unexpected result }Accuracy
alpha.core.TestAfterDivZeroExperimental: Check for division by variable that is later compared against 0. Either the comparison is useless or there is division by zero.void test(int x) { var = 77 / x; if (x == 0) { } // warn }Robustness
alpha.cplusplus.IteratorPastEndExperimental: Check iterators used past endclass A { public: A() { f(); // warn } virtual void f(); }Robustness
alpha.deadcode.UnreachableCodeExperimental: Check unreachable codeint test() { int x = 1; while(x); return x; // warn }Maintainability
alpha.security.ArrayBoundExperimental: Warn about buffer overflows (older checker)void test() { char *s = “”; char c = s[1]; // warn }Robustness
alpha.security.ArrayBoundV2Experimental: Warn about buffer overflowsvoid test() { int buf[100]; int *p = buf; p = p + 99; p[1] = 1; // warn }Robustness
alpha.security.MallocOverflowExperimental: Check for overflows in the arguments to malloc()void test(int n) { void *p = malloc(n * sizeof(int)); // warn }Robustness
alpha.security.ReturnPtrRangeExperimental: Check for an out-of-bound pointer being returned to callersstatic int A[10]; int *test() { int *p = A + 10; return p; // warn }Robustness
alpha.security.taint.TaintPropagationExperimental: Generate taint information used by other checkersvoid test() { char x = getchar(); // ‘x’ marked as tainted system(&x); // warn: untrusted data is passed to a system call }Robustness
alpha.unix.BlockInCriticalSectionExperimental: Check for calls to blocking functions inside a critical sectionRobustness
alpha.unix.ChrootExperimental: Check improper use of chrootvoid f(); void test() { chroot(“/usr/local”); f(); // warn: no call of chdir(“/”) immediately after chroot }Robustness
alpha.unix.cstring.BufferOverlapExperimental: Checks for overlap in two buffer argumentsvoid test() { int a[4] = {0}; memcpy(a + 2, a + 1, 8); // warn }Maintainability
alpha.unix.cstring.NotNullTerminatedExperimental: Check for arguments which are not null-terminating stringsvoid test() { int y = strlen((char *)&test); // warn }Accuracy
alpha.unix.cstring.OutOfBoundsExperimental: Check for out-of-bounds access in string functionsvoid test(char *y) { char x[4]; if (strlen(y) == 4) strncpy(x, y, 5); // warn }Robustness
alpha.unix.PthreadLockExperimental: Simple lock -> unlock checkerpthread_mutex_t mtx; void test() { pthread_mutex_lock(&mtx); pthread_mutex_lock(&mtx); // warn: this lock has already been acquired }Robustness
alpha.unix.SimpleStreamExperimental: Check for misuses of stream APIsvoid test() { FILE *F = fopen(“myfile.txt”, “w”); } // warn: opened file is never closedResource Utilization
alpha.unix.StreamExperimental: Check stream handling functionsvoid test() { FILE *p = fopen(“foo”, “r”); } // warn: opened file is never closedResource Utilization
core.CallAndMessageCheck for logical errors for function calls and Objective-C message expressions (e.g., uninitialized arguments, null function pointers)struct S { int x; }; void f(struct S s); void test() { struct S s; f(s); // warn: passed-by-value arg contain uninitialized data }Accuracy
core.UndefinedBinaryOperatorResultCheck for undefined results of binary operatorsvoid test() { int x; int y = x + 1; // warn: left operand is garbage }Accuracy
core.uninitialized.AssignCheck for assigning uninitialized valuesvoid test() { int x; x |= 1; // warn: left expression is unitialized }Accuracy
core.uninitialized.BranchCheck for uninitialized values used as branch conditionsvoid test() { int x; if (x) // warn return; }Accuracy
core.uninitialized.CapturedBlockVariableCheck for blocks that capture uninitialized valuesvoid test() { int x; ^{ int y = x; }(); // warn }Accuracy
core.uninitialized.UndefReturnCheck for uninitialized values being returned to the callerint test() { int x; return x; // warn }Accuracy
core.VLASizeCheck for declarations of variable length arrays of undefined or zero sizevoid test() { int x; int vla1[x]; // warn: garbage as size }Accuracy
osx.coreFoundation.CFErrorCheck usage of CFErrorRef* parametersvoid test(CFErrorRef *error) { // warn: function accepting CFErrorRef* should have a // non-void return }Understandability
osx.coreFoundation.CFNumberCheck for proper uses of CFNumber APIsCFNumberRef test(unsigned char x) { return CFNumberCreate(0, kCFNumberSInt16Type, &x); // warn: 8 bit integer is used to initialize a 16 bit integer }Understandability
osx.SecKeychainAPICheck for proper uses of Secure Keychain APIsvoid test() { unsigned int *ptr = 0; UInt32 length; SecKeychainItemFreeContent(ptr, &length); // warn: trying to free data which has not been allocated }Robustness
security.insecureAPI.getpwWarn on uses of the ‘getpw’ functionvoid test() { char buff[1024]; getpw(2, buff); // warn }Maintainability
security.insecureAPI.getsWarn on uses of the ‘gets’ functionvoid test() { char buff[1024]; gets(buff); // warn }Maintainability
security.insecureAPI.mkstempWarn when ‘mkstemp’ is passed fewer than 6 X’s in the format stringvoid test() { mkstemp(“XX”); // warn }Maintainability
security.insecureAPI.mktempWarn on uses of the ‘mktemp’ functionvoid test() { char *x = mktemp(“/tmp/zxcv”); // warn: insecure, use mkstemp }Maintainability
security.insecureAPI.randWarn on uses of the ‘rand’, ‘random’, and related functionsvoid test() { random(); // warn }Maintainability
security.insecureAPI.strcpyWarn on uses of the ‘strcpy’ and ‘strcat’ functions – can lead to buffer overflow.void test() { char x[4]; char *y = “abcd”; strcpy(x, y); // warn }Robustness
security.insecureAPI.vforkWarn on uses of the ‘vfork’ functionvoid test() { vfork(); // warn }Maintainability
unix.APICheck calls to various UNIX/Posix functions// Currently the check is performed for apple targets only. void test(const char *path) { int fd = open(path, O_CREAT); // warn: call to ‘open’ requires a third argument when the // ‘O_CREAT’ flag is set }Maintainability
unix.cstring.BadSizeArgCheck the size argument passed into C string functions for common erroneous patternsvoid test() { char dest[3]; strncat(dest, “***”, sizeof(dest)); // warn: potential buffer overflow }Robustness
unix.cstring.NullArgCheck for null pointers being passed as arguments to C string functionsint test() { return strlen(0); // warn }Robustness
unix.MallocSizeofCheck for dubious malloc arguments involving sizeofvoid test() { long *p = malloc(sizeof(short)); // warn: result is converted to ‘long *’, which is // incompatible with operand type ‘short’ free(p); }Accuracy
unix.VforkCheck for proper usage of vforkint test(int x) { pid_t pid = vfork(); // warn if (pid != 0) return 0; switch (x) { case 0: pid = 1; execl(“”, “”, 0); _exit(1); break; case 1: x = 0; // warn: this assignment is prohibited break; case 2: foo(); // warn: this function call is prohibited break; default: return 0; // warn: return is prohibited } while(1); }Maintainability
Returning Local AddressFunction should not return address of local variable because once function exits, all local variables are destroyed. This will affect robustness of code. The solution would be to dynamically allocate memory to a variable to hold the address and pass it to the function as a parameterint* foo(int a,int b)
{
int sum = a + b;

return ∑ /* Non-complaint */
}

int* foo(int a, int b, int* sum)
{
*sum = a + b;
return sum; /* Complaint */
}
Robustness

Medium level issues

RuleDescriptionExampleKPI
alpha.valist.CopyToSelfExperimental: Check for va_lists which are copied onto itself.Maintainability
apiModeling.google.GTestModel gtest assertion APIsMaintainability
core.builtin.BuiltinFunctionsEvaluate compiler builtin functions (e.g., alloca())Maintainability
core.builtin.NoReturnFunctionsEvaluate “panic” functions that are known to not return to the callerMaintainability
core.DynamicTypePropagationGenerate dynamic type informationMaintainability
deadcode.DeadStoresCheck for values stored to variables that are never read afterwardsvoid test() { int x; x = 1; // warn }Resource Utilization
optin.mpi.MPI-CheckerChecks MPI codevoid test() { double buf = 0; MPI_Request sendReq1; MPI_Ireduce(MPI_IN_PLACE, &buf, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD, &sendReq1); } // warn: request ‘sendReq1’ has no matching wait.Maintainability
osx.APICheck for proper uses of various Apple APIsvoid test() { dispatch_once_t pred = 0; dispatch_once(&pred, ^(){}); // warn: dispatch_once uses local }Maintainability
unix.StdCLibraryFunctionsImprove modeling of the C standard library functionsMaintainability
dynamic-castImplementations of dynamic_cast mechanism are unsuitable for use with real-timesystems where low memory usage and determined performance are essential. Dynamic_cast can be replaced with polymorphism, i.e. virtual functions.Compliant code:

struct Base {
virtual ~Base() {}
};

struct Derived: Base {
void name() {}
};


Non-Compliant code:
Base* b1 = new Base;
Derived* d = dynamic_cast(b1);


Robustness
shallow copy assignmentShallow copy assignment and default assignment operator must be avoided when dynamically allocated resources are involved.class Shape {
//default assignment operator
char *ptr; //Non-Compliant
};


class Node {
char *str;
public:

Node& operator=(const Node& pOther){
(*this).str = pOther.str; //Non-Compliant
return *this;
}
};


class Foo {
char *bar;
public:
Foo& operator=(const Foo& pOther) {
bar = nullptr; //Compliant
return *this;
}
};


class Point {

int* xPtr;
int* yPtr;

public:

Point& operator=(const Point& pOther) {
xPtr = pOther.xPtr; //Non-Compliant
yPtr = new int(); //Compliant
return *this;
}
};
Robustness
shallow copy constructShallow copy and default copy constructor must be avoided when dynamically allocated resources are involved.
class Shape {
//default copy constructor
char *ptr; //Non-Compliant
};


class Node {
char *str;
public:
Node(const Node& pOther) {
(*this).str = pOther.str; //Non-Compliant
}
};


class Foo {
char *bar;
public:
Foo(const Foo& pOther) {
bar = nullptr; //Compliant
}
};


class Point {

int* xPtr;
int* yPtr;

public:

Point(const Point& pOther) {
xPtr = pOther.xPtr; //Non-Compliant
yPtr = new int(); //Compliant
}
};
Robustness

Low level issues

RuleDescriptionExampleKPI
debug.AnalysisOrderPrint callbacks that are called during analysis in orderMaintainability
debug.ConfigDumperDump config tableMaintainability
debug.DumpBugHashDump the bug hash for all statements.Maintainability
debug.DumpCallGraphDisplay Call GraphMaintainability
debug.DumpCallsPrint calls as they are traversed by the engineMaintainability
debug.DumpCFGDisplay Control-Flow GraphsMaintainability
debug.DumpDominatorsPrint the dominance tree for a given CFGMaintainability
debug.DumpLiveVarsPrint results of live variable analysisMaintainability
debug.DumpTraversalPrint branch conditions as they are traversed by the engineMaintainability
debug.ExprInspectionCheck the analyzer’s understanding of expressionsMaintainability
debug.StatsEmit warnings with analyzer statisticsMaintainability
debug.TaintTestMark tainted symbols as such.Maintainability
debug.ViewCallGraphView Call Graph using GraphVizMaintainability
debug.ViewCFGView Control-Flow Graphs using GraphVizMaintainability
debug.ViewExplodedGraphView Exploded Graphs using GraphVizMaintainability
llvm.ConventionsCheck code for LLVM codebase conventionsMaintainability
llvm.ConventionsCheck code for LLVM codebase conventionsMaintainability
empty-catch The catch block should not be vacant. If you catch an exception, ensure you process it and avoid an unexpected behavior in the system.Complaint Code:
int x = -1;
try
{
if (x < 0)
{
throw x;
}
}
catch (int x )
{
cout<<"Exception caught";
}



Non-Complaint Code:
int x = -1;
try
{
if (x < 0)
{
throw x;
}
}
catch (int x )
{

}
Maintainability
char signednessSpecify the signess of char explicitly. Else, the compiler which is not portable can cause subtle errors if a char is unexpectedly "signed" instead of unsigned.Complaint Code:
unsigned char abc;
signed char xyz;

Non-Complaint Code:

char abc;
char xyz;
Maintainability
fixed size memory operation Memory operations should not be called with a hard-coded value instead of using a macro or sizeof() or constant. This can be quickly forgotten while changing the size.

Complaint Code:
char str1[] = "abc";
char str2[] = "xyz";
memcpy (str1, str2, sizeof(str2));

Non-Complaint Code:



char str1[] = "abc";
char str2[] = "xyz";
memcpy (str1, str2, 4);
Maintainability
hidden parameterA function declares a variable with the same name as a parameter, which is then "hidden".Complaint Code:



int add(int a, int b)
{
int a1;
int x = 1;



if(x == 1)
{
int b1;
}
return 0;
}




Non-Complaint Code:



int add(int a, int b)
{
int a; /* reuse of 'a' */
int x = 1;



if(x == 1)
{
int b; /* reuse of 'b' */
}
return 0;
}
Maintainability
hidden parameterA function declares a variable with the same name as a parameter, which is then "hidden".Complaint Code:



int add(int a, int b)
{
int a1;
int x = 1;



if(x == 1)
{
int b1;
}
return 0;
}




Non-Complaint Code:



int add(int a, int b)
{
int a; /* reuse of 'a' */
int x = 1;



if(x == 1)
{
int b; /* reuse of 'b' */
}
return 0;
}
Maintainability
deactivated codeCode segments that are permanently disabled by the preprocessor. Indication of inactive code. Only cases with condition would be OK.Non-complaint code:

#if 0 /* Non-Complaint */
#if 1 /* Non-Complaint */

Complaint Code:

#if 0 == xyz /* Complaint */

Maintainability
Assignment Operator Non-Const ArgAssignment operator must not have non-const argument.Non-complaint code:

class Alpha {

const Alpha& operator=(Alpha& pOther) /* Non-Compliant - Argument must be of type "const Alpha&" */
{
//assignment operation
}
};

Complaint Code:
struct Beta {

const Beta& operator=(Beta& pOther) /* Non-Compliant - Argument must be of type "const Beta&" */
{
//assignment operation
}
};

Robustness
Assignment Operator Returns VoidAssignment operator must return a valid object. Return type should not be void.Non-Complaint code:

class Alpha {

void operator=(const Alpha& pOther) /* Non-Compliant - Return type must not be "void" */
{
//assignment operation
}
};


Complaint Code:


struct Beta {

void operator=(const Beta& pOther) /* Non-Compliant - Return type must not be "void" */
{
//assignment operation
}
};
Robustness
Assignment Operator Non-Const ReturnAssignment operator must return const qualified valid object.Non-Complaint code:

class Alpha {

Alpha& operator=(const Alpha& pOther) /* Non-Compliant - Return type must be "const Alpha&" */
{
//assignment operation
return *this;
}
};


Complaint Code:


struct Beta {

Beta& operator=(const Beta& pOther) /* Non-Compliant - Return type must be "const Beta&" */
{
//assignment operation
return *this;
}
};
Robustness

CPP Check Issues

Cppcheck is a static analysis tool for C/C++ code providing unique code analysis to detect bugs and focusing on detecting undefined behaviour and dangerous coding constructs. Visit their website site for more information.


Critical level issues

RuleDescriptionKPI
arrayIndexOutOfBoundsArray ‘array[2]’ index array[1][1] out of bounds.Robustness
assignBoolToPointerBoolean value assigned to pointer.Robustness
autoVariablesDangerous assignment – the function parameter is assigned the address of a local auto-variable. Local auto-variables are reserved from the stack which is freed when the function ends. So the pointer to a local variable is invalid after the function ends.Robustness
autovarInvalidDeallocationThe deallocation of an auto-variable results in undefined behaviour. You should only free memory that has been allocated dynamically.Robustness
boostForeachErrorBOOST_FOREACH caches the end() iterator. It’s undefined behavior if you modify the container inside.Robustness
bufferAccessOutOfBoundsBuffer is accessed out of bounds: bufferResource Utilization
coutCerrMisusageInvalid usage of output stream: ‘<< std::cout'.Robustness
deadpointerDead pointer usage. Pointer ‘pointer’ is dead if it has been assigned ‘&x’ at line 0.Robustness
deallocDeallocDeallocating a deallocated pointer: varnameRobustness
deallocretReturning/dereferencing ‘p’ after it is deallocated / releasedRobustness
deallocuseDereferencing ‘varname’ after it is deallocated / releasedRobustness
doubleFreeMemory pointed to by ‘varname’ is freed twice.Resource Utilization
eraseDereferenceThe iterator ‘iter’ is invalid before being assigned. Dereferencing or comparing it with another iterator is invalid operation.Robustness
floatConversionOverflowUndefined behaviour: float (1e+100) conversion overflow.Resource Utilization
insecureCmdLineArgsBuffer overrun possible for long command line arguments.Resource Utilization
integerOverflowSigned integer overflow for expression ”.Resource Utilization
invalidFunctionArgInvalid func_name() argument nr 1Understandability
invalidFunctionArgBoolInvalid func_name() argument nr 1. A non-boolean value is required.Understandability
invalidIterator1Invalid iterator: iteratorUnderstandability
invalidIterator2After push_back|push_front|insert() the iterator ‘iterator’ may be invalid.Understandability
invalidPointerInvalid pointer ‘pointer’ after push_back().Understandability
invalidScanfFormatWidthWidth 5 given in format string (no. 10) is larger than destination buffer ‘[0]’ use %-1s to prevent overflowing it.Resource Utilization
IOWithoutPositioningRead and write operations without a call to a positioning function (fseek fsetpos or rewind) or fflush in between result in undefined behaviour.Resource Utilization
iteratorsSame iterator is used with different containers ‘container1’ and ‘container2’.Resource Utilization
leakNoVarFunctionCallAllocation with funcName funcName doesn’t release it.Resource Utilization
leakReturnValNotUsedReturn value of allocation function ‘funcName’ is not stored.Maintainability
mallocOnClassErrorMemory for class instance allocated with malloc() but class a std::string. This is unsafe since no constructor is called and class members remain uninitialized. Consider using ‘new’ instead.Resource Utilization
memleakMemory leak: varnameResource Utilization
memleakOnReallocCommon realloc mistake: ‘varname’ nulled but not freed upon failureResource Utilization
memsetClassUsing ‘memfunc’ on class that contains a classname is unsafe because constructor destructor and copy operator calls are omitted. These are necessary for this non-POD type to ensure that a valid object is created.Resource Utilization
memsetClassReferenceUsing ‘memfunc’ on class that contains a reference.Resource Utilization
mismatchAllocDeallocMismatching allocation and deallocation: varnameResource Utilization
mismatchingContainersIterators of different containers are used together.Robustness
mismatchSizeThe allocated size sz is not a multiple of the underlying type’s size.Resource Utilization
negativeArraySizeDeclaration of array ” with negative size is undefined behaviourMaintainability
negativeIndexArray index -1 is out of bounds.Maintainability
negativeMemoryAllocationSizeMemory allocation size is negative.Negative allocation size has no specified behaviour.Resource Utilization
nullPointerNull pointer dereferenceRobustness
nullPointerArithmeticOverflow in pointer arithmetic NULL pointer is subtracted.Robustness
operatorEqMissingReturnStatementNo ‘return’ statement in non-void function causes undefined behavior.Robustness
outOfBoundsindex is out of bounds: Supplied size 2 is larger than actual size 1.Robustness
pointerArithBoolConverting pointer arithmetic result to bool. The boolean result is always true unless there is pointer arithmetic overflow and overflow is undefined behaviour. Probably a dereference is forgotten.Maintainability
preprocessorErrorDirective#error messageUnderstandability
raceAfterInterlockedDecrementRace condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.Robustness
readWriteOnlyFileRead operation on a file that was opened only for writing.Maintainability
resourceLeakResource leak: varnameResource Utilization
returnAddressOfAutoVariableAddress of an auto-variable returned.Robustness
returnAddressOfFunctionParameterAddress of the function parameter ‘parameter’ becomes invalid after the function exits because function parameters are stored on the stack which is freed when the function exits. Thus the returned value is invalid.Robustness
returnLocalVariablePointer to local array variable returned.Robustness
returnReferenceReference to auto variable returned.Robustness
returnTempReferenceReference to temporary returned.Robustness
selfInitializationMember variable ‘var’ is initialized by itself.Robustness
shiftNegativeShifting by a negative value is undefined behaviourRobustness
shiftTooManyBitsShifting 32-bit value by 64 bits is undefined behaviourRobustness
shiftTooManyBitsSignedShifting signed 32-bit value by 31 bits is undefined behaviourRobustness
sprintfOverlappingDataThe variable ‘varname’ is used both as a parameter and as destination in s[n]printf(). The origin and destination buffers overlap. Quote from glibc (C-library) documentation (http://www.gnu.org/software/libc/manual/html_mono/libc.html#Formatted-Output-Functions): If copying takes place between objects that overlap as a result of a call to sprintf() or snprintf() the results are undefined.””Robustness
stlBoundariesIterator compared with operator<. This is dangerous since the order of items in the container is not guaranteed. One should use operator!= instead to compare iterators.Robustness
stlcstrDangerous usage of c_str(). The c_str() return value is only valid until its string is deleted.Robustness
stlOutOfBoundsWhen i==foo.size() foo[i] is out of bounds.Robustness
stringLiteralWriteModifying string literal directly or indirectly is undefined behaviour.Robustness
strPlusCharUnusual pointer arithmetic. A value of type ‘char’ is added to a string literal.Robustness
throwInNoexceptFunctionException thrown in function declared not to throw exceptions.Understandability
uninitdataMemory is allocated but not initialized: varnameResource Utilization
uninitstringDangerous usage of ‘varname’ (strncpy doesn’t always null-terminate it).Robustness
uninitStructMemberUninitialized struct member: a.bRobustness
uninitvarUninitialized variable: varnameRobustness
unknownEvaluationOrderExpression ‘x = x++;’ depends on order of evaluation of side effectsRobustness
useAutoPointerArrayObject pointed by an ‘auto_ptr’ is destroyed using operator ‘delete’. This means that you should only use ‘auto_ptr’ for pointers obtained with operator ‘new’. This excludes arrays which are allocated by operator ‘new[]’ and must be deallocated by operator ‘delete[]’.Robustness
useAutoPointerContainerAn element of container must be able to be copied but ‘auto_ptr’ does not fulfill this requirement. You should consider to use ‘shared_ptr’ or ‘unique_ptr’. It is suitable for use in containers because they no longer copy their values they move them.Robustness
useAutoPointerMallocObject pointed by an ‘auto_ptr’ is destroyed using operator ‘delete’. You should not use ‘auto_ptr’ for pointers obtained with function ‘malloc’. This means that you should only use ‘auto_ptr’ for pointers obtained with operator ‘new’. This excludes use C library allocation functions (for example ‘malloc’) which must be deallocated by the appropriate C library function.Robustness
useClosedFileUsed file that is not opened.Robustness
va_end_missingva_list ‘vl’ was opened but not closed by va_end().Resource Utilization
va_list_usedBeforeStartedva_list ‘vl’ used before va_start() was called.Maintainability
va_start_referencePassedUsing reference ‘arg1’ as parameter for va_start() results in undefined behaviour.Robustness
va_start_subsequentCallsva_start() or va_copy() called subsequently on ‘vl’ without va_end() in between.Maintainability
virtualDestructorClass ‘Base’ which is inherited by class ‘Derived’ does not have a virtual destructor. If you destroy instances of the derived class by deleting a pointer that points to the base class only the destructor of the base class is executed. Thus dynamic memory that is managed by the derived class could leak. This can be avoided by adding a virtual destructor to the base class.Resource Utilization
writeReadOnlyFileWrite operation on a file that was opened only for reading.Robustness
wrongPipeParameterSizeThe pipe()/pipe2() system command takes an argument which is an array of exactly two integers.12The variable ‘varname’ is an array of size dimension which does not match.Maintainability
wrongPrintfScanfArgNumprintf format string requires 3 parameters but only 2 are given.Maintainability
zerodivDivision by zero.Robustness

High level issues

RuleDescriptionKPI
accessForwardedAccess of forwarded variable v.Robustness
accessMovedAccess of moved variable v.Robustness
argumentSizeThe array ‘array’ is too small the function ‘function’ expects a bigger one.Maintainability
arrayIndexOutOfBoundsCondArray ‘x[10]’ accessed at index 20 which is out of bounds. Otherwise condition ‘y==20’ is redundant.Robustness
assertWithSideEffectNon-pure function: ‘function’ is called inside assert statement. Assert statements are removed from release builds so the code inside assert statement is not executed. If the code is needed also in release builds this is a bug.Robustness
assignmentInAssertVariable ‘var’ is modified insert assert statement. Assert statements are removed from release builds so the code inside assert statement is not executed. If the code is needed also in release builds this is a bug.Robustness
badBitmaskCheckResult of operator ‘|’ is always true if one operand is non-zero. Did you intend to use ‘&’?Accuracy
bufferNotZeroTerminatedThe buffer ‘buffer’ is not null-terminated after the call to strncpy(). This will cause bugs later in the code if the code assumes the buffer is null-terminated.Robustness
charBitOpWhen using ‘char’ variables in bit operations sign extension can generate unexpected results. For example:12 char c = 0x80;12 int i = 0 | c;12 if (i & 0x8000)12 printf(not expected”)Robustness
charLiteralWithCharPtrCompareChar literal compared with pointer ‘foo’. Did you intend to dereference it?Accuracy
checkCastIntToCharAndBackWhen saving func_name() return value in char variable there is loss of precision. When func_name() returns EOF this value is truncated. Comparing the char variable with EOF can have unexpected results. For instance a loop while (EOF != (c = func_name())Robustness
clarifyStatementA statement like ‘*A++;’ might not do what you intended. Postfix ‘operator++’ is executed before ‘operator*’. Thus the dereference is meaningless. Did you intend to write ‘(*A)++;’?Robustness
compareBoolExpressionWithIntComparison of a boolean expression with an integer other than 0 or 1.Accuracy
comparisonFunctionIsAlwaysTrueOrFalseThe function isless is designed to compare two variables. Calling this function with one variable (varName) for both parameters leads to a statement which is always false.Accuracy
constStatementRedundant code: Found a statement that begins with type constant.Maintainability
copyCtorAndEqOperatorThe class ‘class’ has ‘operator=’ but lack of ‘copy constructor’.Maintainability
derefInvalidIteratorMake sure to check that the iterator is valid before dereferencing it – not after.Maintainability
divideSizeofDivision of result of sizeof() on pointer type. sizeof() returns the size of the pointer not the size of the memory area it points to.Robustness
duplInheritedMemberThe class ‘class’ defines member variable with name ‘variable’ also defined in its parent class ‘class’.Understandability
exceptDeallocThrowException thrown in invalid state ‘p’ points at deallocated memory.Robustness
exceptThrowInDestructorThe class Class is not safe because its destructor throws an exception. If Class is used and an exception is thrown that is caught in an outer scope the program will terminate.Robustness
funcArgOrderDifferentFunction ‘function’ argument order different: declaration ” definition ”Accuracy
ignoredReturnValueReturn value of function malloc() is not used.Maintainability
incompleteArrayFillThe array ‘buffer’ is filled incompletely. The function ‘memset()’ needs the size given in bytes but an element of the given array is larger than one byte. Did you forget to multiply the size with ‘sizeof(*buffer)’?Resource Utilization
incorrectLogicOperatorLogical disjunction always evaluates to true: foo > 3 && foo < 4. Are these conditions necessary? Did you intend to use && instead? Are the numbers correct? Are you comparing the correct variables?Understandability
incorrectStringBooleanErrorConversion of string literal Hello World” to bool always evaluates to true.”Understandability
incorrectStringCompareString literal Hello World” doesn’t match length argument for substr().”Understandability
invalidLengthModifierError‘I’ in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.Understandability
invalidPrintfArgType_float%f in format string (no. 1) requires ‘double’ but the argument type is Unknown.Maintainability
invalidPrintfArgType_int%X in format string (no. 1) requires ‘unsigned int’ but the argument type is Unknown.Maintainability
invalidPrintfArgType_n%n in format string (no. 1) requires ‘int *’ but the argument type is Unknown.Maintainability
invalidPrintfArgType_p%p in format string (no. 1) requires an address but the argument type is Unknown.Maintainability
invalidPrintfArgType_s%s in format string (no. 1) requires ‘char *’ but the argument type is Unknown.Maintainability
invalidPrintfArgType_sint%i in format string (no. 1) requires ‘int’ but the argument type is Unknown.Maintainability
invalidPrintfArgType_uint%u in format string (no. 1) requires ‘unsigned int’ but the argument type is Unknown.Maintainability
invalidscanfscanf() without field width limits can crash with huge input data. Add a field width specifier to fix this problem.1212Sample program that can crash:1212#include 12int main()12{12 char c[5];12 scanf(%s” c)Robustness
invalidScanfArgType_float%f in format string (no. 1) requires ‘float *’ but the argument type is Unknown.Maintainability
invalidScanfArgType_int%d in format string (no. 1) requires ‘int *’ but the argument type is Unknown.Maintainability
invalidScanfArgType_s%s in format string (no. 1) requires a ‘char *’ but the argument type is Unknown.Maintainability
invalidTestForOverflowInvalid test for overflow ‘x + u < x'. Condition is always false unless there is overflow and overflow is UB.Accuracy
leakUnsafeArgAllocUnsafe allocation. If funcName() throws memory could be leaked. Use make_shared() instead.Resource Utilization
literalWithCharPtrCompareString literal compared with variable ‘foo’. Did you intend to use strcmp() instead?Robustness
mallocOnClassWarningMemory for class instance allocated with malloc() but class provides constructors. This is unsafe since no constructor is called and class members remain uninitialized. Consider using ‘new’ instead.Resource Utilization
memsetValueOutOfRangeThe 2nd memset() argument ‘varname’ doesn’t fit into an ‘unsigned char’. The 2nd parameter is passed as an ‘int’ but the function fills the block of memory using the ‘unsigned char’ conversion of this value.Resource Utilization
memsetZeroBytesmemset() called to fill 0 bytes. The second and third arguments might be inverted. The function memset ( void * ptr int value size_t num ) sets the first num bytes of the block of memory pointed by ptr to the specified value.Resource Utilization
moduloAlwaysTrueFalseComparison of modulo result is predetermined because it is always less than 1.Understandability
multiplySizeofMultiplying sizeof() with sizeof() indicates a logic error.Understandability
nullPointerDefaultArgPossible null pointer dereference if the default parameter value is used: pointerRobustness
nullPointerRedundantCheckEither the condition is redundant or there is possible null pointer dereference: pointer.Robustness
operatorEqToSelfoperator=’ should check for assignment to self to ensure that each block of dynamically allocated memory is owned and managed by only one instance of the class.Robustness
operatorEqVarErrorMember variable ‘classname::’ is not assigned a value in ‘classname::operator=’.Robustness
oppositeInnerConditionOpposite conditions in nested ‘if’ blocks lead to a dead code block.Maintainability
pointerSizeSize of pointer ‘varname’ used instead of size of its data. This is likely to lead to a buffer overflow. You probably intend to write ‘sizeof(*varname)’.Robustness
possibleBufferAccessOutOfBoundsPossible buffer overflow if strlen(source) is larger than or equal to sizeof(destination). The source buffer is larger than the destination buffer so there is the potential for overflowing the destination buffer.Robustness
publicAllocationErrorPossible leak in public function. The pointer ‘varname’ is not deallocated before it is allocated.Resource Utilization
redundantAssignInSwitchVariable ‘var’ is reassigned a value before the old one has been used. ‘break;’ missing?Maintainability
redundantCopyInSwitchBuffer ‘var’ is being written before its old content has been used. ‘break;’ missing?Maintainability
seekOnAppendedFileRepositioning operation performed on a file opened in append mode has no effect.Maintainability
selfAssignmentRedundant assignment of ‘varname’ to itself.Maintainability
signConversionSuspicious code: sign conversion of var in calculation even though var can have a negative valueAccuracy
signedCharArrayIndexSigned ‘char’ type used as array index. If the value can be greater than 127 there will be a buffer underflow because of sign extension.Robustness
sizeArgumentAsCharThe size argument is given as a char constant.Maintainability
sizeofCalculationFound calculation inside sizeof().Understandability
sizeofDivisionMemfuncDivision by result of sizeof(). memset() expects a size in bytes did you intend to multiply instead?Accuracy
sizeofsizeofCalling sizeof for ‘sizeof looks like a suspicious code and most likely there should be just one ‘sizeof’. The current code is equivalent to ‘sizeof(size_t)’Maintainability
sizeofwithnumericparameterIt is unusual to use a constant value with sizeof. For example ‘sizeof(10)’ returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 10. ‘sizeof(‘A’)’ and ‘sizeof(char)’ can return different results.Robustness
sizeofwithsilentarraypointerUsing ‘sizeof’ for array given as function argument returns the size of a pointer. It does not return the size of the whole array in bytes as might be expected. For example this code:12 int f(char a[100]) {12 return sizeof(a);12 }12returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 100 (the size of the array in bytes).Accuracy
staticStringCompareThe compared strings ‘str1’ and ‘str2’ are always unequal. Therefore the comparison is unnecessary and looks suspicious.Understandability
stlIfFindSuspicious condition. The result of find() is an iterator but it is not properly checked.Robustness
StlMissingComparisonThe iterator incrementing is suspicious – it is incremented at line and then at line . The loop might unintentionally skip an element in the container. There is no comparison between these increments to prevent that the iterator is incremented beyond the end.Robustness
stringCompareThe compared strings ‘varname1’ and ‘varname2’ are identical. This could be a logic bug.Maintainability
strncatUsageAt most strncat appends the 3rd parameter’s amount of characters and adds a terminating null byte.12The safe way to use strncat is to subtract one from the remaining space in the buffer and use it as 3rd parameter.Source: http://www.cplusplus.com/reference/cstring/strncat/12Source: http://www.opensource.apple.com/source/Libc/Libc-167/gen.subproj/i386.subproj/strncat.cRobustness
suspiciousCaseUsing an operator like ‘||’ in a case label is suspicious. Did you intend to use a bitwise operator multiple case labels or if/else instead?Accuracy
suspiciousEqualityComparisonFound suspicious equality comparison. Did you intend to assign a value instead?Accuracy
suspiciousSemicolonSuspicious use of ; at the end of ” statement.Accuracy
terminateStrncpyIf the source string’s size fits or exceeds the given size strncpy() does not add a zero at the end of the buffer. This causes bugs later in the code if the code assumes buffer is null-terminated.Robustness
thisSubtractionSuspicious pointer subtraction. Did you intend to write ‘->’?Accuracy
uninitMemberVarMember variable ‘classname::varname’ is not initialized in the constructor.Robustness
unusedLabelSwitchLabel ” is not used. Should this be a ‘case’ of the enclosing switch()?Understandability
useAutoPointerCopystd::auto_ptr’ has semantics of strict ownership meaning that the ‘auto_ptr’ instance is the sole entity responsible for the object’s lifetime. If an ‘auto_ptr’ is copied the source looses the reference.Robustness
uselessAssignmentPtrArgAssignment of function parameter has no effect outside the function. Did you forget dereferencing it?Accuracy
uselessCallsComparestd::string::find()’ returns zero when given itself as parameter (str.find(str)). As it is currently the code is inefficient. It is possible either the string searched (‘str’) or searched for (‘str’) is wrong.Efficiency
uselessCallsEmptyIneffective call of function ’empty()’. Did you intend to call ‘clear()’ instead?Resource Utilization
uselessCallsRemoveThe return value of std::remove() is ignored. This function returns an iterator to the end of the range containing those elements that should be kept. Elements past new end remain valid but with unspecified values. Use the erase method of the container to delete them.Resource Utilization
va_start_wrongParameter‘arg1’ given to va_start() is not last named argument of the function. Did you intend to pass ‘arg2’?Accuracy
wrongmathcallPassing value ‘#’ to #() leads to implementation-defined result.Understandability
wrongPrintfScanfParameterPositionErrorprintf: referencing parameter 2 while 1 arguments givenUnderstandability
zerodivcondEither the condition is redundant or there is division by zero at line 0.Robustness

Medium level issues

RuleDescriptionKPI
arithOperationsOnVoidPointervarname’ is of type ‘vartype’. When using void pointers in calculations the behaviour is undefined. Arithmetic operations on ‘void *’ is a GNU C extension which defines the ‘sizeof(void)’ to be 1.Robustness
AssignmentAddressToIntegerAssigning a pointer to an integer (int/long/etc) is not portable across different platforms and compilers. For example in 32-bit Windows and linux they are same width but in 64-bit Windows and linux they are of different width. In worst case you end up assigning 64-bit address to 32-bit integer. The safe way is to store addresses only in pointer types (or typedefs like uintptr_t).Portability
AssignmentIntegerToAddressAssigning an integer (int/long/etc) to a pointer is not portable across different platforms and compilers. For example in 32-bit Windows and linux they are same width but in 64-bit Windows and linux they are of different width. In worst case you end up assigning 64-bit integer to 32-bit pointer. The safe way is to store addresses only in pointer types (or typedefs like uintptr_t).Portability
CastAddressToIntegerAtReturnReturning an address value in a function with integer (int/long/etc) return type is not portable across different platforms and compilers. For example in 32-bit Windows and Linux they are same width but in 64-bit Windows and Linux they are of different width. In worst case you end up casting 64-bit address down to 32-bit integer. The safe way is to always return an integer.Portability
CastIntegerToAddressAtReturnReturning an integer (int/long/etc) in a function with pointer return type is not portable across different platforms and compilers. For example in 32-bit Windows and Linux they are same width but in 64-bit Windows and Linux they are of different width. In worst case you end up casting 64-bit integer down to 32-bit pointer. The safe way is to always return a pointer.Portability
fflushOnInputStreamfflush() called on input stream ‘stdin’ may result in undefined behaviour on non-linux systems.Portability
functionStaticThe member function ‘class::function’ can be made a static function. Making a function static can bring a performance benefit since no ‘this’ instance is passed to the function. This change should not cause compiler errors but it does not necessarily make sense conceptually. Think about your design and the task of the function first – is it a function that must not access members of class instances?Efficiency
invalidPointerCastCasting between float* and double* which have an incompatible binary data representation.Portability
memsetClassFloatUsing memset() on class which contains a floating point number. This is not portable because memset() sets each byte of a block of memory to a specific value and the actual representation of a floating-point value is implementation defined. Note: In case of an IEEE754-1985 compatible implementation setting all bits to zero results in the value 0.0.Portability
memsetFloatThe 2nd memset() argument ‘varname’ is a float its representation is implementation defined. memset() is used to set each byte of a block of memory to a specific value and the actual representation of a floating-point value is implementation defined.Portability
passedByValueParameter ‘parametername’ is passed by value. It could be passed as a (const) reference which is usually faster and recommended in C++.Efficiency
pointerOutOfBoundsUndefined behaviour pointer arithmetic ” is out of bounds. From chapter 6.5.6 in the C specification:12When an expression that has integer type is added to or subtracted from a pointer ..” and then “If both the pointer operand and the result point to elements of the same array object or one past the last element of the array object the evaluation shall not produce an overflowPortability
postfixOperatorPrefix ++/– operators should be preferred for non-primitive types. Pre-increment/decrement can be more efficient than post-increment/decrement. Post-increment/decrement usually involves keeping a copy of the previous value around and adds a little extra code.Efficiency
redundantCopyBuffer ‘var’ is being written before its old content has been used.Maintainability
redundantCopyLocalConstThe const variable ‘varname’ is assigned a copy of the data. You can avoid the unnecessary data copying by converting ‘varname’ to const reference.Resource Utilization
shiftNegativeLHSShifting a negative value is technically undefined behaviourRobustness
sizeofDereferencedVoidPointer*varname’ is of type ‘void’ the behaviour of ‘sizeof(void)’ is not covered by the ISO C standard. A value for ‘sizeof(void)’ is defined only as part of a GNU C extension which defines ‘sizeof(void)’ to be 1.Robustness
sizeofVoidBehaviour of ‘sizeof(void)’ is not covered by the ISO C standard. A value for ‘sizeof(void)’ is defined only as part of a GNU C extension which defines ‘sizeof(void)’ to be 1.Robustness
stlcstrParamThe conversion from const char* as returned by c_str() to std::string creates an unnecessary string copy. Solve that by directly passing the string.Efficiency
stlcstrReturnThe conversion from const char* as returned by c_str() to std::string creates an unnecessary string copy. Solve that by directly returning the string.Efficiency
stlIfStrFindEither inefficient or wrong usage of string::find(). string::compare() will be faster if string::find’s result is compared with 0 because it will not scan the whole string. If your intention is to check that there are no findings in the string you should compare with std::string::npos.Efficiency
stlSizeChecking for ‘list’ emptiness might be inefficient. Using list.empty() instead of list.size() can be faster. list.size() can take linear time but list.empty() is guaranteed to take constant time.Efficiency
unknownSignCharArrayIndexchar’ type used as array index. Values greater that 127 will be treated depending on whether ‘char’ is signed or unsigned on target platform.Robustness
useInitializationListWhen an object of a class is created the constructors of all member variables are called consecutively in the order the variables are declared even if you don’t explicitly write them to the initialization list. You could avoid assigning ‘variable’ a value by passing the value to the constructor in the initialization list.Efficiency
uselessCallsSubstrIneffective call of function ‘substr’ because it returns a copy of the object. Use operator= instead.Accuracy
uselessCallsSwapThe ‘swap()’ function has no logical effect when given itself as parameter (str.swap(str)). As it is currently the code is inefficient. Is the object or the parameter wrong here?Efficiency
varFuncNullUBPassing NULL after the last typed argument to a variadic function leads to undefined behaviour.12The C99 standard in section 7.15.1.1 states that if the type used by va_arg() is not compatible with the type of the actual next argument (as promoted according to the default argument promotions) the behavior is undefined.12The value of the NULL macro is an implementation-defined null pointer constant (7.17) which can be any integer constant expression with the value 0 or such an expression casted to (void*) (6.3.2.3). This includes values like 0 0L or even 0LL.12In practice on common architectures this will cause real crashes if sizeof(int) != sizeof(void*) and NULL is defined to 0 or any other null pointer constant that promotes to int.12To reproduce you might be able to use this little code example on 64bit platforms. If the output includes ERROR” the sentinel had only 4 out of 8 bytes initialized to zero and was not detected as the final argument to stop argument processing via va_arg(). Changing the 0 to (void*)0 or 0L will make the “ERROR” output go away.12#include 12#include 1212void f(char *s …) {12 va_list apRobustness
misra-c2012-1.3There shall be no occurrence of undefined or critical unspecified behaviorRobustness
misra-c2012-2.1A project shall not contain unreachable codeRobustness
misra-c2012-2.2There shall be no dead codeRobustness
misra-c2012-2.4A project should not contain unused tag declarationsRobustness
misra-c2012-2.6A function should not contain unused label declarationsRobustness
misra-c2012-3.1The character sequences /* an // shall not be used within a commentRobustness
misra-c2012-4.1Octal and hexadecimal escape sequences shall be terminatedRobustness
misra-c2012-5.1External identifiers shall be distinctRobustness
misra-c2012-5.3An identifier declared in an inner scope shall not hide an identifier declared in an outer scopeRobustness
misra-c2012-5.4Macro identifiers shall be distinctRobustness
misra-c2012-5.5Identifiers shall be distinct from macro namesRobustness
misra-c2012-7.1Octal constants shall not be usedRobustness
misra-c2012-7.3The lowercase character ‘l’ shall not be used in a literal suffixRobustness
misra-c2012-8.3All declarations of an object or function shall use the same names and type qualifiersRobustness
misra-c2012-8.11When an array with external linkage is declared, its size should be explicitly specifiedRobustness
misra-c2012-8.12Within an enumerator list, the value of an implicitly-specified enumeration constant shall be uniqueRobustness
misra-c2012-8.14The restrict type qualifier shall not be usedRobustness
misra-c2012-9.1The value of an object with automatic storage duration shall not be read before it has been setRobustness
misra-c2012-9.5Where designated initializers are used to initialize an array object the size of the array shall be specified explicitlyRobustness
misra-c2012-10.4Both operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type categoryRobustness
misra-c2012-10.6The value of a composite expression shall not be assigned to an object with wider essential typeRobustness
misra-c2012-10.8The value of a composite expression shall not be cast to a different essential type category or a wider essential typeRobustness
misra-c2012-11.3A cast shall not be performed between a pointer to object type and a pointer to a different object typeRobustness
misra-c2012-11.4A conversion should not be performed between a pointer to object and an integer typeRobustness
misra-c2012-11.5A conversion should not be performed from pointer to void into pointer to objectRobustness
misra-c2012-11.6A cast shall not be performed between pointer to void and an arithmetic typeRobustness
misra-c2012-11.7A cast shall not be performed between pointer to object and a noninteger arithmetic typeRobustness
misra-c2012-11.8A cast shall not remove any const or volatile qualification from the type pointed to by a pointerRobustness
misra-c2012-11.9The macro NULL shall be the only per mitted form of integer null pointer constantRobustness
misra-c2012-12.1The precedence of operators within expressions should be made explicitRobustness
misra-c2012-12.2The right-hand operand of a shift operator shall lie in the range zero to one less than the width in bits of the essential type of the left-hand operandRobustness
misra-c2012-12.3The comma operator should not be usedRobustness
misra-c2012-12.4Evaluation of constant expressions should not lead to unsigned integer wrap-aroundRobustness
misra-c2012-13.1Initializer lists shall not contain persistent side effectsRobustness
misra-c2012-13.2The value of an expression and its persistent side effects shall be the same under all permitted evaluation ordersRobustness
misra-c2012-13.3A full expression containing an increment (++) or decrement (–) operator should have no other potential side effects other than that caused by the increment or decrement operatorRobustness
misra-c2012-13.4The result of an assignment operator should not be usedRobustness
misra-c2012-13.5The right-hand operand of a logical && or || operator shall not contain persistent side effectsRobustness
misra-c2012-13.6The operand of the sizeof operator shall not contain any expression which has potential side effectsRobustness
misra-c2012-14.1A loop counter shall not have essentially floating typeRobustness
misra-c2012-14.2A for loop shall be well-formedRobustness
misra-c2012-14.4The controlling expression of an if statement and the controlling expression of an iteration- statement shall have essentially Boolean typeRobustness
misra-c2012-15.1The goto statement should not be usedRobustness
misra-c2012-15.2The goto statement shall jump to a label declared later in the same functionRobustness
misra-c2012-15.3Any label referenced by a goto statement shall be declared in the same block, or in any block enclosing the goto statementRobustness
misra-c2012-15.5A function should have a single point of exit at the endRobustness
misra-c2012-15.6The body of an iteration-statement or a selection-statement shall be a compound-statementRobustness
misra-c2012-15.7All if … else if constructs shall be terminated with an else statementRobustness
misra-c2012-16.2A switch label shall only be used when the most closely-enclosing compound statement is the body of a switch statementRobustness
misra-c2012-16.3An unconditional break statement shall terminate every switch-clauseRobustness
misra-c2012-16.4Every switch statement shall have a default labelRobustness
misra-c2012-16.5A default label shall appear as either the first or the last switch label of a switch statementRobustness
misra-c2012-16.6Every switch statement shall have at least two switch-clausesRobustness
misra-c2012-16.7A switch-expression shall not have essentially Boolean typeRobustness
misra-c2012-17.1The features of shall not be usedRobustness
misra-c2012-17.5The function argument corresponding to a parameter declared to have an array type shall have an appropriate number of elementsRobustness
misra-c2012-17.6The declaration of an array parameter shall not contain the static keyword between the [ ]Robustness
misra-c2012-17.8A function parameter should not be modifiedRobustness
misra-c2012-18.1A pointer resulting from arithmetic on a pointer operand shall address an element of the same array as that pointer operandRobustness
misra-c2012-18.5Declarations should contain no more than two levels of pointer nestingRobustness
misra-c2012-18.6The address of an object with automatic storage shall not be copied to another object that persists after the first object has ceased to existRobustness
misra-c2012-18.8Variable-length array types shall not be usedRobustness
misra-c2012-19.2The union keyword should not be usedRobustness
misra-c2012-20.1#include directives should only be preceded by preprocessor directives or commentsRobustness
misra-c2012-20.2The ‘, ” or characters and the /* or // character sequences shall not occur in a header fi le nameRobustness
misra-c2012-20.3The #include directive shall be followed by either a or “filename” sequenceRobustness
misra-c2012-20.4A macro shall not be defined with the same name as a keywordRobustness
misra-c2012-20.5#undef should not be usedRobustness
misra-c2012-21.3The memory allocation and deallocation functions of shall not be usedRobustness
misra-c2012-21.4The standard header file shall not be usedRobustness
misra-c2012-21.5The standard header file shall not be usedRobustness
misra-c2012-21.7The atof, atoi, atol and atoll functions of shall not be usedRobustness
misra-c2012-21.8The library functions abort, exit, getenv and system of shall not be usedRobustness
misra-c2012-21.9The library functions bsearch and qsort of shall not be usedRobustness
misra-c2012-21.11The standard header file shall not be usedRobustness
misra-c2012-22.1All resources obtained dynamically by means of Standard Library functions shall be explicitly releasedRobustness
misra-c2012-22.2A block of memory shall only be freed if it was allocated by means of a Standard Library functionRobustness
misra-c2012-22.4There shall be no attempt to write to a stream which has been opened as read-onlyRobustness
misra-c2012-22.6The value of a pointer to a FILE shall not be used after the associated stream has been closedRobustness

Low level issues

RuleDescriptionKPI
arrayIndexThenCheckDefensive programming: The variable ‘index’ is used as an array index before it is checked that is within limits. This can mean that the array might be accessed out of bounds. Reorder conditions such as ‘(a[i] && i < 10)' to '(i < 10 && a[i])'. That way the array will not be accessed if the index is out of limits.Maintainability
assignBoolToFloatBoolean value assigned to floating point variable.Maintainability
assignIfErrorMismatching assignment and comparison comparison ” is always false.Maintainability
bitwiseOnBooleanBoolean variable ‘varname’ is used in bitwise operation. Did you mean ‘&&’?Maintainability
catchExceptionByValueThe exception is caught by value. It could be caught as a (const) reference which is usually recommended in C++.Robustness
clarifyCalculationSuspicious calculation. Please use parentheses to clarify the code. The code ”a+b?c:d” should be written as either ”(a+b)?c:d” or ”a+(b?c:d)”.Maintainability
clarifyConditionSuspicious condition (assignment + comparison); Clarify expression with parentheses.Maintainability
commaSeparatedReturnComma is used in return statement. When comma is used in a return statement it can easily be misread as a semicolon. For example in the code below the value of ‘b’ is returned if the condition is true but it is easy to think that ‘a+1’ is returned:12 if (x)12 return a + 112 b++;12However it can be useful to use comma in macros. Cppcheck does not warn when such a macro is then used in a return statement it is less likely such code is misunderstood.Maintainability
comparisonErrorThe expression ‘(X & 0x6) == 0x1’ is always false. Check carefully constants and operators used these errors might be hard to spot sometimes. In case of complex expression it might help to split it to separate expressions.Maintainability
comparisonOfBoolWithBoolErrorThe variable ‘var_name’ is of type ‘bool’ and comparing ‘bool’ value using relational (< > <= or >=) operator could cause unexpected results.Maintainability
comparisonOfFuncReturningBoolErrorThe return type of function ‘func_name’ is ‘bool’ and result is of type ‘bool’. Comparing ‘bool’ value using relational (< > <= or >=) operator could cause unexpected results.Maintainability
comparisonOfTwoFuncsReturningBoolErrorThe return type of function ‘func_name1’ and function ‘func_name2’ is ‘bool’ and result is of type ‘bool’. Comparing ‘bool’ value using relational (< > <= or >=) operator could cause unexpected results.Maintainability
copyCtorPointerCopyingValue of pointer ‘var’ which points to allocated memory is copied in copy constructor instead of allocating new memory.Maintainability
cstyleCastC-style pointer casting detected. C++ offers four different kinds of casts as replacements: static_cast const_cast dynamic_cast and reinterpret_cast. A C-style cast could evaluate to any of those automatically thus it is considered safer if the programmer explicitly states which kind of cast is expected. See also: https://www.securecoding.cert.org/confluence/display/cplusplus/EXP05-CPP.+Do+not+use+C-style+casts.Maintainability
duplicateBranchFinding the same code in an ‘if’ and related ‘else’ branch is suspicious and might indicate a cut and paste or logic error. Please examine this code carefully to determine if it is correct.Maintainability
duplicateBreakConsecutive return break continue goto or throw statements are unnecessary. The second statement can never be executed and so should be removed.Maintainability
duplicateExpressionFinding the same expression on both sides of an operator is suspicious and might indicate a cut and paste or logic error. Please examine this code carefully to determine if it is correct.Maintainability
duplicateExpressionTernaryFinding the same expression in both branches of ternary operator is suspicious as the same code is executed regardless of the condition.Maintainability
exceptRethrowCopyRethrowing an exception with ‘throw varname;’ creates an unnecessary copy of ‘varname’. To rethrow the caught exception without unnecessary copying or slicing use a bare ‘throw;’.Understandability
funcArgNamesDifferentFunction ‘function’ argument 2 names different: declaration ‘A’ definition ‘B’.Understandability
functionConstThe member function ‘class::function’ can be made a const function. Making this function ‘const’ should not cause compiler errors. Even though the function can be made const function technically it may not make sense conceptually. Think about your design and the task of the function first – is it a function that must not change object internal state?Maintainability
incrementbooleanThe operand of a postfix increment operator may be of type bool but it is deprecated by C++ Standard (Annex D-1) and the operand is always set to true. You should assign it the value ‘true’ instead.Maintainability
initializerListMember variable ‘class::variable’ is in the wrong place in the initializer list. Members are initialized in the order they are declared not in the order they are in the initializer list. Keeping the initializer list in the same order that the members were declared prevents order dependent initialization errors.Maintainability
knownConditionTrueFalseCondition ‘x’ is always trueUnderstandability
mismatchingBitAndMismatching bitmasks. Result is always 0 (X = Y & 0xf0; Z = X & 0x1; => Z=0).Understandability
multiConditionExpression is always false because ‘else if’ condition matches previous condition at line 1.Understandability
nanInArithmeticExpressionUsing NaN/Inf in a computation. Although nothing bad really happens it is suspicious.Maintainability
noConstructorThe class ‘classname’ does not have a constructor although it has private member variables. Member variables of builtin types are left uninitialized when the class is instantiated. That may cause bugs or undefined behavior.Maintainability
noCopyConstructorclass ‘class’ does not have a copy constructor which is recommended since the class contains a pointer to allocated memory.Robustness
noExplicitConstructorClass ‘classname’ has a constructor with 1 argument that is not explicit. Such constructors should in general be explicit for type safety reasons. Using the explicit keyword in the constructor means some mistakes when using the class can be avoided.Maintainability
operatorEqThe class::operator= does not conform to standard C/C++ behaviour. To conform to standard C/C++ behaviour return a reference to self (such as: ‘class &class::operator=(..) { .. return *this; }’. For safety reasons it might be better to not fix this message. If you think that safety is always more important than conformance then please ignore/suppress this message. For more details about this topic see the book Effective C++” by Scott Meyers.”Robustness
operatorEqRetRefThis‘operator=’ should return reference to ‘this’ instance.Accuracy
operatorEqShouldBeLeftUnimplementedoperator=’ should either return reference to ‘this’ instance or be declared private and left unimplemented.Accuracy
pointerLessThanZeroA pointer cannot be negative so it is either pointless or an error to check if it is.Maintainability
pointerPositiveA pointer cannot be negative so it is either pointless or an error to check if it is not.Maintainability
reademptycontainerReading from empty STL container ‘var’Understandability
redundantAssignmentVariable ‘var’ is reassigned a value before the old one has been used.Maintainability
redundantConditionRedundant condition: If x > 11 the condition x > 10 is always true.Maintainability
redundantIfRemoveRedundant checking of STL container element existence before removing it. It is safe to call the remove method on a non-existing element.Maintainability
redundantPointerOpRedundant pointer operation on ‘varname’ – it’s already a pointer.Maintainability
truncLongCastAssignmentint result is assigned to long variable. If the variable is long to avoid loss of information then there is loss of information. To avoid loss of information you must cast a calculation operand to long for example ‘l = a * b;’ => ‘l = (long)a * b;’.Robustness
truncLongCastReturnint result is returned as long value. If the return value is long to avoid loss of information then there is loss of information. To avoid loss of information you must cast a calculation operand to long for example ‘return a*b;’ => ‘return (long)a*b’.Robustness
unassignedVariableVariable ‘varname’ is not assigned a value.Maintainability
unhandledExceptionSpecificationUnhandled exception specification when calling function foo(). Either use a try/catch around the function call or add a exception specification for funcname() also.Maintainability
unpreciseMathCallExpression ‘1 – erf(x)’ can be replaced by ‘erfc(x)’ to avoid loss of precision.Maintainability
unreachableCodeStatements following return break continue goto or throw will never be executed.Maintainability
unreadVariableVariable ‘varname’ is assigned a value that is never used.Understandability
unsafeClassCanLeakThe class ‘class’ is unsafe wrong usage can cause memory/resource leaks for ‘class::varname’. This can for instance be fixed by adding proper cleanup in the destructor.Resource Utilization
unsignedLessThanZeroThe unsigned variable ‘varname’ will never be negative so it is either pointless or an error to check if it is.Maintainability
unsignedPositiveUnsigned variable ‘varname’ can’t be negative so it is unnecessary to test it.Maintainability
unusedAllocatedMemoryVariable ‘varname’ is allocated memory that is never used.Resource Utilization
unusedFunctionThe function ‘funcName’ is never used.Understandability
unusedLabelLabel ” is not used.Understandability
unusedPrivateFunctionUnused private function: ‘classname::funcname’Understandability
unusedScopedObjectInstance of ‘varname’ object is destroyed immediately.Understandability
unusedStructMemberstruct member ‘structname::variable’ is never used.Understandability
unusedVariableUnused variable: varnameUnderstandability
uselessAssignmentArgAssignment of function parameter has no effect outside the function.Understandability
variableScopeThe scope of the variable ‘varname’ can be reduced. Warning: Be careful when fixing this message especially when there are inner loops. Here is an example where cppcheck will write that the scope for ‘i’ can be reduced:12void f(int x)12{12 int i = 0;12 if (x) {12 // it’s safe to move ‘int i = 0;’ here12 for (int n = 0; n < 10; ++n) {12 // it is possible but not safe to move 'int i = 0;' here12 do_something(&i);12 }12 }12}12When you see this message it is always safe to reduce the variable scope 1 level.Maintainability

C#

We have discovered some checks and rules for C#. Following section briefs, about the Embold CS code issues.


EmboldCS Issues

Embold comes with a proprietary and state-of-the-art analyser. In addition to integrating and building upon good work from the open source space, we have created our own checks and rules to discover code issues that were not sufficiently covered by other tools.


Critical level issues


RuleDescriptionExampleKPI
ArithmeticExpressionsMustDeclarePrecedenceThis statement contains a complex arithmetic expression which omits parenthesis around operationsNon-complaint Code:

int x = 5 + y * b / 6 % z – 2;

Complaint Code:

int x = 5 + (y * ((b / 6) % z)) – 2;
This rule is intended to increase the readability and maintainability of this type of code, and to reduce the risk of introducing bugs later, by forcing the developer to insert parenthesis to explicitly declare the operator precedence.
Robustness
AvoidExceptionsInsideStaticConstructorsIf any exception is thrown from within a static constructor, the type is unusable for the lifetime of the programCause:
Static constructor are called before the first time a class is used but the caller doesn’t control when exactly.
The exception is thrown in this context force callers to use ‘try’ block around any usage of the class and should be avoided.

Non-complaint Code:

public class MyClass
{
static MyClass()
{
throw new System.Exception(“error message”);
}
}


Complaint Code:

public class MyClass
{
static MyClass()
{
}
}
Robustness
ConditionalExpressionsMustDeclarePrecedenceA C# statement contains a complex conditional expression which omits parenthesis around operationsCause:
This rule is intended to increase the readability and maintainability of this type of code, and to reduce the risk of introducing bugs later, by forcing the developer to insert parenthesis to explicitly declare the operator precedence.

Non-Complaint Code:

if (x || y && z && a || b)
{
}


Complaint Code:

if ((x || y) && z && (a || b))
{
}
//or
if (x || (y && z && a) || b)
{
}


Inserting parenthesis makes the code more obvious and easy to understand and removes the need for the reader to make assumptions about the code.
Robustness
EmptyCatchBlockAn empty catch block suppress all errors and shouldn’t be usedAnalyzability
RegexExpressionIsIncorrectThe regular expression is invalid and will fail at run-timeCause:
The regular expression pattern is invalid and will fail at run-time.

Non-complaint Code:

string input = “/content/Somefile.cs”;
Match match1 = Regex.Match(input, @”content/-z0-9-]+).a$”);


Complaint code:

string input = “/content/Somefile.cs”;
Match match = Regex.Match(input, @”content/([A-Za-z0-9-]+).cs$”);
Robustness
VirtualMethodCalledOnConstructorIf you make a virtual method call in a constructor, and it is not the most derived type in its inheritance hierarchy, then it might be called on a class whose constructor has not been runNon-complaint Code:

public class VirtualMethodOnConstructorTests
{
public VirtualMethodOnConstructorTests(string foo)
{
DoFoo(foo);
}
public virtual void DoFoo(string foo)
{
}
}


Solution:

There are 2 options:
1. This problem can be mitigated by marking the class as sealed to ensure that it is the most derived type in the inheritance hierarchy – in which case it is perfectly safe to call the virtual method.
2. Remove the call from the constructor.
Robustness
VulnerableEncryptionSecure the encryption mode by combining Cipher Block Chaining with an authenticity check (HMAC-SHA256 for example) on the cipher text.Example For Issue Occurrence:
AesManaged aes = new AesManaged
{
KeySize = 128,
BlockSize = 128,
Mode = CipherMode.ECB, // Noncompliant
Padding = PaddingMode.PKCS7
};
Security
WeakEncryptionWeak encryption algorithms provide very less security and insufficient protection for sensitive data hence its recommended to use a more secure encryption algorithm, such as AES.Non-complaint Code:
using (var tripleDES = new TripleDESCryptoServiceProvider()) //Noncompliant
{
//...
}


Complaint Code:
AesManaged aes = new AesManaged
{
KeySize = 128,
BlockSize = 128,
Padding = PaddingMode.PKCS7
};
Security

High level issues


RuleDescriptionExampleKPI
AllocationOfReferenceTypeEnumeratorNon-ValueType enumerator may result in an heap allocation.Non-complaint Code:

IList iListData = new[] { 123, 32, 4 };
foreach (var i in iListData) // Allocations (line 19)
{
Console.WriteLine(i);
}


Complaint Code:

int[] intData = new[] { 123, 32, 4 };
foreach (var i in intData)
{
Console.WriteLine(i);
}

Efficiency
ArrayAllocationForParamsParameterUnnecessary array allocation will occur even if no parameter is passed in for the params parameter.Non-complaint Code:

class Test
{
void Method()
{
Params(1, 2);
}
public void Params(params int[] args)
{
}
}


Complaint Code:

class Test
{
void Method()
{
Params(new[] { 1, 2 });

}
public void Params(params int[] args)
{
}
}
Efficiency
CodeAnalysisSuppressionMustHaveJustificationThe SuppressMessage attribute does not include a justification. Justification increases the long term maintainability of the code.Cause:
A violation of this rule occurs when the code contains a Code Analysis SuppressMessage attribute, but a justification for the suppression has not been provided within the attribute.Whenever a Code Analysis rule is suppressed, a justification should be provided.This can increase the long-term maintainability of the code.


Complaint Code:

[SuppressMessage(“Microsoft.Performance”, “TestSuppressAttribute”, Justification = “Used for testing”)]public bool Method1()
{

}

To fix an instance of this violation, add a Justification tag and justification text to the SuppressMessage attribute describing the reason for the suppression.

Robustness
DisposablesShouldCallSuppressFinalizeClasses implementing IDisposable should call the GC.SuppressFinalize method in their finalize method to avoid any finalizer from being called. This rule should be followed even if the class doesn’t have a finalizer as a derived class could have one.Cause:
Classes implementing IDisposable should call the GC.SuppressFinalize method in their finalize method to avoid any finalizer from being called. This rule should be followed even if the class doesn’t have a finalizer as a derived class could have one.

Non-complaint code:
public class MyClass : System.IDisposable
{
public void Dispose()
{
var x = 1;
}
}


Compliant code:
public class MyClass : System.IDisposable
{
public void Dispose()
{
var x = 1;
GC.SuppressFinalize(this);
}
}
Robustness
DoNotChangeLoopVariablesDon’t change a loop variable inside a for loop.Robustness
DontConcatenateStringsInLoopsDon’t concatenate strings in a loop. Using a StringBuilder will require less memory and time.Cause:
Do not concatenate a string on a loop. It will allocate a lot of memory. Use a StringBuilder instead.
It will will require less allocation, less garbage collector work, less CPU cycles, and less overall time.

Non-complaint code:

var values = “”;
foreach (var item in Enum.GetValues(typeof(LoaderOptimization)))
{
values += item.ToString();
}


Complaint code:

var values = “”;
var builder = new StringBuilder();
builder.Append(values);
foreach (var item in Enum.GetValues(typeof(LoaderOptimization)))
{
builder.Append(item.ToString());
}
values = builder.ToString();
Efficiency
MakeFieldReadonlyA field that is only assigned in the constructor can be made readonly.Cause:
A field that is only assigned when declared or in the constructor can be made read-only. A read-only field cannot be assigned anywhere else after the object is created, making it immutable.

Non-complaint code:

class Class1
{
private int x = 0;
}


Complaint code:

class Class1
{
private readonly int x = 0;
}
Maintainability
NonOverriddenVirtualMethodCallOnValueTypeNon-overridden virtual method is called on a value type.Cause:
An additional boxing or constrained instruction is needed for a non-overridden virtual method call on a value type because the CLR will automatically instantiate the corresponding class from a value type if you call some method on it.

Complaint code:

using System;

var normal = new Normal().GetHashCode();
var overridden = new OverrideToHashCode().GetHashCode();

struct Normal
{

}

struct OverrideToHashCode
{

public override int GetHashCode()
{
return -1;
}
}

Efficiency
RemoveEmptyFinalizersAn empty finalizer will stop your object from being collected immediately by the Garbage Collector when no longer used. It will instead be placed in the finalizer queue needlessly using resources.Cause:
Due to the finalize method, GC will not clear the entire memory associated with object in the first attempt. Memory used by managed resources is still in heap as inaccessible reference. Hence it is recommended that the Finalize method should not be used until it is extremely necessary.

Non-complaint code:

public class MyClass
{
//At runtime C# destructor is automatically Converted to Finalize method
~MyClass()
{
Dispose(false);
}
}



Complaint code:
public class MyClass
{
}
Resource Utilization
SwitchWithoutDefaultClauseConsider adding default case to the switchNon-complaint code:

switch (value)
{
case 1:
Console.WriteLine(1);
break;
case 2:
Console.WriteLine(2);
break;
}


Complaint code:
switch (value)
{
case 1:
Console.WriteLine(1);
break;
case 2:
Console.WriteLine(2);
break;
default:
Console.WriteLine(0);
break;
}
Robustness
Invalid Logging Class NameConsider creating the logger name in context to the current class name.// Cause:
//The log instace created should belong to the current class for logging consistency, consider changing the log class name to current class.

//Example For Issue Occurrence:

class ExampleClass
{
private static ILog logger = LogManager.GetLogger("otherClass");

static void Main(string[] args)
{
try
{
logger.Info("");
}
catch (Exception e)
{
}
}
}

//CODE FIX:

class ExampleClass
{
private static ILog logger = LogManager.GetLogger("ExampleClass");

static void Main(string[] args)
{
try
{
logger.Info("");
}
catch (Exception e)
{
}
}
}
Usage
Class Implements ICloneableConsider defining your own Clone() or Copy() methods and document whether they perform deep or shallow copying instead of using ICloneable interface.// Cause:
//Implementing 'ICloneable' is discouraged due to its ambiguous effect on the code.

//Example For Issue Occurrence:

using System;

public class Class1 : ICloneable
{
public int a;
public int b;

public Class1(int aa, int bb)
{
a = aa;
b = bb;
}

public string ToString()
{
return "(" + a + "," + b + ")";
}

public virtual object Cloning()
{
return new Class1(a, b);
}
object ICloneable.Clone()
{
return Cloning();
}
}
Reliability

Medium level issues

RuleDescriptionExampleKPI
CatchBlocksShouldRethrowAny catch block should rethrow or throw and not eat exceptions.Cause:
A Catch block that does don't throw any exception is not recommended.


Non-complaint Code:

try
{
// do something
}
catch
{
}


Complaint Code:

try
{
// do something
}
catch (Exception ex)
{
throw;
}

Analyzability
CompilerWarningLevelIsSetTooLowBuild with the highest warning levelCause:
Warnings are potential problems with your code. Turning on the warnings at the highest level will highlight these problems, allowing you to fix them //early, rather than let them become potential bugs at a later date.


Complaint Code:

You can change the warning level for a project by right-clicking on it, going to its properties page and then setting warning level to highest ie.4 on its Build tab.
Understandability
DisposeFieldsProperlyThis class has a disposable field and is not disposing it.Non-Complaint Code:

internal class D : System.IDisposable
{
}
class Class1
{
private D field = D.Open();
}


Compliant code:
class Class1 : System.IDisposable
{
private D field = D.Open();

public void Dispose()
{
field.Dispose();
}
}

Maintainability
DoNotHideInheritedMembersOn hiding an inherited member, the derived version of the member replaces the base class versionCause:
Using a new keyword for a base class member in the derived class, hides the base class member. Ensure the required functionality and look out for compiler warnings. To simply put, if a method is not hiding the base method, it should be overriding it.

Complaint code:
public class B
{
public virtual void M(int i)
{
}
}

public class C : B
{
public new void M(int i)
{
}
}



Non-compliant code:
public class B
{
public virtual void M(int i)
{
}
}

public class C : B
{
public override void M(int i)
{
}
}
Understandability
DoNotPrefixLocalCallsWithThisKeyword A call to an instance member of the local class or a base class is prefixed with ‘this’. Non-compliant code:
class Employee
{
public string FirstName;
public string LastName;
public string Salary;

public void SetName(
string newFirstName, string newLastName)
{
this.FirstName = newFirstName;
this.LastName = newLastName;
}
}


Compliant code:
class Employee
{
public string FirstName;
public string LastName;
public string Salary;

public void SetName(
string newFirstName, string newLastName)
{
FirstName = newFirstName;
LastName = newLastName;
}
}

Understandability
FieldsMustBePrivateMake the field private and add a property to expose the field outside of the classCause:
A violation of this rule occurs whenever a field in a class is given non-private access. For maintainability reasons,
//properties should always be used as the mechanism for exposing fields outside of a class, and fields should always be
//declared with private access. This allows the internal implementation of the property to change over time without changing
//the interface of the class.

Issue occurence:

Fields located within C# structs are allowed to have any access level.

Solution:

To fix a violation of this rule, make the field private, and add a property to expose the field outside of the class.
Maintainability
HardCodedStringsAndMagicNumbersHard coded values should be moved to resources for better maintainabilityCause:
For better maintainability of code it is recommended to have all strings in one place and you only need to change it there to update the whole program.

Non-complaint code:

public void MyMethod()
{
if (s != “some hard-coded value”)
{
}
}


Compliant code:

public void MyMethod()
{
if (s.Equals(Resources.SomeValue))
{
}
}
Maintainability
MakeLocalVariableConstant If a variable is assigned a constant value and never changed, it can be made ‘const’Cause:
The variable is assigned a constant value and never changed, it can be made a const

Non-compliant code:

class Class1
{
int Method1()
{
int x = 30;

return x;
}
}


Compliant code:
class Class1
{
int Method1()
{
const int x = 30;

return z;
}
}
Maintainability
RedundantFieldAssignmentConsider not assigning the default value to a field for performance optimisationCause:
It’s recommended not to assign the default value to a field as a performance optimization.

Non-complaint code:

class SampleClass
{
private int number = 0;
// …
}



Complaint code:
class SampleClass
{
private int number;
// …
}
Efficiency
ThrowDoesNothingIf an exception is caught and then thrown again the original stack trace will be lost. It is best to throw an exception without using any parametersCause:
Throwing the same exception as passed to the ‘catch’ block lose the original stack trace and will make debugging this exception a lot more difficult. The correct way to rethrow an exception without changing it is by using ‘throw’ without any parameter.

Non-complaint code:
try { }
catch (System.Exception ex)
{
throw ex;
}


Complaint code:
You will have two choices, you can rethrow the original exception as-is:

try { }
catch (System.Exception ex)
{
throw;
}

//Or you can rethrow the original exception as an inner exception, like so:

try { }
catch (System.Exception ex)
{
throw new Exception(“some reason to rethrow”, ex);
}
Analyzability
UseConfigureAwaitFalseOnAwaitedTaskConsider using ConfigureAwait(false) on the awaited taskNon-complaint code:

public async Task TestAsync()
{
await GetValueAsync(); // RCS1090
}


Complaint code:
public async Task TestAsync()
{
await GetValueAsync().ConfigureAwait(false);
}
Robustness
UseOfRegexIsMatchMightBeImprovedInstantiating the Regex object multiple times might be bad for performance. Consider using the static IsMatch method from Regex class and/or compile the regexCause:
When IsMatch() method is called multiple times, you should be using the static Regex.IsMatch method, as that can be cached and won’t be interpreted //every time you call the method, it will give you better performance.


Non-complaint code:

public static bool TestRegex(string parameterValue)
{
string pattern = @”p{Sc}+s*d+”;
Regex test = new Regex(pattern);
return test.IsMatch(parameterValue);
}


Complaint code:
public static bool TestRegex(string parameterValue)
{
string pattern = @”p{Sc}+s*d+”;
return Regex.IsMatch(parameterValue, pattern);
}
Efficiency
UseStaticMethodIf the method is not referencing any instance variable and if you are not creating a virtual/abstract/new or partial method and if it is not an overridden method, your instance method can be changed to a static method.Non-complaint code:

public class Program
{
public int calculation(int x, int y)
{
int val = x * y;
return val;
}
static void Main(string[] args)
{
Program obj = new Program();
int result = obj.calculation(18, 14);
Console.WriteLine(result);
Console.ReadKey();
}
}


Complaint code:
public class Program
{
public static int calculation(int x, int y)
{
int val = x * y;
return val;
}
static void Main(string[] args)
{
int result = calculation(18, 14);
Console.WriteLine(result);
Console.ReadKey();
}
}
Robustness
UseSwitchMultiple ‘if’ and ‘else if’ statements can be replaced with a ‘switch’Cause
In a switch statement, all elements get the same access time, compared to a list of if-else’s where the last element takes much more time to reach as //it has to evaluate every previous condition first. Thus the compiler is better in optimizing a switch-statement than an if-statement.

Non-complaint code:

public void DoThis(string s)
{
if (s == “A”)
{
// ..
}
else if (s == “B”)
{
// ..
}
else if (s == “C”)
{
// ..
}
else
{
// ..
}
}


Complaint code:
public void DoThis(string s)
{
switch (s)
{
case “A”:
break;
case “B”:
break;
case “C”:
break;
default:
break;
}
}
Efficiency
LogErrorInCatchThe log level inside Catch block should be ErrorCause
A log level less than an Error is not recommended within a Catch Block especially when there is an exception.

Non-complaint code:

try
{
var testVar = 10/0;
}
catch (Exception e)
{
log.Info("Divide by zero exception occured");
}


Non-complaint code:
try
{
var testVar = 10/0;
}
catch (Exception e)
{
log.Error("Divide by zero exception occured");
}
Maintainability

Low level issues

Rule Description Example KPI
AbstractClassShouldNotHavePublicConstructors Abstract class should not have public constructors // Cause:
//Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type,
//and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed.

 

 

 

 

 

 

//Example For Issue Occurrence:

public abstract class Book
{
public Book()
{
}
}

//CODE FIX:

public abstract class Book
{
protected Book()
{
}
}

//To fix a violation of this rule, either make the constructor protected or do not declare the type as abstract.

Understandability
AccessModifierMustBeDeclared The access modifier for a C# element has not been explicitly defined // Cause:
//The access modifier for a C# element has not been explicitly defined.

 

 

 

 

 

 

//C# allows elements to be defined without an access modifier. Depending upon the type of element, C# will automatically
//assign an access level to the element in this case. This rule requires an access modifier to be explicitly defined for
//every element.This removes the need for the reader to make assumptions about the code, improving the readability of the code.

Understandability
CallExtensionMethodAsExtension Consider simplifying a call to some static methods by using their Extension method implementation. //Example For Issue Occurrence:

 

 

 

 

 

 

public void DoThis()
{
var source = new int[] { 100, 102, 104 };
Enumerable.Any(source, x => x > 100);
}

//CODE FIX:

public void DoThis()
{
var source = new int[] { 100, 102, 104 };
source.Any(x => x > 100);
}

Understandability
ChangeForExpressionValue Change an expression for its value if the expression is made of literal values //Example For Issue Occurrence:

 

 

 

 

 

 

var minutes = 24 * 60;

//CODE FIX:

var minutes = 1440;

//If the expression is made up of literal values an additional computation cycle is introduced to calculate the final value hence it is better to use the //final value directly thereby reducing the computational cost of the given expression.

Understandability
CodeMustNotContainSpaceAfterNewKeywordInImplicitlyTypedArrayAllocation An implicitly typed new array allocation within a C# code file is not spaced correctly // Cause:
//A violation of this rule occurs whenever the code contains an implicitly typed new array allocation which is not
//spaced correctly. Within an implicitly typed new array allocation, there should not be any space between the new
//keyword and the opening array bracket.

 

 

 

 

 

 

//Example For Issue Occurrence:

var test = new[] { 1, 2, 3, 4};

//To fix a violation of this rule, remove any whitespace between the new keyword and the opening array bracket.

Understandability
ComplexFieldsMustBeReadonly Consider making this field readonly // Cause:
//Fields of reference type objects should be made readonly.
//Example For Issue Occurrence:

 

 

 

 

 

 

private System.DateTime d = new System.DateTime(1);

//CODE FIX:

private readonly System.DateTime d = new System.DateTime(1);

Robustness
IncorrectStringFormatUsage The format argument in String.Format determines the number of other arguments that need to be passed into the method based on the number of curly braces used. Consider checking the arguments are being passed.   Accuracy
InterfaceNamesMustBeginWithI The name of an interface must begin with the capital letter I // Cause:
//A violation of this rule occurs when the name of an interface does not begin with the capital letter I.
//Interface names should always begin with I.For example, ICustomer.

 

 

 

 

 

 

//To fix a violation of this rule, add the capital letter I to the front of the interface name.

Understandability
InvalidArgumentName The argument passed to ArgumentException constructor must be the name of one of the method arguments. It can be either specified directly or using the nameof() operator (C#6 only) // Cause:
//The string passed as the ‘paramName’ argument of ArgumentException constructor must be the name of one of the
//method arguments. It can be either specified directly or using the nameof() operator (C#6 only)

 

 

 

 

 

 

//Example For Issue Occurrence:
public async Task DoThis(int x, int y)
{
throw new ArgumentException(“message”, “c”);
}

//CODE FIX:
public async Task DoThis(int x, int y)
{
throw new ArgumentException(“message”, “x”);
}

Maintainability
NameOfOperatorAnalyzer The nameof() operator should be used to specify the name of a program element instead of a string literal as it produces code that is easier to refactor //Example For Issue Occurrence:

 

 

 

 

 

 

void Class1(string example)
{
var test = “example”;
}

//CODE FIX:

void Class1(string example)
{
var test = nameof(example);
}

Maintainability
PartialElementsMustDeclareAccess The partial element does not have an access modifier defined. // Cause:
//A violation of this rule occurs when the partial class or a partial method does not have an access modifier defined.

 

 

 

 

 

 

//To fix an instance of this violation, specify an access modifier for the partial element.

Understandability
ProtectedMustComeBeforeInternal The keyword ‘protected’ is positioned after the keyword ‘internal’ within the declaration of a protected internal C# element to improve readability // Cause:
//The keyword protected is positioned after the keyword internal within the declaration of a protected internal C# element.

 

 

 

 

 

 

//To make the code easier to read and more consistent, standardizing the ordering of these keywords is helpful, so that a
//protected internal element will always be described as such, and never as internal protected. This can help to reduce
//confusion about whether these access levels are indeed the same.

Understandability
RemoveLambdaExprForMethodWithSameSignature The extra unnecessary layer of indirection induced by the lambda expression can be avoided by passing the method group instead. //Example For Issue Occurrence:

 

 

 

 

 

 

var test = a.Where(item => filter(item));

//CODE FIX:

var test = a.Where(filter);

//In the above example the method can be directly passed as the condition and thereby an unnecessary layer of introducing the simple lambda expression //can be avoided. This in turn will reduce the computational cost of the entire expression.

Efficiency
RemoveRedundantElse An empty else clause only adds complexity. You may safely remove it. // Cause:
//Certain if-else conditions can safely have their else clause removed. Only use an else segment if you want a mutually exclusive logical branch in the //program’s execution. There’s no need to use an explicit else, it just adds to the length of the code.

 

 

 

 

 

 

//Example For Issue Occurrence:

if (true)
{
//some statement (not a comment)
}
else
{
}

//CODE FIX:

if (true)
{
//some statement (not a comment)
}

Efficiency
RemoveTheWhereInvocationWhenItIsPossible Use linq operator that supports a predicate parameter instead of using ‘where’ followed by the operator // Cause:
//When a linq operator supports a predicate parameter, it should be used instead of using ‘Where’ followed by the operator

 

 

 

 

 

 

//Example For Issue Occurrence:

var a = new int[10];
var f = a.Where(item => item > 10).First();

//CODE FIX:

var a = new int[10];
var f = a.First(item => item > 10)

Efficiency
ReturnConditionDirectly Using an if/else statement to return a boolean can be avoided by directly returning a boolean. // Cause:
//Using an if/else to return true/false depending on the condition isn’t useful, as the condition is already
//a boolean it can be returned directly.

 

 

 

 

 

 

//Example For Issue Occurrence:

private bool CheckAll()
{
if ( ….)
{
return true;
}
return false;
}

//CODE FIX:

private bool CheckAll()
{
return (your_condition);
}

Maintainability
ReturnInterfacesToCollections Return an IEnumerable or ICollection instead of a concrete collection class. //Example For Issue Occurrence:

 

 

 

 

 

 

List M()
{
throw new NotImplementedException();
}

//CODE FIX:

ICollection M()
{
throw new NotImplementedException();
}

Robustness
SetPropertyShouldBePrivate Use private set for automatic properties // Cause:
//A property with a private set; can be set from everywhere inside that class.
Maintainability
ShouldDisposeObject When a disposable object is created it should be disposed as soon as possible. This warning will appear if you create a disposable object and don’t store, return or dispose it //Example For Issue Occurrence:

 

 

 

 

 

 

void Test()
{
var t = new MemoryStream();
//other statements
}

//CODE FIX:

void Test()
{
using (var t = new MemoryStream())
{
//other statements
}
}

Resource Utilization
SimplifyExpression This expression can be more simplified //Example For Issue Occurrence:

 

 

 

 

 

 

bool foo= true;
if(foo!=true)
{
//
}

//CODE FIX:

bool foo= true;
if(!foo)
{
//
}

Maintainability
TerminateAsyncMethodWithAsyncKeyword Asynchronous method name should end with ‘Async’ //Example For Issue Occurrence:

 

 

 

 

 

 

public static async Task Foo()
{
return await Task.FromResult(false);
}

//CODE FIX:

public static async Task FooAsync()
{
return await Task.FromResult(false);
}

Understandability
UnnecessaryParenthesis Statement must not use unnecessary parenthesis // Cause:
//There is no need to specify that the no-parameter constructor is used with an initializer as it is implicit

 

 

 

 

 

 

//Example For Issue Occurrence:

var t = new Test() { X = 1 };

//CODE FIX:

var t = new Test { X = 1 };

Understandability
UnnecessaryToStringCallInStringConcatenation The runtime automatically calls ‘ToString()’ for string concatenation when there is no parameter. Consider removing it. //Example For Issue Occurrence:

 

 

 

 

 

 

string x = s.ToString();

//CODE FIX:

string x = s;

Understandability
UnusedMethod Unused private methods can be safely removed as they are unnecessary // Cause:
//Removes a private method that is not in use.

 

 

 

 

 

 

//Example For Issue Occurrence:

public class MyClass
{
private int field;

public MyClass() { }

private void MyMethod()
{
field = 1;
}
}

//CODE FIX:

public class MyClass
{
private int field;

public MyClass() { }
}

Maintainability
UnusedParameters A method with an unused parameter creates unnecessary confusion and should be deleted. // Cause:
//When a method declares a parameter and does not use it might bring incorrect conclusions for anyone reading the
//code and also demands the parameter when the method is called, unnecessarily.

 

 

 

 

 

 

//Example For Issue Occurrence:

public static void Method1(string name)
{
}

//CODE FIX:

public static void Method1()
{
}

Understandability
UseExpressionBodiedMembersWheneverPossible Usage of an expression bodied members improves readability of the code //Example For Issue Occurrence:

 

 

 

 

 

 

public override string ToString()
{
return this.Name;
}

//CODE FIX:

public override string ToString() => this.Name;

Understandability
UseForeach for loop can be converted into foreach loop // Cause:
//Foreach loop should be used when iterating through a collection that implements IEnumerable.

 

 

 

 

 

 

//Example For Issue Occurrence:

int[] ints = new int[100000];
int j;
for (int i = 0; i < 100000; i++) { j = ints[i]; } //CODE FIX: int[] ints = new int[100000]; int j; foreach(int i in ints) { j = i; }

Understandability
UseLambdaSyntax Lambda expressions are more succinct and easier to read than anonymous methods so they should/are preferred whenever the two are functionally equivalent. //Example For Issue Occurrence:

 

 

 

 

 

 

var x = items.Select(delegate (object f)
{
return f.ToString();
});

//CODE FIX:

var x = items.Select((object f) =>
{
return f.ToString();
});

Understandability
UseObjectInitializer When possible an object initializer should be used to initialize the properties of an object instead of multiple assignments. //Example For Issue Occurrence:

 

 

 

 

 

 

Code c;
c = new Code();
c.Language = “CSharp”;
c.Loc = 1105;

//CODE FIX:

Code c;
c = new Code()
{
Language = “CSharp”,
Loc = 1105
};

Maintainability
UseReadableConditions When a comparison is made between a variable and a literal the variable should be placed on the left hand side to maximize readability. //Example For Issue Occurrence:

 

 

 

 

 

 

public void Method(string value)
{
if (null == value)
{
//some code
}
}

//CODE FIX:

public void Method(string value)
{
if (value == null)
{
//some code
}
}

Understandability
UseStringEmpty Consider using ‘String.Empty’ instead of “” // Cause:
//This will cause the compiler to embed an empty string into the compiled code. Rather than including
//a hard-coded empty string, use the static string.Empty property

 

 

 

 

 

 

//Example For Issue Occurrence:

string s = “”;

//CODE FIX:

string s = string.Empty;

Understandability
UseStringInterpolationInsteadOfStringFormat String interpolation allows for better reading of the resulting string when compared to String.Format. You should use String.Format only when another method is supplying the format string. //Example For Issue Occurrence:

 

 

 

 

 

 

decimal pricePerOunce = 17.36m;
string s = string.Format(“The current price is {0} per ounce.”,
pricePerOunce);

//CODE FIX:

decimal pricePerOunce = 17.36m;
string s = $”The current price is {pricePerOunce} per ounce.”;

Understandability
UseTernaryOperator Consider using ternary operator instead of if else when dealing with direct value comparisons and assignments // Cause:
//If-else statements can be changed to ternary operators.

 

 

 

 

 

 

//Example For Issue Occurrence:

var result = true;
if (result)
return 1;
else
return 2;

//CODE FIX:

var result = true;
return result? 1 : 2;

Understandability
VerbatimString Change to verbatim string // Cause:
//A regular string can be converted into a verbatim string. A verbatim means that special chars don’t need to be escaped and thereby it reduces the //overhead to explicitly escape the control characters in the sting.

 

 

 

 

 

 

//Example For Issue Occurrence:

var str = “c:TestFolder”;

//CODE FIX:

var str = @”c:TestFolder”;

Accuracy

Objective- C

We have discovered some checks and rules for Objective C. Following section briefs, about the Embold CXX code issues.


Embold CXX Issues

Embold comes with a state-of-the-art proprietary analyser. In addition to integrating and building upon great work from the open source space, we have created our own checks and rules to discover code issues that were not sufficiently covered by other tools.


Critical level issues

Rule Description Example KPI
core.DivideZero Check for division by zero void test(int z) { if (z == 0) int x = 1 / z; // warn } Robustness
core.NonNullParamChecker Check for null pointers passed as arguments to a function whose arguments are references or marked with the ‘nonnull’ attribute int f(int *p) __attribute__((nonnull)); void test(int *p) { if (!p) f(p); // warn } Robustness
core.NullDereference Check for dereferences of null pointers void test(int *p) { if (p) return; int x = p[0]; // warn } Robustness
nullability.NullableDereferenced Warns when a nullable pointer is dereferenced. struct LinkedList { int data; struct LinkedList *next; }; struct LinkedList * _Nullable getNext(struct LinkedList *l); void updateNextData(struct LinkedList *list, int newData) { struct LinkedList *next = getNext(list); // Warning: Nullable pointer is dereferenced next->data = 7; } Robustness
nullability.NullablePassedToNonnull Warns when a nullable pointer is passed to a pointer which has a _Nonnull type. typedef struct Dummy { int val; } Dummy; Dummy *_Nullable returnsNullable(); void takesNonnull(Dummy *_Nonnull); void test() { Dummy *p = returnsNullable(); takesNonnull(p); // warn } Robustness
nullability.NullableReturnedFromNonnull Warns when a nullable pointer is returned from a function that has _Nonnull return type.   Robustness
nullability.NullPassedToNonnull Warns when a null pointer is passed to a pointer which has a _Nonnull type. if (name != nil) return; // Warning: nil passed to a callee that requires a non-null 1st parameter NSString *greeting = [@”Hello ” stringByAppendingString:name]; Robustness
nullability.NullReturnedFromNonnull Warns when a null pointer is returned from a function that has _Nonnull return type. – (nonnull id)firstChild { id result = nil; if ([_children count] > 0) result = _children[0]; // Warning: nil returned from a method that is expected // to return a non-null value return result; } Robustness
osx.cocoa.AtSync Check for nil pointers used as mutexes for @synchronized void test(id x) { if (!x) @synchronized(x) {} // warn: nil value used as mutex } Robustness
osx.cocoa.Dealloc Warn about Objective-C classes that lack a correct implementation of -dealloc @interface MyObject : NSObject { id _myproperty; } @end @implementation MyObject // warn: lacks ‘dealloc’ Robustness
osx.cocoa.IncompatibleMethodTypes Warn about Objective-C method signatures with type incompatibilities @interface MyClass1 : NSObject – (int)foo; @end @implementation MyClass1 – (int)foo { return 1; } @end @interface MyClass2 : MyClass1 – (float)foo; @end @implementation MyClass2 – (float)foo { return 1.0; } // warn @end Robustness
osx.cocoa.NilArg Check for prohibited nil arguments to ObjC method calls NSComparisonResult test(NSString *s) { NSString *aString = nil; return [s caseInsensitiveCompare:aString]; // warn: argument to ‘NSString’ method // ‘caseInsensitiveCompare:’ cannot be nil } Robustness
osx.cocoa.RetainCount Check for leaks and improper reference count management void test() { NSString *s = [[NSString alloc] init]; // warn } Resource Utilization
osx.cocoa.SelfInit Check that ‘self’ is properly initialized inside an initializer method @interface MyObj : NSObject { id x; } – (id)init; @end @implementation MyObj – (id)init { [super init]; x = 0; // warn: instance variable used while ‘self’ is not // initialized return 0; } @end Robustness
osx.cocoa.SuperDealloc Warn about improper use of ‘[super dealloc]’ in Objective-C @interface SuperDeallocThenReleaseIvarClass : NSObject { NSObject *_ivar; } @end @implementation SuperDeallocThenReleaseIvarClass – (void)dealloc { [super dealloc]; [_ivar release]; // warn } @end Resource Utilization
osx.cocoa.VariadicMethodTypes Check for passing non-Objective-C types to variadic collection initialization methods that expect only Objective-C types void test() { [NSSet setWithObjects:@”Foo”, “Bar”, nil]; // warn: argument should be an ObjC pointer type, not ‘char *’ } Robustness
osx.NumberObjectConversion Check for erroneous conversions of objects representing numbers into numbers NSNumber *photoCount = [albumDescriptor objectForKey:@”PhotoCount”]; // Warning: Comparing a pointer value of type ‘NSNumber *’ // to a scalar integer value if (photoCount > 0) { [self displayPhotos]; } Robustness
unix.MismatchedDeallocator Check for mismatched deallocators. // C, C++ void test() { int *p = (int *)malloc(sizeof(int)); delete p; // warn } Robustness

High level issues

Rule Description Example KPI
core.CallAndMessage Check for logical errors for function calls and Objective-C message expressions (e.g., uninitialized arguments, null function pointers) struct S { int x; }; void f(struct S s); void test() { struct S s; f(s); // warn: passed-by-value arg contain uninitialized data } Accuracy
osx.cocoa.MissingSuperCall Warn about Objective-C methods that lack a necessary call to super @interface Test : UIViewController @end @implementation test – (void)viewDidLoad {} // warn @end Accuracy
osx.cocoa.NSError Check usage of NSError** parameters @interface A : NSObject – (void)foo:(NSError **)error; @end @implementation A – (void)foo:(NSError **)error { // warn: method accepting NSError** should have a non-void // return value } @end Understandability
osx.cocoa.ObjCGenerics Check for type errors when using Objective-C generics NSMutableArray *names = [NSMutableArray array]; NSMutableArray *birthDates = names; // Warning: Conversion from value of type ‘NSDate *’ // to incompatible type ‘NSString *’ [birthDates addObject: [NSDate date]]; Accuracy
alpha.clone.CloneChecker Experimental: Reports similar pieces of code. void log(); int max(int a, int b) { // warn log(); if (a > b) return a; return b; } int maxClone(int x, int y) { // similar code here log(); if (x > y) return x; return y; } Maintainability
alpha.core.BoolAssignment Experimental: Warn about assigning non-{0,1} values to Boolean variables void test() { BOOL b = -1; // warn } Maintainability
alpha.core.Conversion Experimental: Loss of sign/precision in implicit conversions void test(unsigned U, signed S) { if (S > 10) { if (U < S) { } } if (S < -10) { if (U < S) { // warn (loss of sign) } } } Accuracy
alpha.core.DynamicTypeChecker Experimental: Check for cases where the dynamic and the static type of an object are unrelated. id date = [NSDate date]; // Warning: Object has a dynamic type ‘NSDate *’ which is // incompatible with static type ‘NSNumber *'” NSNumber *number = date; [number doubleValue]; Maintainability
alpha.core.TestAfterDivZero Experimental: Check for division by variable that is later compared against 0. Either the comparison is useless or there is division by zero. void test(int x) { var = 77 / x; if (x == 0) { } // warn } Robustness
alpha.deadcode.UnreachableCode Experimental: Check unreachable code int test() { int x = 1; while(x); return x; // warn } Maintainability
alpha.osx.cocoa.DirectIvarAssignment Experimental: Check for direct assignments to instance variables @interface MyClass : NSObject {} @property (readonly) id A; – (void) foo; @end @implementation MyClass – (void) foo { _A = 0; // warn } @end Maintainability
alpha.osx.cocoa.DirectIvarAssignmentForAnnotatedFunctions Experimental: Check for direct assignments to instance variables in the methods annotated with objc_no_direct_instance_variable_assignment @interface MyClass : NSObject {} @property (readonly) id A; – (void) fAnnotated __attribute__(( annotate(“objc_no_direct_instance_variable_assignment”))); – (void) fNotAnnotated; @end @implementation MyClass – (void) fAnnotated { _A = 0; // warn } – (void Maintainability
alpha.osx.cocoa.InstanceVariableInvalidation Experimental: Check that the invalidatable instance variables are invalidated in the methods annotated with objc_instance_variable_invalidator @protocol Invalidation – (void) invalidate __attribute__((annotate(“objc_instance_variable_invalidator”))); @end @interface InvalidationImpObj : NSObject @end @interface SubclassInvalidationImpObj : InvalidationImpObj { Invalidat Maintainability
alpha.osx.cocoa.localizability.PluralMisuseChecker Experimental: Warns against using one vs. many plural pattern in code when generating localized strings. NSString *reminderText = NSLocalizedString(@”None”, @”Indicates no reminders”); if (reminderCount == 1) { // Warning: Plural cases are not supported accross all languages. // Use a .stringsdict file instead reminderText = NSLocalizedString(@”1 Reminder”, @”Indicates single reminder”); } else if (reminderCount >= 2) { // Warning: Plural cases are not supported accross all languages. // Use a .stringsdict file instead reminderText = [NSString stringWithFormat: NSLocalizedString(@”%@ Reminders”, @”Indicates multiple reminders”), reminderCount]; } Maintainability
alpha.osx.cocoa.MissingInvalidationMethod Experimental: Check that the invalidation methods are present in classes that contain invalidatable instance variables @protocol Invalidation – (void)invalidate __attribute__((annotate(“objc_instance_variable_invalidator”))); @end @interface NeedInvalidation : NSObject @end @interface MissingInvalidationMethodDecl : NSObject { NeedInvalidation *V Resource Utilization

Medium level issues

Rule Description Example KPI
optin.osx.cocoa.localizability.NonLocalizedStringChecker Warns about uses of non-localized NSStrings passed to UI methods expecting localized NSStrings NSString *alarmText = NSLocalizedString(@”Enabled”, @”Indicates alarm is turned on”); if (!isEnabled) { alarmText = @”Disabled”; } UILabel *alarmStateLabel = [[UILabel alloc] init]; // Warning: User-facing text should use localized string macro [alarmStateLabel setText:alarmText]; Maintainability
osx.cocoa.ClassRelease Check for sending ‘retain’, ‘release’, or ‘autorelease’ directly to a Class @interface MyClass : NSObject @end void test(void) { [MyClass release]; // warn } Maintainability
osx.ObjCProperty Check for proper uses of Objective-C properties   Maintainability

Low level issues

RuleDescriptionExampleKPI
optin.osx.cocoa.localizability.EmptyLocalizationContextCheckeCheck that NSLocalizedString macros include a comment for context– (void)test { NSString *string = NSLocalizedString(@”LocalizedString”, nil); // warn NSString *string2 = NSLocalizedString(@”LocalizedString”, @” “); // warn NSString *string3 = NSLocalizedStringWithDefaultValue( @”LocalizedString”, nil, [[NSBundle allocMaintainability
osx.cocoa.LoopsImproved modeling of loops using Cocoa collection typesMaintainability
osx.cocoa.NonNilReturnValueModel the APIs that are guaranteed to return a non-nil valueMaintainability
osx.cocoa.NSAutoreleasePoolWarn for suboptimal uses of NSAutoreleasePool in Objective-C GC modevoid test() { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [pool release]; // warn }Maintainability
osx.cocoa.UnusedIvarsWarn about private ivars that are never used@interface MyObj : NSObject { @private id x; // warn } @end @implementation MyObj @endMaintainability

Java

The section below covers the Embold Java code issues, PMD, and SpotBugs code issues.


Embold Java Issues

Embold comes with a state-of-the-art proprietary analyser. In addition to integrating and building upon great work from the open source space, we have created our own checks and rules to discover code issues that were not sufficiently covered by other tools.

Critical level issues

RuleDescriptionExampleKPITags
Compile Regex OncePattern object compiles the regular expressions which are passed to them and this compilation happens in the memory. If a regular expression is used many times, then this compilation should be performed only once.Non-compliant code:
Class Foo {
// This method can call multiple times
void findText(String inputText) {
Pattern pattern = Pattern.compile("(.*)(\\d+)(.*)");
Matcher matcher = pattern.matcher(inputText);
if(matcher.find()) {
MatchResult result = matcher.toMatchResult();
}
}
}


Compliant code:
Class Foo {
Pattern pattern = Pattern.compile("(.*)(\\d+)(.*)");

void findText(String inputText) {
Matcher matcher = pattern.matcher(inputText);
if(matcher.find()) {
MatchResult result = matcher.toMatchResult();
}
}
}
Efficiency
Disabled Spring Securitys CSRFCSRF protection is enabled by default in the Java configuration. Disabling CSRF protection can create a major security threat.
Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated.

More Info - OWASP Top 10 A6:2017 - Security Misconfiguration
CWE-352 - Cross-Site Request Forgery (CSRF)
Non-compliant code:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}


Compliant code:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// Do not disable CSRF
// http.csrf().disable();
}
}
Security
Resource LeakResource should be closed in finally block. Another way is to use try-with-resource. In case of either exception or no exception, close() should always be put in finally clause.Non-compliant code:
class Demo {

public void process1() {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("out.txt", true)));
out.println("the text");
out.close(); //close() is in try clause
} catch (IOException e) {
logger.error("resource is closed in try block",e);
}
}

//Non-compliant code
//resource is not closed anywhere
public void process2() {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("out.txt", true)));
out.println("the text");
} catch (IOException e) {
logger.error("Resource is not closed anywhere.",e);
}
}
}


Compliant code:
class Demo {
public void process2() {
printWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter("out.txt", true)));
out.println("the text");
} catch (IOException e) {
logger.error("Resource is closed in finally block",e);
} finally {
if (out != null) {
out.close(); //close() is in finally clause
}
}
}

//compliant code
//try-with-resource statement
public void process3() {
try (PrintWriter out2 = new PrintWriter(new BufferedWriter(new FileWriter("out.txt", true)))) {
out2.println("the text");
} catch (IOException e) {
logger.error("try-with-resource",e);
}
}
}
Resource Utilization
Weak Cipher AlgorithmUse strong cryptographic algorithms as they are less vulnerable to brute force attacks among others.
For more information : : OWASP Top 10 2017 Category A3 - Sensitive Data Exposure
MITRE, CWE-327 - Use of a Broken or Risky Cryptographic Algorithm
Non-compliant code:
class CipherExample
{
public void foo()
{
try
{
Cipher c = Cipher.getInstance("DES"); // Or DESede, RC2, RC4 as these are known to be vulnerable
} catch (NoSuchAlgorithmException | NoSuchPaddingException e)
{
logger.error("Invalid algorithm",e);
}
}
}


Compliant code:

class CipherExample
{
public void foo()
{
try
{
Cipher c = Cipher.getInstance("AES/GCM/NoPadding"); // Compliant
} catch(NoSuchAlgorithmException|NoSuchPaddingException e)
{
logger.error("Invalid algorithm",e);
}
}
}
Security
Possible Thread Leak In Executor Service Thread leak can be possible if ExecutorService is not getting shutdown.There is a queue of tasks between client threads and thread pool. When the normal thread finishes the "run" method (Runnable or Callable), it will be passed to garbage collector for collection. But with ExecuterService, threads will be simply put on hold and they will not be selected for garbage collection. Therefore, the shutdown is needed for ExecutorService.
Non-compliant code:
class Demo {

//ExecutorService is not closed anywhere
public void process1() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
try {
doTask();
} catch (Exception e) {
logger.error("indexing failed", e);
}
}
});
}
}


Compliant code:
class Demo {

public void process2() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
try {
doTask();
} catch (Exception e) {
logger.error("indexing failed", e);
}
}
});
executorService.shutdown();
}
}

Resource Utilization
Non Private Field In Synchronized BlockNon-private, non-final field accessed in synchronized block indicates possibly partial synchronization, and does not protect direct access to the field from other parts of the system without synchronization.
Make the field private and/or final, and provide accessors which can enforce synchronization.

More Info - CWE-820 - Missing synchronization
Non-compliant code:
class NonPrivateFieldAccessInSynchronizedBlock {

protected List statuses = new ArrayList<>(); // or public
private Object lock = new Object();

void foo() {
// Some processing
synchronized(lock) {
statuses.add("Running");
}
}
// Some more processing
}


Compliant code
class NonPrivateFieldAccessInSynchronizedBlock {

private List statuses = new ArrayList<>();
private Object lock = new Object();

void foo() {
// Some processing
synchronized(lock) {
statuses.add("Running");
}

// Some more processing
}

void updateStatus(String status) {
synchronized(lock) {
statuses.add(status);
}
}
}
Robustness, Security
Database Should Be Password ProtectedDatabase connection should always be password protected. Attacker can access the sensitive data from the database, in case it is not secured by password.

More Info
- [OWASP Top 10 2017 Category A3] - Sensitive Data Exposure
- [MITRE, CWE-521] - Weak Password Requirements
Non-compliant code:
class CipherExample {
public void foo() {

Connection conn1 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", "");
Connection conn2 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true?user=user&password=");
Connection conn3 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true?user=user");
}
}


Compliant code
class CipherExample {
public void foo() {
Connection conn4 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", "password");
Connection conn5 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true?user=user&password=text");
Connection conn6 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true&password=text", "AppLogin", "");
}
}
Security
Should Not Use getRequestedSessionId APIThis method returns the session ID specified by the client and may not be the same as the ID of the current valid session for this request. If the client does not mention a session ID, it returns null.
The session ID returned is either transmitted in a cookie or a URL parameter, hence by definition nothing prevents the end-user from manually updating the value of this session ID in the HTTP request.

More Info
- [CWE-807] - Reliance on Untrusted Inputs in a Security Decision

- [OWASP] - Broken Authentication

class Demo{
// Non-compliant code
public void method(HttpServletRequest request) {
if(isActiveSession(request.getRequestedSessionId()) ){

}
}
}

Security
Web Application Contains Main MethodThis method returns the session ID specified by the client and may not be the same as the ID of the current valid session for this request. If the client does not mention a session ID, it returns null.
The session ID returned is either transmitted in a cookie or a URL parameter, hence by definition nothing prevents the end-user from manually updating the value of this session ID in the HTTP request.

More Info

- [CWE-489] - Leftover Debug Code

- [OWASP] - Sensitive Data Exposure

class Demo{
// Non-compliant code
public void method(HttpServletRequest request) {
if(isActiveSession(request.getRequestedSessionId()) ){

}
}
}


```
Security
Authenticate LDAP Connection Anonymous binds and unauthenticated binds allow access to information in the LDAP directory without providing a password. Therefore using these binds is strongly discouraged.

More Info

- [OWASP Top 10 2017 Category A2]- Broken Authentication

- [CWE-521] - Weak Password Requirements

- [ldapwiki.com] - Simple Authentication

//Non-compliant code
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
// Use anonymous authentication
env.put(Context.SECURITY_AUTHENTICATION, "none"); // Noncompliant

// Compliant code
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");

Security
Potential Command InjectionAvoid using unfiltered input to process executor APIs because that can lead to arbitrary command execution.

More Info

- [OWASP] - Command Injection

- [OWASP: Top 10 2013 A1] -Injection

- [CWE-78] - Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')


// Non-compliant code
import java.lang.Runtime;
class Demo{
Runtime r = Runtime.getRuntime();
r.exec("/bin/sh -c sometool" + input);
}

Security
Potential Path Traversal Path traversal is a web security vulnerability that allows an attacker to read arbitrary files on the server that is running an application.
This might include application code and data, credentials for back-end systems, and sensitive operating system files.

More Info
- [CWE-22] - Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

- [OWASP] - Path Traversal

// Non-compliant code
class Demo{
@GET
@Path("/images/{image}")
@Produces("images/*")
public Response getImage(@javax.ws.rs.PathParam("image") String image) {
File file = new File("resources/images/", image); //Weak point

if (!file.exists()) {
return Response.status(Status.NOT_FOUND).build();
}

return Response.ok().entity(new FileInputStream(file)).build();
}

// Compliant code
}
import org.apache.commons.io.FilenameUtils;
class Demo1{
@GET
@Path("/images/{image}")
@Produces("images/*")
public Response getImage(@javax.ws.rs.PathParam("image") String image) {
File file = new File("resources/images/", FilenameUtils.getName(image)); //Fix

if (!file.exists()) {
return Response.status(Status.NOT_FOUND).build();
}

return Response.ok().entity(new FileInputStream(file)).build();
}
}


Security
Accessing Android external storage is security-sensitiveFiles or data stored in the android application should be security-sensitive. Files can be globally readable or writable as they are stored on external storage.
Avoid storing sensitive information on the external storage as anyone can tamper with the data or remove the files by using any application.

**More Info**
- [OWASP Top 10 2017 Category A1](https://owasp.org/www-project-top-ten/2017/A1_2017-Injection.html) - Injection
- [OWASP Top 10 2017 Category A3](https://owasp.org/www-project-top-ten/2017/A3_2017-Sensitive_Data_Exposure) - Sensitive Data Exposure
- [CWE-312](https://cwe.mitre.org/data/definitions/312.html) - Cleartext Storage of Sensitive Information
- [CWE-20](https://cwe.mitre.org/data/definitions/20.html) - Improper Input Validation accessing android external storage


```java
//non-compliant
import android.content.Context;
import android.os.Environment;
public class AccessExternalFiles {
public void accessFiles(Context context) {
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); // non-compliant
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
// non-compliant
}
}


Security
Using unsafe Jackson deserialization configuration is security-sensitiveJThe untrusted data could cause abuse to application logic. Jackson's deserialization should be configured securely.
Implement @JsonTypeName and @JsonSubTypes to prevent serialized data from an untrusted source. It can help to safeguard the data from external attackers.

**More Info**
- [OWASP Top 10 2017 Category A8](https://owasp.org/www-project-top-ten/2017/A8_2017-Insecure_Deserialization) - Insecure Deserialization
- [CWE-502](https://cwe.mitre.org/data/definitions/502.html) - Deserialization of Untrusted Data


//non-compliant
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(); // non-compliant
@JsonTypeInfo(use = Id.CLASS) // non-compliant
abstract class PhoneNumber {
}



Security
Setting JavaBean properties is security-sensitiveThe JavaBean property uses a set or get functions that are exposed to other applications. An attacker can modify its properties, attack malicious code that can be risky. Avoid storing sensitive information under this JavaBean property as it may help the user to retain its software integrity.

**More Info**
- [OWASP Top 10 2017 Category A8](https://owasp.org/www-project-top-ten/2017/A8_2017-Insecure_Deserialization) - Insecure Deserialization
- [CWE-502](https://cwe.mitre.org/data/definitions/502.html) - Deserialization of Untrusted Data


//non-compliant
class Demo{
Company bean = new Company();
HashMap map = new HashMap();
Enumeration names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
map.put(name, request.getParameterValues(name));
}
BeanUtils.populate(bean, map); // "map" is populated with data coming from user input, here "request.getParameterNames()"
}



Security
Run Should Not Be Called DirectlyThe program accidentally calls the Thread.run() method and causes the code to be executed in the current thread, just like any other method call. Instead, use Thread.start() to actually create a new thread so that the runnable's 'run()' method is executed in parallel.

More Info
[CWE-572] - Call to Thread run() instead of start()
Non-compliant code
class Demo {
Thread myThread = new Thread(runnable);
myThread.run();

}


Compliant code
class Demo {
Thread myThread = new Thread(runnable);
myThread.start();
}
Functionality, Efficiency
Exclude SpringBootApplication And ComponentScan From The Default PackageExclude "SpringBootApplication" and "@ComponentScan" from the default package.Non-compliant code
import org.springframework.boot.SpringApplication;
@SpringBootApplication
public class SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackage {
public static void main(String[] args)
{
SpringApplication.run(SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackage.class, args);
}
}


Compliant code
package javacodechecker;
import org.springframework.boot.SpringApplication;
@SpringBootApplication
public class SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackage {
public static void main(String[] args)
{
SpringApplication.run(SpringBootApplicationAndComponentScanNotBeUsedInDefaultPackage.class, args);
}
}
Efficiencyspring

High level issues

RuleDescriptionExampleKPI
Initialization Of Secure Random At Method Level"SecureRandom" should not be initialized in method. Every SecureRandom generation is seeded from some entropy pool. Creating a new SecureRandom method on every call might slow down the application as it might block the creation of seed. Use a statically created instance instead.Non-compliant code
class Demo {

public int generateSecureKey() {
SecureRandom secureRandom = new SecureRandom();
return secureRandom.nextInt();
}
}


Compliant code
class SecureRandomGenerator {
static SecureRandom secureRandom = new SecureRandom();
public int generateSecureKey() {
return secureRandom.nextInt();
}
}
Security
Security Sensitive RegexRegular expressions are security-sensitive. Evaluating regular expressions with input string can be an extremely CPU-intensive task. The regular expression naive algorithm builds a Nondeterministic Finite Automaton (NFA), the attacker might use the knowledge of states of finite state machine to look for applications that use regular expressions, containing an Evil Regex, and send a well-crafted input, that will hang the system. Alternatively, if a Regex itself is affected by a user input, the attacker can inject an Evil Regex, and make the system vulnerable.
Examples of Evil Patterns:
Examples of Evil pattern : 1) (a+)+ 2) ([a-zA-Z]+)* 3) (a|aa)+ 4) (a|a?)+ 5) (.*a){2} for x > 10

E.g
Pattern: /(a+)+b/;
Input string:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab
Instead use Pattern:(/a+b/) //fixed the hard-coded regex pattern to avoid possible captures, possessive quantifiers and back-references

To avoid possible attacks, if the regex pattern is defined with an user-controlled input, it should be sanitized in order to escape characters which are part of the regular expression syntax.

Non-compliant code
class Demo { public boolean validate1(javax.servlet.http.HttpServletRequest request) { String regex = " /(a+)+b/"; String input = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab"; input.matches(regex); //Noncompliant
}
}


Compliant code
class Demo { public boolean
{
validate2(javax.servlet.http.HttpServletRequest request)
{ String regex = "/a+b/"; String input = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab";
input.matches(Pattern.quote(regex)); // Compliant
} }

Efficiency, Security
Use Of System.err.println 1. System.err.println is an IO-operation and therefore is time consuming.
2. The better approach is to use a logging framework for a message queue.
3. Moreover, you can configure separate log files for different purposes.
Non-compliant code
class Demo {
public void process1() {
System.err.println("Error while processing");
}
}


Compliant code
class Demo {
public void process2() {
logger.error("Error while processing",e);
}
}
Analyzability
Invalid Logging Class Name Avoid incorrect class names while creating logger. Ignoring this may create confusion while analysing logs.
Non-compliant code
public class LoggingClass extends BaseChecker {
private static Logger logger = LogManager.getLogger(InvalidLoggingClass.class.getName());
}


Compliant code
public class LoggingClass extends BaseChecker {
private static Logger logger = LogManager.getLogger(LoggingClass.class.getName());
}

Analyzability
Use Of System.out.println 1.Sending messages to stdout is usually inappropriate in a production environment. E.g. If you are coding a GUI app, the information should be presented to the user and not to the stdout method anywhere.
2.System.out.println is an IO-operation and therefore is time consuming. The better approach is to use a logging framework for a message queue.
3.Moreover, you can configure separate log files for different purposes.
Non-compliant code
class Demo {
public void process1() {
//some statements
System.out.println("Some text");
}


Compliant code
public void process2() {
//some statements
logger.info("Some text");
}
}

Analyzability
Complex Regex PatternAvoid usage of complex Regex pattern as it involves heavy processing.In some cases complex Regex performance test shows that regex is significantly inefficient. //Non-compliant code
class Demo {
String regex = "(.*)(\\d+)(.*)";
Pattern p = Pattern.compile(regex);
}

Efficiency
Empty Catch BlockEmpty Catch Block finds instances where an exception is caught, but nothing is done. In most circumstances, this ignores an exception which should either be acted on or reported. Avoid keeping the catch block empty. // Non-compliant code
class Demo {

public void process1() {
try {
FileInputStream fis = new FileInputStream("/tmp/bugger");
} catch (IOException ioe) {
}
}


// compliant code
public void process2() {
try {
FileInputStream fis = new FileInputStream("/tmp/bugger");
} catch (IOException ex) {
logger.error("Inside catch block",ex);
}
}
}
Analyzability
Empty Catch BlockEmpty Catch Block finds instances where an exception is caught, but nothing is done. In most circumstances, this ignores an exception which should either be acted on or reported. Avoid keeping the catch block empty. // Non-compliant code
class Demo {

public void process1() {
try {
FileInputStream fis = new FileInputStream("/tmp/bugger");
} catch (IOException ioe) {
}
}


// compliant code
public void process2() {
try {
FileInputStream fis = new FileInputStream("/tmp/bugger");
} catch (IOException ex) {
logger.error("Inside catch block",ex);
}
}
}
Analyzability
Sensitive Info LoggedLogger is used for recording application activity. Information displayed on the logs is visible to different stakeholders. Avoid logging sensitive information such as password, key, social security number etc. Not complying may compromise the system security.Non-compliant code:
class Demo {
void process1(String password) {
//Displaying sensitive information in logs
logger.info("Password received "+ password);
}
}


Compliant code
class Demo {
void process1(String password) {
//doSomething
logger.info("Password received");
}
}
Security
Main Should Not Throw AnythingThe main method should not throw any checked exception, instead, it needs to handle properly. If a non-checked exception is thrown (and not catch) in the main method, it will terminate.Non-compliant code:

public static void main(String args[]) throws Exception{
System.out.println("Hello");
}

}


Compliant code
public static void main(String[] args) {
try {
int data=50/0;
}
catch(ArithmeticException e){
System.out.println(e);
}
}
Functionality
Avoid Synchronized At Method LevelAvoid synchronized at method level. When new code is added to the existing method then method-level synchronization can cause problems so to avoid these kind of problems use block-level synchronization. Block-level synchronization helps to ensure that only the code that needs synchronization gets it.Non-compliant code:

public class SynchronizedCounter {
// Non-compliant code
private int c = 0;
public synchronized void increment() {
c++;
}
}


Compliant code
public class SynchronizedCounter {
// compliant code
private int c = 0;
public void increment() {
synchronized(Test.class) {
c++;
}
}
}
Efficiency
Shortcircuit Logic Should Be Used In Boolean ContextsUsing non-short-curcuit logic is a mistake it can also cause serious problem error.Non-compliant code:

if(getTrue() | getFalse()) {
...
}


Compliant code

if(getTrue() || getFalse()) {
...
}
Efficiency

Medium level issues

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

Low level issues

RuleDescriptionExampleKPI
Log Level Info In Catch BlockThe catch block handles exception that occurs in associated try block. In this block, the logger level is expected to be as "error". This is a good list describing the log levels :
1. Debug : Used for development and testing.
2. Information : Used to output information that is useful to run and manage your system.
3. Warning : Used for handled 'exceptions' or other important log events.
4. Error : Used to log all unhandled exceptions. This is typically logged inside a catch block at the boundary of your application.
5. Fatal : Used for special exceptions/conditions where it is imperative that we can quickly pick out these events.
Non-compliant code:
class Demo {
public void process1() {
try {
//statements where exceptions may occur
} catch(Exception ex) {
logger.info("some information",ex);
}
}
}


Compliant code:
class Demo {
public void process2() {
try {
//statements where exceptions may occur
} catch(Exception ex) {
logger.error("some information",ex);
}
}
}
Analyzability
Non Thread Safe Field DeclarationA field declared inside the spring component should be thread safe. By default, beans in spring are singleton. Multiple threads accessing the same component may produce inconsistent results, if they access fields declared globally.Non-compliant code:
class Demo {
@Service
public class LoggingClass extends BaseChecker {
private Map map = new HashMap();
void modifyMap(){
map.add("key","value");
}
}
}


Compliant code:
class Demo {
@Service
public class LoggingClass extends BaseChecker {
void modifyMap(){
Map map = new HashMap();
map.add("key","value");
}
}
}

Robustness

Info level issues

RuleDescriptionExampleKPI
String Concatenation In LoggingInstead of string concatenation use parameterized logging. Concatenation is calculated before the condition check. If you call your logging framework multiple times which turns to be false, this effort will be a waste of time. E.g. if you call your logging framework 10K times conditionally and all of them evaluates to be false, concatenation will happen 10K times.Non-compliant code:
class Demo {
//If log level is not debug, then also string concatenation will happen.
public void process1() {
logger.debug("Comparing objects: " + object1 + " and " + object2);
}
}


Compliant code:
class Demo {
public void process2() {
//Compliant code
logger.debug("Comparing objects: {} and {}",object1, object2);
}
}
Efficiency
Tightly Coupled ClassA spring component such as repository, service and controller should auto-wire the interface, instead of its implementation class. Ignoring this, will increase tight coupling among the classes Non-compliant code:
class Demo {
@RequestMapping("/users")
public class UserController
{
@Autowire
UserServiceImpl userServiceImpl;
}
}

Compliant code:
class Demo {
@RequestMapping("/users")
public class UserController
{
@Autowire
UserService userService;
}
}
Maintainability

PMD Issues

PMD is an open source static code analyser which detects code issues and bugs in Java programs. Visit their website for more detailed information on PMD and the ruleset found below.


Critical level issues

Rule Description KPI url
DoubleCheckedLocking Partially created objects can be returned by the Double Checked Locking pattern when used in Java. An optimizing JRE may assign a reference to the baz variable before it calls the constructor of the object the reference points to. Note: With Java 5, you can make Double checked locking work, if you declare the variable to be `volatile`. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
AvoidUsingShortType Java uses the ‘short’ type to reduce memory usage, not to optimize calculation. In fact, the JVM does not have any arithmetic capabilities for the short type: the JVM must convert the short into an int, do the proper calculation and convert the int back to a short. Thus any storage gains found through use of the ‘short’ type may be offset by adverse impacts on performance. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
ConstructorCallsOverridableMethod Calling overridable methods during construction poses a risk of invoking methods on an incompletely constructed object and can be difficult to debug. It may leave the sub-class unable to construct its superclass or forced to replicate the construction process completely within itself, losing the ability to call super(). If the default constructor contains a call to an overridable method, the subclass may be completely uninstantiable. Note that this includes method calls throughout the control flow graph – i.e., if a constructor Foo() calls a private method bar() that calls a public method buz(), this denotes a problem. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
CloseResource Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after use. Resource Utilization https://pmd.github.io/pmd/pmd_rules_java.html
NonThreadSafeSingleton 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. Other possible fixes are to synchronize the entire method or to use an initialize-on-demand holder class (do not use the double-check idiom). Robustness https://pmd.github.io/pmd/pmd_rules_java.html
VariableNamingConventions A variable naming conventions rule – customize this to your liking. Currently, it checks for final variables that should be fully capitalized and non-final variables that should not include underscores. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
MethodNamingConventions Method names should always begin with a lower case character, and should not contain underscores. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
ClassNamingConventions Class names should always begin with an upper case character. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidThrowingNullPointerException Avoid throwing NullPointerExceptions. These are confusing because most people will assume that the virtual machine threw it. Consider using an IllegalArgumentException instead; this will be clearly seen as a programmer-initiated exception. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html

High level issues

Rule Description KPI url
OverrideBothEqualsAndHashcode Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither. Even if you are inheriting a hashCode() from a parent class, consider implementing hashCode and explicitly delegating to your superclass. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
BrokenNullCheck The null check is broken since it will throw a NullPointerException itself. It is likely that you used || instead of&&or vice versa. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
AvoidMultipleUnaryOperators The use of multiple unary operators may be problematic, and/or confusing. Ensure that the intended usage is not a bug, or consider simplifying the expression. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
AvoidBranchingStatementAsLastInLoop Using a branching statement as the last part of a loop may be a bug, and/or is confusing. Ensure that the usage is not a bug, or consider using another approach. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
ProperCloneImplementation Object clone() should be implemented with super.clone(). Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
AvoidUsingVolatile Use of the keyword ‘volatile’ is generally used to fine tune a Java application, and therefore, requires a good expertise of the Java Memory Model. Moreover, its range of action is somewhat misknown. Therefore, the volatile keyword should not be used for maintenance purpose and portability. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidUsingNativeCode Unnecessary reliance on Java Native Interface (JNI) calls directly reduces application portability and increases the maintenance burden. Portability https://pmd.github.io/pmd/pmd_rules_java.html
DoNotCallGarbageCollectionExplicitly 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. Moreover, “modern” jvms do a very good job handling garbage collections. If memory usage issues unrelated to memory leaks develop within an application, it should be dealt with JVM options rather than within the code itself. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidReassigningParameters Reassigning values to incoming parameters is not recommended. Use temporary local variables instead. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
EqualsNull Tests for null should not use the equals() method. The ‘==’ operator should be used instead. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
AvoidSynchronizedAtMethodLevel 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. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
MissingBreakInSwitch 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. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
CompareObjectsWithEquals Use equals() to compare object references; avoid comparing them with == Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
SingleMethodSingleton Some classes contain overloaded getInstance. The problem with overloaded getInstance methods is that the instance created using the overloaded method is not cached and so, for each call and new objects will be created for every invocation. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
SingletonClassReturningNewInstance Some classes contain overloaded getInstance. The problem with overloaded getInstance methods is that the instance created using the overloaded method is not cached and so, for each call and new objects will be created for every invocation. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
ReturnEmptyArrayRatherThanNull 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. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
AbstractClassWithoutAnyMethod 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. In this case, it is probably better to use a private or protected constructor in order to prevent instantiation than make the class misleadingly abstract. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
GuardLogStatement Whenever using a log level, one should check if the loglevel is actually enabled, or otherwise skip the associate String creation and manipulation. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html
MoreThanOneLogger Normally only one logger is used in each class. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html
LoggerIsNotStaticFinal In most cases, the Logger reference can be declared as static and final. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
SystemPrintln References to System.(out|err).print are usually intended for debugging purposes and can remain in the codebase even in production code. By using a logger one can enable/disable this behaviour at will (and by priority) and avoid clogging the Standard out log. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
GuardLogStatementJavaUtil Whenever using a log level, one should check if the loglevel is actually enabled, or otherwise skip the associate String creation and manipulation. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidEnumAsIdentifier Use of the term ‘enum’ will conflict with newer versions of Java since it is a reserved word. Portability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidAssertAsIdentifier Use of the term ‘assert’ will conflict with newer versions of Java since it is a reserved word. Portability https://pmd.github.io/pmd/pmd_rules_java.html
IntegerInstantiation Calling new Integer() causes memory allocation that can be avoided by the static Integer.valueOf(). It makes use of an internal cache that recycles earlier instances making it more memory efficient. Resource Utilization https://pmd.github.io/pmd/pmd_rules_java.html
ByteInstantiation Calling new Byte() causes memory allocation that can be avoided by the static Byte.valueOf(). It makes use of an internal cache that recycles earlier instances making it more memory efficient. Resource Utilization https://pmd.github.io/pmd/pmd_rules_java.html
ShortInstantiation Calling new Short() causes memory allocation that can be avoided by the static Short.valueOf(). It makes use of an internal cache that recycles earlier instances making it more memory efficient. Resource Utilization https://pmd.github.io/pmd/pmd_rules_java.html
LongInstantiation Calling new Long() causes memory allocation that can be avoided by the static Long.valueOf(). It makes use of an internal cache that recycles earlier instances making it more memory efficient. Resource Utilization https://pmd.github.io/pmd/pmd_rules_java.html
SuspiciousEqualsMethodName The method name and parameter number are suspiciously close to equals(Object), which can denote an intention to override the equals(Object) method. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidCatchingNPE Code should never throw NullPointerExceptions under normal circumstances. A catch block may hide the original error, causing other, more subtle problems later on. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
AvoidThrowingRawExceptionTypes Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable, Exception, or Error, use a subclassed exception or error instead. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
AvoidLosingExceptionInformation 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. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html
StringInstantiation Avoid instantiating String objects; this is usually unnecessary since they are immutable and can be safely shared. Resource Utilization https://pmd.github.io/pmd/pmd_rules_java.html

Medium level issues

Rule Description KPI url
JumbledIncrementer Avoid jumbled loop incrementers – its usually a mistake, and is confusing even if intentional. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
ForLoopShouldBeWhileLoop Some for loops can be simplified to while loops, this makes them more concise. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
ReturnFromFinallyBlock Avoid returning from a finally block, this can discard exceptions. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html
UnconditionalIfStatement Do not use “if” statements whose conditionals are always true or always false. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
BooleanInstantiation Avoid instantiating Boolean objects; you can reference Boolean.TRUE, Boolean.FALSE, or call Boolean.valueOf() instead. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
CollapsibleIfStatements Sometimes two consecutive ‘if’ statements can be consolidated by separating their conditions with a boolean short-circuit operator. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
ClassCastExceptionWithToArray 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 resultin a ClassCastException. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
AvoidDecimalLiteralsInBigDecimalConstructor   Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
MisplacedNullCheck 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. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
AvoidThreadGroup Avoid using java.lang.ThreadGroup; although it is intended to be used in a threaded environment it contains methods that are not thread-safe. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
BigIntegerInstantiation Don’t create instances of already existing BigInteger (BigInteger.ZERO, BigInteger.ONE) and for Java 1.5 onwards, BigInteger.TEN and BigDecimal (BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN) Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidUsingOctalValues Integer literals should not start with zero since this denotes that the rest of literal will be interpreted as an octal value. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
AvoidUsingHardCodedIP Application with hard-coded IP addresses can become impossible to deploy in some cases. Externalizing IP adresses is preferable. Portability https://pmd.github.io/pmd/pmd_rules_java.html
CheckResultSet 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. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
CheckSkipResult The skip() method may skip a smaller number of bytes than requested. Check the returned value to find out if it was the case or not. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
DontUseFloatTypeForLoopIndices Don’t use floating point for loop indices. If you must use floating point, use double unless you’re certain that float provides enough precision and you have a compelling performance need (space or time). Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
SimplifiedTernary Look for ternary operators with the form condition ? literalBoolean : foo or condition ? foo : literalBoolean. These expressions can be simplified respectively to condition || foo when the literalBoolean is true !condition && foo when the literalBoolean is false or !condition || foo when the literalBoolean is true condition && foo when the literalBoolean is false Understandability https://pmd.github.io/pmd/pmd_rules_java.html
IfStmtsMustUseBraces Avoid using if statements without using braces to surround the code block. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
WhileLoopsMustUseBraces Avoid using ‘while’ statements without using braces to surround the code block. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
IfElseStmtsMustUseBraces Avoid using if..else statements without using surrounding braces. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
ForLoopsMustUseBraces Avoid using ‘for’ statements without using curly braces. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
CloneThrowsCloneNotSupportedException The method clone() should throw a CloneNotSupportedException. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
CloneMethodMustImplementCloneable 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. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
CloneMethodReturnTypeMustMatchClassName If a class implements cloneable the return type of the method clone() must be the class name. That way, the caller of the clone method doesn’t need to cast the returned clone to the correct type. Note: This is only possible with Java 1.5 or higher. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
CloneMethodMustBePublic The java Manual says “By convention, classes that implement this interface should override Object.clone (which is protected) with a public method.” Understandability https://pmd.github.io/pmd/pmd_rules_java.html
NPathComplexity The NPath complexity of a method is the number of acyclic execution paths through that method. A threshold of 200 is generally considered the point where measures should be taken to reduce complexity and increase readability. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
ExcessiveMethodLength When methods are excessively long this usually indicates that the method is doing more than its name/signature might suggest. They also become challenging for others to digest since excessive scrolling causes readers to lose focus. Try to reduce the method length by creating helper methods and removing any copy/pasted code. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
ExcessiveParameterList Methods with numerous parameters are a challenge to maintain, especially if most of them share the same datatype. These situations usually denote the need for new objects to wrap the numerous parameters. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
ExcessiveClassLength Excessive class file lengths are usually indications that the class may be burdened with excessive responsibilities that could be provided by external classes or functions. In breaking these methods apart the code becomes more managable and ripe for reuse. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
ExcessivePublicCount Classes with large numbers of public methods and attributes require disproportionate testing efforts since combinational side effects grow rapidly and increase risk. Refactoring these classes into smaller ones not only increases testability and reliability but also allows new variations to be developed easily. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
TooManyFields Classes that have too many fields can become unwieldy and could be redesigned to have fewer fields, possibly through grouping related fields in new objects. For example, a class with individual city/state/zip fields could park them within a single Address field. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
NcssMethodCount This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of lines of code for a given method. NCSS ignores comments, and counts actual statements. Using this algorithm, lines of code that are split are counted as one. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
NcssTypeCount This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of lines of code for a given type. NCSS ignores comments, and counts actual statements. Using this algorithm, lines of code that are split are counted as one. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
NcssConstructorCount This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of lines of code for a given constructor. NCSS ignores comments, and counts actual statements. Using this algorithm, lines of code that are split are counted as one. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
TooManyMethods A class with too many methods is probably a good suspect for refactoring, in order to reduce its complexity and find a way to have more fine grained objects. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
CommentDefaultAccessModifier To avoid mistakes if we want that a Method, Field or Nested class have a default access modifier we must add a comment at the beginning of the Method, Field or Nested class. By default the comment must be /* default */, if you want another, you have to provide a regex. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
UnnecessaryConstructor This rule detects when a constructor is not necessary; i.e., when there is only one constructor, its public, has an empty body, and takes no arguments. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
NullAssignment Assigning a “null” to a variable (outside of its declaration) is usually bad form. Sometimes, this type of assignment is an indication that the programmer doesn’t completely understand what is going on in the code. NOTE: This sort of assignment may used in some cases to dereference objects and encourage garbage collection. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
OnlyOneReturn A method should have only one exit point, and that should be the last statement in the method. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AssignmentInOperand Avoid assignments in operands; this can make code more complicated and harder to read. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AtLeastOneConstructor Each class should declare at least one constructor. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
SuspiciousOctalEscape A suspicious octal escape sequence was found inside a String literal. The Java language specification (section 3.10.6) says an octal escape sequence inside a literal String shall consist of a backslash followed by: OctalDigit | OctalDigit OctalDigit | ZeroToThree OctalDigit OctalDigit Any octal escape sequence followed by non-octal digits can be confusing, e.g. “38” is interpreted as the octal escape sequence “3” followed by the literal character “8”. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
CallSuperInConstructor It is a good practice to call super() in a constructor. If super() is not called but another constructor (such as an overloaded constructor) is called, this rule will not report it. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
DefaultPackage Use explicit scoping instead of accidental usage of default package private level. The rule allows methods and fields annotated with Guava’s @VisibleForTesting. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidFinalLocalVariable Avoid using final local variables, turn them into fields. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidAccessibilityAlteration Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(), as the interface PrivilegedAction, allows for the runtime alteration of variable, class, or method visibility, even if they are private. This violates the principle of encapsulation. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidLiteralsInIfCondition Avoid using hard-coded literals in conditional statements. By declaring them as static variables or private members with descriptive names maintainability is enhanced. By default, the literals “-1” and “0” are ignored. More exceptions can be defined with the property “ignoreMagicNumbers”. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UseObjectForClearerAPI When you write a public method, you should be thinking in terms of an API. If your method is public, it means other class will use it, therefore, you want (or need) to offer a comprehensive and evolutive API. If you pass a lot of information as a simple series of Strings, you may think of using an Object to represent all those information. You’ll get a simpler API (such as doWork(Workload workload), rather than a tedious series of Strings) and more importantly, if you need at some point to pass extra data, you’ll be able to do so by simply modifying or extending Workload without any modification to your API. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UseConcurrentHashMap Since Java5 brought a new implementation of the Map designed for multi-threaded access, you can perform efficient map reads without blocking other threads. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
CouplingBetweenObjects This rule counts the number of unique attributes, local variables, and return types within an object. A number higher than the specified threshold can indicate a high degree of coupling. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
ExcessiveImports A high number of imports can indicate a high degree of coupling within an object. This rule counts the number of unique imports and reports a violation if the count is above the user-specified threshold. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
LooseCoupling The use of implementation types as object references limits your ability to use alternate implementations in the future as requirements change. Whenever available, referencing objects by their interface types provides much more flexibility. Changeability https://pmd.github.io/pmd/pmd_rules_java.html
LoosePackageCoupling Avoid using classes from the configured package hierarchy outside of the package hierarchy, except when using one of the configured allowed classes. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
LawOfDemeter The Law of Demeter is a simple rule, that says “only talk to friends”. It helps to reduce coupling between classes or objects. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
UseUtilityClass For classes that only have static methods, consider making them utility classes. Note that this doesn’t apply to abstract classes, since their subclasses may well include non-static methods. Also, if you want this class to be a utility class, remember to add a private constructor to prevent instantiation. (Note, that this use was known before PMD 5.1.0 as UseSingleton). Understandability https://pmd.github.io/pmd/pmd_rules_java.html
SimplifyBooleanReturns Avoid unnecessary if-then-else statements when returning a boolean. The result of the conditional test can be returned instead. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
SimplifyBooleanExpressions Avoid unnecessary comparisons in boolean expressions, they serve no purpose and impacts readability. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
SwitchStmtsShouldHaveDefault All switch statements should include a default option to catch any unspecified values. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidDeeplyNestedIfStmts Avoid creating deeply nested if-then statements since they are harder to read and error-prone to maintain. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
SwitchDensity A high ratio of statements to labels in a switch statement implies that the switch statement is overloaded. Consider moving the statements into new methods or creating subclasses based on the switch variable. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AccessorClassGeneration Instantiation by way of private constructors from outside of the constructor’s class often causes the generation of an accessor. A factory method, or non-privatization of the constructor can eliminate this situation. The generated class file is actually an interface. It gives the accessing class the ability to invoke a new hidden package scope constructor that takes the interface as a supplementary parameter. This turns a private constructor effectively into one with package scope, and is challenging to discern. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
FinalFieldCouldBeStatic If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead in each object at runtime. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
NonStaticInitializer A non-static initializer block will be called any time a constructor is invoked (just prior to invoking the constructor). While this is a valid language construct, it is rarely used and is confusing. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
DefaultLabelNotLastInSwitchStmt By convention, the default label should be the last label in a switch statement. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
NonCaseLabelInSwitchStatement 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. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
OptimizableToArrayCall Calls to a collection’s toArray() method should specify target arrays sized to match the size of the collection. Initial arrays that are too small are discarded in favour of new ones that have to be created that are the proper size. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
BadComparison Avoid equality comparisons with Double.NaN. Due to the implicit lack of representation precision when comparing floating point numbers these are likely to cause logic errors. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
IdempotentOperations Avoid idempotent operations – they have no effect. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
SimpleDateFormatNeedsLocale Be sure to specify a Locale when creating SimpleDateFormat instances to ensure that locale-appropriate formatting is used. Portability https://pmd.github.io/pmd/pmd_rules_java.html
ImmutableField Identifies private fields whose values never change once they are initialized either in the declaration of the field or by a constructor. This helps in converting existing classes to becoming immutable ones. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UseLocaleWithCaseConversions When doing String.toLowerCase()/toUpperCase() conversions, use Locales to avoids problems with languages that have unusual conventions, i.e. Turkish. Portability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidProtectedFieldInFinalClass Do not use protected fields in final classes since they cannot be subclassed. Clarify your intent by using private or package access modifiers instead. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AssignmentToNonFinalStatic Identifies a possible unsafe usage of a static field. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
MissingStaticMethodInNonInstantiatableClass A class that has private constructors and does not have any static methods or fields cannot be used. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UseNotifyAllInsteadOfNotify 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; thus its usually safer to call notifyAll() instead. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidInstanceofChecksInCatchClause Each caught exception type should be handled in its own catch clause. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AbstractClassWithoutAbstractMethod 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. If the class is intended to be used as a base class only (not to be instantiated directly) a protected constructor can be provided prevent direct instantiation. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
SimplifyConditional No need to check for null before an instanceof; the instanceof keyword returns false when given a null argument. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
PositionLiteralsFirstInComparisons Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
PositionLiteralsFirstInCaseInsensitiveComparisons Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
UncommentedEmptyMethodBody Uncommented Empty Method Body finds instances where a method body does not contain statements, but there is no comment. By explicitly commenting empty method bodies it is easier to distinguish between intentional (commented) and unintentional empty methods. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UncommentedEmptyConstructor Uncommented Empty Constructor finds instances where a constructor does not contain statements, but there is no comment. By explicitly commenting empty constructors it is easier to distinguish between intentional (commented) and unintentional empty constructors. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidConstantsInterface An interface should be used only to characterize the external behaviour of an implementing class: using an interface as a container of constants is a poor usage pattern and not recommended. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UnsynchronizedStaticDateFormatter 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 either on method or block level. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
PreserveStackTrace 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. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html
UseCollectionIsEmpty 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. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
ClassWithOnlyPrivateConstructorsShouldBeFinal A class with only private constructors should be final, unless the private constructor is invoked by a inner class. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
EmptyMethodInAbstractClassShouldBeAbstract Empty or auto-generated methods in an abstract class should be tagged as abstract. This helps to remove their inapproprate usage by developers who should be implementing their own versions in the concrete subclasses. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
SingularField 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. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
TooFewBranchesForASwitchStatement Switch statements are indended 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. In these cases use the if-then statement to increase code readability. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
LogicInversion Use opposite operator instead of negating the whole expression with a logic complement operator. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
FieldDeclarationsShouldBeAtStartOfClass Fields should be declared at the top of the class, before any method declarations, constructors, initializers or inner classes. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidProtectedMethodInFinalClassNotExtending Do not use protected methods in most final classes since they cannot be subclassed. This should only be allowed in final classes that extend other classes with protected methods (whose visibility cannot be reduced). Clarify your intent by using private or package access modifiers instead. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
ConstantsInInterface Avoid constants in interfaces. Interfaces should define types, constants are implementation details better placed in classes or enums. See Effective Java, item 19. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
EmptyCatchBlock Empty Catch Block finds instances where an exception is caught, but nothing is done. In most circumstances, this swallows an exception which should either be acted on or reported. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html
EmptyIfStmt Empty If Statement finds instances where a condition is checked but nothing is done about it. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
EmptyWhileStmt 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; if it is a while loop that does a lot in the exit expression, rewrite it to make it clearer. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
EmptyTryBlock Avoid empty try blocks – what’s the point? Understandability https://pmd.github.io/pmd/pmd_rules_java.html
EmptyFinallyBlock Empty finally blocks serve no purpose and should be removed. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
EmptySwitchStatements Empty switch statements serve no purpose and should be removed. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
EmptySynchronizedBlock Empty synchronized blocks serve no purpose and should be removed. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
EmptyStatementNotInLoop 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. It could also be a double semicolon, which has no purpose and should be removed. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
EmptyInitializer Empty initializers serve no purpose and should be removed. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
EmptyStatementBlock Empty block statements serve no purpose and should be removed. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
EmptyStaticInitializer An empty static initializer serve no purpose and should be removed. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
EmptyFinalizer Empty finalize methods serve no purpose and should be removed. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
FinalizeOnlyCallsSuperFinalize If the finalize() is implemented, it should do something besides just calling super.finalize(). Understandability https://pmd.github.io/pmd/pmd_rules_java.html
FinalizeOverloaded 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. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
FinalizeDoesNotCallSuperFinalize If the finalize() is implemented, its last action should be to call super.finalize. Resource Utilization https://pmd.github.io/pmd/pmd_rules_java.html
FinalizeShouldBeProtected When overriding the finalize(), the new method should be set as protected. If made public, other classes may invoke it at inappropriate times. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidCallingFinalize 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. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
ImportFromSamePackage There is no need to import a type that lives in the same package. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
TooManyStaticImports 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. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from (Sun 1.5 Language Guide). Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UseProperClassLoader In J2EE, the getClassLoader() method might not work as expected. Use Thread.currentThread().getContextClassLoader() instead. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
DoNotCallSystemExit Web applications should not call System.exit(), since only the web container or the application server should stop the JVM. This rule also checks for the equivalent call Runtime.getRuntime().exit(). Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
StaticEJBFieldShouldBeFinal According to the J2EE specification, an EJB should not have any static fields with write access. However, static read-only fields are allowed. This ensures proper behavior especially when instances are distributed by the container on several JREs. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
DoNotUseThreads The J2EE specification explicitly forbids the use of threads. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
BeanMembersShouldSerialize If a class is a bean, or is referenced by a bean directly or indirectly it needs to be serializable. Member variables need to be marked as transient, static, or have accessor methods in the class. Marking variables as transient is the safest and easiest modification. Accessor methods should follow the Java naming conventions, i.e. for a variable named foo, getFoo() and setFoo() accessor methods should be provided. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
MissingSerialVersionUID Serializable classes should provide a serialVersionUID field. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
JUnitStaticSuite The suite() method in a JUnit test needs to be both public and static. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
JUnitSpelling Some JUnit framework methods are easy to misspell. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
JUnitAssertionsShouldIncludeMessage JUnit assertions should include an informative message – i.e., use the three-argument version of assertEquals(), not the two-argument version. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
JUnitTestsShouldIncludeAssert 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. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
TestClassWithoutTestCases 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. Test classes have test methods named testXXX. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UnnecessaryBooleanAssertion 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). If you just want a test to halt after finding an error, use the fail() method and provide an indication message of why it did. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UseAssertEqualsInsteadOfAssertTrue This rule detects JUnit assertions in object equality. These assertions should be made by more specific methods, like assertEquals. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UseAssertSameInsteadOfAssertTrue This rule detects JUnit assertions in object references equality. These assertions should be made by more specific methods, like assertSame, assertNotSame. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UseAssertNullInsteadOfAssertTrue This rule detects JUnit assertions in object references equality. These assertions should be made by more specific methods, like assertNull, assertNotNull. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
SimplifyBooleanAssertion Avoid negation in an assertTrue or assertFalse test. For example, rephrase: assertTrue(!expr); as: assertFalse(expr); Understandability https://pmd.github.io/pmd/pmd_rules_java.html
JUnitTestContainsTooManyAsserts JUnit tests should not contain too many asserts. Many asserts are indicative of a complex test, for which it is harder to verify correctness. Consider breaking the test scenario into multiple, shorter test scenarios. Customize the maximum number of assertions used by this Rule to suit your needs. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UseAssertTrueInsteadOfAssertEquals When asserting a value is the same as a literal or Boxed boolean, use assertTrue/assertFalse, instead of assertEquals. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
UseCorrectExceptionLogging To make sure the full stacktrace is printed out, use the logging statement with two arguments: a String and a Throwable. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html
ProperLogger A logger should normally be defined private static final and be associated with the correct class. Private final Log log; is also allowed for rare cases where loggers need to be passed around, with the restriction that the logger needs to be passed into the constructor. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html
GuardDebugLogging When log messages are composed by concatenating strings, the whole section should be guarded by a isDebugEnabled() check to avoid performance and memory issues. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidPrintStackTrace Avoid printStackTrace(); use a logger call instead. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
ReplaceVectorWithList Consider replacing Vector usages with the newer java.util.ArrayList if expensive thread-safe operations are not required. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
ReplaceHashtableWithMap Consider replacing Hashtable usage with the newer java.util.Map if thread safety is not required. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
ReplaceEnumerationWithIterator Consider replacing Enumeration usages with the newer java.util.Iterator Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
JUnit4TestShouldUseBeforeAnnotation In JUnit 3, the setUp method was used to set up all data entities required in running tests. JUnit 4 skips the setUp method and executes all methods annotated with @Before before all tests Understandability https://pmd.github.io/pmd/pmd_rules_java.html
JUnit4TestShouldUseAfterAnnotation In JUnit 3, the tearDown method was used to clean up all data entities required in running tests. JUnit 4 skips the tearDown method and executes all methods annotated with @After after running each test Understandability https://pmd.github.io/pmd/pmd_rules_java.html
JUnit4TestShouldUseTestAnnotation In JUnit 3, the framework executed all methods which started with the word test as a unit test. In JUnit 4, only methods annotated with the @Test annotation are executed. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
JUnit4SuitesShouldUseSuiteAnnotation In JUnit 3, test suites are indicated by the suite() method. In JUnit 4, suites are indicated through the @RunWith(Suite.class) annotation. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
JUnitUseExpected In JUnit4, use the @Test(expected) annotation to denote tests that should throw exceptions. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
ShortVariable Fields, local variables, or parameter names that are very short are not helpful to the reader. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
LongVariable Fields, formal arguments, or local variable names that are too long can make the code difficult to follow. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
ShortMethodName Method names that are very short are not helpful to the reader. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AbstractNaming Abstract classes should be named ‘AbstractXXX’. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidDollarSigns Avoid using dollar signs in variable/method/class/interface names. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
MethodWithSameNameAsEnclosingClass Non-constructor methods should not have the same name as the enclosing class. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
SuspiciousHashcodeMethodName The method name and return type are suspiciously close to hashCode(), which may denote an intention to override the hashCode() method. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
SuspiciousConstantFieldName Field names using all uppercase characters – Sun’s Java naming conventions indicating constants – should be declared as final. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidFieldNameMatchingTypeName It is somewhat confusing to have a field name matching the declaring class name. This probably means that type and/or field names should be chosen more carefully. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidFieldNameMatchingMethodName It can be confusing to have a field name with the same name as a method. While this is permitted, having information (field) and actions (method) is not clear naming. Developers versed in Smalltalk often prefer this approach as the methods denote accessor methods. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
NoPackage Detects when a class or interface does not have a package definition. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
PackageCase Detects when a package definition contains uppercase characters. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
MisleadingVariableName Detects when a non-field has a name starting with ‘m_’. This usually denotes a field and could be confusing. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
LocalVariableCouldBeFinal A local variable assigned only once can be declared final. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
MethodArgumentCouldBeFinal A method argument that is never re-assigned within the method can be declared final. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
AvoidInstantiatingObjectsInLoops New objects created within loops should be checked to see if they can created outside them and reused. Resource Utilization https://pmd.github.io/pmd/pmd_rules_java.html
UseArrayListInsteadOfVector ArrayList is a much better Collection implementation than Vector if thread-safe operation is not required. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
SimplifyStartsWith Since it passes in a literal of length 1, calls to (string).startsWith can be rewritten using (string).charAt(0) at the expense of some readability. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
UseStringBufferForStringAppends 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. Resource Utilization https://pmd.github.io/pmd/pmd_rules_java.html
UseArraysAsList 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. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
AvoidArrayLoops Instead of manually copying data between two arrays, use the efficient System.arraycopy method instead. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
UnnecessaryWrapperObjectCreation 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 begarbage-collected later. Resource Utilization https://pmd.github.io/pmd/pmd_rules_java.html
AddEmptyString 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. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
RedundantFieldInitializer 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). Understandability https://pmd.github.io/pmd/pmd_rules_java.html
PrematureDeclaration Checks for variables that are defined before they might be used. A reference is deemed to be premature if it is created right before a block of code that doesn’t use it that also has the ability to return or throw an exception. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
AvoidCatchingThrowable 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. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
SignatureDeclareThrowsException Methods that declare the generic Exception as a possible throwable are not very helpful since their failure modes are unclear. Use a class derived from RuntimeException or a more specific checked exception. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html
ExceptionAsFlowControl 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. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidRethrowingException Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
DoNotExtendJavaLangError Errors are system exceptions. Do not extend them. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
DoNotThrowExceptionInFinally 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” Robustness https://pmd.github.io/pmd/pmd_rules_java.html
AvoidThrowingNewInstanceOfSameException 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. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
AvoidCatchingGenericException Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block Robustness https://pmd.github.io/pmd/pmd_rules_java.html
AvoidDuplicateLiterals Code containing duplicate String literals can usually be improved by declaring the String as a constant field. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
StringToString Avoid calling toString() on objects already known to be string instances; this is unnecessary. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
InefficientStringBuffering Avoid concatenating non-literals in a StringBuffer constructor or append() since intermediate buffers will need to be be created and destroyed by the JVM. Resource Utilization https://pmd.github.io/pmd/pmd_rules_java.html
UnnecessaryCaseChange Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals() Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
UseStringBufferLength Use StringBuffer.length() to determine StringBuffer length rather than using StringBuffer.toString().equals(“”) or StringBuffer.toString().length() == … Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
AppendCharacterWithChar Avoid concatenating characters as strings in StringBuffer/StringBuilder.append methods. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
ConsecutiveAppendsShouldReuse Consecutively calls to StringBuffer/StringBuilder .append should reuse the target object. This can improve the performance. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
ConsecutiveLiteralAppends Consecutively calling StringBuffer/StringBuilder.append with String literals Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
UseIndexOfChar Use String.indexOf(char) when checking for the index of a single character; it executes faster. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
InefficientEmptyStringCheck String.trim().length() is an inefficient way to check if a String is really empty, as it creates a new String object just to check its size. Consider creating a static function that loops through a string, checking Character.isWhitespace() on each character and returning false if a non-whitespace character is found. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
InsufficientStringBufferDeclaration Failing to pre-size a StringBuffer or StringBuilder properly could cause it to re-size many times during runtime. This rule attempts to determine the total number the characters that are actually passed into StringBuffer.append(), but represents a best guess “worst case” scenario. An empty StringBuffer/StringBuilder constructor initializes the object to 16 characters. This default is assumed if the length of the constructor can not be determined. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
UselessStringValueOf No need to call String.valueOf to append to a string; just use the valueOf() argument directly. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
UseEqualsToCompareStrings Using ‘==’ or ‘!=’ to compare strings only works if intern version is used on both sides. Use the equals() method instead. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
AvoidStringBufferField StringBuffers/StringBuilders can grow considerably, and so may become a source of memory leaks if held within objects with long lifetimes. Resource Utilization https://pmd.github.io/pmd/pmd_rules_java.html
MethodReturnsInternalArray 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. Robustness https://pmd.github.io/pmd/pmd_rules_java.html
ArrayIsStoredDirectly Constructors and methods receiving arrays should clone objects and store the copy. This prevents future changes from the user from affecting the original array. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
UnnecessaryConversionTemporary Avoid the use temporary objects when converting primitives to Strings. Use the static conversion methods
on the wrapper classes instead.
Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
UnnecessaryReturn Avoid the use of unnecessary return statements. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UnnecessaryFinalModifier When a class has the final modifier, all the methods are automatically final and do not need to be tagged as such. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
UselessOverridingMethod The overriding method merely calls the same method defined in a superclass. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UselessOperationOnImmutable 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. Therefore, ignoring the operation result is an error.
Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
UnusedNullCheckInEquals After checking an object reference for null, you should invoke equals() on that object rather than passing it to another object’s equals() method. Accuracy https://pmd.github.io/pmd/pmd_rules_java.html
UselessQualifiedThis Look for qualified this usages in the same class. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UnusedPrivateField Detects when a private field is declared and/or assigned a value, but not used. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UnusedLocalVariable Detects when a local variable is declared and/or assigned, but not used. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UnusedPrivateMethod Unused Private Method detects when a private method is declared but is unused. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UnusedFormalParameter Avoid passing parameters to methods or constructors without actually referencing them in the method body. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
UnusedModifier Fields in interfaces are automatically public static final, and methods are public abstract. Classes or interfaces nested in an interface are automatically public and static (all nested interfaces are automatically static). For historical reasons, modifiers which are implied by the context are accepted by the compiler, but are superfluous. Understandability https://pmd.github.io/pmd/pmd_rules_java.html

Low level issue

Rule Description KPI url
ExtendsObject No need to explicitly extend Object. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
DontCallThreadRun Explicitly calling Thread.run() method will execute in the caller’s thread of control. Instead, call Thread.start() for the intended behavior. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
CommentRequired Denotes whether comments are required (or unwanted) for specific language elements. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
CommentSize Determines whether the dimensions of non-header comments found are within the specified limits. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
CommentContent A rule for the politically correct… we don’t want to offend anyone. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
DontImportSun Avoid importing anything from the ‘sun.*’ packages. These packages are not portable and are likely to change. Portability https://pmd.github.io/pmd/pmd_rules_java.html
UnnecessaryParentheses Sometimes expressions are wrapped in unnecessary parentheses, making them look like function calls. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
DataflowAnomalyAnalysis The dataflow analysis tracks local definitions, undefinitions and references to variables on different paths on the data flow. From those informations there can be found various problems. (1.) UR – Anomaly: There is a reference to a variable that was not defined before. This is a bug and leads to an error. (2.) DU – Anomaly: A recently defined variable is undefined. These anomalies may appear in normal source text. (3.) DD – Anomaly: A recently defined variable is redefined. This is ominous but don’t have to be a bug. Maintainability https://pmd.github.io/pmd/pmd_rules_java.html
OneDeclarationPerLine Java allows the use of several variables declaration of the same type on one line. However, it can lead to quite messy code. This rule looks for several declarations on the same line. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
AvoidPrefixingMethodParameters Prefixing parameters by ‘in’ or ‘out’ pollutes the name of the parameters and reduces code readability. To indicate whether or not a parameter will be modify in a method, its better to document method behavior with Javadoc. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
ConfusingTernary Avoid negation within an “if” expression with an “else” clause. For example, rephrase: if (x != y) diff(); else same(); as: if (x == y) same(); else diff(); Most “if (x != y)” cases without an “else” are often return cases, so consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, such as “does the error case go first?” or “does the common case go first?”. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
InstantiationToGetClass Avoid instantiating an object just to call getClass() on it; use the .class public member instead. Resource Utilization https://pmd.github.io/pmd/pmd_rules_java.html
UnnecessaryLocalBeforeReturn Avoid the creation of unnecessary local variables Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UseVarargs 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. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
DuplicateImports Duplicate or overlapping import statements should be avoided. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
DontImportJavaLang Avoid importing anything from the package ‘java.lang’. These classes are automatically imported (JLS 7.5.3). Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UnusedImports Avoid the use of unused import statements to prevent unwanted dependencies. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
UnnecessaryFullyQualifiedName 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. Consider using the non-fully qualified name. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
MDBAndSessionBeanNamingConvention The EJB Specification states that any MessageDrivenBean or SessionBean should be suffixed by ‘Bean’. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
RemoteSessionInterfaceNamingConvention A Remote Home interface type of a Session EJB should be suffixed by ‘Home’. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
LocalInterfaceSessionNamingConvention The Local Interface of a Session EJB should be suffixed by ‘Local’. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
LocalHomeNamingConvention The Local Home interface of a Session EJB should be suffixed by ‘LocalHome’. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
RemoteInterfaceNamingConvention Remote Interface of a Session EJB should not have a suffix. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
InvalidSlf4jMessageFormat Check for invalid message format in slf4j loggers. Analyzability https://pmd.github.io/pmd/pmd_rules_java.html
BooleanGetMethodName 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. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
ShortClassName Short Classnames with fewer than e.g. five characters are not recommended. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
GenericsNaming Names for references to generic values should be limited to a single uppercase letter. Understandability https://pmd.github.io/pmd/pmd_rules_java.html
StringBufferInstantiationWithChar Individual character values provided as initialization arguments will be converted into integers. This can lead to internal buffer sizes that are larger than expected. Efficiency https://pmd.github.io/pmd/pmd_rules_java.html
UselessParentheses Useless parentheses should be removed. Understandability https://pmd.github.io/pmd/pmd_rules_java.html

Info level issues

RuleDescriptionExampleKPI
ControlStatementBracesEnforce a policy for braces on control statements. It is recommended to use braces on ‘if … else’ statements and loop statements, even if they are optional.

More info
while (true) // not recommended
x++;

while (true) { // preferred approach
x++;
}
Maintainability
IdenticalCatchBranchesIdentical catch branches use up vertical space and increase the complexity of code without adding functionality. It’s better style to collapse identical branches into a single multi-catch branch.

More info
try {
// do something
} catch (IllegalArgumentException e) {
throw e;
} catch (IllegalStateException e) { // Can be collapsed into the previous block
throw e;
}

try {
// do something
} catch (IllegalArgumentException | IllegalStateException e) { // This is better
throw e;
}
Maintainability
LinguisticNamingThis rule finds Linguistic Naming Antipatterns. It checks for fields, that are named, as if they should be boolean but have a different type. It also checks for methods, that according to their name, should return a boolean, but don’t.

More info
public class LinguisticNaming {
int isValid; // the field name indicates a boolean, but it is an int.
boolean isTrue; // correct type of the field

void myMethod() {
int hasMoneyLocal; // the local variable name indicates a boolean, but it is an int.
boolean hasSalaryLocal; // correct naming and type
}

// the name of the method indicates, it is a boolean, but the method returns an int.
int isValid() {
return 1;
}
// correct naming and return type
boolean isSmall() {
return true;
}

// the name indicates, this is a setter, but it returns something
int setName() {
return 1;
}

// the name indicates, this is a getter, but it doesn't return anything
void getName() {
// nothing to return?
}

// the name indicates, it transforms an object and should return the result
void toDataType() {
// nothing to return?
}
// the name indicates, it transforms an object and should return the result
void grapeToWine() {
// nothing to return?
}
}
Maintainability
LocalVariableNamingConventionsConfigurable naming conventions for local variable declarations and other locally-scoped variables.

More info

class Foo {
void bar() {
int localVariable = 1; // This is in camel case, so it's ok
int local_variable = 1; // This will be reported unless you change the regex

final int i_var = 1; // final local variables can be configured separately

try {
foo();
} catch (IllegalArgumentException e_illegal) {
// exception block parameters can be configured separately
}

}
}
Maintainability

SpotBugs code checker

FindBugs is an open source static code analyzer which detects code issues and bugs in Java programs. FindBugs is released through the Lesser GNU Public License and more information can be found on their website.


High level issues

Rule Description KPI URL
NP_BOOLEAN_RETURN_NULL A method that returns either Boolean.TRUE, Boolean.FALSE or null is an accident waiting to happen. This method can be invoked as though it returned a value of type boolean, and the compiler will insert automatic unboxing of the Boolean value. If a null value is returned, this will result in a NullPointerException. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-method-with-boolean-return-type-returns-explicit-null-np-boolean-return-null
FI_FINALIZER_NULLS_FIELDS This finalizer nulls out fields. This is usually an error, as it does not aid garbage collection, and the object is going to be garbage collected anyway. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fi-finalizer-nulls-fields-fi-finalizer-nulls-fields
CN_IDIOM_NO_SUPER_CALL This non-final class defines a clone() method that does not call super.clone(). If this class (“A”) is extended by a subclass (“B”), and the subclass B calls super.clone(), then it is likely that B’s clone() method will return an object of type A, which violates the standard contract for clone().

If all clone() methods call super.clone(), then they are guaranteed to use Object.clone(), which always returns an object of the correct type.

Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#cn-clone-method-does-not-call-super-clone-cn-idiom-no-super-call
DE_MIGHT_DROP This method might drop an exception. In general, exceptions should be handled or reported in some way, or they should be thrown out of the method. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#de-method-might-drop-exception-de-might-drop
DE_MIGHT_IGNORE This method might ignore an exception. In general, exceptions should be handled or reported in some way, or they should be thrown out of the method. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#de-method-might-ignore-exception-de-might-ignore
DM_EXIT Invoking System.exit shuts down the entire Java virtual machine. This should only been done when it is appropriate. Such calls make it hard or impossible for your code to be invoked by other code. Consider throwing a RuntimeException instead. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-method-invokes-system-exit-dm-exit
JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS The class is annotated with net.jcip.annotations.Immutable or javax.annotation.concurrent.Immutable, and the rules for those annotations require that all fields are final. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#jcip-fields-of-immutable-classes-should-be-final-jcip-field-isnt-final-in-immutable-class
DM_RUN_FINALIZERS_ON_EXIT Never call System.runFinalizersOnExit or Runtime.runFinalizersOnExit for any reason: they are among the most dangerous methods in the Java libraries. — Joshua Bloch Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-method-invokes-dangerous-method-runfinalizersonexit-dm-run-finalizers-on-exit
NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT This implementation of equals(Object) violates the contract defined by java.lang.Object.equals() because it does not check for null being passed as the argument. All equals() methods should return false if passed a null value. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-equals-method-does-not-check-for-null-argument-np-equals-should-handle-null-argument
FI_NULLIFY_SUPER This empty finalize() method explicitly negates the effect of any finalizer defined by its superclass. Any finalizer actions defined for the superclass will not be performed. Unless this is intended, delete this method. Analyzability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fi-finalizer-nullifies-superclass-finalizer-fi-nullify-super
FI_USELESS The only thing this finalize() method does is call the superclass’s finalize() method, making it redundant. Delete it. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fi-finalizer-does-nothing-but-call-superclass-finalizer-fi-useless
FI_MISSING_SUPER_CALL This finalize() method does not make a call to its superclass’s finalize() method. So, any finalizer actions defined for the superclass will not be performed. Add a call to super.finalize(). Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fi-finalizer-does-not-call-superclass-finalizer-fi-missing-super-call
FI_EXPLICIT_INVOCATION This method contains an explicit invocation of the finalize() method on an object. Because finalizer methods are supposed to be executed once, and only by the VM, this is a bad idea.

If a connected set of objects beings finalizable, then the VM will invoke the finalize method on all the finalizable object, possibly at the same time in different threads. Thus, it is a particularly bad idea, in the finalize method for a class X, invoke finalize on objects referenced by X, because they may already be getting finalized in a separate thread.

Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fi-explicit-invocation-of-finalizer-fi-explicit-invocation
EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS This equals method is checking to see if the argument is some incompatible type (i.e., a class that is neither a supertype nor subtype of the class that defines the equals method). Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-equals-checks-for-incompatible-operand-eq-check-for-operand-not-compatible-with-this
EQ_GETCLASS_AND_CLASS_CONSTANT This class has an equals method that will be broken if it is inherited by subclasses. It compares a class literal with the class of the argument (e.g., in class Foo it might check if Foo.class == o.getClass()). It is better to check if this.getClass() == o.getClass(). Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-equals-method-fails-for-subtypes-eq-getclass-and-class-constant
CO_COMPARETO_INCORRECT_FLOATING This method compares double or float values using pattern like this: val1 > val2 ? 1 : val1 < val2 ? -1 : 0. This pattern works incorrectly for -0.0 and NaN values which may result in incorrect sorting result or broken collection (if compared values are used as keys). Consider using Double.compare or Float.compare static methods which handle all the special cases correctly. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#co-compareto-compare-incorrectly-handles-float-or-double-value-co-compareto-incorrect-floating
ES_COMPARING_STRINGS_WITH_EQ This code compares java.lang.String objects for reference equality using the == or != operators. Unless both strings are either constants in a source file, or have been interned using the String.intern() method, the same string value may be represented by two different String objects. Consider using the equals(Object) method instead. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#es-comparison-of-string-objects-using-or-es-comparing-strings-with-eq
ES_COMPARING_PARAMETER_STRING_WITH_EQ This code compares a java.lang.String parameter for reference equality using the == or != operators. Requiring callers to pass only String constants or interned strings to a method is unnecessarily fragile, and rarely leads to measurable performance gains. Consider using the equals(Object) method instead. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#es-comparison-of-string-parameter-using-or-es-comparing-parameter-string-with-eq
HE_HASHCODE_NO_EQUALS This class defines a hashCode() method but not an equals() method. Therefore, the class may violate the invariant that equal objects must have equal hashcodes. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#he-class-defines-hashcode-but-not-equals-he-hashcode-no-equals
HE_EQUALS_USE_HASHCODE This class overrides equals(Object), but does not override hashCode(), and inherits the implementation of hashCode() from java.lang.Object (which returns the identity hash code, an arbitrary value assigned to the object by the VM). Therefore, the class is very likely to violate the invariant that equal objects must have equal hashcodes. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#he-class-defines-equals-and-uses-object-hashcode-he-equals-use-hashcode
HE_INHERITS_EQUALS_USE_HASHCODE This class inherits equals(Object) from an abstract superclass, and hashCode() from java.lang.Object (which returns the identity hash code, an arbitrary value assigned to the object by the VM). Therefore, the class is very likely to violate the invariant that equal objects must have equal hashcodes.

If you don’t want to define a hashCode method, and/or don’t believe the object will ever be put into a HashMap/Hashtable, define the hashCode() method to throw UnsupportedOperationException.

Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#he-class-inherits-equals-and-uses-object-hashcode-he-inherits-equals-use-hashcode
HE_EQUALS_NO_HASHCODE This class overrides equals(Object), but does not override hashCode(). Therefore, the class may violate the invariant that equal objects must have equal hashcodes. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#he-class-defines-equals-but-not-hashcode-he-equals-no-hashcode
IT_NO_SUCH_ELEMENT This class implements the java.util.Iterator interface. However, its next() method is not capable of throwing java.util.NoSuchElementException. The next() method should be changed so it throws NoSuchElementException if is called when there are no more elements to return. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#it-iterator-next-method-can-t-throw-nosuchelementexception-it-no-such-element
SE_NO_SERIALVERSIONID This class implements the Serializable interface, but does not define a serialVersionUID field. A change as simple as adding a reference to a .class object will add synthetic fields to the class, which will unfortunately change the implicit serialVersionUID (e.g., adding a reference to String.class will generate a static field class$java$lang$String). Also, different source code to bytecode compilers may use different naming conventions for synthetic variables generated for references to class objects or inner classes. To ensure interoperability of Serializable across versions, consider adding an explicit serialVersionUID. Portability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#snvi-class-is-serializable-but-doesn-t-define-serialversionuid-se-no-serialversionid
SE_TRANSIENT_FIELD_NOT_RESTORED This class contains a field that is updated at multiple places in the class, thus it seems to be part of the state of the class. However, since the field is marked as transient and not set in readObject or readResolve, it will contain the default value in any deserialized instance of the class. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#se-transient-field-that-isn-t-set-by-deserialization-se-transient-field-not-restored
NP_TOSTRING_COULD_RETURN_NULL This toString method seems to return null in some circumstances. A liberal reading of the spec could be interpreted as allowing this, but it is probably a bad idea and could cause other code to break. Return the empty string or some other appropriate string rather than null. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-tostring-method-may-return-null-np-tostring-could-return-null
OS_OPEN_STREAM The method creates an IO stream object, does not assign it to any fields, pass it to other methods that might close it, or return it, and does not appear to close the stream on all paths out of the method. This may result in a file descriptor leak. It is generally a good idea to use a finally block to ensure that streams are closed. Resource Utilization https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#os-method-may-fail-to-close-stream-os-open-stream
OS_OPEN_STREAM_EXCEPTION_PATH The method creates an IO stream object, does not assign it to any fields, pass it to other methods, or return it, and does not appear to close it on all possible exception paths out of the method. This may result in a file descriptor leak. It is generally a good idea to use a finally block to ensure that streams are closed. Resource Utilization https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#os-method-may-fail-to-close-stream-on-exception-os-open-stream-exception-path
RC_REF_COMPARISON_BAD_PRACTICE This method compares a reference value to a constant using the == or != operator, where the correct way to compare instances of this type is generally with the equals() method. It is possible to create distinct instances that are equal but do not compare as == since they are different objects. Examples of classes which should generally not be compared by reference are java.lang.Integer, java.lang.Float, etc. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rc-suspicious-reference-comparison-to-constant-rc-ref-comparison-bad-practice
RC_REF_COMPARISON_BAD_PRACTICE_BOOLEAN This method compares two Boolean values using the == or != operator. Normally, there are only two Boolean values (Boolean.TRUE and Boolean.FALSE), but it is possible to create other Boolean objects using the new Boolean(b) constructor. It is best to avoid such objects, but if they do exist, then checking Boolean objects for equality using == or != will give results than are different than you would get using .equals(…). Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rc-suspicious-reference-comparison-of-boolean-values-rc-ref-comparison-bad-practice-boolean
ODR_OPEN_DATABASE_RESOURCE The method creates a database resource (such as a database connection or row set), does not assign it to any fields, pass it to other methods, or return it, and does not appear to close the object on all paths out of the method. Failure to close database resources on all paths out of a method may result in poor performance, and could cause the application to have problems communicating with the database. Resource Utilization https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#odr-method-may-fail-to-close-database-resource-odr-open-database-resource
ODR_OPEN_DATABASE_RESOURCE_EXCEPTION_PATH The method creates a database resource (such as a database connection or row set), does not assign it to any fields, pass it to other methods, or return it, and does not appear to close the object on all exception paths out of the method. Failure to close database resources on all paths out of a method may result in poor performance, and could cause the application to have problems communicating with the database. Resource Utilization https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#odr-method-may-fail-to-close-database-resource-on-exception-odr-open-database-resource-exception-path
J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION This code seems to be storing a non-serializable object into an HttpSession. If this session is passivated or migrated, an error will result. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#j2ee-store-of-non-serializable-object-into-httpsession-j2ee-store-of-non-serializable-object-into-session
DMI_USING_REMOVEALL_TO_CLEAR_COLLECTION If you want to remove all elements from a collection c, use c.clear, not c.removeAll(c). Calling c.removeAll(c) to clear a collection is less clear, susceptible to errors from typos, less efficient and for some collections, might throw a ConcurrentModificationException. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-don-t-use-removeall-to-clear-a-collection-dmi-using-removeall-to-clear-collection
NP_OPTIONAL_RETURN_NULL The usage of Optional return type (java.util.Optional or com.google.common.base.Optional) always means that explicit null returns were not desired by design. Returning a null value in such case is a contract violation and will most likely break client code. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-method-with-optional-return-type-returns-explicit-null-np-optional-return-null
VR_UNRESOLVABLE_REFERENCE This class makes a reference to a class or method that can not be resolved using against the libraries it is being analyzed with. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#vr-class-makes-reference-to-unresolvable-class-or-method-vr-unresolvable-reference
IL_INFINITE_LOOP This loop doesn’t seem to have a way to terminate (other than by perhaps throwing an exception). Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#il-an-apparent-infinite-loop-il-infinite-loop
FL_MATH_USING_FLOAT_PRECISION The method performs math operations using floating point precision. Floating point precision is very imprecise. For example, 16777216.0f + 1.0f = 16777216.0f. Consider using double math instead. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fl-method-performs-math-using-floating-point-precision-fl-math-using-float-precision
NP_ARGUMENT_MIGHT_BE_NULL A parameter to this method has been identified as a value that should always be checked to see whether or not it is null, but it is being dereferenced without a preceding null check. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-method-does-not-check-for-null-argument-np-argument-might-be-null
EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC This class defines an equals method that overrides an equals method in a superclass. Both equals methods methods use instanceof in the determination of whether two objects are equal. This is fraught with peril, since it is important that the equals method is symmetrical (in other words, a.equals(b) == b.equals(a)). If B is a subtype of A, and A’s equals method checks that the argument is an instanceof A, and B’s equals method checks that the argument is an instanceof B, it is quite likely that the equivalence relation defined by these methods is not symmetric. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-equals-method-overrides-equals-in-superclass-and-may-not-be-symmetric-eq-overriding-equals-not-symmetric
EQ_DONT_DEFINE_EQUALS_FOR_ENUM This class defines an enumeration, and equality on enumerations are defined using object identity. Defining a covariant equals method for an enumeration value is exceptionally bad practice, since it would likely result in having two different enumeration values that compare as equals using the covariant enum method, and as not equal when compared normally. Don’t do it. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-covariant-equals-method-defined-for-enum-eq-dont-define-equals-for-enum
RANGE_ARRAY_INDEX Array operation is performed, but array index is out of bounds, which will result in ArrayIndexOutOfBoundsException at runtime. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#range-array-index-is-out-of-bounds-range-array-index
RANGE_ARRAY_OFFSET Method is called with array parameter and offset parameter, but the offset is out of bounds. This will result in IndexOutOfBoundsException at runtime. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#range-array-offset-is-out-of-bounds-range-array-offset
RANGE_ARRAY_LENGTH Method is called with array parameter and length parameter, but the length is out of bounds. This will result in IndexOutOfBoundsException at runtime. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#range-array-length-is-out-of-bounds-range-array-length
RANGE_STRING_INDEX String method is called and specified string index is out of bounds. This will result in StringIndexOutOfBoundsException at runtime. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#range-string-index-is-out-of-bounds-range-string-index
NP_ALWAYS_NULL A null pointer is dereferenced here. This will lead to a NullPointerException when the code is executed. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-null-pointer-dereference-np-always-null
NP_CLOSING_NULL close() is being invoked on a value that is always null. If this statement is executed, a null pointer exception will occur. But the big risk here you never close something that should be closed. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-close-invoked-on-a-value-that-is-always-null-np-closing-null
NP_STORE_INTO_NONNULL_FIELD A value that could be null is stored into a field that has been annotated as @Nonnull. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-store-of-null-value-into-field-annotated-nonnull-np-store-into-nonnull-field
NP_ALWAYS_NULL_EXCEPTION A pointer which is null on an exception path is dereferenced here. This will lead to a NullPointerException when the code is executed. Note that because SpotBugs currently does not prune infeasible exception paths, this may be a false warning.

Also note that SpotBugs considers the default case of a switch statement to be an exception path, since the default case is often infeasible.

Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-null-pointer-dereference-in-method-on-exception-path-np-always-null-exception
NP_NULL_ON_SOME_PATH There is a branch of statement that, if executed, guarantees that a null value will be dereferenced, which would generate a NullPointerException when the code is executed. Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can’t ever be executed; deciding that is beyond the ability of SpotBugs. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-possible-null-pointer-dereference-np-null-on-some-path
NP_NULL_ON_SOME_PATH_EXCEPTION A reference value which is null on some exception control path is dereferenced here. This may lead to a NullPointerException when the code is executed. Note that because SpotBugs currently does not prune infeasible exception paths, this may be a false warning.

Also note that SpotBugs considers the default case of a switch statement to be an exception path, since the default case is often infeasible.

Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-possible-null-pointer-dereference-in-method-on-exception-path-np-null-on-some-path-exception
NP_NULL_PARAM_DEREF This method call passes a null value for a non-null method parameter. Either the parameter is annotated as a parameter that should always be non-null, or analysis has shown that it will always be dereferenced. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-method-call-passes-null-for-non-null-parameter-np-null-param-deref
NP_NULL_PARAM_DEREF_NONVIRTUAL A possibly-null value is passed to a non-null method parameter. Either the parameter is annotated as a parameter that should always be non-null, or analysis has shown that it will always be dereferenced. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-non-virtual-method-call-passes-null-for-non-null-parameter-np-null-param-deref-nonvirtual
NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS A possibly-null value is passed at a call site where all known target methods require the parameter to be non-null. Either the parameter is annotated as a parameter that should always be non-null, or analysis has shown that it will always be dereferenced. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-method-call-passes-null-for-non-null-parameter-np-null-param-deref-all-targets-dangerous
NP_GUARANTEED_DEREF There is a statement or branch that if executed guarantees that a value is null at this point, and that value that is guaranteed to be dereferenced (except on forward paths involving runtime exceptions).

Note that a check such as if (x == null) throw new NullPointerException(); is treated as a dereference of x.

Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-null-value-is-guaranteed-to-be-dereferenced-np-guaranteed-deref
RC_REF_COMPARISON This method compares two reference values using the == or != operator, where the correct way to compare instances of this type is generally with the equals() method. It is possible to create distinct instances that are equal but do not compare as == since they are different objects. Examples of classes which should generally not be compared by reference are java.lang.Integer, java.lang.Float, etc. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rc-suspicious-reference-comparison-rc-ref-comparison
VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG This code passes a primitive array to a function that takes a variable number of object arguments. This creates an array of length one to hold the primitive array and passes it to the function. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#va-primitive-array-passed-to-function-expecting-a-variable-number-of-object-arguments-va-primitive-array-passed-to-object-vararg
BAC_BAD_APPLET_CONSTRUCTOR This constructor calls methods in the parent Applet that rely on the AppletStub. Since the AppletStub isn’t initialized until the init() method of this applet is called, these methods will not perform correctly. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bac-bad-applet-constructor-relies-on-uninitialized-appletstub-bac-bad-applet-constructor
DMI_LONG_BITS_TO_DOUBLE_INVOKED_ON_INT The Double.longBitsToDouble method is invoked, but a 32 bit int value is passed as an argument. This almost certainly is not intended and is unlikely to give the intended result. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-double-longbitstodouble-invoked-on-an-int-dmi-long-bits-to-double-invoked-on-int
BC_IMPOSSIBLE_CAST This cast will always throw a ClassCastException. SpotBugs tracks type information from instanceof checks, and also uses more precise information about the types of values returned from methods and loaded from fields. Thus, it may have more precise information that just the declared type of a variable, and can use this to determine that a cast will always throw an exception at runtime. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bc-impossible-cast-bc-impossible-cast
OBL_UNSATISFIED_OBLIGATION This method may fail to clean up (close, dispose of) a stream, database object, or other resource requiring an explicit cleanup operation.

In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns.

This bug pattern is essentially the same as the OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE bug patterns, but is based on a different (and hopefully better) static analysis technique. We are interested is getting feedback about the usefulness of this bug pattern.

Resource Utilization https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#obl-method-may-fail-to-clean-up-stream-or-resource-obl-unsatisfied-obligation
OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE This method may fail to clean up (close, dispose of) a stream, database object, or other resource requiring an explicit cleanup operation. In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns.

This bug pattern is essentially the same as the OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE bug patterns, but is based on a different (and hopefully better) static analysis technique. We are interested is getting feedback about the usefulness of this bug pattern. In particular, the false-positive suppression heuristics for this bug pattern have not been extensively tuned, so reports about false positives are helpful to us.

Resource Utilization https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#obl-method-may-fail-to-clean-up-stream-or-resource-on-checked-exception-obl-unsatisfied-obligation-exception-edge
DP_DO_INSIDE_DO_PRIVILEGED This code invokes a method that requires a security permission check. If this code will be granted security permissions, but might be invoked by code that does not have security permissions, then the invocation needs to occur inside a doPrivileged block. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dp-method-invoked-that-should-be-only-be-invoked-inside-a-doprivileged-block-dp-do-inside-do-privileged
DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED This code creates a classloader, which needs permission if a security manage is installed. If this code might be invoked by code that does not have security permissions, then the classloader creation needs to occur inside a doPrivileged block. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dp-classloaders-should-only-be-created-inside-doprivileged-block-dp-create-classloader-inside-do-privileged
MS_EXPOSE_REP A public static method returns a reference to an array that is part of the static state of the class. Any code that calls this method can freely modify the underlying array. One fix is to return a copy of the array. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ms-public-static-method-may-expose-internal-representation-by-returning-array-ms-expose-rep
EI_EXPOSE_REP Returning a reference to a mutable object value stored in one of the object’s fields exposes the internal representation of the object. If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Returning a new copy of the object is better approach in many situations. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ei-may-expose-internal-representation-by-returning-reference-to-mutable-object-ei-expose-rep
EI_EXPOSE_REP2 This code stores a reference to an externally mutable object into the internal representation of the object. If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Storing a copy of the object is better approach in many situations. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ei2-may-expose-internal-representation-by-incorporating-reference-to-mutable-object-ei-expose-rep2
EI_EXPOSE_STATIC_REP2 This code stores a reference to an externally mutable object into a static field. If unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Storing a copy of the object is better approach in many situations. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ms-may-expose-internal-static-state-by-storing-a-mutable-object-into-a-static-field-ei-expose-static-rep2
DL_SYNCHRONIZATION_ON_SHARED_CONSTANT The code synchronizes on interned String. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dl-synchronization-on-interned-string-dl-synchronization-on-shared-constant
DL_SYNCHRONIZATION_ON_BOOLEAN The code synchronizes on a boxed primitive constant, such as a Boolean. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dl-synchronization-on-boolean-dl-synchronization-on-boolean
DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE The code synchronizes on a boxed primitive constant, such as an Integer. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dl-synchronization-on-boxed-primitive-dl-synchronization-on-boxed-primitive
DL_SYNCHRONIZATION_ON_UNSHARED_BOXED_PRIMITIVE The code synchronizes on an apparently unshared boxed primitive, such as an Integer. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dl-synchronization-on-boxed-primitive-values-dl-synchronization-on-unshared-boxed-primitive
SC_START_IN_CTOR The constructor starts a thread. This is likely to be wrong if the class is ever extended/subclassed, since the thread will be started before the subclass constructor is started. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#sc-constructor-invokes-thread-start-sc-start-in-ctor
UL_UNRELEASED_LOCK This method acquires a JSR-166 (java.util.concurrent) lock, but does not release it on all paths out of the method. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ul-method-does-not-release-lock-on-all-paths-ul-unreleased-lock
UL_UNRELEASED_LOCK_EXCEPTION_PATH This method acquires a JSR-166 (java.util.concurrent) lock, but does not release it on all exception paths out of the method. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ul-method-does-not-release-lock-on-all-exception-paths-ul-unreleased-lock-exception-path
LI_LAZY_INIT_STATIC This method contains an unsynchronized lazy initialization of a non-volatile static field. Because the compiler or processor may reorder instructions, threads are not guaranteed to see a completely initialized object, if the method can be called by multiple threads. You can make the field volatile to correct the problem. For more information, see the Java Memory Model web site. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#li-incorrect-lazy-initialization-of-static-field-li-lazy-init-static
LI_LAZY_INIT_UPDATE_STATIC This method contains an unsynchronized lazy initialization of a static field. After the field is set, the object stored into that location is further updated or accessed. The setting of the field is visible to other threads as soon as it is set. If the further accesses in the method that set the field serve to initialize the object, then you have a very serious multithreading bug, unless something else prevents any other thread from accessing the stored object until it is fully initialized.

Even if you feel confident that the method is never called by multiple threads, it might be better to not set the static field until the value you are setting it to is fully populated/initialized.

Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#li-incorrect-lazy-initialization-and-update-of-static-field-li-lazy-init-update-static
SWL_SLEEP_WITH_LOCK_HELD This method calls Thread.sleep() with a lock held. This may result in very poor performance and scalability, or a deadlock, since other threads may be waiting to acquire the lock. It is a much better idea to call wait() on the lock, which releases the lock and allows other threads to run. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#swl-method-calls-thread-sleep-with-a-lock-held-swl-sleep-with-lock-held
DMI_BLOCKING_METHODS_ON_URL The equals and hashCode method of URL perform domain name resolution, this can result in a big performance hit. See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html for more information. Consider using java.net.URI instead. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-the-equals-and-hashcode-methods-of-url-are-blocking-dmi-blocking-methods-on-url
DMI_COLLECTION_OF_URLS This method or field is or uses a Map or Set of URLs. Since both the equals and hashCode method of URL perform domain name resolution, this can result in a big performance hit. See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html for more information. Consider using java.net.URI instead. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-maps-and-sets-of-urls-can-be-performance-hogs-dmi-collection-of-urls
DM_GC Code explicitly invokes garbage collection. Except for specific use in benchmarking, this is very dubious.

In the past, situations where people have explicitly invoked the garbage collector in routines such as close or finalize methods has led to huge performance black holes. Garbage collection can be expensive. Any situation that forces hundreds or thousands of garbage collections will bring the machine to a crawl.

Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-explicit-garbage-collection-extremely-dubious-except-in-benchmarking-code-dm-gc
WMI_WRONG_MAP_ITERATOR This method accesses the value of a Map entry, using a key that was retrieved from a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#wmi-inefficient-use-of-keyset-iterator-instead-of-entryset-iterator-wmi-wrong-map-iterator
XSS_REQUEST_PARAMETER_TO_SEND_ERROR This code directly writes an HTTP parameter to a Server error page (using HttpServletResponse.sendError). Echoing this untrusted input allows for a reflected cross site scripting vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting for more information.

SpotBugs looks only for the most blatant, obvious cases of cross site scripting. If SpotBugs found any, you almost certainly have more cross site scripting vulnerabilities that SpotBugs doesn’t report. If you are concerned about cross site scripting, you should seriously consider using a commercial static analysis or pen-testing tool.

Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#xss-servlet-reflected-cross-site-scripting-vulnerability-in-error-page-xss-request-parameter-to-send-error
XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER This code directly writes an HTTP parameter to Servlet output, which allows for a reflected cross site scripting vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting for more information.

SpotBugs looks only for the most blatant, obvious cases of cross site scripting. If SpotBugs found any, you almost certainly have more cross site scripting vulnerabilities that SpotBugs doesn’t report. If you are concerned about cross site scripting, you should seriously consider using a commercial static analysis or pen-testing tool.

Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#xss-servlet-reflected-cross-site-scripting-vulnerability-xss-request-parameter-to-servlet-writer
XSS_REQUEST_PARAMETER_TO_JSP_WRITER This code directly writes an HTTP parameter to JSP output, which allows for a cross site scripting vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting for more information.

SpotBugs looks only for the most blatant, obvious cases of cross site scripting. If SpotBugs found any, you almost certainly have more cross site scripting vulnerabilities that SpotBugs doesn’t report. If you are concerned about cross site scripting, you should seriously consider using a commercial static analysis or pen-testing tool.

Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#xss-jsp-reflected-cross-site-scripting-vulnerability-xss-request-parameter-to-jsp-writer
HRS_REQUEST_PARAMETER_TO_HTTP_HEADER This code directly writes an HTTP parameter to an HTTP header, which allows for a HTTP response splitting vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting for more information.

SpotBugs looks only for the most blatant, obvious cases of HTTP response splitting. If SpotBugs found any, you almost certainly have more vulnerabilities that SpotBugs doesn’t report. If you are concerned about HTTP response splitting, you should seriously consider using a commercial static analysis or pen-testing tool.

Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#hrs-http-response-splitting-vulnerability-hrs-request-parameter-to-http-header
HRS_REQUEST_PARAMETER_TO_COOKIE This code constructs an HTTP Cookie using an untrusted HTTP parameter. If this cookie is added to an HTTP response, it will allow a HTTP response splitting vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting for more information.

SpotBugs looks only for the most blatant, obvious cases of HTTP response splitting. If SpotBugs found any, you almost certainly have more vulnerabilities that SpotBugs doesn’t report. If you are concerned about HTTP response splitting, you should seriously consider using a commercial static analysis or pen-testing tool.

Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#hrs-http-cookie-formed-from-untrusted-input-hrs-request-parameter-to-cookie
PT_ABSOLUTE_PATH_TRAVERSAL The software uses an HTTP request parameter to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as “/abs/path” that can resolve to a location that is outside of that directory. See http://cwe.mitre.org/data/definitions/36.html for more information.

SpotBugs looks only for the most blatant, obvious cases of absolute path traversal. If SpotBugs found any, you almost certainly have more vulnerabilities that SpotBugs doesn’t report. If you are concerned about absolute path traversal, you should seriously consider using a commercial static analysis or pen-testing tool.

Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#pt-absolute-path-traversal-in-servlet-pt-absolute-path-traversal
PT_RELATIVE_PATH_TRAVERSAL The software uses an HTTP request parameter to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as “..” that can resolve to a location that is outside of that directory. See http://cwe.mitre.org/data/definitions/23.html for more information.

SpotBugs looks only for the most blatant, obvious cases of relative path traversal. If SpotBugs found any, you almost certainly have more vulnerabilities that SpotBugs doesn’t report. If you are concerned about relative path traversal, you should seriously consider using a commercial static analysis or pen-testing tool.

Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#pt-relative-path-traversal-in-servlet-pt-relative-path-traversal
DMI_CONSTANT_DB_PASSWORD This code creates a database connect using a hardcoded, constant password. Anyone with access to either the source code or the compiled code can easily learn the password. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-hardcoded-constant-database-password-dmi-constant-db-password
DMI_EMPTY_DB_PASSWORD This code creates a database connect using a blank or empty password. This indicates that the database is not protected by a password. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-empty-database-password-dmi-empty-db-password
SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE The method invokes the execute or addBatch method on an SQL statement with a String that seems to be dynamically generated. Consider using a prepared statement instead. It is more efficient and less vulnerable to SQL injection attacks.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#sql-nonconstant-string-passed-to-execute-or-addbatch-method-on-an-sql-statement-sql-nonconstant-string-passed-to-execute
SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING The code creates an SQL prepared statement from a nonconstant String. If unchecked, tainted data from a user is used in building this String, SQL injection could be used to make the prepared statement do something unexpected and undesirable.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#sql-a-prepared-statement-is-generated-from-a-nonconstant-string-sql-prepared-statement-generated-from-nonconstant-string
CAA_COVARIANT_ARRAY_FIELD Array of covariant type is assigned to a field. This is confusing and may lead to ArrayStoreException at runtime if the reference of some other type will be stored in this array later like in the following code:

Number[] arr = new Integer[10];
arr[0] = 1.0;

  https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#caa-covariant-array-assignment-to-a-field-caa-covariant-array-field
CAA_COVARIANT_ARRAY_RETURN Array of covariant type is returned from the method. This is confusing and may lead to ArrayStoreException at runtime if the calling code will try to store the reference of some other type in the returned array.

Consider changing the type of created array or the method return type.

  https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#caa-covariant-array-is-returned-from-the-method-caa-covariant-array-return
CAA_COVARIANT_ARRAY_LOCAL Array of covariant type is assigned to a local variable. This is confusing and may lead to ArrayStoreException at runtime if the reference of some other type will be stored in this array later like in the following code:

Number[] arr = new Integer[10];
arr[0] = 1.0;

  https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#caa-covariant-array-assignment-to-a-local-variable-caa-covariant-array-local
DMI_UNSUPPORTED_METHOD All targets of this method invocation throw an UnsupportedOperationException.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-call-to-unsupported-method-dmi-unsupported-method
DMI_THREAD_PASSED_WHERE_RUNNABLE_EXPECTED A Thread object is passed as a parameter to a method where a Runnable is expected. This is rather unusual, and may indicate a logic error or cause unexpected behavior.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-thread-passed-where-runnable-expected-dmi-thread-passed-where-runnable-expected
NS_DANGEROUS_NON_SHORT_CIRCUIT This code seems to be using non-short-circuit logic (e.g., & or |) rather than short-circuit logic (&& or ||). In addition, it seem possible that, depending on the value of the left hand side, you might not want to evaluate the right hand side (because it would have side effects, could cause an exception or could be expensive.

Non-short-circuit logic causes both sides of the expression to be evaluated even when the result can be inferred from knowing the left-hand side. This can be less efficient and can result in errors if the left-hand side guards cases when evaluating the right-hand side can generate an error.

  https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ns-potentially-dangerous-use-of-non-short-circuit-logic-ns-dangerous-non-short-circuit
IC_INIT_CIRCULARITY A circularity was detected in the static initializers of the two classes referenced by the bug instance. Many kinds of unexpected behavior may arise from such circularity.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ic-initialization-circularity-ic-init-circularity
QF_QUESTIONABLE_FOR_LOOP Are you sure this for loop is incrementing the correct variable? It appears that another variable is being initialized and checked by the for loop.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#qf-complicated-subtle-or-wrong-increment-in-for-loop-qf-questionable-for-loop
NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD The program is dereferencing a public or protected field that does not seem to ever have a non-null value written to it. Unless the field is initialized via some mechanism not seen by the analysis, dereferencing this value will generate a null pointer exception.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-read-of-unwritten-public-or-protected-field-np-unwritten-public-or-protected-field
UCF_USELESS_CONTROL_FLOW_NEXT_LINE This method contains a useless control flow statement in which control flow follows to the same or following line regardless of whether or not the branch is taken. Often, this is caused by inadvertently using an empty statement as the body of an if statement.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ucf-useless-control-flow-to-next-line-ucf-useless-control-flow-next-line
REC_CATCH_EXCEPTION This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { … } catch (Exception e) { something } as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, masking potential bugs.

A better approach is to either explicitly catch the specific exceptions that are thrown, or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions.

  https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rec-exception-is-caught-when-exception-is-not-thrown-rec-catch-exception
FE_FLOATING_POINT_EQUALITY This operation compares two floating point values for equality. Because floating point calculations may involve rounding, calculated float and double values may not be accurate. For values that must be precise, such as monetary values, consider using a fixed-precision type such as BigDecimal. For values that need not be precise, consider comparing for equality within some range, for example: if ( Math.abs(x – y) < .0000001 ). See the Java Language Specification, section 4.2.4.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fe-test-for-floating-point-equality-fe-floating-point-equality
CD_CIRCULAR_DEPENDENCY This class has a circular dependency with other classes. This makes building these classes difficult, as each is dependent on the other to build correctly. Consider using interfaces to break the hard dependency.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#cd-test-for-circular-dependencies-among-classes-cd-circular-dependency
PS_PUBLIC_SEMAPHORES This class uses synchronization along with wait(), notify() or notifyAll() on itself (the this reference). Client classes that use this class, may, in addition, use an instance of this class as a synchronizing object. Because two classes are using the same object for synchronization, Multithread correctness is suspect. You should not synchronize nor call semaphore methods on a public reference. Consider using a internal private member variable to control synchronization.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ps-class-exposes-synchronization-and-semaphores-in-its-public-interface-ps-public-semaphores
IM_AVERAGE_COMPUTATION_COULD_OVERFLOW The code computes the average of two integers using either division or signed right shift, and then uses the result as the index of an array. If the values being averaged are very large, this can overflow (resulting in the computation of a negative average). Assuming that the result is intended to be nonnegative, you can use an unsigned right shift instead. In other words, rather that using (low+high)/2, use (low+high) >>> 1

This bug exists in many earlier implementations of binary search and merge sort. Martin Buchholz found and fixed it in the JDK libraries, and Joshua Bloch widely publicized the bug pattern.

  https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#im-computation-of-average-could-overflow-im-average-computation-could-overflow
NP_METHOD_RETURN_RELAXING_ANNOTATION A method should always implement the contract of a method it overrides. Thus, if a method takes is annotated as returning a @Nonnull value, you shouldn’t override that method in a subclass with a method annotated as returning a @Nullable or @CheckForNull value. Doing so violates the contract that the method shouldn’t return null.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-method-relaxes-nullness-annotation-on-return-value-np-method-return-relaxing-annotation
NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION A method should always implement the contract of a method it overrides. Thus, if a method takes a parameter that is marked as @Nullable, you shouldn’t override that method in a subclass with a method where that parameter is @Nonnull. Doing so violates the contract that the method should handle a null parameter.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-method-tightens-nullness-annotation-on-parameter-np-method-parameter-tightens-annotation

Medium level issues

Rule Description KPI URL
SW_SWING_METHODS_INVOKED_IN_SWING_THREAD (From JDC Tech Tip): The Swing methods show(), setVisible(), and pack() will create the associated peer for the frame. With the creation of the peer, the system creates the event dispatch thread. This makes things problematic because the event dispatch thread could be notifying listeners while pack and validate are still processing. This situation could result in two threads going through the Swing component-based GUI — it’s a serious flaw that could result in deadlocks or other related threading issues. A pack call causes components to be realized. As they are being realized (that is, not necessarily visible), they could trigger listener notification on the event dispatch thread. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#sw-certain-swing-methods-needs-to-be-invoked-in-swing-thread-sw-swing-methods-invoked-in-swing-thread
FI_FINALIZER_ONLY_NULLS_FIELDS This finalizer does nothing except null out fields. This is completely pointless, and requires that the object be garbage collected, finalized, and then garbage collected again. You should just remove the finalize method. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fi-finalizer-only-nulls-fields-fi-finalizer-only-nulls-fields
UI_INHERITANCE_UNSAFE_GETRESOURCE Calling this.getClass().getResource(…) could give results other than expected if this class is extended by a class in another package. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ui-usage-of-getresource-may-be-unsafe-if-class-is-extended-ui-inheritance-unsafe-getresource
AM_CREATES_EMPTY_ZIP_FILE_ENTRY The code calls putNextEntry(), immediately followed by a call to closeEntry(). This results in an empty ZipFile entry. The contents of the entry should be written to the ZipFile between the calls to putNextEntry() and closeEntry(). Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#am-creates-an-empty-zip-file-entry-am-creates-empty-zip-file-entry
AM_CREATES_EMPTY_JAR_FILE_ENTRY The code calls putNextEntry(), immediately followed by a call to closeEntry(). This results in an empty JarFile entry. The contents of the entry should be written to the JarFile between the calls to putNextEntry() and closeEntry(). Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#am-creates-an-empty-jar-file-entry-am-creates-empty-jar-file-entry
IMSE_DONT_CATCH_IMSE IllegalMonitorStateException is generally only thrown in case of a design flaw in your code (calling wait or notify on an object you do not hold a lock on). Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#imse-dubious-catching-of-illegalmonitorstateexception-imse-dont-catch-imse
CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE This class defines a clone() method but the class doesn’t implement Cloneable. There are some situations in which this is OK (e.g., you want to control how subclasses can clone themselves), but just make sure that this is what you intended. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#cn-class-defines-clone-but-doesn-t-implement-cloneable-cn-implements-clone-but-not-cloneable
CN_IDIOM Class implements Cloneable but does not define or use the clone method. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#cn-class-implements-cloneable-but-does-not-define-or-use-clone-method-cn-idiom
NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER The identifier is a word that is reserved as a keyword in later versions of Java, and your code will need to be changed in order to compile it in later versions of Java. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#nm-use-of-identifier-that-is-a-keyword-in-later-versions-of-java-nm-future-keyword-used-as-identifier
NM_FUTURE_KEYWORD_USED_AS_MEMBER_IDENTIFIER This identifier is used as a keyword in later versions of Java. This code, and any code that references this API, will need to be changed in order to compile it in later versions of Java. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#nm-use-of-identifier-that-is-a-keyword-in-later-versions-of-java-nm-future-keyword-used-as-member-identifier
FI_EMPTY Empty finalize() methods are useless, so they should be deleted. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fi-empty-finalizer-should-be-deleted-fi-empty
EQ_SELF_NO_OBJECT This class defines a covariant version of equals(). To correctly override the equals() method in java.lang.Object, the parameter of equals() must have type java.lang.Object. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-covariant-equals-method-defined-eq-self-no-object
CO_SELF_NO_OBJECT This class defines a covariant version of compareTo(). To correctly override the compareTo() method in the Comparable interface, the parameter of compareTo() must have type java.lang.Object. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#co-covariant-compareto-method-defined-co-self-no-object
CO_COMPARETO_RESULTS_MIN_VALUE In some situation, this compareTo or compare method returns the constant Integer.MIN_VALUE, which is an exceptionally bad practice. The only thing that matters about the return value of compareTo is the sign of the result. But people will sometimes negate the return value of compareTo, expecting that this will negate the sign of the result. And it will, except in the case where the value returned is Integer.MIN_VALUE. So just return -1 rather than Integer.MIN_VALUE. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#co-compareto-compare-returns-integer-min-value-co-compareto-results-min-value
RV_NEGATING_RESULT_OF_COMPARETO This code negatives the return value of a compareTo or compare method. This is a questionable or bad programming practice, since if the return value is Integer.MIN_VALUE, negating the return value won’t negate the sign of the result. You can achieve the same intended result by reversing the order of the operands rather than by negating the results. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rv-negating-the-result-of-compareto-compare-rv-negating-result-of-compareto
EQ_COMPARETO_USE_OBJECT_EQUALS This class defines a compareTo(…) method but inherits its equals() method from java.lang.Object. Generally, the value of compareTo should return zero if and only if equals returns true. If this is violated, weird and unpredictable failures will occur in classes such as PriorityQueue. In Java 5 the PriorityQueue.remove method uses the compareTo method, while in Java 6 it uses the equals method.

 

 

 

 

 

 

From the JavaDoc for the compareTo method in the Comparable interface:
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is “Note: this class has a natural ordering that is inconsistent with equals.”

Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-class-defines-compareto-and-uses-object-equals-eq-compareto-use-object-equals
HE_HASHCODE_USE_OBJECT_EQUALS This class defines a hashCode() method but inherits its equals() method from java.lang.Object (which defines equality by comparing object references). Although this will probably satisfy the contract that equal objects must have equal hashcodes, it is probably not what was intended by overriding the hashCode() method. (Overriding hashCode() implies that the object’s identity is based on criteria more complicated than simple reference equality.) Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#he-class-defines-hashcode-and-uses-object-equals-he-hashcode-use-object-equals
EQ_ABSTRACT_SELF This class defines a covariant version of equals(). To correctly override the equals() method in java.lang.Object, the parameter of equals() must have type java.lang.Object. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-abstract-class-defines-covariant-equals-method-eq-abstract-self
CO_ABSTRACT_SELF This class defines a covariant version of compareTo(). To correctly override the compareTo() method in the Comparable interface, the parameter of compareTo() must have type java.lang.Object. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#co-abstract-class-defines-covariant-compareto-method-co-abstract-self
IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION During the initialization of a class, the class makes an active use of a subclass. That subclass will not yet be initialized at the time of this use. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ic-superclass-uses-subclass-during-initialization-ic-superclass-uses-subclass-during-initialization
SI_INSTANCE_BEFORE_FINALS_ASSIGNED The class’s static initializer creates an instance of the class before all of the static final fields are assigned. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#si-static-initializer-creates-instance-before-all-static-final-fields-assigned-si-instance-before-finals-assigned
ME_MUTABLE_ENUM_FIELD A mutable public field is defined inside a public enum, thus can be changed by malicious code or by accident from another package. Though mutable enum fields may be used for lazy initialization, it’s a bad practice to expose them to the outer world. Consider declaring this field final and/or package-private. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#me-enum-field-is-public-and-mutable-me-mutable-enum-field
ME_ENUM_FIELD_SETTER This public method declared in public enum unconditionally sets enum field, thus this field can be changed by malicious code or by accident from another package. Though mutable enum fields may be used for lazy initialization, it’s a bad practice to expose them to the outer world. Consider removing this method or declaring it package-private. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#me-public-enum-method-unconditionally-sets-its-field-me-enum-field-setter
NM_SAME_SIMPLE_NAME_AS_INTERFACE This class/interface has a simple name that is identical to that of an implemented/extended interface, except that the interface is in a different package (e.g., alpha.Foo extends beta.Foo). This can be exceptionally confusing, create lots of situations in which you have to look at import statements to resolve references and creates many opportunities to accidentally define methods that do not override methods in their superclasses. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#nm-class-names-shouldn-t-shadow-simple-name-of-implemented-interface-nm-same-simple-name-as-interface
NM_SAME_SIMPLE_NAME_AS_SUPERCLASS This class has a simple name that is identical to that of its superclass, except that its superclass is in a different package (e.g., alpha.Foo extends beta.Foo). This can be exceptionally confusing, create lots of situations in which you have to look at import statements to resolve references and creates many opportunities to accidentally define methods that do not override methods in their superclasses. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#nm-class-names-shouldn-t-shadow-simple-name-of-superclass-nm-same-simple-name-as-superclass
NM_WRONG_PACKAGE_INTENTIONAL The method in the subclass doesn’t override a similar method in a superclass because the type of a parameter doesn’t exactly match the type of the corresponding parameter in the superclass. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#nm-method-doesn-t-override-method-in-superclass-due-to-wrong-package-for-parameter-nm-wrong-package-intentional
RR_NOT_CHECKED This method ignores the return value of one of the variants of java.io.InputStream.read() which can return multiple bytes. If the return value is not checked, the caller will not be able to correctly handle the case where fewer bytes were read than the caller requested. This is a particularly insidious kind of bug, because in many programs, reads from input streams usually do read the full amount of data requested, causing the program to fail only sporadically. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rr-method-ignores-results-of-inputstream-read-rr-not-checked
SR_NOT_CHECKED This method ignores the return value of java.io.InputStream.skip() which can skip multiple bytes. If the return value is not checked, the caller will not be able to correctly handle the case where fewer bytes were skipped than the caller requested. This is a particularly insidious kind of bug, because in many programs, skips from input streams usually do skip the full amount of data requested, causing the program to fail only sporadically. With Buffered streams, however, skip() will only skip data in the buffer, and will routinely fail to skip the requested number of bytes. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rr-method-ignores-results-of-inputstream-skip-sr-not-checked
SE_NO_SUITABLE_CONSTRUCTOR This class implements the Serializable interface and its superclass does not. When such an object is deserialized, the fields of the superclass need to be initialized by invoking the void constructor of the superclass. Since the superclass does not have one, serialization and deserialization will fail at runtime. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#se-class-is-serializable-but-its-superclass-doesn-t-define-a-void-constructor-se-no-suitable-constructor
SE_NO_SUITABLE_CONSTRUCTOR_FOR_EXTERNALIZATION This class implements the Externalizable interface, but does not define a void constructor. When Externalizable objects are deserialized, they first need to be constructed by invoking the void constructor. Since this class does not have one, serialization and deserialization will fail at runtime. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#se-class-is-externalizable-but-doesn-t-define-a-void-constructor-se-no-suitable-constructor-for-externalization
SE_COMPARATOR_SHOULD_BE_SERIALIZABLE This class implements the Comparator interface. You should consider whether or not it should also implement the Serializable interface. If a comparator is used to construct an ordered collection such as a TreeMap, then the TreeMap will be serializable only if the comparator is also serializable. As most comparators have little or no state, making them serializable is generally easy and good defensive programming. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#se-comparator-doesn-t-implement-serializable-se-comparator-should-be-serializable
SE_READ_RESOLVE_MUST_RETURN_OBJECT In order for the readResolve method to be recognized by the serialization mechanism, it must be declared to have a return type of Object. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#se-the-readresolve-method-must-be-declared-with-a-return-type-of-object-se-read-resolve-must-return-object
SE_NONFINAL_SERIALVERSIONID This class defines a serialVersionUID field that is not final. The field should be made final if it is intended to specify the version UID for purposes of serialization. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#se-serialversionuid-isn-t-final-se-nonfinal-serialversionid
SE_NONSTATIC_SERIALVERSIONID This class defines a serialVersionUID field that is not static. The field should be made static if it is intended to specify the version UID for purposes of serialization. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#se-serialversionuid-isn-t-static-se-nonstatic-serialversionid
SE_NONLONG_SERIALVERSIONID This class defines a serialVersionUID field that is not long. The field should be made long if it is intended to specify the version UID for purposes of serialization. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#se-serialversionuid-isn-t-long-se-nonlong-serialversionid
SE_BAD_FIELD This Serializable class defines a non-primitive instance field which is neither transient, Serializable, or java.lang.Object, and does not appear to implement the Externalizable interface or the readObject() and writeObject() methods. Objects of this class will not be deserialized correctly if a non-Serializable object is stored in this field. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#se-non-transient-non-serializable-instance-field-in-serializable-class-se-bad-field
SE_INNER_CLASS This Serializable class is an inner class. Any attempt to serialize it will also serialize the associated outer instance. The outer instance is serializable, so this won’t fail, but it might serialize a lot more data than intended. If possible, making the inner class a static inner class (also known as a nested class) should solve the problem. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#se-serializable-inner-class-se-inner-class
SE_BAD_FIELD_INNER_CLASS This Serializable class is an inner class of a non-serializable class. Thus, attempts to serialize it will also attempt to associate instance of the outer class with which it is associated, leading to a runtime error.

 

 

 

 

 

 

If possible, making the inner class a static inner class should solve the problem. Making the outer class serializable might also work, but that would mean serializing an instance of the inner class would always also serialize the instance of the outer class, which it often not what you really want.

Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#se-non-serializable-class-has-a-serializable-inner-class-se-bad-field-inner-class
SE_BAD_FIELD_STORE A non-serializable value is stored into a non-transient field of a serializable class. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#se-non-serializable-value-stored-into-instance-field-of-a-serializable-class-se-bad-field-store
RV_RETURN_VALUE_IGNORED_BAD_PRACTICE This method returns a value that is not checked. The return value should be checked since it can indicate an unusual or unexpected function execution. For example, the File.delete() method returns false if the file could not be successfully deleted (rather than throwing an Exception). If you don’t check the result, you won’t notice if the method invocation signals unexpected behavior by returning an atypical return value. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rv-method-ignores-exceptional-return-value-rv-return-value-ignored-bad-practice
NP_CLONE_COULD_RETURN_NULL This clone method seems to return null in some circumstances, but clone is never allowed to return a null value. If you are convinced this path is unreachable, throw an AssertionError instead. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-clone-method-may-return-null-np-clone-could-return-null
VA_FORMAT_STRING_USES_NEWLINE This format string includes a newline character (n). In format strings, it is generally preferable to use %n, which will produce the platform-specific line separator. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fs-format-string-should-use-n-rather-than-n-va-format-string-uses-newline
BIT_SIGNED_CHECK This method compares an expression such as ((event.detail & SWT.SELECTED) > 0). Using bit arithmetic and then comparing with the greater than operator can lead to unexpected results (of course depending on the value of SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate for a bug. Even when SWT.SELECTED is not negative, it seems good practice to use ‘!= 0’ instead of ‘> 0’. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bit-check-for-sign-of-bitwise-operation-bit-signed-check
ISC_INSTANTIATE_STATIC_CLASS This class allocates an object that is based on a class that only supplies static methods. This object does not need to be created, just access the static methods directly using the class name as a qualifier. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#isc-needless-instantiation-of-class-that-only-supplies-static-methods-isc-instantiate-static-class
DMI_RANDOM_USED_ONLY_ONCE This code creates a java.util.Random object, uses it to generate one random number, and then discards the Random object. This produces mediocre quality random numbers and is inefficient. If possible, rewrite the code so that the Random object is created once and saved, and each time a new random number is required invoke a method on the existing Random object to obtain it.

 

 

 

 

 

 

If it is important that the generated Random numbers not be guessable, you must not create a new Random for each random number; the values are too easily guessable. You should strongly consider using a java.security.SecureRandom instead (and avoid allocating a new SecureRandom for each random number needed).

Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-random-object-created-and-used-only-once-dmi-random-used-only-once
BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS The equals(Object o) method shouldn’t make any assumptions about the type of o. It should simply return false if o is not the same type as this. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bc-equals-method-should-not-assume-anything-about-the-type-of-its-argument-bc-equals-method-should-work-for-all-objects
GC_UNCHECKED_TYPE_IN_GENERIC_CALL This call to a generic collection method passes an argument while compile type Object where a specific type from the generic type parameters is expected. Thus, neither the standard Java type system nor static analysis can provide useful information on whether the object being passed as a parameter is of an appropriate type. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#gc-unchecked-type-in-generic-call-gc-unchecked-type-in-generic-call
PZ_DONT_REUSE_ENTRY_OBJECTS_IN_ITERATORS The entrySet() method is allowed to return a view of the underlying Map in which an Iterator and Map.Entry. This clever idea was used in several Map implementations, but introduces the possibility of nasty coding mistakes. If a map m returns such an iterator for an entrySet, then c.addAll(m.entrySet()) will go badly wrong. All of the Map implementations in OpenJDK 1.7 have been rewritten to avoid this, you should to. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#pz-don-t-reuse-entry-objects-in-iterators-pz-dont-reuse-entry-objects-in-iterators
DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS The entrySet() method is allowed to return a view of the underlying Map in which a single Entry object is reused and returned during the iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so. When iterating through such a Map, the Entry value is only valid until you advance to the next iteration. If, for example, you try to pass such an entrySet to an addAll method, things will go badly wrong. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-adding-elements-of-an-entry-set-may-fail-due-to-reuse-of-entry-objects-dmi-entry-sets-may-reuse-entry-objects
IO_APPENDING_TO_OBJECT_OUTPUT_STREAM This code opens a file in append mode and then wraps the result in an object output stream. This won’t allow you to append to an existing object output stream stored in a file. If you want to be able to append to an object output stream, you need to keep the object output stream open.

 

 

 

 

 

 

The only situation in which opening a file in append mode and the writing an object output stream could work is if on reading the file you plan to open it in random access mode and seek to the byte offset where the append started.

Resource Utilization https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#io-doomed-attempt-to-append-to-an-object-output-stream-io-appending-to-object-output-stream
IL_INFINITE_RECURSIVE_LOOP This method unconditionally invokes itself. This would seem to indicate an infinite recursive loop that will result in a stack overflow. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#il-an-apparent-infinite-recursive-loop-il-infinite-recursive-loop
IL_CONTAINER_ADDED_TO_ITSELF A collection is added to itself. As a result, computing the hashCode of this set will throw a StackOverflowException. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#il-a-collection-is-added-to-itself-il-container-added-to-itself
DMI_FUTILE_ATTEMPT_TO_CHANGE_MAXPOOL_SIZE_OF_SCHEDULED_THREAD_POOL_EXECUTOR (Javadoc) While ScheduledThreadPoolExecutor inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-futile-attempt-to-change-max-pool-size-of-scheduledthreadpoolexecutor-dmi-futile-attempt-to-change-maxpool-size-of-scheduled-thread-pool-executor
DMI_BIGDECIMAL_CONSTRUCTED_FROM_DOUBLE This code creates a BigDecimal from a double value that doesn’t translate well to a decimal number. For example, one might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. You probably want to use the BigDecimal.valueOf(double d) method, which uses the String representation of the double to create the BigDecimal (e.g., BigDecimal.valueOf(0.1) gives 0.1). Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-bigdecimal-constructed-from-double-that-isn-t-represented-precisely-dmi-bigdecimal-constructed-from-double
DMI_SCHEDULED_THREAD_POOL_EXECUTOR_WITH_ZERO_CORE_THREADS (Javadoc) A ScheduledThreadPoolExecutor with zero core threads will never execute anything; changes to the max pool size are ignored. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-creation-of-scheduledthreadpoolexecutor-with-zero-core-threads-dmi-scheduled-thread-pool-executor-with-zero-core-threads
DMI_ANNOTATION_IS_NOT_VISIBLE_TO_REFLECTION Unless an annotation has itself been annotated with @Retention(RetentionPolicy.RUNTIME), the annotation can’t be observed using reflection (e.g., by using the isAnnotationPresent method). Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-can-t-use-reflection-to-check-for-presence-of-annotation-without-runtime-retention-dmi-annotation-is-not-visible-to-reflection
RV_ABSOLUTE_VALUE_OF_RANDOM_INT This code generates a random signed integer and then computes the absolute value of that random integer. If the number returned by the random number generator is Integer.MIN_VALUE, then the result will be negative as well (since Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE). (Same problem arises for long values as well). Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rv-bad-attempt-to-compute-absolute-value-of-signed-random-integer-rv-absolute-value-of-random-int
RV_ABSOLUTE_VALUE_OF_HASHCODE This code generates a hashcode and then computes the absolute value of that hashcode. If the hashcode is Integer.MIN_VALUE, then the result will be negative as well (since Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE).

 

 

 

 

 

 

One out of 2^32 strings have a hashCode of Integer.MIN_VALUE, including “polygenelubricants” “GydZG_” and “”DESIGNING WORKHOUSES”.

Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rv-bad-attempt-to-compute-absolute-value-of-signed-32-bit-hashcode-rv-absolute-value-of-hashcode
RV_01_TO_INT A random value from 0 to 1 is being coerced to the integer value 0. You probably want to multiply the random value by something else before coercing it to an integer, or use the Random.nextInt(n) method. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rv-random-value-from-0-to-1-is-coerced-to-the-integer-0-rv-01-to-int
DM_INVALID_MIN_MAX This code tries to limit the value bounds using the construct like Math.min(0, Math.max(100, value)). However the order of the constants is incorrect: it should be Math.min(100, Math.max(0, value)). As the result this code always produces the same result (or NaN if the value is NaN). Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-incorrect-combination-of-math-max-and-math-min-dm-invalid-min-max
EQ_COMPARING_CLASS_NAMES This method checks to see if two objects are the same class by checking to see if the names of their classes are equal. You can have different classes with the same name if they are loaded by different class loaders. Just check to see if the class objects are the same. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-equals-method-compares-class-names-rather-than-class-objects-eq-comparing-class-names
EQ_ALWAYS_TRUE This class defines an equals method that always returns true. This is imaginative, but not very smart. Plus, it means that the equals method is not symmetric. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-equals-method-always-returns-true-eq-always-true
EQ_ALWAYS_FALSE This class defines an equals method that always returns false. This means that an object is not equal to itself, and it is impossible to create useful Maps or Sets of this class. More fundamentally, it means that equals is not reflexive, one of the requirements of the equals method. The likely intended semantics are object identity: that an object is equal to itself. This is the behavior inherited from class Object. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-equals-method-always-returns-false-eq-always-false
EQ_SELF_USE_OBJECT This class defines a covariant version of the equals() method, but inherits the normal equals(Object) method defined in the base java.lang.Object class. The class should probably define a boolean equals(Object) method. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-covariant-equals-method-defined-object-equals-object-inherited-eq-self-use-object
EQ_OTHER_USE_OBJECT This class defines an equals() method, that doesn’t override the normal equals(Object) method defined in the base java.lang.Object class. The class should probably define a boolean equals(Object) method. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-equals-method-defined-that-doesn-t-override-object-equals-object-eq-other-use-object
EQ_OTHER_NO_OBJECT This class defines an equals() method, that doesn’t override the normal equals(Object) method defined in the base java.lang.Object class. Instead, it inherits an equals(Object) method from a superclass. The class should probably define a boolean equals(Object) method. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-equals-method-defined-that-doesn-t-override-equals-object-eq-other-no-object
HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS A method, field or class declares a generic signature where a non-hashable class is used in context where a hashable class is required. A class that declares an equals method but inherits a hashCode() method from Object is unhashable, since it doesn’t fulfill the requirement that equal objects have equal hashCodes. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#he-signature-declares-use-of-unhashable-class-in-hashed-construct-he-signature-declares-hashing-of-unhashable-class
HE_USE_OF_UNHASHABLE_CLASS A class defines an equals(Object) method but not a hashCode() method, and thus doesn’t fulfill the requirement that equal objects have equal hashCodes. An instance of this class is used in a hash data structure, making the need to fix this problem of highest importance. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#he-use-of-class-without-a-hashcode-method-in-a-hashed-data-structure-he-use-of-unhashable-class
UR_UNINIT_READ This constructor reads a field which has not yet been assigned a value. This is often caused when the programmer mistakenly uses the field instead of one of the constructor’s parameters. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ur-uninitialized-read-of-field-in-constructor-ur-uninit-read
UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR This method is invoked in the constructor of the superclass. At this point, the fields of the class have not yet initialized. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ur-uninitialized-read-of-field-method-called-from-constructor-of-superclass-ur-uninit-read-called-from-super-constructor
NM_WRONG_PACKAGE The method in the subclass doesn’t override a similar method in a superclass because the type of a parameter doesn’t exactly match the type of the corresponding parameter in the superclass. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#nm-method-doesn-t-override-method-in-superclass-due-to-wrong-package-for-parameter-nm-wrong-package
SE_READ_RESOLVE_IS_STATIC In order for the readResolve method to be recognized by the serialization mechanism, it must not be declared as a static method. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#se-the-readresolve-method-must-not-be-declared-as-a-static-method-se-read-resolve-is-static
NP_UNWRITTEN_FIELD The program is dereferencing a field that does not seem to ever have a non-null value written to it. Unless the field is initialized via some mechanism not seen by the analysis, dereferencing this value will generate a null pointer exception. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-read-of-unwritten-field-np-unwritten-field
UWF_UNWRITTEN_FIELD This field is never written. All reads of it will return the default value. Check for errors (should it have been initialized?), or remove it if it is useless. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#uwf-unwritten-field-uwf-unwritten-field
SIC_THREADLOCAL_DEADLY_EMBRACE This class is an inner class, but should probably be a static inner class. As it is, there is a serious danger of a deadly embrace between the inner class and the thread local in the outer class. Because the inner class isn’t static, it retains a reference to the outer class. If the thread local contains a reference to an instance of the inner class, the inner and outer instance will both be reachable and not eligible for garbage collection. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#sic-deadly-embrace-of-non-static-inner-class-and-thread-local-sic-threadlocal-deadly-embrace
NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH There is a statement or branch on an exception path that if executed guarantees that a value is null at this point, and that value that is guaranteed to be dereferenced (except on forward paths involving runtime exceptions). Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-value-is-null-and-guaranteed-to-be-dereferenced-on-exception-path-np-guaranteed-deref-on-exception-path
DMI_ARGUMENTS_WRONG_ORDER The arguments to this method call seem to be in the wrong order. For example, a call Preconditions.checkNotNull(“message”, message) has reserved arguments: the value to be checked is the first argument. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-reversed-method-arguments-dmi-arguments-wrong-order
RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE A value is checked here to see whether it is null, but this value can’t be null because it was previously dereferenced and if it were null a null pointer exception would have occurred at the earlier dereference. Essentially, this code and the previous dereference disagree as to whether this value is allowed to be null. Either the check is redundant or the previous dereference is erroneous. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rcn-nullcheck-of-value-previously-dereferenced-rcn-redundant-nullcheck-would-have-been-a-npe
VA_FORMAT_STRING_BAD_CONVERSION One of the arguments is incompatible with the corresponding format string specifier. As a result, this will generate a runtime exception when executed. For example, String.format(“%d”, “1”) will generate an exception, since the String “1” is incompatible with the format specifier %d. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fs-the-type-of-a-supplied-argument-doesn-t-match-format-specifier-va-format-string-bad-conversion
VA_FORMAT_STRING_NO_PREVIOUS_ARGUMENT The format string specifies a relative index to request that the argument for the previous format specifier be reused. However, there is no previous argument Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fs-no-previous-argument-for-format-string-va-format-string-no-previous-argument
VA_FORMAT_STRING_BAD_ARGUMENT The format string placeholder is incompatible with the corresponding argument. For example, System.out.println(“%dn”, “hello”);

 

 

 

 

 

 

The %d placeholder requires a numeric argument, but a string value is passed instead. A runtime exception will occur when this statement is executed.

Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fs-format-string-placeholder-incompatible-with-passed-argument-va-format-string-bad-argument
VA_FORMAT_STRING_MISSING_ARGUMENT Not enough arguments are passed to satisfy a placeholder in the format string. A runtime exception will occur when this statement is executed. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fs-format-string-references-missing-argument-va-format-string-missing-argument
VA_FORMAT_STRING_ILLEGAL The format string is syntactically invalid, and a runtime exception will occur when this statement is executed. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fs-illegal-format-string-va-format-string-illegal
VA_FORMAT_STRING_EXTRA_ARGUMENTS_PASSED A format-string method with a variable number of arguments is called, but more arguments are passed than are actually used by the format string. This won’t cause a runtime exception, but the code may be silently omitting information that was intended to be included in the formatted string. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fs-more-arguments-are-passed-than-are-actually-used-in-the-format-string-va-format-string-extra-arguments-passed
VA_FORMAT_STRING_EXPECTED_MESSAGE_FORMAT_SUPPLIED A method is called that expects a Java printf format string and a list of arguments. However, the format string doesn’t contain any format specifiers (e.g., %s) but does contain message format elements (e.g., {0}). It is likely that the code is supplying a MessageFormat string when a printf-style format string is required. At runtime, all of the arguments will be ignored and the format string will be returned exactly as provided without any formatting. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fs-messageformat-supplied-where-printf-style-format-expected-va-format-string-expected-message-format-supplied
EC_UNRELATED_TYPES_USING_POINTER_EQUALITY This method uses using pointer equality to compare two references that seem to be of different types. The result of this comparison will always be false at runtime. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ec-using-pointer-equality-to-compare-different-types-ec-unrelated-types-using-pointer-equality
EC_UNRELATED_TYPES This method calls equals(Object) on two references of different class types and analysis suggests they will be to objects of different classes at runtime. Further, examination of the equals methods that would be invoked suggest that either this call will always return false, or else the equals method is not be symmetric (which is a property required by the contract for equals in class Object). Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ec-call-to-equals-comparing-different-types-ec-unrelated-types
EC_ARRAY_AND_NONARRAY This method invokes the .equals(Object o) to compare an array and a reference that doesn’t seem to be an array. If things being compared are of different types, they are guaranteed to be unequal and the comparison is almost certainly an error. Even if they are both arrays, the equals method on arrays only determines of the two arrays are the same object. To compare the contents of the arrays, use java.util.Arrays.equals(Object[], Object[]). Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ec-equals-used-to-compare-array-and-nonarray-ec-array-and-nonarray
EC_NULL_ARG This method calls equals(Object), passing a null value as the argument. According to the contract of the equals() method, this call should always return false. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ec-call-to-equals-null-ec-null-arg
EC_UNRELATED_INTERFACES This method calls equals(Object) on two references of unrelated interface types, where neither is a subtype of the other, and there are no known non-abstract classes which implement both interfaces. Therefore, the objects being compared are unlikely to be members of the same class at runtime (unless some application classes were not analyzed, or dynamic class loading can occur at runtime). According to the contract of equals(), objects of different classes should always compare as unequal; therefore, according to the contract defined by java.lang.Object.equals(Object), the result of this comparison will always be false at runtime. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ec-call-to-equals-comparing-different-interface-types-ec-unrelated-interfaces
EC_UNRELATED_CLASS_AND_INTERFACE This method calls equals(Object) on two references, one of which is a class and the other an interface, where neither the class nor any of its non-abstract subclasses implement the interface. Therefore, the objects being compared are unlikely to be members of the same class at runtime (unless some application classes were not analyzed, or dynamic class loading can occur at runtime). According to the contract of equals(), objects of different classes should always compare as unequal; therefore, according to the contract defined by java.lang.Object.equals(Object), the result of this comparison will always be false at runtime. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ec-call-to-equals-comparing-unrelated-class-and-interface-ec-unrelated-class-and-interface
INT_BAD_COMPARISON_WITH_INT_VALUE This code compares an int value with a long constant that is outside the range of values that can be represented as an int value. This comparison is vacuous and possibly to be incorrect. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#int-bad-comparison-of-int-value-with-long-constant-int-bad-comparison-with-int-value
INT_BAD_COMPARISON_WITH_SIGNED_BYTE Signed bytes can only have a value in the range -128 to 127. Comparing a signed byte with a value outside that range is vacuous and likely to be incorrect. To convert a signed byte b to an unsigned value in the range 0..255, use 0xff & b. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#int-bad-comparison-of-signed-byte-int-bad-comparison-with-signed-byte
INT_BAD_COMPARISON_WITH_NONNEGATIVE_VALUE This code compares a value that is guaranteed to be non-negative with a negative constant or zero. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#int-bad-comparison-of-nonnegative-value-with-negative-constant-or-zero-int-bad-comparison-with-nonnegative-value
BIT_ADD_OF_SIGNED_BYTE Adds a byte value and a value which is known to have the 8 lower bits clear. Values loaded from a byte array are sign extended to 32 bits before any bitwise operations are performed on the value. Thus, if b[0] contains the value 0xff, and x is initially 0, then the code ((x << 8) + b[0]) will sign extend 0xff to get 0xffffffff, and thus give the value 0xffffffff as the result. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bit-bitwise-add-of-signed-byte-value-bit-add-of-signed-byte
BIT_IOR_OF_SIGNED_BYTE Loads a byte value (e.g., a value loaded from a byte array or returned by a method with return type byte) and performs a bitwise OR with that value. Byte values are sign extended to 32 bits before any bitwise operations are performed on the value. Thus, if b[0] contains the value 0xff, and x is initially 0, then the code ((x << 8) | b[0]) will sign extend 0xff to get 0xffffffff, and thus give the value 0xffffffff as the result. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bit-bitwise-or-of-signed-byte-value-bit-ior-of-signed-byte
BIT_SIGNED_CHECK_HIGH_BIT This method compares a bitwise expression such as ((val & CONSTANT) > 0) where CONSTANT is the negative number. Using bit arithmetic and then comparing with the greater than operator can lead to unexpected results. This comparison is unlikely to work as expected. The good practice is to use ‘!= 0’ instead of ‘> 0’. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bit-check-for-sign-of-bitwise-operation-involving-negative-number-bit-signed-check-high-bit
BIT_AND This method compares an expression of the form (e & C) to D, which will always compare unequal due to the specific values of constants C and D. This may indicate a logic error or typo. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bit-incompatible-bit-masks-bit-and
BIT_AND_ZZ This method compares an expression of the form (e & 0) to 0, which will always compare equal. This may indicate a logic error or typo. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bit-check-to-see-if-0-0-bit-and-zz
BIT_IOR This method compares an expression of the form (e | C) to D. which will always compare unequal due to the specific values of constants C and D. This may indicate a logic error or typo.

 

 

 

 

 

 

Typically, this bug occurs because the code wants to perform a membership test in a bit set, but uses the bitwise OR operator (“|”) instead of bitwise AND (“&”).

Also such bug may appear in expressions like (e & A | B) == C which is parsed like ((e & A) | B) == C while (e & (A | B)) == C was intended.

Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bit-incompatible-bit-masks-bit-ior
IJU_ASSERT_METHOD_INVOKED_FROM_RUN_METHOD A JUnit assertion is performed in a run method. Failed JUnit assertions just result in exceptions being thrown. Thus, if this exception occurs in a thread other than the thread that invokes the test method, the exception will terminate the thread but not result in the test failing. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#iju-junit-assertion-in-run-method-will-not-be-noticed-by-junit-iju-assert-method-invoked-from-run-method
IJU_BAD_SUITE_METHOD Class is a JUnit TestCase and defines a suite() method. However, the suite method needs to be declared as either. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#iju-testcase-declares-a-bad-suite-method-iju-bad-suite-method
IJU_SETUP_NO_SUPER Class is a JUnit TestCase and implements the setUp method. The setUp method should call super.setUp(), but doesn’t. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#iju-testcase-defines-setup-that-doesn-t-call-super-setup-iju-setup-no-super
IJU_TEARDOWN_NO_SUPER Class is a JUnit TestCase and implements the tearDown method. The tearDown method should call super.tearDown(), but doesn’t. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#iju-testcase-defines-teardown-that-doesn-t-call-super-teardown-iju-teardown-no-super
IJU_SUITE_NOT_STATIC Class is a JUnit TestCase and implements the suite() method. The suite method should be declared as being static, but isn’t. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#iju-testcase-implements-a-non-static-suite-method-iju-suite-not-static
BOA_BADLY_OVERRIDDEN_ADAPTER This method overrides a method found in a parent class, where that class is an Adapter that implements a listener defined in the java.awt.event or javax.swing.event package. As a result, this method will not get called when the event occurs. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#boa-class-overrides-a-method-implemented-in-super-class-adapter-wrongly-boa-badly-overridden-adapter
SQL_BAD_RESULTSET_ACCESS A call to getXXX or updateXXX methods of a result set was made where the field index is 0. As ResultSet fields start at index 1, this is always a mistake. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#sql-method-attempts-to-access-a-result-set-field-with-index-0-sql-bad-resultset-access
SQL_BAD_PREPARED_STATEMENT_ACCESS A call to a setXXX method of a prepared statement was made where the parameter index is 0. As parameter indexes start at index 1, this is always a mistake. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#sql-method-attempts-to-access-a-prepared-statement-parameter-with-index-0-sql-bad-prepared-statement-access
EC_INCOMPATIBLE_ARRAY_COMPARE This method invokes the .equals(Object o) to compare two arrays, but the arrays of of incompatible types (e.g., String[] and StringBuffer[], or String[] and int[]). They will never be equal. In addition, when equals(…) is used to compare arrays it only checks to see if they are the same array, and ignores the contents of the arrays. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ec-equals-used-to-compare-incompatible-arrays-ec-incompatible-array-compare
DLS_DEAD_LOCAL_INCREMENT_IN_RETURN This statement has a return such as return x++;. A postfix increment/decrement does not impact the value of the expression, so this increment/decrement has no effect. Please verify that this statement does the right thing. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dls-useless-increment-in-return-statement-dls-dead-local-increment-in-return
DLS_DEAD_STORE_OF_CLASS_LITERAL This instruction assigns a class literal to a variable and then never uses it. The behavior of this differs in Java 1.4 and in Java 5. In Java 1.4 and earlier, a reference to Foo.class would force the static initializer for Foo to be executed, if it has not been executed already. In Java 5 and later, it does not.

 

 

 

 

 

 

See Sun’s article on Java SE compatibility for more details and examples, and suggestions on how to force class initialization in Java 5.

Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dls-dead-store-of-class-literal-dls-dead-store-of-class-literal
IP_PARAMETER_IS_DEAD_BUT_OVERWRITTEN The initial value of this parameter is ignored, and the parameter is overwritten here. This often indicates a mistaken belief that the write to the parameter will be conveyed back to the caller. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ip-a-parameter-is-dead-upon-entry-to-a-method-but-overwritten-ip-parameter-is-dead-but-overwritten
MF_CLASS_MASKS_FIELD This class defines a field with the same name as a visible instance field in a superclass. This is confusing, and may indicate an error if methods update or access one of the fields when they wanted the other. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#mf-class-defines-field-that-masks-a-superclass-field-mf-class-masks-field
FE_TEST_IF_EQUAL_TO_NOT_A_NUMBER This code checks to see if a floating point value is equal to the special Not A Number value (e.g., if (x == Double.NaN)). However, because of the special semantics of NaN, no value is equal to Nan, including NaN. Thus, x == Double.NaN always evaluates to false. To check to see if a value contained in x is the special Not A Number value, use Double.isNaN(x) (or Float.isNaN(x) if x is floating point precision). Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fe-doomed-test-for-equality-to-nan-fe-test-if-equal-to-not-a-number
ICAST_INT_2_LONG_AS_INSTANT This code converts a 32-bit int value to a 64-bit long value, and then passes that value for a method parameter that requires an absolute time value. An absolute time value is the number of milliseconds since the standard base time known as “the epoch”, namely January 1, 1970, 00:00:00 GMT. For example, the following method, intended to convert seconds since the epoch into a Date, is badly broken:

 

 

 

 

 

 

Date getDate(int seconds) { return new Date(seconds * 1000); }

The multiplication is done using 32-bit arithmetic, and then converted to a 64-bit value. When a 32-bit value is converted to 64-bits and used to express an absolute time value, only dates in December 1969 and January 1970 can be represented.

Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#icast-int-value-converted-to-long-and-used-as-absolute-time-icast-int-2-long-as-instant
ICAST_INT_CAST_TO_DOUBLE_PASSED_TO_CEIL This code converts an integral value (e.g., int or long) to a double precision floating point number and then passing the result to the Math.ceil() function, which rounds a double to the next higher integer value. This operation should always be a no-op, since the converting an integer to a double should give a number with no fractional part. It is likely that the operation that generated the value to be passed to Math.ceil was intended to be performed using double precision floating point arithmetic. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#icast-integral-value-cast-to-double-and-then-passed-to-math-ceil-icast-int-cast-to-double-passed-to-ceil
ICAST_INT_CAST_TO_FLOAT_PASSED_TO_ROUND This code converts an int value to a float precision floating point number and then passing the result to the Math.round() function, which returns the int/long closest to the argument. This operation should always be a no-op, since the converting an integer to a float should give a number with no fractional part. It is likely that the operation that generated the value to be passed to Math.round was intended to be performed using floating point arithmetic. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#icast-int-value-cast-to-float-and-then-passed-to-math-round-icast-int-cast-to-float-passed-to-round
NP_NULL_INSTANCEOF This instanceof test will always return false, since the value being checked is guaranteed to be null. Although this is safe, make sure it isn’t an indication of some misunderstanding or some other logic error. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-a-known-null-value-is-checked-to-see-if-it-is-an-instance-of-a-type-np-null-instanceof
BC_IMPOSSIBLE_DOWNCAST This cast will always throw a ClassCastException. The analysis believes it knows the precise type of the value being cast, and the attempt to downcast it to a subtype will always fail by throwing a ClassCastException. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bc-impossible-downcast-bc-impossible-downcast
BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY This code is casting the result of calling toArray() on a collection to a type more specific than Object[], as in:

 

 

 

 

 

 

String[] getAsArray(Collection c) {
return (String[]) c.toArray();
}

This will usually fail by throwing a ClassCastException. The toArray() of almost all collections return an Object[]. They can’t really do anything else, since the Collection object has no reference to the declared generic type of the collection.

The correct way to do get an array of a specific type from a collection is to use c.toArray(new String[]); or c.toArray(new String[c.size()]); (the latter is slightly more efficient).

There is one common/known exception to this. The toArray() method of lists returned by Arrays.asList(…) will return a covariantly typed array. For example, Arrays.asArray(new String[] { “a” }).toArray() will return a String []. SpotBugs attempts to detect and suppress such cases, but may miss some.

Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bc-impossible-downcast-of-toarray-result-bc-impossible-downcast-of-toarray
BC_IMPOSSIBLE_INSTANCEOF This instanceof test will always return false. Although this is safe, make sure it isn’t an indication of some misunderstanding or some other logic error. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bc-instanceof-will-always-return-false-bc-impossible-instanceof
RE_POSSIBLE_UNINTENDED_PATTERN A String function is being invoked and “.” or “|” is being passed to a parameter that takes a regular expression as an argument. Is this what you intended? Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#re-or-used-for-regular-expression-re-possible-unintended-pattern
RE_BAD_SYNTAX_FOR_REGULAR_EXPRESSION The code here uses a regular expression that is invalid according to the syntax for regular expressions. This statement will throw a PatternSyntaxException when executed. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#re-invalid-syntax-for-regular-expression-re-bad-syntax-for-regular-expression
ICAST_BAD_SHIFT_AMOUNT The code performs shift of a 32 bit int by a constant amount outside the range -31..31. The effect of this is to use the lower 5 bits of the integer value to decide how much to shift by (e.g., shifting by 40 bits is the same as shifting by 8 bits, and shifting by 32 bits is the same as shifting by zero bits). This probably isn’t what was expected, and it is at least confusing. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bshift-32-bit-int-shifted-by-an-amount-not-in-the-range-31-31-icast-bad-shift-amount
BSHIFT_WRONG_ADD_PRIORITY The code performs an operation like (x << 8 + y). Although this might be correct, probably it was meant to perform (x << 8) + y, but shift operation has a lower precedence, so it’s actually parsed as x << (8 + y). Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bshift-possible-bad-parsing-of-shift-operation-bshift-wrong-add-priority
IM_MULTIPLYING_RESULT_OF_IREM The code multiplies the result of an integer remaining by an integer constant. Be sure you don’t have your operator precedence confused. For example i % 60 * 1000 is (i % 60) * 1000, not i % (60 * 1000). Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#im-integer-multiply-of-result-of-integer-remainder-im-multiplying-result-of-irem
DMI_INVOKING_HASHCODE_ON_ARRAY The code invokes hashCode on an array. Calling hashCode on an array returns the same value as System.identityHashCode, and ignores the contents and length of the array. If you need a hashCode that depends on the contents of an array a, use java.util.Arrays.hashCode(a). Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-invocation-of-hashcode-on-an-array-dmi-invoking-hashcode-on-array
DMI_BAD_MONTH This code passes a constant month value outside the expected range of 0..11 to a method. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-bad-constant-value-for-month-dmi-bad-month
DMI_CALLING_NEXT_FROM_HASNEXT The hasNext() method invokes the next() method. This is almost certainly wrong, since the hasNext() method is not supposed to change the state of the iterator, and the next method is supposed to change the state of the iterator. Accuracy https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-hasnext-method-invokes-next-dmi-calling-next-from-hasnext
GC_UNRELATED_TYPES This call to a generic collection method contains an argument with an incompatible class from that of the collection’s parameter (i.e., the type of the argument is neither a supertype nor a subtype of the corresponding generic type argument). Therefore, it is unlikely that the collection contains any objects that are equal to the method argument used here. Most likely, the wrong value is being passed to the method.

 

 

 

 

 

 

In general, instances of two unrelated classes are not equal. For example, if the Foo and Bar classes are not related by subtyping, then an instance of Foo should not be equal to an instance of Bar. Among other issues, doing so will likely result in an equals method that is not symmetrical. For example, if you define the Foo class so that a Foo can be equal to a String, your equals method isn’t symmetrical since a String can only be equal to a String.

In rare cases, people do define nonsymmetrical equals methods and still manage to make their code work. Although none of the APIs document or guarantee it, it is typically the case that if you check if a Collection contains a Foo, the equals method of argument (e.g., the equals method of the Foo class) used to perform the equality checks.

Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#gc-no-relationship-between-generic-parameter-and-method-argument-gc-unrelated-types
DMI_VACUOUS_SELF_COLLECTION_CALL This call doesn’t make sense. For any collection c, calling c.containsAll(c) should always be true, and c.retainAll(c) should have no effect. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-vacuous-call-to-collections-dmi-vacuous-self-collection-call
DMI_DOH This partical method invocation doesn’t make sense, for reasons that should be apparent from inspection. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-d-oh-a-nonsensical-method-invocation-dmi-doh
DMI_COLLECTIONS_SHOULD_NOT_CONTAIN_THEMSELVES This call to a generic collection’s method would only make sense if a collection contained itself (e.g., if s.contains(s) were true). This is unlikely to be true and would cause problems if it were true (such as the computation of the hash code resulting in infinite recursion). It is likely that the wrong value is being passed as a parameter. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-collections-should-not-contain-themselves-dmi-collections-should-not-contain-themselves
TQ_UNKNOWN_VALUE_USED_WHERE_ALWAYS_STRICTLY_REQUIRED A value is being used in a way that requires the value be annotation with a type qualifier. The type qualifier is strict, so the tool rejects any values that do not have the appropriate annotation.

 

 

 

 

 

 

To coerce a value to have a strict annotation, define an identity function where the return value is annotated with the strict annotation. This is the only way to turn a non-annotated value into a value with a strict type qualifier annotation.

Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#tq-value-without-a-type-qualifier-used-where-a-value-is-required-to-have-that-qualifier-tq-unknown-value-used-where-always-strictly-required
TQ_COMPARING_VALUES_WITH_INCOMPATIBLE_TYPE_QUALIFIERS A value specified as carrying a type qualifier annotation is compared with a value that doesn’t ever carry that qualifier.

 

 

 

 

 

 

More precisely, a value annotated with a type qualifier specifying when=ALWAYS is compared with a value that where the same type qualifier specifies when=NEVER.

Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#tq-comparing-values-with-incompatible-type-qualifiers-tq-comparing-values-with-incompatible-type-qualifiers
TQ_NEVER_VALUE_USED_WHERE_ALWAYS_REQUIRED A value specified as not carrying a type qualifier annotation is guaranteed to be consumed in a location or locations requiring that the value does carry that annotation.

 

 

 

 

 

 

More precisely, a value annotated with a type qualifier specifying when=NEVER is guaranteed to reach a use or uses where the same type qualifier specifies when=ALWAYS.

Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#tq-value-annotated-as-never-carrying-a-type-qualifier-used-where-value-carrying-that-qualifier-is-required-tq-never-value-used-where-always-required
TQ_MAYBE_SOURCE_VALUE_REACHES_ALWAYS_SINK A value that is annotated as possibility not being an instance of the values denoted by the type qualifier, and the value is guaranteed to be used in a way that requires values denoted by that type qualifier. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#tq-value-that-might-not-carry-a-type-qualifier-is-always-used-in-a-way-requires-that-type-qualifier-tq-maybe-source-value-reaches-always-sink
TQ_MAYBE_SOURCE_VALUE_REACHES_NEVER_SINK A value that is annotated as possibility being an instance of the values denoted by the type qualifier, and the value is guaranteed to be used in a way that prohibits values denoted by that type qualifier. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#tq-value-that-might-carry-a-type-qualifier-is-always-used-in-a-way-prohibits-it-from-having-that-type-qualifier-tq-maybe-source-value-reaches-never-sink
DM_DEFAULT_ENCODING Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly. Portability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-reliance-on-default-encoding-dm-default-encoding
FI_PUBLIC_SHOULD_BE_PROTECTED A class’s finalize() method should have protected access, not public. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#fi-finalizer-should-be-protected-not-public-fi-public-should-be-protected
MS_OOI_PKGPROTECT A final static field that is defined in an interface references a mutable object such as an array or hashtable. This mutable object could be changed by malicious code or by accident from another package. To solve this, the field needs to be moved to a class and made package protected to avoid this vulnerability. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ms-field-should-be-moved-out-of-an-interface-and-made-package-protected-ms-ooi-pkgprotect
MS_FINAL_PKGPROTECT A mutable static field could be changed by malicious code or by accident from another package. The field could be made package protected and/or made final to avoid this vulnerability. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ms-field-should-be-both-final-and-package-protected-ms-final-pkgprotect
MS_SHOULD_BE_FINAL This static field public but not final, and could be changed by malicious code or by accident from another package. The field could be made final to avoid this vulnerability. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ms-field-isn-t-final-but-should-be-ms-should-be-final
MS_SHOULD_BE_REFACTORED_TO_BE_FINAL This static field public but not final, and could be changed by malicious code or by accident from another package. The field could be made final to avoid this vulnerability. However, the static initializer contains more than one write to the field, so doing so will require some refactoring. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ms-field-isn-t-final-but-should-be-refactored-to-be-so-ms-should-be-refactored-to-be-final
MS_PKGPROTECT A mutable static field could be changed by malicious code or by accident. The field could be made package protected to avoid this vulnerability. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ms-field-should-be-package-protected-ms-pkgprotect
MS_MUTABLE_HASHTABLE A final static field references a Hashtable and can be accessed by malicious code or by accident from another package. This code can freely modify the contents of the Hashtable. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ms-field-is-a-mutable-hashtable-ms-mutable-hashtable
MS_MUTABLE_ARRAY A final static field references an array and can be accessed by malicious code or by accident from another package. This code can freely modify the contents of the array. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ms-field-is-a-mutable-array-ms-mutable-array
MS_MUTABLE_COLLECTION A mutable collection instance is assigned to a final static field, thus can be changed by malicious code or by accident from another package. Consider wrapping this field into Collections.unmodifiableSet/List/Map/etc. to avoid this vulnerability. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ms-field-is-a-mutable-collection-ms-mutable-collection
MS_MUTABLE_COLLECTION_PKGPROTECT A mutable collection instance is assigned to a final static field, thus can be changed by malicious code or by accident from another package. The field could be made package protected to avoid this vulnerability. Alternatively you may wrap this field into Collections.unmodifiableSet/List/Map/etc. to avoid this vulnerability. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ms-field-is-a-mutable-collection-which-should-be-package-protected-ms-mutable-collection-pkgprotect
MS_CANNOT_BE_FINAL A mutable static field could be changed by malicious code or by accident from another package. Unfortunately, the way the field is used doesn’t allow any easy fix to this problem. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ms-field-isn-t-final-and-can-t-be-protected-from-malicious-code-ms-cannot-be-final
STCAL_STATIC_CALENDAR_INSTANCE Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multithreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application. Under 1.4 problems seem to surface less often than under Java 5 where you will probably see random ArrayIndexOutOfBoundsExceptions or IndexOutOfBoundsExceptions in sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate(). You may also experience serialization problems. Using an instance field is recommended. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#stcal-static-calendar-field-stcal-static-calendar-instance
STCAL_STATIC_SIMPLE_DATE_FORMAT_INSTANCE As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application. You may also experience serialization problems. Using an instance field is recommended. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#stcal-static-dateformat-stcal-static-simple-date-format-instance
STCAL_INVOKE_ON_STATIC_CALENDAR_INSTANCE Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multithreaded use. The detector has found a call to an instance of Calendar that has been obtained via a static field. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#stcal-call-to-static-calendar-stcal-invoke-on-static-calendar-instance
STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. The detector has found a call to an instance of DateFormat that has been obtained via a static field. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#stcal-call-to-static-dateformat-stcal-invoke-on-static-date-format-instance
VO_VOLATILE_REFERENCE_TO_ARRAY This declares a volatile reference to an array, which might not be what you want. With a volatile reference to an array, reads and writes of the reference to the array are treated as volatile, but the array elements are non-volatile. To get volatile array elements, you will need to use one of the atomic array classes in java.util.concurrent (provided in Java 5.0). Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#vo-a-volatile-reference-to-an-array-doesn-t-treat-the-array-elements-as-volatile-vo-volatile-reference-to-array
VO_VOLATILE_INCREMENT This code increments a volatile field. Increments of volatile fields aren’t atomic. If more than one thread is incrementing the field at the same time, increments could be lost. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#vo-an-increment-to-a-volatile-field-isn-t-atomic-vo-volatile-increment
DM_USELESS_THREAD This method creates a thread without specifying a run method either by deriving from the Thread class, or by passing a Runnable object. This thread, then, does nothing but waste time. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-a-thread-was-created-using-the-default-empty-run-method-dm-useless-thread
DC_DOUBLECHECK This method may contain an instance of double-checked locking. This idiom is not correct according to the semantics of the Java memory model. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dc-possible-double-check-of-field-dc-doublecheck
WL_USING_GETCLASS_RATHER_THAN_CLASS_LITERAL This instance method synchronizes on this.getClass(). If this class is subclassed, subclasses will synchronize on the class object for the subclass, which isn’t likely what was intended. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#wl-synchronization-on-getclass-rather-than-class-literal-wl-using-getclass-rather-than-class-literal
ESync_EMPTY_SYNC The code contains an empty synchronized block. Empty synchronized blocks are far more subtle and hard to use correctly than most people recognize, and empty synchronized blocks are almost never a better solution than less contrived solutions. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#esync-empty-synchronized-block-esync-empty-sync
MSF_MUTABLE_SERVLET_FIELD A web server generally only creates one instance of servlet or JSP class (i.e., treats the class as a Singleton), and will have multiple threads invoke methods on that instance to service multiple simultaneous requests. Thus, having a mutable instance field generally creates race conditions. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#msf-mutable-servlet-field-msf-mutable-servlet-field
IS2_INCONSISTENT_SYNC The fields of this class appear to be accessed inconsistently with respect to synchronization. This bug report indicates that the bug pattern detector judged that
– The class contains a mix of locked and unlocked accesses,
– The class is not annotated as javax.annotation.concurrent.NotThreadSafe,
– At least one locked access was performed by one of the class’s own methods, and
– The number of unsynchronized field accesses (reads and writes) was no more than one third of all accesses, with writes being weighed twice as high as reads
– A typical bug matching this bug pattern is forgetting to synchronize one of the methods in a class that is intended to be thread-safe.

 

 

 

 

 

 

You can select the nodes labeled “Unsynchronized access” to show the code locations where the detector believed that a field was accessed without synchronization.

Note that there are various sources of inaccuracy in this detector; for example, the detector cannot statically detect all situations in which a lock is held. Also, even when the detector is accurate in distinguishing locked vs. unlocked accesses, the code in question may still be correct.

Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#is-inconsistent-synchronization-is2-inconsistent-sync
RU_INVOKE_RUN This method explicitly invokes run() on an object. In general, classes implement the Runnable interface because they are going to have their run() method invoked in a new thread, in which case Thread.start() is the right method to call. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ru-invokes-run-on-a-thread-did-you-mean-to-start-it-instead-ru-invoke-run
SP_SPIN_ON_FIELD This method spins in a loop which reads a field. The compiler may legally hoist the read out of the loop, turning the code into an infinite loop. The class should be changed so it uses proper synchronization (including wait and notify calls). Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#sp-method-spins-on-field-sp-spin-on-field
UW_UNCOND_WAIT This method contains a call to java.lang.Object.wait() which is not guarded by conditional control flow. The code should verify that condition it intends to wait for is not already satisfied before calling wait; any previous notifications will be ignored. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#uw-unconditional-wait-uw-uncond-wait
UG_SYNC_SET_UNSYNC_GET This class contains similarly-named get and set methods where the set method is synchronized and the get method is not. This may result in incorrect behavior at runtime, as callers of the get method will not necessarily see a consistent state for the object. The get method should be made synchronized. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ug-unsynchronized-get-method-synchronized-set-method-ug-sync-set-unsync-get
IS_FIELD_NOT_GUARDED This field is annotated with net.jcip.annotations.GuardedBy or javax.annotation.concurrent.GuardedBy, but can be accessed in a way that seems to violate those annotations. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#is-field-not-guarded-against-concurrent-access-is-field-not-guarded
WS_WRITEOBJECT_SYNC This class has a writeObject() method which is synchronized; however, no other method of the class is synchronized. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ws-class-s-writeobject-method-is-synchronized-but-nothing-else-is-ws-writeobject-sync
RS_READOBJECT_SYNC This serializable class defines a readObject() which is synchronized. By definition, an object created by deserialization is only reachable by one thread, and thus there is no need for readObject() to be synchronized. If the readObject() method itself is causing the object to become visible to another thread, that is an example of very dubious coding style. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rs-class-s-readobject-method-is-synchronized-rs-readobject-sync
WA_NOT_IN_LOOP This method contains a call to java.lang.Object.wait() which is not in a loop. If the monitor is used for multiple conditions, the condition the caller intended to wait for might not be the one that actually occurred. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#wa-wait-not-in-loop-wa-not-in-loop
WA_AWAIT_NOT_IN_LOOP This method contains a call to java.util.concurrent.await() (or variants) which is not in a loop. If the object is used for multiple conditions, the condition the caller intended to wait for might not be the one that actually occurred. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#wa-condition-await-not-in-loop-wa-await-not-in-loop
NO_NOTIFY_NOT_NOTIFYALL This method calls notify() rather than notifyAll(). Java monitors are often used for multiple conditions. Calling notify() only wakes up one thread, meaning that the thread woken up might not be the one waiting for the condition that the caller just satisfied. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#no-using-notify-rather-than-notifyall-no-notify-not-notifyall
MWN_MISMATCHED_WAIT This method calls Object.wait() without obviously holding a lock on the object. Calling wait() without a lock held will result in an IllegalMonitorStateException being thrown. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#mwn-mismatched-wait-mwn-mismatched-wait
MWN_MISMATCHED_NOTIFY This method calls Object.notify() or Object.notifyAll() without obviously holding a lock on the object. Calling notify() or notifyAll() without a lock held will result in an IllegalMonitorStateException being thrown. Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#mwn-mismatched-notify-mwn-mismatched-notify
JML_JSR166_CALLING_WAIT_RATHER_THAN_AWAIT This method calls wait(), notify() or notifyAll()() on an object that also provides an await(), signal(), signalAll() method (such as util.concurrent Condition objects). This probably isn’t what you want, and even if you do want it, you should consider changing your design, as other developers will find it exceptionally confusing. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#jlm-using-monitor-style-wait-methods-on-util-concurrent-abstraction-jml-jsr166-calling-wait-rather-than-await
JLM_JSR166_LOCK_MONITORENTER This method performs synchronization on an object that implements java.util.concurrent.locks.Lock. Such an object is locked/unlocked using acquire()/release() rather than using the synchronized (…) construct. Maintainability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#jlm-synchronization-performed-on-lock-jlm-jsr166-lock-monitorenter
RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED putIfAbsent Robustness https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rv-return-value-of-putifabsent-ignored-value-passed-to-putifabsent-reused-rv-return-value-of-putifabsent-ignored
DM_STRING_CTOR Using the java.lang.String(String) constructor wastes memory because the object so constructed will be functionally indistinguishable from the String passed as a parameter. Just use the argument String directly. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-method-invokes-inefficient-new-string-string-constructor-dm-string-ctor
DM_STRING_VOID_CTOR Creating a new java.lang.String object using the no-argument constructor wastes memory because the object so created will be functionally indistinguishable from the empty string constant “”. Java guarantees that identical string constants will be represented by the same String object. Therefore, you should just use the empty string constant directly. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-method-invokes-inefficient-new-string-constructor-dm-string-void-ctor
DM_NUMBER_CTOR Using new Integer(int) is guaranteed to always result in a new object whereas Integer.valueOf(int) allows caching of values to be done by the compiler, class library, or JVM. Using of cached values avoids object allocation and the code will be faster.

 

 

 

 

 

 

Values between -128 and 127 are guaranteed to have corresponding cached instances and using valueOf is approximately 3.5 times faster than using constructor. For values outside the constant range the performance of both styles is the same.

Unless the class must be compatible with JVMs predating Java 1.5, use either autoboxing or the valueOf() method when creating instances of Long, Integer, Short, Character, and Byte.

Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bx-method-invokes-inefficient-number-constructor-use-static-valueof-instead-dm-number-ctor
DM_FP_NUMBER_CTOR Using new Double(double) is guaranteed to always result in a new object whereas Double.valueOf(double) allows caching of values to be done by the compiler, class library, or JVM. Using of cached values avoids object allocation and the code will be faster.

 

 

 

 

 

 

Unless the class must be compatible with JVMs predating Java 1.5, use either autoboxing or the valueOf() method when creating instances of Double and Float.

Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bx-method-invokes-inefficient-floating-point-number-constructor-use-static-valueof-instead-dm-fp-number-ctor
DM_BOXED_PRIMITIVE_TOSTRING A boxed primitive is allocated just to call toString(). It is more effective to just use the static form of toString which takes the primitive value. So,

 

 

 

 

 

 

Replace…With this… new Integer(1).toString()Integer.toString(1) new Long(1).toString()Long.toString(1) new Float(1.0).toString()Float.toString(1.0) new Double(1.0).toString()Double.toString(1.0) new Byte(1).toString()Byte.toString(1) new Short(1).toString()Short.toString(1) new Boolean(true).toString()Boolean.toString(true)

Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bx-method-allocates-a-boxed-primitive-just-to-call-tostring-dm-boxed-primitive-tostring
DM_BOXED_PRIMITIVE_FOR_PARSING A boxed primitive is created from a String, just to extract the unboxed primitive value. It is more efficient to just call the static parseXXX method. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bx-boxing-unboxing-to-parse-a-primitive-dm-boxed-primitive-for-parsing
DM_BOXED_PRIMITIVE_FOR_COMPARE A boxed primitive is created just to call compareTo method. It’s more efficient to use static compare method (for double and float since Java 1.4, for other primitive types since Java 1.7) which works on primitives directly. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bx-boxing-a-primitive-to-compare-dm-boxed-primitive-for-compare
BX_UNBOXING_IMMEDIATELY_REBOXED A boxed value is unboxed and then immediately reboxed. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bx-boxed-value-is-unboxed-and-then-immediately-reboxed-bx-unboxing-immediately-reboxed
SIC_INNER_SHOULD_BE_STATIC This class is an inner class, but does not use its embedded reference to the object which created it. This reference makes the instances of the class larger, and may keep the reference to the creator object alive longer than necessary. If possible, the class should be made static. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#sic-should-be-a-static-inner-class-sic-inner-should-be-static
SIC_INNER_SHOULD_BE_STATIC_NEEDS_THIS This class is an inner class, but does not use its embedded reference to the object which created it except during construction of the inner object. This reference makes the instances of the class larger, and may keep the reference to the creator object alive longer than necessary. If possible, the class should be made into a static inner class. Since the reference to the outer object is required during construction of the inner instance, the inner class will need to be refactored so as to pass a reference to the outer instance to the constructor for the inner class. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#sic-could-be-refactored-into-a-static-inner-class-sic-inner-should-be-static-needs-this
SIC_INNER_SHOULD_BE_STATIC_ANON This class is an inner class, but does not use its embedded reference to the object which created it. This reference makes the instances of the class larger, and may keep the reference to the creator object alive longer than necessary. If possible, the class should be made into a static inner class. Since anonymous inner classes cannot be marked as static, doing this will require refactoring the inner class so that it is a named inner class. Understandability https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#sic-could-be-refactored-into-a-named-static-inner-class-sic-inner-should-be-static-anon
SBSC_USE_STRINGBUFFER_CONCATENATION The method seems to be building a String using concatenation in a loop. In each iteration, the String is converted to a StringBuffer/StringBuilder, appended to, and converted back to a String. This can lead to a cost quadratic in the number of iterations, as the growing string is recopied in each iteration.

 

 

 

 

 

 

Better performance can be obtained by using a StringBuffer (or StringBuilder in Java 1.5) explicitly.

Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#sbsc-method-concatenates-strings-using-in-a-loop-sbsc-use-stringbuffer-concatenation
IIL_ELEMENTS_GET_LENGTH_IN_LOOP The method calls NodeList.getLength() inside the loop and NodeList was produced by getElementsByTagName call. This NodeList doesn’t store its length, but computes it every time in not very optimal way. Consider storing the length to the variable before the loop. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#iil-nodelist-getlength-called-in-a-loop-iil-elements-get-length-in-loop
IIL_PREPARE_STATEMENT_IN_LOOP The method calls Connection.prepareStatement inside the loop passing the constant arguments. If the PreparedStatement should be executed several times there’s no reason to recreate it for each loop iteration. Move this call outside of the loop. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#iil-method-calls-preparestatement-in-a-loop-iil-prepare-statement-in-loop
IIL_PATTERN_COMPILE_IN_LOOP The method calls Pattern.compile inside the loop passing the constant arguments. If the Pattern should be used several times there’s no reason to compile it for each loop iteration. Move this call outside of the loop or even into static final field. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#iil-method-calls-pattern-compile-in-a-loop-iil-pattern-compile-in-loop
IIL_PATTERN_COMPILE_IN_LOOP_INDIRECT The method creates the same regular expression inside the loop, so it will be compiled every iteration. It would be more optimal to precompile this regular expression using Pattern.compile outside of the loop. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#iil-method-compiles-the-regular-expression-in-a-loop-iil-pattern-compile-in-loop-indirect
IIO_INEFFICIENT_INDEX_OF This code passes a constant string of length 1 to String.indexOf(). It is more efficient to use the integer implementations of String.indexOf(). f. e. call myString.indexOf(‘.’) instead of myString.indexOf(“.”) Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#iio-inefficient-use-of-string-indexof-string-iio-inefficient-index-of
IIO_INEFFICIENT_LAST_INDEX_OF This code passes a constant string of length 1 to String.lastIndexOf(). It is more efficient to use the integer implementations of String.lastIndexOf(). f. e. call myString.lastIndexOf(‘.’) instead of myString.lastIndexOf(“.”) Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#iio-inefficient-use-of-string-lastindexof-string-iio-inefficient-last-index-of
ITA_INEFFICIENT_TO_ARRAY This method uses the toArray() method of a collection derived class, and passes in a zero-length prototype array argument. It is more efficient to use myCollection.toArray(new Foo[myCollection.size()]) If the array passed in is big enough to store all of the elements of the collection, then it is populated and returned directly. This avoids the need to create a second array (by reflection) to return as the result. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ita-method-uses-toarray-with-zero-length-array-argument-ita-inefficient-to-array
IMA_INEFFICIENT_MEMBER_ACCESS This method of an inner class reads from or writes to a private member variable of the owning class, or calls a private method of the owning class. The compiler must generate a special method to access this private member, causing this to be less efficient. Relaxing the protection of the member variable or method will allow the compiler to treat this as a normal access. Efficiency https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ima-method-accesses-a-private-member-variable-of-owning-class-ima-inefficient-member-access
NP_DEREFERENCE_OF_READLINE_VALUE The result of invoking readLine() is dereferenced without checking to see if the result is null. If there are no more lines of text to read, readLine() will return null and dereferencing that will generate a null pointer exception.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-dereference-of-the-result-of-readline-without-nullcheck-np-dereference-of-readline-value
NP_IMMEDIATE_DEREFERENCE_OF_READLINE The result of invoking readLine() is immediately dereferenced. If there are no more lines of text to read, readLine() will return null and dereferencing that will generate a null pointer exception.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-immediate-dereference-of-the-result-of-readline-np-immediate-dereference-of-readline
RV_REM_OF_RANDOM_INT This code generates a random signed integer and then computes the remainder of that value modulo another value. Since the random number can be negative, the result of the remainder operation can also be negative. Be sure this is intended, and strongly consider using the Random.nextInt(int) method instead.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rv-remainder-of-32-bit-signed-random-integer-rv-rem-of-random-int
RV_REM_OF_HASHCODE This code computes a hashCode, and then computes the remainder of that value modulo another value. Since the hashCode can be negative, the result of the remainder operation can also be negative.

 

 

 

 

 

 

Assuming you want to ensure that the result of your computation is nonnegative, you may need to change your code. If you know the divisor is a power of 2, you can use a bitwise and operator instead (i.e., instead of using x.hashCode()%n, use x.hashCode()&(n-1)). This is probably faster than computing the remainder as well. If you don’t know that the divisor is a power of 2, take the absolute value of the result of the remainder operation (i.e., use Math.abs(x.hashCode()%n)).

  https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rv-remainder-of-hashcode-could-be-negative-rv-rem-of-hashcode
EQ_DOESNT_OVERRIDE_EQUALS This class extends a class that defines an equals method and adds fields, but doesn’t define an equals method itself. Thus, equality on instances of this class will ignore the identity of the subclass and the added fields. Be sure this is what is intended, and that you don’t need to override the equals method. Even if you don’t need to override the equals method, consider overriding it anyway to document the fact that the equals method for the subclass just return the result of invoking super.equals(o).   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#eq-class-doesn-t-override-equals-in-superclass-eq-doesnt-override-equals
NS_NON_SHORT_CIRCUIT This code seems to be using non-short-circuit logic (e.g., & or |) rather than short-circuit logic (&& or ||). Non-short-circuit logic causes both sides of the expression to be evaluated even when the result can be inferred from knowing the left-hand side. This can be less efficient and can result in errors if the left-hand side guards cases when evaluating the right-hand side can generate an error.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ns-questionable-use-of-non-short-circuit-logic-ns-non-short-circuit
IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD An inner class is invoking a method that could be resolved to either a inherited method or a method defined in an outer class. For example, you invoke foo(17), which is defined in both a superclass and in an outer method. By the Java semantics, it will be resolved to invoke the inherited method, but this may not be what you intend.

 

 

 

 

 

 

If you really intend to invoke the inherited method, invoke it by invoking the method on super (e.g., invoke super.foo(17)), and thus it will be clear to other readers of your code and to SpotBugs that you want to invoke the inherited method, not the method in the outer class.

If you call this.foo(17), then the inherited method will be invoked. However, since SpotBugs only looks at classfiles, it can’t tell the difference between an invocation of this.foo(17) and foo(17), it will still complain about a potential ambiguous invocation.

  https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ia-potentially-ambiguous-invocation-of-either-an-inherited-or-outer-method-ia-ambiguous-invocation-of-inherited-or-outer-method
SF_SWITCH_FALLTHROUGH This method contains a switch statement where one case branch will fall through to the next case. Usually you need to end this case with a break or return.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#sf-switch-statement-found-where-one-case-falls-through-to-the-next-case-sf-switch-fallthrough
UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD No writes were seen to this public/protected field. All reads of it will return the default value. Check for errors (should it have been initialized?), or remove it if it is useless.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#uwf-unwritten-public-or-protected-field-uwf-unwritten-public-or-protected-field
RV_RETURN_VALUE_IGNORED_INFERRED This code calls a method and ignores the return value. The return value is the same type as the type the method is invoked on, and from our analysis it looks like the return value might be important (e.g., like ignoring the return value of String.toLowerCase()).

 

 

 

 

 

 

We are guessing that ignoring the return value might be a bad idea just from a simple analysis of the body of the method. You can use a @CheckReturnValue annotation to instruct SpotBugs as to whether ignoring the return value of this method is important or acceptable.

Please investigate this closely to decide whether it is OK to ignore the return value.

  https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rv-method-ignores-return-value-is-this-ok-rv-return-value-ignored-inferred
RV_CHECK_FOR_POSITIVE_INDEXOF The method invokes String.indexOf and checks to see if the result is positive or non-positive. It is much more typical to check to see if the result is negative or non-negative. It is positive only if the substring checked for occurs at some place other than at the beginning of the String.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rv-method-checks-to-see-if-result-of-string-indexof-is-positive-rv-check-for-positive-indexof
RV_DONT_JUST_NULL_CHECK_READLINE The value returned by readLine is discarded after checking to see if the return value is non-null. In almost all situations, if the result is non-null, you will want to use that non-null value. Calling readLine again will give you a different line.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#rv-method-discards-result-of-readline-after-checking-if-it-is-non-null-rv-dont-just-null-check-readline
NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE The return value from a method is dereferenced without a null check, and the return value of that method is one that should generally be checked for null. This may lead to a NullPointerException when the code is executed.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-possible-null-pointer-dereference-due-to-return-value-of-called-method-np-null-on-some-path-from-return-value
NP_NULL_ON_SOME_PATH_MIGHT_BE_INFEASIBLE There is a branch of statement that, if executed, guarantees that a null value will be dereferenced, which would generate a NullPointerException when the code is executed. Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can’t ever be executed; deciding that is beyond the ability of SpotBugs. Due to the fact that this value had been previously tested for nullness, this is a definite possibility.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#np-possible-null-pointer-dereference-on-branch-that-might-be-infeasible-np-null-on-some-path-might-be-infeasible
DLS_DEAD_LOCAL_STORE_SHADOWS_FIELD This instruction assigns a value to a local variable, but the value is not read or used in any subsequent instruction. Often, this indicates an error, because the value computed is never used. There is a field with the same name as the local variable. Did you mean to assign to that variable instead?   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dls-dead-store-to-local-variable-that-shadows-field-dls-dead-local-store-shadows-field
RI_REDUNDANT_INTERFACES This class declares that it implements an interface that is also implemented by a superclass. This is redundant because once a superclass implements an interface, all subclasses by default also implement this interface. It may point out that the inheritance hierarchy has changed since this class was created, and consideration should be given to the ownership of the interface’s implementation.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#ri-class-implements-same-interface-as-superclass-ri-redundant-interfaces
MTIA_SUSPECT_STRUTS_INSTANCE_FIELD This class extends from a Struts Action class, and uses an instance member variable. Since only one instance of a struts Action class is created by the Struts framework, and used in a multithreaded way, this paradigm is highly discouraged and most likely problematic. Consider only using method local variables. Only instance fields that are written outside of a monitor are reported.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#mtia-class-extends-struts-action-class-and-uses-instance-variables-mtia-suspect-struts-instance-field
MTIA_SUSPECT_SERVLET_INSTANCE_FIELD This class extends from a Servlet class, and uses an instance member variable. Since only one instance of a Servlet class is created by the J2EE framework, and used in a multithreaded way, this paradigm is highly discouraged and most likely problematic. Consider only using method local variables.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#mtia-class-extends-servlet-class-and-uses-instance-variables-mtia-suspect-servlet-instance-field
ICAST_INTEGER_MULTIPLY_CAST_TO_LONG This code performs integer multiply and then converts the result to a long.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#icast-result-of-integer-multiplication-cast-to-long-icast-integer-multiply-cast-to-long
ICAST_IDIV_CAST_TO_DOUBLE This code casts the result of an integral division (e.g., int or long division) operation to double or float. Doing division on integers truncates the result to the integer value closest to zero. The fact that the result was cast to double suggests that this precision should have been retained. What was probably meant was to cast one or both of the operands to double before performing the division.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#icast-integral-division-result-cast-to-double-or-float-icast-idiv-cast-to-double
BC_BAD_CAST_TO_CONCRETE_COLLECTION This code casts an abstract collection (such as a Collection, List, or Set) to a specific concrete implementation (such as an ArrayList or HashSet). This might not be correct, and it may make your code fragile, since it makes it harder to switch to other concrete implementations at a future point. Unless you have a particular reason to do so, just use the abstract collection class.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bc-questionable-cast-to-concrete-collection-bc-bad-cast-to-concrete-collection
BC_BAD_CAST_TO_ABSTRACT_COLLECTION This code casts a Collection to an abstract collection (such as List, Set, or Map). Ensure that you are guaranteed that the object is of the type you are casting to. If all you need is to be able to iterate through a collection, you don’t need to cast it to a Set or List.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#bc-questionable-cast-to-abstract-collection-bc-bad-cast-to-abstract-collection
IM_BAD_CHECK_FOR_ODD The code uses x % 2 == 1 to check to see if a value is odd, but this won’t work for negative numbers (e.g., (-5) % 2 == -1). If this code is intending to check for oddness, consider using x & 1 == 1, or x % 2 != 0.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#im-check-for-oddness-that-won-t-work-for-negative-numbers-im-bad-check-for-odd
DMI_HARDCODED_ABSOLUTE_FILENAME This code constructs a File object using a hard coded to an absolute pathname (e.g., new File(“/home/dannyc/workspace/j2ee/src/share/com/sun/enterprise/deployment”);   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-code-contains-a-hard-coded-reference-to-an-absolute-pathname-dmi-hardcoded-absolute-filename
ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#st-write-to-static-field-from-instance-method-st-write-to-static-from-instance-method
DMI_NONSERIALIZABLE_OBJECT_WRITTEN This code seems to be passing a non-serializable object to the ObjectOutput.writeObject method. If the object is, indeed, non-serializable, an error will result.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dmi-non-serializable-object-written-to-objectoutput-dmi-nonserializable-object-written
XFB_XML_FACTORY_BYPASS This method allocates a specific implementation of an xml interface. It is preferable to use the supplied factory classes to create these objects so that the implementation can be changed at runtime.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#xfb-method-directly-allocates-a-specific-implementation-of-xml-interfaces-xfb-xml-factory-bypass
TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_NEVER_SINK A value is used in a way that requires it to be never be a value denoted by a type qualifier, but there is an explicit annotation stating that it is not known where the value is prohibited from having that type qualifier. Either the usage or the annotation is incorrect.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#tq-value-required-to-not-have-type-qualifier-but-marked-as-unknown-tq-explicit-unknown-source-value-reaches-never-sink
TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_ALWAYS_SINK A value is used in a way that requires it to be always be a value denoted by a type qualifier, but there is an explicit annotation stating that it is not known where the value is required to have that type qualifier. Either the usage or the annotation is incorrect.   https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#tq-value-required-to-have-type-qualifier-but-marked-as-unknown-tq-explicit-unknown-source-value-reaches-always-sink

SpotBugs Security: Medium level issues

Rule Description KPI url
ME_ENUM_FIELD_SETTER This public method declared in public enum unconditionally sets enum field, thus this field can be changed by malicious code or by accident from another package. Though mutable enum fields may be used for lazy initialization, it’s a bad practice to expose them to the outer world. Consider removing this method or declaring it package-private. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#me-public-enum-method-unconditionally-sets-its-field-me-enum-field-setter

SpotBugs Security: High level issues

Rule Description KPI url
ANDROID_BROADCAST Broadcast intents can be listen by any application with the appropriate permission. It is suggested to avoid transmitting sensitive information when possible. Security https://find-sec-bugs.github.io/bugs.htm#ANDROID_BROADCAST
ANDROID_EXTERNAL_FILE_ACCESS The application write data to external storage (potentially SD card). There are multiple security implication to this action. First, file store on SD card will be accessible to the application having the READ_EXTERNAL_STORAGE permission. Also, if the data persisted contains confidential information about the user, encryption would be needed. Security https://find-sec-bugs.github.io/bugs.htm#ANDROID_EXTERNAL_FILE_ACCESS
ANDROID_GEOLOCATION It is suggested to ask the user for a confirmation about obtaining its geolocation. Security https://find-sec-bugs.github.io/bugs.htm#ANDROID_GEOLOCATION
ANDROID_WEB_VIEW_JAVASCRIPT Enabling JavaScript for the WebView means that it is now susceptible to XSS. The page render should be inspected for potential reflected XSS, stored XSS and DOM XSS.

WebView myWebView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

Security https://find-sec-bugs.github.io/bugs.htm#ANDROID_WEB_VIEW_JAVASCRIPT
ANDROID_WEB_VIEW_JAVASCRIPT_INTERFACE The use of JavaScript Interface could expose the WebView to risky API. If an XSS is triggered in the WebView, the class could be called by the malicious JavaScript code. Security https://find-sec-bugs.github.io/bugs.htm#ANDROID_WEB_VIEW_JAVASCRIPT_INTERFACE
ANDROID_WORLD_WRITABLE The file written in this context is using the creation mode MODE_WORLD_READABLE. It might not be the expected behavior to exposed the content being written. Security https://find-sec-bugs.github.io/bugs.htm#ANDROID_WORLD_WRITABLE
AWS_QUERY_INJECTION Constructing SimpleDB queries containing user input can allow an attacker to view unauthorized records. The following example dynamically constructs and executes a SimpleDB select() query allowing the user to specify the productCategory. The attacker can modify the query, bypass the required authentication for customerID and view records matching any customer. Security https://find-sec-bugs.github.io/bugs.htm#AWS_QUERY_INJECTION
BAD_HEXA_CONVERSION When converting a byte array containing a hash signature to a human readable string, a conversion mistake can be made if the array is read byte by byte. The following sample illustrates the use of Integer.toHexString() which will trim any leading zeroes from each byte of the computed hash value. Security https://find-sec-bugs.github.io/bugs.htm#BAD_HEXA_CONVERSION
BEAN_PROPERTY_INJECTION An attacker can set arbitrary bean properties that can compromise system integrity. Bean population functions allow to set a bean property or a nested property. An attacker can leverage this functionality to access special bean properties like class.classLoader that will allow him to override system properties and potentially execute arbitrary code. Security https://find-sec-bugs.github.io/bugs.htm#BEAN_PROPERTY_INJECTION
BLOWFISH_KEY_SIZE The Blowfish cipher supports keysizes from 32 bits to 448 bits. A small key size makes the ciphertext vulnerable to brute force attacks. At least 128 bits of entropy should be used when generating the key if use of Blowfish is required. If the algorithm can be changed, the AES block cipher should be used instead. Security https://find-sec-bugs.github.io/bugs.htm#BLOWFISH_KEY_SIZE
CIPHER_INTEGRITY The ciphertext produced is susceptible to alteration by an adversary. This mean that the cipher provides no way to detect that the data has been tampered with. If the ciphertext can be controlled by an attacker, it could be altered without detection. The solution is to used a cipher that includes a Hash based Message Authentication Code (HMAC) to sign the data. Combining a HMAC function to the existing cipher is prone to error [1]. Specifically, it is always recommended that you be able to verify the HMAC first, and only if the data is unmodified, do you then perform any cryptographic functions on the data. The following modes are vulnerable because they don’t provide a HMAC: – CBC – OFB – CTR – ECB The following snippets code are some examples of vulnerable code. Security https://find-sec-bugs.github.io/bugs.htm#CIPHER_INTEGRITY
COMMAND_INJECTION The highlighted API is used to execute a system command. If unfiltered input is passed to this API, it can lead to arbitrary command execution. Security https://find-sec-bugs.github.io/bugs.htm#COMMAND_INJECTION
COOKIE_PERSISTENT Storing sensitive data in a persistent cookie for an extended period of time can lead to a breach of confidentiality or account compromise. Explanation: If private information is stored in persistent cookies, attackers have a larger time window in which to steal this data – especially since persistent cookies are often set to expire in the distant future. Persistent cookies are generally stored in a text file on the client and an attacker with access to the victim’s machine can steal this information. Persistent cookies are often used to profile users as they interact with a site. Depending on what is done with this tracking data, it is possible to use persistent cookies to violate users’ privacy. Security https://find-sec-bugs.github.io/bugs.htm#COOKIE_PERSISTENT
COOKIE_USAGE The information stored in a custom cookie should not be sensitive or related to the session. In most cases, sensitive data should only be stored in session and referenced by the user’s session cookie. See HttpSession (HttpServletRequest.getSession()) Custom cookies can be used for information that needs to live longer than and is independent of a specific session. Security https://find-sec-bugs.github.io/bugs.htm#COOKIE_USAGE
CRLF_INJECTION_LOGS When data from an untrusted source is put into a logger and not neutralized correctly, an attacker could forge log entries or include malicious content. Inserted false entries could be used to skew statistics, distract the administrator or even to implicate another party in the commission of a malicious act. If the log file is processed automatically, the attacker can render the file unusable by corrupting the format of the file or injecting unexpected characters. An attacker may also inject code or other commands into the log file and take advantage of a vulnerability in the log processing utility (e.g. command injection or XSS). Security https://find-sec-bugs.github.io/bugs.htm#CRLF_INJECTION_LOGS
CUSTOM_INJECTION The method identified is susceptible to injection. The input should be validated and properly escaped. Security https://find-sec-bugs.github.io/bugs.htm#CUSTOM_INJECTION
CUSTOM_MESSAGE_DIGEST Implementing a custom MessageDigest is error-prone.

NIST recommends the use of SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, or SHA-512/256.
“SHA-1 for digital signature generation: SHA-1 may only be used for digital signature generation where specifically allowed by NIST protocol-specific guidance. For all other applications, SHA-1 shall not be used for digital signature generation. SHA-1 for digital signature verification: For digital signature verification, SHA-1 is allowed for legacy-use. […] SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, and SHA-512/256: The use of these hash functions is acceptable for all hash function applications.” – NIST: Transitions: Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Lengths p.15

Security https://find-sec-bugs.github.io/bugs.htm#CUSTOM_MESSAGE_DIGEST
DEFAULT_HTTP_CLIENT   Security https://find-sec-bugs.github.io/bugs.htm#DEFAULT_HTTP_CLIENT
DES_USAGE DES is considered strong ciphers for modern applications. Currently, NIST recommends the usage of AES block ciphers instead of DES. Security https://find-sec-bugs.github.io/bugs.htm#DES_USAGE
DESERIALIZATION_GADGET Deserialization gadget are class that could be used by an attacker to take advantage of a remote API using Native Serialization. This class is either adding custom behavior to deserialization with the readObject method (Serializable) or can be called from a serialized object (InvocationHandler). This detector is intended to be used mostly by researcher. The real issue is using deserialization for remote operation. Removing gadget is an hardening practice to reduce the risk of being exploited. Security https://find-sec-bugs.github.io/bugs.htm#DESERIALIZATION_GADGET
ECB_MODE An authentication cipher mode which provides better confidentiality of the encrypted data should be used instead of Electronic Codebook (ECB) mode, which does not provide good confidentiality. Specifically, ECB mode produces the same output for the same input each time. So, for example, if a user is sending a password, the encrypted value is the same each time. This allows an attacker to intercept and replay the data. To fix this, something like Galois/Counter Mode (GCM) should be used instead. Security https://find-sec-bugs.github.io/bugs.htm#ECB_MODE
EL_INJECTION A expression is built with a dynamic value. The source of the value(s) should be verified to avoid that unfiltered values fall into this risky code evaluation. Security https://find-sec-bugs.github.io/bugs.htm#EL_INJECTION
ESAPI_ENCRYPTOR The ESAPI has a small history of vulnerabilities within the cryptography component. Here is a quick validation list to make sure the Authenticated Encryption is working as expected. Security https://find-sec-bugs.github.io/bugs.htm#ESAPI_ENCRYPTOR
EXTERNAL_CONFIG_CONTROL Allowing external control of system settings can disrupt service or cause an application to behave in unexpected, and potentially malicious ways. An attacker could cause an error by providing a nonexistent catalog name or connect to an unauthorized portion of the database. Security https://find-sec-bugs.github.io/bugs.htm#EXTERNAL_CONFIG_CONTROL
FILE_UPLOAD_FILENAME The filename provided by the FileUpload API can be tampered with by the client to reference unauthorized files.

Therefore, such values should not be passed directly to the filesystem API. If acceptable, the application should generate its own file names and use those. Otherwise, the provided filename should be properly validated to ensure it’s properly structured, contains no unauthorized path characters (e.g., / ), and refers to an authorized file.

Security https://find-sec-bugs.github.io/bugs.htm#FILE_UPLOAD_FILENAME
FORMAT_STRING_MANIPULATION Allowing user input to control format parameters could enable an attacker to cause exceptions to be thrown or leak information. Attackers may be able to modify the format string argument, such that an exception is thrown. If this exception is left uncaught, it may crash the application. Alternatively, if sensitive information is used within the unused arguments, attackers may change the format string to reveal this information. The example code below lets the user specify the decimal points to which it shows the balance. The user can in fact specify anything causing an exception to be thrown which could lead to application failure. Even more critical within this example, if an attacker can specify the user input “2f %3$s %4$.2”, the format string would be “The customer: %s %s has the balance %4$.2f %3$s %4$.2”. This would then lead to the sensitive accountNo to be included within the resulting string. Security https://find-sec-bugs.github.io/bugs.htm#FORMAT_STRING_MANIPULATION
HARD_CODE_KEY Cryptographic keys should not be kept in the source code. The source code can be widely shared in an enterprise environment, and is certainly shared in open source. To be managed safely, passwords and secret keys should be stored in separate configuration files or keystores. (Hard coded passwords are reported separately by Hard Coded Password pattern). Security https://find-sec-bugs.github.io/bugs.htm#HARD_CODE_KEY
HARD_CODE_PASSWORD Passwords should not be kept in the source code. The source code can be widely shared in an enterprise environment, and is certainly shared in open source. To be managed safely, passwords and secret keys should be stored in separate configuration files or keystores. (Hard coded keys are reported separately by Hard Coded Key pattern) Security https://find-sec-bugs.github.io/bugs.htm#HARD_CODE_PASSWORD
HAZELCAST_SYMMETRIC_ENCRYPTION The network communications for Hazelcast is configured to use a symmetric cipher (probably DES or blowfish). Those ciphers alone do not provide integrity or secure authentication. The use of asymmetric encryption is preferred. Security https://find-sec-bugs.github.io/bugs.htm#HAZELCAST_SYMMETRIC_ENCRYPTION
HTTP_PARAMETER_POLLUTION Concatenating unvalidated user input into a URL can allow an attacker to override the value of a request parameter. Attacker may be able to override existing parameter values, inject a new parameter or exploit variables out of a direct reach. HTTP Parameter Pollution (HPP) attacks consist of injecting encoded query string delimiters into other existing parameters. If a web application does not properly sanitize the user input, a malicious user may compromise the logic of the application to perform either client-side or server-side attacks. In the following example the programmer has not considered the possibility that an attacker could provide a lang such as en&user_id=1, which would enable him to change the user_id at will. Security https://find-sec-bugs.github.io/bugs.htm#HTTP_PARAMETER_POLLUTION
HTTP_RESPONSE_SPLITTING When an HTTP request contains unexpected CR and LF characters, the server may respond with an output stream that is interpreted as two different HTTP responses (instead of one). An attacker can control the second response and mount attacks such as cross-site scripting and cache poisoning attacks. According to OWASP, the issue has been fixed in virtually all modern Java EE application servers, but it is still better to validate the input. If you are concerned about this risk, you should test on the platform of concern to see if the underlying platform allows for CR or LF characters to be injected into headers. This weakness is reported with lower priority than SQL injection etc., if you are using a vulnerable platform, please check low-priority warnings too. Security https://find-sec-bugs.github.io/bugs.htm#HTTP_RESPONSE_SPLITTING
HTTPONLY_COOKIE A new cookie is created without the HttpOnly flag set. The HttpOnly flag is a directive to the browser to make sure that the cookie can not be red by malicious script. When a user is the target of a “Cross-Site Scripting”, the attacker would benefit greatly from getting the session id for example. Security https://find-sec-bugs.github.io/bugs.htm#HTTPONLY_COOKIE
INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE The sensitive information may be valuable information on its own (such as a password), or it may be useful for launching other, more deadly attacks. If an attack fails, an attacker may use error information provided by the server to launch another more focused attack. For example, an attempt to exploit a path traversal weakness (CWE-22) might yield the full pathname of the installed application. In turn, this could be used to select the proper number of “..” sequences to navigate to the targeted file. An attack using SQL injection (CWE-89) might not initially succeed, but an error message could reveal the malformed query, which would expose query logic and possibly even passwords or other sensitive information used within the query. Security https://find-sec-bugs.github.io/bugs.htm#INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE
INSECURE_COOKIE A new cookie is created without the Secure flag set. The Secure flag is a directive to the browser to make sure that the cookie is not sent for insecure communication (http://). Security https://find-sec-bugs.github.io/bugs.htm#INSECURE_COOKIE
INSECURE_SMTP_SSL Server identity verification is disabled when making SSL connections. Some email libraries that enable SSL connections do not verify the server certificate by default. This is equivalent to trusting all certificates. When trying to connect to the server, this application would readily accept a certificate issued to “hackedserver.com”. The application would now potentially leak sensitive user information on a broken SSL connection to the hacked server. Security https://find-sec-bugs.github.io/bugs.htm#INSECURE_SMTP_SSL
JACKSON_UNSAFE_DESERIALIZATION When the Jackson databind library is used incorrectly the deserialization of untrusted data can lead to remote code execution, if there is a class in classpath that allows the trigger of malicious operation. Security https://find-sec-bugs.github.io/bugs.htm#JACKSON_UNSAFE_DESERIALIZATION
JAXRS_ENDPOINT This method is part of a REST Web Service (JSR311). The security of this web service should be analyzed. For example:

1. Authentication, if enforced, should be tested.
2. Access control, if enforced, should be tested.
3. The inputs should be tracked for potential vulnerabilities.
4. The communication should ideally be over SSL.
5. If the service supports writes (e.g., via POST), its vulnerability to CSRF should be investigated.[1]

Security https://find-sec-bugs.github.io/bugs.htm#JAXRS_ENDPOINT
JAXWS_ENDPOINT This method is part of a SOAP Web Service (JSR224). The security of this web service should be analyzed. For example:

1. Authentication, if enforced, should be tested.
2. Access control, if enforced, should be tested.
3. The inputs should be tracked for potential vulnerabilities.
4. The communication should ideally be over SSL.

Security https://find-sec-bugs.github.io/bugs.htm#JAXWS_ENDPOINT
JSP_INCLUDE The inclusion of JSP file allow the entry of dynamic value. It may allow an attacker to control the JSP page included. If this is the case, an attacker will try to include a file on disk that he controls. By including arbitrary files, the attacker gets the ability to execute any code. Security https://find-sec-bugs.github.io/bugs.htm#JSP_INCLUDE
JSP_JSTL_OUT A potential XSS was found. It could be used to execute unwanted JavaScript in a client’s browser. (See references) Security https://find-sec-bugs.github.io/bugs.htm#JSP_JSTL_OUT
JSP_SPRING_EVAL A Spring expression is built with a dynamic value. The source of the value(s) should be verified to avoid that unfiltered values fall into this risky code evaluation. Security https://find-sec-bugs.github.io/bugs.htm#JSP_SPRING_EVAL
JSP_XSLT XSLT (Extensible Stylesheet Language Transformations) is a language for transforming XML documents into other XML documents. It is possible to attach malicious behavior to those stylesheets. Therefore, if an attacker can control the content or the source of the stylesheet, he might be able to trigger remote code execution. Security https://find-sec-bugs.github.io/bugs.htm#JSP_XSLT
LDAP_ANONYMOUS Without proper access control, executing an LDAP statement that contains a user-controlled value can allow an attacker to abuse poorly configured LDAP environment. All LDAP queries executed against ctx will be performed without authentication and access control. An attacker may be able to manipulate one of these queries in an unexpected way to gain access to records that would otherwise be protected by the directory’s access control mechanism. Security https://find-sec-bugs.github.io/bugs.htm#LDAP_ANONYMOUS
LDAP_ENTRY_POISONING JNDI API support the binding of serialize object in LDAP directories. If certain attributes are presented, the deserialization of object will be made in the application querying the directory (See Black Hat USA 2016 white paper for details). Object deserialization should be threated as risky operation that can lead to remote code execution. The exploitation of the vulnerability will be possible if the attacker has an entry point in an LDAP base query, by adding attributes to an existing LDAP entry or by configuring the application to use a malicious LDAP server. Security https://find-sec-bugs.github.io/bugs.htm#LDAP_ENTRY_POISONING
LDAP_INJECTION Just like SQL, all inputs passed to an LDAP query need to be passed in safely. Unfortunately, LDAP doesn’t have prepared statement interfaces like SQL. Therefore, the primary defense against LDAP injection is strong input validation of any untrusted data before including it in an LDAP query. Security https://find-sec-bugs.github.io/bugs.htm#LDAP_INJECTION
MALICIOUS_XSLT “XSLT (Extensible Stylesheet Language Transformations) is a language for transforming XML documents into other XML documents”. It is possible to attach malicious behavior to those stylesheets. Therefore, if an attacker can control the content or the source of the stylesheet, he might be able to trigger remote code execution. Security https://find-sec-bugs.github.io/bugs.htm#MALICIOUS_XSLT
NULL_CIPHER The NullCipher is rarely used intentionally in production applications. It implements the Cipher interface by returning ciphertext identical to the supplied plaintext. In a few contexts, such as testing, a NullCipher may be appropriate. Security https://find-sec-bugs.github.io/bugs.htm#NULL_CIPHER
OBJECT_DESERIALIZATION Object deserialization of untrusted data can lead to remote code execution, if there is a class in classpath that allows the trigger of malicious operation. Libraries developers tend to fix class that provided potential malicious trigger. There are still classes that are known to trigger Denial of Service. Deserialization is a sensible operation that has a great history of vulnerabilities. The web application might become vulnerable as soon as a new vulnerability is found in the Java Virtual Machine. Security https://find-sec-bugs.github.io/bugs.htm#OBJECT_DESERIALIZATION
OGNL_INJECTION A expression is built with a dynamic value. The source of the value(s) should be verified to avoid that unfiltered values fall into this risky code evaluation. Security https://find-sec-bugs.github.io/bugs.htm#OGNL_INJECTION
PADDING_ORACLE This specific mode of CBC with PKCS5Padding is susceptible to padding oracle attacks. An adversary could potentially decrypt the message if the system exposed the difference between plaintext with invalid padding or valid padding. The distinction between valid and invalid padding is usually revealed through distinct error messages being returned for each condition. Security https://find-sec-bugs.github.io/bugs.htm#PADDING_ORACLE
PATH_TRAVERSAL_IN A file is opened to read its content. The filename comes from an input parameter. If an unfiltered parameter is passed to this file API, files from an arbitrary filesystem location could be read. This rule identifies potential path traversal vulnerabilities. In many cases, the constructed file path cannot be controlled by the user. If that is the case, the reported instance is a false positive. Security https://find-sec-bugs.github.io/bugs.htm#PATH_TRAVERSAL_IN
PATH_TRAVERSAL_OUT A file is opened to write to its contents. The filename comes from an input parameter. If an unfiltered parameter is passed to this file API, files at an arbitrary filesystem location could be modified. This rule identifies potential path traversal vulnerabilities. In many cases, the constructed file path cannot be controlled by the user. If that is the case, the reported instance is a false positive. Security https://find-sec-bugs.github.io/bugs.htm#PATH_TRAVERSAL_OUT
PERMISSIVE_CORS Prior to HTML5, Web browsers enforced the Same Origin Policy which ensures that in order for JavaScript to access the contents of a Web page, both the JavaScript and the Web page must originate from the same domain. Without the Same Origin Policy, a malicious website could serve up JavaScript that loads sensitive information from other websites using a client’s credentials, cull through it, and communicate it back to the attacker. HTML5 makes it possible for JavaScript to access data across domains if a new HTTP header called Access-Control-Allow-Origin is defined. With this header, a Web server defines which other domains are allowed to access its domain using cross-origin requests. However, caution should be taken when defining the header because an overly permissive CORS policy will allow a malicious application to communicate with the victim application in an inappropriate way, leading to spoofing, data theft, relay and other attacks. Security https://find-sec-bugs.github.io/bugs.htm#PERMISSIVE_CORS
PLAY_UNVALIDATED_REDIRECT Unvalidated redirects occur when an application redirects a user to a destination URL specified by a user supplied parameter that is not validated. Such vulnerabilities can be used to facilitate phishing attacks.

Scenario:
1. A user is tricked into visiting the malicious URL: “http://website.com/login?redirect=http://evil.vvebsite.com/fake/login “
2. The user is redirected to a fake login page that looks like a site they trust. (“http://evil.vvebsite.com/fake/login”)
3. The user enters his credentials.
4. The evil site steals the user’s credentials and redirects him to the original website. This attack is plausible because most users don’t double check the URL after the redirection. Also, redirection to an authentication page is very common.

Security https://find-sec-bugs.github.io/bugs.htm#PLAY_UNVALIDATED_REDIRECT
PREDICTABLE_RANDOM The use of a predictable random value can lead to vulnerabilities when used in certain security critical contexts. For example, when the value is used as:
1. a CSRF token: a predictable token can lead to a CSRF attack as an attacker will know the value of the token
2. a password reset token (sent by email): a predictable password token can lead to an account takeover, since an attacker will guess the URL of the change password form
3. any other secret value

A quick fix could be to replace the use of java.util.Random with something stronger, such as java.security.SecureRandom.

Security https://find-sec-bugs.github.io/bugs.htm#PREDICTABLE_RANDOM
PREDICTABLE_RANDOM_SCALA The use of a predictable random value can lead to vulnerabilities when used in certain security critical contexts. For example, when the value is used as:
1. a CSRF token: a predictable token can lead to a CSRF attack as an attacker will know the value of the token
2. a password reset token (sent by email): a predictable password token can lead to an account takeover, since an attacker will guess the URL of the change password form
3. any other secret value

A quick fix could be to replace the use of java.util.Random with something stronger, such as java.security.SecureRandom.

Security https://find-sec-bugs.github.io/bugs.htm#PREDICTABLE_RANDOM_SCALA
REDOS Regular expressions (regexs) are frequently subject to Denial of Service (DOS) attacks (called ReDOS). This is due to the fact that regex engines may take a large amount of time when analyzing certain strings, depending on how the regex is defined. For example, for the regex: ^(a+)+$, the input “aaaaaaaaaaaaaaaaX” will cause the regex engine to analyze 65536 different paths. Therefore, it is possible that a single request may cause a large amount of computation on the server side. The problem with this regex, and others like it, is that there are two different ways the same input character can be accepted by the Regex due to the + (or a *) inside the parenthesis, and the + (or a *) outside the parenthesis. The way this is written, either + could consume the character ‘a’. To fix this, the regex should be rewritten to eliminate the ambiguity. For example, this could simply be rewritten as: ^a+$, which is presumably what the author meant anyway (any number of a’s). Assuming that’s what the original regex meant, this new regex can be evaluated quickly, and is not subject to ReDOS. Security https://find-sec-bugs.github.io/bugs.htm#REDOS
REQUESTDISPATCHER_FILE_DISCLOSURE Constructing a server-side redirect path with user input could allow an attacker to download application binaries (including application classes or jar files) or view arbitrary files within protected directories. An attacker may be able to forge a request parameter to match sensitive file locations. For example, requesting “http://example.com/?jspFile=../applicationContext.xml%3F” would display the application’s applicationContext.xml file. The attacker would be able to locate and download the applicationContext.xml referenced in the other configuration files, and even class files or jar files, obtaining sensitive information and launching other types of attacks. Security https://find-sec-bugs.github.io/bugs.htm#REQUESTDISPATCHER_FILE_DISCLOSURE
RSA_KEY_SIZE The NIST recommends the use of 2048 bits and higher keys for the RSA algorithm.
1. “Digital Signature Verification | RSA: 1024 ≤ len(n) < 2048 | Legacy-use” 2. “Digital Signature Verification | RSA: len(n) ≥ 2048 | Acceptable”
Security https://find-sec-bugs.github.io/bugs.htm#RSA_KEY_SIZE
RSA_NO_PADDING The software uses the RSA algorithm but does not incorporate Optimal Asymmetric Encryption Padding (OAEP), which might weaken the encryption. Security https://find-sec-bugs.github.io/bugs.htm#RSA_NO_PADDING
SCALA_COMMAND_INJECTION The highlighted API is used to execute a system command. If unfiltered input is passed to this API, it can lead to arbitrary command execution. Security https://find-sec-bugs.github.io/bugs.htm#SCALA_COMMAND_INJECTION
SCALA_PATH_TRAVERSAL_IN A file is opened to read its content. The filename comes from an input parameter. If an unfiltered parameter is passed to this file API, files from an arbitrary filesystem location could be read. This rule identifies potential path traversal vulnerabilities. In many cases, the constructed file path cannot be controlled by the user. If that is the case, the reported instance is a false positive. Security https://find-sec-bugs.github.io/bugs.htm#SCALA_PATH_TRAVERSAL_IN
SCALA_PLAY_SSRF Server-Side Request Forgery occur when a web server executes a request to a user supplied destination parameter that is not validated. Such vulnerabilities could allow an attacker to access internal services or to launch attacks from your web server. Security https://find-sec-bugs.github.io/bugs.htm#SCALA_PLAY_SSRF
SCALA_SENSITIVE_DATA_EXPOSURE Applications can unintentionally leak information about their configuration, internal workings, or violate privacy through a variety of application problems. Pages that provide different responses based on the validity of the data can lead to Information Leakage; specifically when data deemed confidential is being revealed as a result of the web application’s design. Examples of sensitive data includes (but is not limited to): API keys, passwords, product versions or environment configurations. Security https://find-sec-bugs.github.io/bugs.htm#SCALA_SENSITIVE_DATA_EXPOSURE
SCALA_SQL_INJECTION_ANORM The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Security https://find-sec-bugs.github.io/bugs.htm#SCALA_SQL_INJECTION_ANORM
SCALA_SQL_INJECTION_SLICK The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Security https://find-sec-bugs.github.io/bugs.htm#SCALA_SQL_INJECTION_SLICK
SCALA_XSS_MVC_API A potential XSS was found. It could be used to execute unwanted JavaScript in a client’s browser. (See references) Security https://find-sec-bugs.github.io/bugs.htm#SCALA_XSS_MVC_API
SCALA_XSS_TWIRL A potential XSS was found. It could be used to execute unwanted JavaScript in a client’s browser. (See references)

Vulnerable Code:
@(value: Html)

@value

Solution:
@(value: String)

@value

The best defense against XSS is context sensitive output encoding like the example above. There are typically 4 contexts to consider: HTML, JavaScript, CSS (styles), and URLs. Please follow the XSS protection rules defined in the OWASP XSS Prevention Cheat Sheet, which explains these defenses in significant detail.

Security https://find-sec-bugs.github.io/bugs.htm#SCALA_XSS_TWIRL
SCRIPT_ENGINE_INJECTION Dymanic code is being evaluate. A careful analysis of the code construction should be made. Malicious code execution could lead to data leakage or operating system compromised. If the evaluation of user code is intended, a proper sandboxing should be applied (see references). Security https://find-sec-bugs.github.io/bugs.htm#SCRIPT_ENGINE_INJECTION
SEAM_LOG_INJECTION Seam Logging API support an expression language to introduce bean property to log messages. The expression language can also be the source to unwanted code execution. In this context, an expression is built with a dynamic value. The source of the value(s) should be verified to avoid that unfiltered values fall into this risky code evaluation. Security https://find-sec-bugs.github.io/bugs.htm#SEAM_LOG_INJECTION
SERVLET_CONTENT_TYPE The HTTP header Content-Type can be controlled by the client. As such, its value should not be used in any security critical decisions. Security https://find-sec-bugs.github.io/bugs.htm#SERVLET_CONTENT_TYPE
SERVLET_HEADER Request headers can easily be altered by the requesting user. In general, no assumption should be made that the request came from a regular browser without modification by an attacker. As such, it is recommended that you not trust this value in any security decisions you make with respect to a request. Security https://find-sec-bugs.github.io/bugs.htm#SERVLET_HEADER
SERVLET_HEADER_REFERER Behavior: Any value can be assigned to this header if the request is coming from a malicious user. The “Referer” will not be present if the request was initiated from another origin that is secure (https).

Recommendations: No access control should be based on the value of this header. No CSRF protection should be based only on this value (because it is optional).

Security https://find-sec-bugs.github.io/bugs.htm#SERVLET_HEADER_REFERER
SERVLET_HEADER_USER_AGENT The header “User-Agent” can easily be spoofed by the client. Adopting different behaviors based on the User-Agent (for crawler UA) is not recommended. Security https://find-sec-bugs.github.io/bugs.htm#SERVLET_HEADER_USER_AGENT
SERVLET_PARAMETER The Servlet can read GET and POST parameters from various methods. The value obtained should be considered unsafe. You may need to validate or sanitize those values before passing them to sensitive APIs such as:

1. SQL query (May lead to SQL injection)
2. File opening (May lead to path traversal)
3. Command execution (Potential Command injection)
4. HTML construction (Potential XSS)
5. etc…

Security https://find-sec-bugs.github.io/bugs.htm#SERVLET_PARAMETER
SERVLET_QUERY_STRING The query string is the concatenation of the GET parameter names and values. Parameters other than those intended can be passed in.

For the URL request /app/servlet.htm?a=1&b=2, the query string extract will be a=1&b=2

Just as is true for individual parameter values retrieved via methods like HttpServletRequest.getParameter(), the value obtained from HttpServletRequest.getQueryString() should be considered unsafe. You may need to validate or sanitize anything pulled from the query string before passing it to sensitive API

Security https://find-sec-bugs.github.io/bugs.htm#SERVLET_QUERY_STRING
SERVLET_SERVER_NAME The hostname header can be controlled by the client. As such, its value should not be used in any security critical decisions. Both ServletRequest.getServerName() and HttpServletRequest.getHeader(“Host”) have the same behavior which is to extract the Host header.

GET /testpage HTTP/1.1
Host: www.example.com
[…]

The web container serving your application may redirect requests to your application by default. This would allow a malicious user to place any value in the Host header. It is recommended that you do not trust this value in any security decisions you make with respect to a request.

Security https://find-sec-bugs.github.io/bugs.htm#SERVLET_SERVER_NAME
SERVLET_SESSION_ID The method HttpServletRequest.getRequestedSessionId() typically returns the value of the cookie JSESSIONID. This value is normally only accessed by the session management logic and not normal developer code. The value passed to the client is generally an alphanumeric value (e.g., JSESSIONID=jp6q31lq2myn). However, the value can be altered by the client. The following HTTP request illustrates the potential modification.

GET /somePage HTTP/1.1
Host: yourwebsite.com
User-Agent: Mozilla/5.0
Cookie: JSESSIONID=Any value of the user’s choice!!??”'”>

As such, the JSESSIONID should only be used to see if its value matches an existing session ID. If it does not, the user should be considered an unauthenticated user. In addition, the session ID value should never be logged. If it is, then the log file could contain valid active session IDs, allowing an insider to hijack any sessions whose IDs have been logged and are still active.

Security https://find-sec-bugs.github.io/bugs.htm#SERVLET_SESSION_ID
SMTP_HEADER_INJECTION Simple Mail Transfer Protocol (SMTP) is a the text based protocol used for email delivery. Like with HTTP, headers are separate by new line separator. If user input is place in a header line, the application should remove or replace new line characters (CR / LF). You should use a safe wrapper such as Apache Common Email and Simple Java Mail which filter special characters that can lead to header injection. Security https://find-sec-bugs.github.io/bugs.htm#SMTP_HEADER_INJECTION
SPEL_INJECTION A Spring expression is built with a dynamic value. The source of the value(s) should be verified to avoid that unfiltered values fall into this risky code evaluation. Security https://find-sec-bugs.github.io/bugs.htm#SPEL_INJECTION
SPRING_CSRF_PROTECTION_DISABLED Disabling Spring Security’s CSRF protection is unsafe for standard web applications. A valid use case for disabling this protection would be a service exposing state-changing operations that is guaranteed to be used only by non-browser clients. Security https://find-sec-bugs.github.io/bugs.htm#SPRING_CSRF_PROTECTION_DISABLED
SPRING_CSRF_UNRESTRICTED_REQUEST_MAPPING Methods annotated with RequestMapping are by default mapped to all the HTTP request methods. However, Spring Security’s CSRF protection is not enabled by default for the HTTP request methods GET, HEAD, TRACE, and OPTIONS (as this could cause the tokens to be leaked). Therefore, state-changing methods annotated with RequestMapping and not narrowing the mapping to the HTTP request methods POST, PUT, DELETE, or PATCH are vulnerable to CSRF attacks. Security https://find-sec-bugs.github.io/bugs.htm#SPRING_CSRF_UNRESTRICTED_REQUEST_MAPPING
SPRING_ENDPOINT This class is a Spring Controller. All methods annotated with RequestMapping (as well as its shortcut annotations GetMapping, PostMapping, PutMapping, DeleteMapping, and PatchMapping) are reachable remotely. This class should be analyzed to make sure that remotely exposed methods are safe to expose to potential attackers. Security https://find-sec-bugs.github.io/bugs.htm#SPRING_ENDPOINT
SPRING_FILE_DISCLOSURE Constructing a server-side redirect path with user input could allow an attacker to download application binaries (including application classes or jar files) or view arbitrary files within protected directories. An attacker may be able to forge a request parameter to match sensitive file locations. For example, requesting “http://example.com/?returnURL=WEB-INF/applicationContext.xml” would display the application’s applicationContext.xml file. The attacker would be able to locate and download the applicationContext.xml referenced in the other configuration files, and even class files or jar files, obtaining sensitive information and launching other types of attacks. Security https://find-sec-bugs.github.io/bugs.htm#SPRING_FILE_DISCLOSURE
SPRING_UNVALIDATED_REDIRECT Unvalidated redirects occur when an application redirects a user to a destination URL specified by a user supplied parameter that is not validated. Such vulnerabilities can be used to facilitate phishing attacks.

Scenario:
1. A user is tricked into visiting the malicious URL: “http://website.com/login?redirect=http://evil.vvebsite.com/fake/login”
2. The user is redirected to a fake login page that looks like a site they trust. (“http://evil.vvebsite.com/fake/login”)
3. The user enters his credentials.
4. The evil site steals the user’s credentials and redirects him to the original website. This attack is plausible because most users don’t double check the URL after the redirection. Also, redirection to an authentication page is very common.

Security https://find-sec-bugs.github.io/bugs.htm#SPRING_UNVALIDATED_REDIRECT
SQL_INJECTION The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Alternatively to prepare statements, each parameter can be escaped manually. Security https://find-sec-bugs.github.io/bugs.htm#SQL_INJECTION
SQL_INJECTION_ANDROID The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Security https://find-sec-bugs.github.io/bugs.htm#SQL_INJECTION_ANDROID
SQL_INJECTION_HIBERNATE The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Alternatively to prepare statements, Hibernate Criteria can be used. Security https://find-sec-bugs.github.io/bugs.htm#SQL_INJECTION_HIBERNATE
SQL_INJECTION_JDBC The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Security https://find-sec-bugs.github.io/bugs.htm#SQL_INJECTION_JDBC
SQL_INJECTION_JDO The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Security https://find-sec-bugs.github.io/bugs.htm#SQL_INJECTION_JDO
SQL_INJECTION_JPA The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Security https://find-sec-bugs.github.io/bugs.htm#SQL_INJECTION_JPA
SQL_INJECTION_SPRING_JDBC The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Security https://find-sec-bugs.github.io/bugs.htm#SQL_INJECTION_SPRING_JDBC
SQL_INJECTION_TURBINE The input values included in SQL queries need to be passed in safely. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection. Turbine API provide a DSL to build query with Java code. Security https://find-sec-bugs.github.io/bugs.htm#SQL_INJECTION_TURBINE
SSL_CONTEXT   Security https://find-sec-bugs.github.io/bugs.htm#SSL_CONTEXT
STATIC_IV Initialization vector must be regenerated for each message to be encrypted. Security https://find-sec-bugs.github.io/bugs.htm#STATIC_IV
STRUTS_FILE_DISCLOSURE Constructing a server-side redirect path with user input could allow an attacker to download application binaries (including application classes or jar files) or view arbitrary files within protected directories. An attacker may be able to forge a request parameter to match sensitive file locations. For example, requesting “http://example.com/?returnURL=WEB-INF/applicationContext.xml” would display the application’s applicationContext.xml file. The attacker would be able to locate and download the applicationContext.xml referenced in the other configuration files, and even class files or jar files, obtaining sensitive information and launching other types of attacks. Security https://find-sec-bugs.github.io/bugs.htm#STRUTS_FILE_DISCLOSURE
STRUTS_FORM_VALIDATION Form inputs should have minimal input validation. Preventive validation helps provide defense in depth against a variety of risks. Validation can be introduce by implementing a validate method. Security https://find-sec-bugs.github.io/bugs.htm#STRUTS_FORM_VALIDATION
STRUTS1_ENDPOINT This class is a Struts 1 Action. Security https://find-sec-bugs.github.io/bugs.htm#STRUTS1_ENDPOINT
STRUTS2_ENDPOINT In Struts 2, the endpoints are Plain Old Java Objects (POJOs) which means no Interface/Class needs to be implemented/extended.

Security https://find-sec-bugs.github.io/bugs.htm#STRUTS2_ENDPOINT
TAPESTRY_ENDPOINT A Tapestry endpoint was discovered at application startup. Tapestry apps are structured with a backing Java class and a corresponding Tapestry Markup Language page (a .tml file) for each page. When a request is received, the GET/POST parameters are mapped to specific inputs in the backing Java class. The mapping is either done with fieldName:

[…]
protected String input;
[…]

or the definition of an explicit annotation:

[…]
@org.apache.tapestry5.annotations.Parameter
protected String parameter1;

@org.apache.tapestry5.annotations.Component(id = “password”)
private PasswordField passwordField;
[…]

The page is mapped to the view [/resources/package/PageName].tml.

Each Tapestry page in this application should be researched to make sure all inputs that are automatically mapped in this way are properly validated before they are used.

Security https://find-sec-bugs.github.io/bugs.htm#TAPESTRY_ENDPOINT
TDES_USAGE Triple DES (also known as 3DES or DESede) is considered strong ciphers for modern applications. Currently, NIST recommends the usage of AES block ciphers instead of 3DES. Security https://find-sec-bugs.github.io/bugs.htm#TDES_USAGE
TEMPLATE_INJECTION_FREEMARKER Freemarker template engine is powerful. It is possible to add logic including condition statements, loops and external calls. It is not design to be sandbox to templating operations. A malicious user in control of a template can run malicious code on the server-side. Freemarker templates should be seen as scripts. Security https://find-sec-bugs.github.io/bugs.htm#TEMPLATE_INJECTION_FREEMARKER
TEMPLATE_INJECTION_VELOCITY Velocity template engine is powerful. It is possible to add logic including condition statements, loops and external calls. It is not design to be sandbox to templating operations. A malicious user in control of a template can run malicious code on the server-side. Velocity templates should be seen as scripts. Security https://find-sec-bugs.github.io/bugs.htm#TEMPLATE_INJECTION_VELOCITY
TRUST_BOUNDARY_VIOLATION “A trust boundary can be thought of as line drawn through a program. On one side of the line, data is untrusted. On the other side of the line, data is assumed to be trustworthy. The purpose of validation logic is to allow data to safely cross the trust boundary – to move from untrusted to trusted. A trust boundary violation occurs when a program blurs the line between what is trusted and what is untrusted. By combining trusted and untrusted data in the same data structure, it becomes easier for programmers to mistakenly trust unvalidated data.” Security https://find-sec-bugs.github.io/bugs.htm#TRUST_BOUNDARY_VIOLATION
UNENCRYPTED_SERVER_SOCKET The communication channel used is not encrypted. The traffic could be read by an attacker intercepting the network traffic. Security https://find-sec-bugs.github.io/bugs.htm#UNENCRYPTED_SERVER_SOCKET
UNENCRYPTED_SOCKET The communication channel used is not encrypted. The traffic could be read by an attacker intercepting the network traffic. Security https://find-sec-bugs.github.io/bugs.htm#UNENCRYPTED_SOCKET
UNSAFE_HASH_EQUALS An attacker might be able to detect the value of the secret hash due to the exposure of comparison timing. When the functions Arrays.equals() or String.equals() are called, they will exited earlier if less bytes are matched. Security https://find-sec-bugs.github.io/bugs.htm#UNSAFE_HASH_EQUALS
UNVALIDATED_REDIRECT Unvalidated redirects occur when an application redirects a user to a destination URL specified by a user supplied parameter that is not validated. Such vulnerabilities can be used to facilitate phishing attacks.

Scenario:.
1. A user is tricked into visiting the malicious URL: “http://website.com/login?redirect=http://evil.vvebsite.com/fake/login”
2. The user is redirected to a fake login page that looks like a site they trust. (“http://evil.vvebsite.com/fake/login”)
3. The user enters his credentials.
4. The evil site steals the user’s credentials and redirects him to the original website. This attack is plausible because most users don’t double check the URL after the redirection. Also, redirection to an authentication page is very common.

Security https://find-sec-bugs.github.io/bugs.htm#UNVALIDATED_REDIRECT
URL_REWRITING The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. URL rewriting has significant security risks. Since session ID appears in the URL, it may be easily seen by third parties. Session ID in the URL can be disclosed in many ways, for example:
1. Log files,
2. The browser history,
3. By copy-and-pasting it into an e-mail or posting,
4. The HTTP Referrer.
Security https://find-sec-bugs.github.io/bugs.htm#URL_REWRITING
URLCONNECTION_SSRF_FD Server-Side Request Forgery occur when a web server executes a request to a user supplied destination parameter that is not validated. Such vulnerabilities could allow an attacker to access internal services or to launch attacks from your web server. URLConnection can be used with file:// protocol or other protocols to access local filesystem and potentially other services. Security https://find-sec-bugs.github.io/bugs.htm#URLCONNECTION_SSRF_FD
WEAK_FILENAMEUTILS Some FilenameUtils’ methods don’t filter NULL bytes (0x00). If a null byte is injected into a filename, if this filename is passed to the underlying OS, the file retrieved will be the name of the file that is specified prior to the NULL byte, since at the OS level, all strings are terminated by a null byte even though Java itself doesn’t care about null bytes or treat them special. This OS behavior can be used to bypass filename validation that looks at the end of the filename (e.g., endswith “.log”) to make sure its a safe file to access. Security https://find-sec-bugs.github.io/bugs.htm#WEAK_FILENAMEUTILS
WEAK_HOSTNAME_VERIFIER A HostnameVerifier that accept any host are often use because of certificate reuse on many hosts. As a consequence, this is vulnerable to Man-in-the-middle attacks since the client will trust any certificate. A TrustManager allowing specific certificates (based on a truststore for example) should be built. Wildcard certificates should be created for reused on multiples subdomains. Security https://find-sec-bugs.github.io/bugs.htm#WEAK_HOSTNAME_VERIFIER
WEAK_MESSAGE_DIGEST_MD5 The algorithms MD2, MD4 and MD5 are not a recommended MessageDigest. PBKDF2 should be used to hash password for example.

“The security of the MD5 hash function is severely compromised. A collision attack exists that can find collisions within seconds on a computer with a 2.6 GHz Pentium 4 processor (complexity of 224.1).[1] Further, there is also a chosen-prefix collision attack that can produce a collision for two inputs with specified prefixes within hours, using off-the-shelf computing hardware (complexity 239).[2]” – Wikipedia: MD5 – Security

“SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, and SHA-512/256: The use of these hash functions is acceptable for all hash function applications.” – NIST: Transitions: Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Lengths p.15

“The main idea of a PBKDF is to slow dictionary or brute force attacks on the passwords by increasing the time needed to test each password. An attacker with a list of likely passwords can evaluate the PBKDF using the known iteration counter and the salt. Since an attacker has to spend a significant amount of computing time for each try, it becomes harder to apply the dictionary or brute force attacks.” – NIST: Recommendation for Password-Based Key Derivation p.12

Security https://find-sec-bugs.github.io/bugs.htm#WEAK_MESSAGE_DIGEST_MD5
WEAK_MESSAGE_DIGEST_SHA1 The algorithms SHA-1 is not a recommended algorithm for hash password, for signature verification and other uses. PBKDF2 should be used to hash password for example.

“SHA-1 for digital signature generation: SHA-1 may only be used for digital signature generation where specifically allowed by NIST protocol-specific guidance. For all other applications, SHA-1 shall not be used for digital signature generation. SHA-1 for digital signature verification: For digital signature verification, SHA-1 is allowed for legacy-use. […] SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, and SHA-512/256: The use of these hash functions is acceptable for all hash function applications.” – NIST: Transitions: Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Lengths p.15

“The main idea of a PBKDF is to slow dictionary or brute force attacks on the passwords by increasing the time needed to test each password. An attacker with a list of likely passwords can evaluate the PBKDF using the known iteration counter and the salt. Since an attacker has to spend a significant amount of computing time for each try, it becomes harder to apply the dictionary or brute force attacks.” – NIST: Recommendation for Password-Based Key Derivation p.12

Security https://find-sec-bugs.github.io/bugs.htm#WEAK_MESSAGE_DIGEST_SHA1
WEAK_TRUST_MANAGER Empty TrustManager implementations are often used to connect easily to a host that is not signed by a root certificate authority. As a consequence, this is vulnerable to Man-in-the-middle attacks since the client will trust any certificate. A TrustManager allowing specific certificates (based on a truststore for example) should be built. Security https://find-sec-bugs.github.io/bugs.htm#WEAK_TRUST_MANAGER
WICKET_ENDPOINT XMLDecoder should not be used to parse untrusted data. Deserializing user input can lead to arbitrary code execution. This is possible because XMLDecoder supports arbitrary method invocation. This capability is intended to call setter methods, but in practice, any method can be called.

Malicious XML example:

/tmp/Hacked.txt

Hello World!

The XML code above will cause the creation of a file with the content “Hello World!”.

Vulnerable Code:
XMLDecoder d = new XMLDecoder(in);
try {
Object result = d.readObject();
}
[…]

Solution: The solution is to avoid using XMLDecoder to parse content from an untrusted source.

Security https://find-sec-bugs.github.io/bugs.htm#WICKET_ENDPOINT
XML_DECODER XMLDecoder should not be used to parse untrusted data. Deserializing user input can lead to arbitrary code execution. This is possible because XMLDecoder supports arbitrary method invocation. This capability is intended to call setter methods, but in practice, any method can be called. Security https://find-sec-bugs.github.io/bugs.htm#XML_DECODER
XPATH_INJECTION XPath injection risks are similar to SQL injection. If the XPath query contains untrusted user input, the complete datasource could be exposed. This could allow an attacker to access unauthorized data or maliciously modify the target XML. Security https://find-sec-bugs.github.io/bugs.htm#XPATH_INJECTION
XSS_JSP_PRINT A potential XSS was found. It could be used to execute unwanted JavaScript in a client’s browser. (See references) Security https://find-sec-bugs.github.io/bugs.htm#XSS_JSP_PRINT
XSS_REQUEST_WRAPPER An implementation of HttpServletRequestWrapper called XSSRequestWrapper was published through various blog sites.

The filtering is weak for a few reasons:
1. It covers only parameters not headers and side-channel inputs
2. The replace chain can be bypassed easily (see example below)
3. It’s a black list of very specific bad patterns (rather than a white list of good/valid input)

Security https://find-sec-bugs.github.io/bugs.htm#XSS_REQUEST_WRAPPER
XSS_SERVLET A potential XSS was found. It could be used to execute unwanted JavaScript in a client’s browser. (See references) Security https://find-sec-bugs.github.io/bugs.htm#XSS_SERVLET
XXE_DOCUMENT Attack: XML External Entity (XXE) attacks can occur when an XML parser supports XML entities while processing XML received from an untrusted source. Security https://find-sec-bugs.github.io/bugs.htm#XXE_DOCUMENT
XXE_DTD_TRANSFORM_FACTORY Attack: XML External Entity (XXE) attacks can occur when an XML parser supports XML entities while processing XML received from an untrusted source. Security https://find-sec-bugs.github.io/bugs.htm#XXE_DTD_TRANSFORM_FACTORY
XXE_SAXPARSER Attack: XML External Entity (XXE) attacks can occur when an XML parser supports XML entities while processing XML received from an untrusted source. Security https://find-sec-bugs.github.io/bugs.htm#XXE_SAXPARSER
XXE_XMLREADER Attack: XML External Entity (XXE) attacks can occur when an XML parser supports XML entities while processing XML received from an untrusted source. Security https://find-sec-bugs.github.io/bugs.htm#XXE_XMLREADER
XXE_XMLSTREAMREADER Attack: XML External Entity (XXE) attacks can occur when an XML parser supports XML entities while processing XML received from an untrusted source. Security https://find-sec-bugs.github.io/bugs.htm#XXE_XMLSTREAMREADER
XXE_XSLT_TRANSFORM_FACTORY Attack: XSLT External Entity (XXE) attacks can occur when an XSLT parser supports external entities while processing XSLT received from an untrusted source. Security https://find-sec-bugs.github.io/bugs.htm#XXE_XSLT_TRANSFORM_FACTORY
DP_DO_INSIDE_DO_PRIVILEGED This code invokes a method that requires a security permission check. If this code will be granted security permissions, but might be invoked by code that does not have security permissions, then the invocation needs to occur inside a doPrivileged block. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dp-method-invoked-that-should-be-only-be-invoked-inside-a-doprivileged-block-dp-do-inside-do-privileged
DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED This code creates a classloader, which needs permission if a security manage is installed. If this code might be invoked by code that does not have security permissions, then the classloader creation needs to occur inside a doPrivileged block. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dp-classloaders-should-only-be-created-inside-doprivileged-block-dp-create-classloader-inside-do-privileged
XSS_REQUEST_PARAMETER_TO_SEND_ERROR This code directly writes an HTTP parameter to a Server error page (using HttpServletResponse.sendError). Echoing this untrusted input allows for a reflected cross site scripting vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting for more information. SpotBugs looks only for the most blatant, obvious cases of cross site scripting. If SpotBugs found any, you almost certainly have more cross site scripting vulnerabilities that SpotBugs doesn’t report. If you are concerned about cross site scripting, you should seriously consider using a commercial static analysis or pen-testing tool. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#xss-servlet-reflected-cross-site-scripting-vulnerability-in-error-page-xss-request-parameter-to-send-error
XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER This code directly writes an HTTP parameter to Servlet output, which allows for a reflected cross site scripting vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting for more information. SpotBugs looks only for the most blatant, obvious cases of cross site scripting. If SpotBugs found any, you almost certainly have more cross site scripting vulnerabilities that SpotBugs doesn’t report. If you are concerned about cross site scripting, you should seriously consider using a commercial static analysis or pen-testing tool. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#xss-servlet-reflected-cross-site-scripting-vulnerability-xss-request-parameter-to-servlet-writer
XSS_REQUEST_PARAMETER_TO_JSP_WRITER This code directly writes an HTTP parameter to JSP output, which allows for a cross site scripting vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting for more information. SpotBugs looks only for the most blatant, obvious cases of cross site scripting. If SpotBugs found any, you almost certainly have more cross site scripting vulnerabilities that SpotBugs doesn’t report. If you are concerned about cross site scripting, you should seriously consider using a commercial static analysis or pen-testing tool. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#xss-jsp-reflected-cross-site-scripting-vulnerability-xss-request-parameter-to-jsp-writer
HRS_REQUEST_PARAMETER_TO_HTTP_HEADER This code directly writes an HTTP parameter to an HTTP header, which allows for a HTTP response splitting vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting for more information. SpotBugs looks only for the most blatant, obvious cases of HTTP response splitting. If SpotBugs found any, you almost certainly have more vulnerabilities that SpotBugs doesn’t report. If you are concerned about HTTP response splitting, you should seriously consider using a commercial static analysis or pen-testing tool. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#hrs-http-response-splitting-vulnerability-hrs-request-parameter-to-http-header
HRS_REQUEST_PARAMETER_TO_COOKIE This code constructs an HTTP Cookie using an untrusted HTTP parameter. If this cookie is added to an HTTP response, it will allow a HTTP response splitting vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting for more information. SpotBugs looks only for the most blatant, obvious cases of HTTP response splitting. If SpotBugs found any, you almost certainly have more vulnerabilities that SpotBugs doesn’t report. If you are concerned about HTTP response splitting, you should seriously consider using a commercial static analysis or pen-testing tool. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#hrs-http-cookie-formed-from-untrusted-input-hrs-request-parameter-to-cookie
PT_ABSOLUTE_PATH_TRAVERSAL The software uses an HTTP request parameter to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as “/abs/path” that can resolve to a location that is outside of that directory. See http://cwe.mitre.org/data/definitions/36.html for more information. SpotBugs looks only for the most blatant, obvious cases of absolute path traversal. If SpotBugs found any, you almost certainly have more vulnerabilities that SpotBugs doesn’t report. If you are concerned about absolute path traversal, you should seriously consider using a commercial static analysis or pen-testing tool. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#pt-absolute-path-traversal-in-servlet-pt-absolute-path-traversal
PT_RELATIVE_PATH_TRAVERSAL The software uses an HTTP request parameter to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as “..” that can resolve to a location that is outside of that directory. See http://cwe.mitre.org/data/definitions/23.html for more information. SpotBugs looks only for the most blatant, obvious cases of relative path traversal. If SpotBugs found any, you almost certainly have more vulnerabilities that SpotBugs doesn’t report. If you are concerned about relative path traversal, you should seriously consider using a commercial static analysis or pen-testing tool. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#pt-relative-path-traversal-in-servlet-pt-relative-path-traversal
DMI_CONSTANT_DB_PASSWORD This code creates a database connect using a hardcoded, constant password. Anyone with access to either the source code or the compiled code can easily learn the password. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-hardcoded-constant-database-password-dmi-constant-db-password
DMI_EMPTY_DB_PASSWORD This code creates a database connect using a blank or empty password. This indicates that the database is not protected by a password. Security https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html#dm-empty-database-password-dmi-empty-db-password

Python

The section below covers the Pylint code issues.


Pylint Code Issues

Pylint is an open source static code analyzer which detects code issues and bugs in Python programs. Visit their website for more detailed information on Pylint and the ruleset found below.


Critical level issues

Rule Description KPI URL
E1004-missingArgumentToSuperMethod Missing argument to super() Accuracy http://pylint-messages.wikidot.com/all-codes
F0001-analysisError Used when an error occured preventing the analysis of a module (unable to find it for instance). Accuracy http://pylint-messages.wikidot.com/all-codes
F0002-errorBuildingASTNGRepresentation Used when an unexpected error occured while building the ASTNG representation. Accuracy http://pylint-messages.wikidot.com/all-codes
F0003-ignoredBuiltinModule Used to indicate that the user asked to analyze a builtin module which has been skipped. Accuracy http://pylint-messages.wikidot.com/all-codes
F0004-unexpectedInferredValue Used to indicate that some value of an unexpected type has been infered. Accuracy http://pylint-messages.wikidot.com/all-codes
F0010-codeParsingError Used to indicate that a parsing error has occurred. Accuracy http://pylint-messages.wikidot.com/all-codes
F0220-interfacesNotResolved Used when PyLint has failed to find interfaces implemented by a class Accuracy http://pylint-messages.wikidot.com/all-codes
F0321-formatDetectionError Used when an unexpected error occured in bad format detection. Accuracy http://pylint-messages.wikidot.com/all-codes
F0401-unableToImport Used when PyLint has been unable to import a module. Maintainability http://pylint-messages.wikidot.com/all-codes
W0122-useOfExec Use of the exec statement is discouraged Security http://pylint-messages.wikidot.com/all-codes

High level issues

Rule Description KPI URL
E0102-alreadyDefinedLine Prohibits the redefinition of functions, classes and methods. Understandability http://pylint-messages.wikidot.com/all-codes
E0105-yieldOutsideFunction A yield statement is found outside a function or method. Understandability http://pylint-messages.wikidot.com/all-codes
E0106-returnWithArgInsideGenerator A return statement with an argument is found in a generator function or method (e.g. with some yield statements). Understandability http://pylint-messages.wikidot.com/all-codes
E0202-hiddenMethod A class defines a method which is hidden by an instance attribute with the same name. Understandability http://pylint-messages.wikidot.com/all-codes
E0203-accessToMethodBeforeDefinition An instance member is accessed before it’s actually assigned. Understandability http://pylint-messages.wikidot.com/all-codes
E0211-noArgumentInMethod A method which should have the bound instance as first argument has no argument defined. Accuracy http://pylint-messages.wikidot.com/all-codes
E0213-selfArgumentMissing The first argument of a (instance) method has a name other than self. Understandability http://pylint-messages.wikidot.com/all-codes
E0221-resolvedInterfaceIsNotClass A class claims to implement an interface which is not a class. Understandability http://pylint-messages.wikidot.com/all-codes
E0222-missingMethodFromInterface A method declared in an interface is missing from a class implementing this interface. Understandability http://pylint-messages.wikidot.com/all-codes
E0501-noEncodingSpecified Non-ASCII characters found but no encoding specified Accuracy http://pylint-messages.wikidot.com/all-codes
E0502-wrongEncoding Wrong encoding specified Accuracy http://pylint-messages.wikidot.com/all-codes
E0503-unknownEncoding Unknown encoding specified Accuracy http://pylint-messages.wikidot.com/all-codes
E0601-localVarUserBeforeAssignment Avoid using a local variable from being accessed before it’s actually assigned. Accuracy http://pylint-messages.wikidot.com/all-codes
E0602-undefinedVariable An undefined variable is accessed. Accuracy http://pylint-messages.wikidot.com/all-codes
E0701-incorrectExceptClausesOrder Except clauses are not in the correct order (from the more specific to the more generic). If you don’t fix the order, some exceptions may not be caught by the most specific handler. Accuracy http://pylint-messages.wikidot.com/all-codes
E0711-notImplementedRaised Avoid raising NotImplemented, NotImplementedError should be raised instead. Understandability http://pylint-messages.wikidot.com/all-codes
E1102-ObjectNotCallable Avoid invocation of an object that has been inferred to a non-callable object. Robustness http://pylint-messages.wikidot.com/all-codes
E1111-incorrectAssignmentOfFunction An assigment is done on a function call but the inferred function doesn’t return anything. Understandability http://pylint-messages.wikidot.com/all-codes
E1301-avoidPartialConversionInString Avoid partial conversion specifiers from being used in string format operations. Understandability http://pylint-messages.wikidot.com/all-codes
E1304-missingKeyInFormatStringDictionary Avoid mapping for format string operations of having undefined conversion specifiers. Understandability http://pylint-messages.wikidot.com/all-codes
E1306-insufficientArgForFormatString A format string that uses unnamed conversion specifiers is given too few arguments Understandability http://pylint-messages.wikidot.com/all-codes
E9900-unsupportedFormatCharacter A character with an unsupported format has been used. Understandability http://pylint-messages.wikidot.com/all-codes
W0702-noExceptionTypeSpecified An except clause doesn’t specify exceptions type to catch. Accuracy http://pylint-messages.wikidot.com/all-codes
E0118-nameUsedBeforeDeclaration Emitted when a name is used prior a global declaration, which results in an error since Python 3.6. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0237-incorrectAssignmentForSlotClass Used when assigning to an attribute not defined in the class slots. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0401-unableToImportModule Used when pylint has been unable to import a module. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0632-tupleUnpackingUnbalancedTuple Used when there is an unbalanced tuple unpacking in assignment Robustness https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0633-attemptToUnpackNonSequence Used when something which is not a sequence is used in an unpack assignment Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1129-contextManagerError Used when an instance in a with statement doesn’t implement the context manager protocol(__enter__/__exit__). Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1130-invalidUnaryOperand Emitted when a unary operand is used on an object which does not support this type of operation Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1131-unsupportedBinaryOperation Emitted when a binary arithmetic operation between two operands is not supported. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1133-noniterableValueInIteratingContext Used when a non-iterable value is used in place where iterable is expected Robustness https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1134-nonMappingValueInIteratingContext Used when a non-mapping value is used in place where mapping is expected Robustness https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1135-membershipProtocolException Emitted when an instance in membership test expression doesn’t implement membership protocol (__contains__/__iter__/__getitem__) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1136-valueUnsubscriptable Emitted when a subscripted value doesn’t support subscription(i.e. doesn’t define __getitem__ method) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1137-itemAssignmentNotSupported Emitted when an object does not support item assignment (i.e. doesn’t define __setitem__ method) Accuracy https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1138-itemDeletionNotSupported Emitted when an object does not support item deletion (i.e. doesn’t define __delitem__ method) Accuracy https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1139-invalidMetaclassUsed Emitted whenever we can detect that a class is using, as a metaclass, something which might be invalid for using as a metaclass. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1601-printStatementUsed Used when a print statement is used (print is a function in Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1602-parameterUnpackingSpecified Used when parameter unpacking is specified for a function(Python 3 doesn’t allow it) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1603-implicitUnpackingNotSupported Python3 will not allow implicit unpacking of exceptions in except clauses. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1605-invalidOperatorUsed Used when the deprecated ‘“’ (backtick) operator is used instead of the str() function Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1606-usedLongAsSuffix Used when ‘l’ or ‘L’ is used to mark a long integer. This will not work in Python 3, since int and long types have merged. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1607-invalidNegationOperator Used when the deprecated ‘<>’ operator is used instead of ‘!=’. This is removed in Python 3. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1608-oldOctalSyntaxUsed Used when encountering the old octal syntax, removed in Python 3. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1610-notAsciiByteLiteralsNotSupported Used when non-ascii bytes literals are found in a program. They are no longer supported in Python 3. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1701-asyncContextManagerProtocolNotImplemented Used when an async context manager is used with an object that does not implement the async context management protocol. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
F0202-unableToCheckMethodSignature Used when Pylint has been unable to check methods signature compatibility for an unexpected reason Robustness https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0111-reversedArgumentNotSequenced The first reversed() argument is not a sequence Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0113-incorrectStarredAssignment Don’t unpack multiple values using a sole starred assignment target. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0114-useStarredExprInAssignmentTarget Do not use a starred variable expression in other places than an assignment. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0115-nameIsNonlocalAndNonGlobal Do not declare a variable as both nonlocal and global, only one can be picked. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0116-continueInFinallyNotSupported Using continue in a finally statement is a SyntaxError. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0239-inheritingSomethingWhichIsNotAClass Do not inherit from something which is not a class. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0240-inconsistentMethodResolutionOrderForClass Avoid defining a class for which a method resolution order could not be determined. Accuracy https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0301-_iterReturnsNonIterator _iter__ should always return an iterator, otherwise an error will occur. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0302-enforceCorrectSignatureForSpecialMethod Enforce correct signature of special methods Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0704-raiseNotInsideExceptClause Do not place raise in other places than an except clause. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1126-sequenceIndexNotAnInt Always index a sequence with an integer, a slice or an instance providing an __index__ method. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html

Medium level issues

Rule Description KPI URL
E0011-unrecognizedFileOption Used when an unknown PyLint option is encountered. Understandability http://pylint-messages.wikidot.com/all-codes
E0012-badOption Used when a bad value for a PyLint option is encountered. The option exists but its value is not valid. Understandability http://pylint-messages.wikidot.com/all-codes
E0100-avoidInitMethodInGenerator Avoid special class method __init__() from being turned into a generator by a yield statement in its body. Accuracy http://pylint-messages.wikidot.com/all-codes
E0101-avoidReturnInInitMethod Avoid the special class method __init__() from having an explicit return value. Accuracy http://pylint-messages.wikidot.com/all-codes
E0103-avoidBreakOrContinueOutsideLoop Avoid using the break or continue keywords outside of a loop. Understandability http://pylint-messages.wikidot.com/all-codes
E0104-returnOutsideFunction A return statement is found outside a function or method. Understandability http://pylint-messages.wikidot.com/all-codes
E0107-nonexistentOpt Avoid using operators that do not exist in Python. Understandability http://pylint-messages.wikidot.com/all-codes
E0108-duplicateArgumentNameInFunctionDef An argument name is used more than once in a function or method definition. Understandability http://pylint-messages.wikidot.com/all-codes
E0110-instantiationError Avoid instantiating classes which have unimplemented abstract methods. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0235-invalidExitmethodArguments the __exit__ method of a context manager class does not have exactly three arguments. Accuracy http://pylint-messages.wikidot.com/all-codes
E0603-undefinedVariableIn__all__ Avoid using undefined variables in the __all__ variable Accuracy http://pylint-messages.wikidot.com/all-codes
E0604-invalidObjectIn__all__ Use of string literals in the module variable __all__ is encouraged Accuracy http://pylint-messages.wikidot.com/all-codes
E0611-noNameInModule A name cannot be found in a module. Accuracy http://pylint-messages.wikidot.com/all-codes
E0702-typeErrorRaised Something which is neither a class, an instance or a string is raised (i.e. a TypeError will be raised) Robustness http://pylint-messages.wikidot.com/all-codes
E0710-newStyleClassError A new style class which doesn’t inherit from BaseException raised. Robustness http://pylint-messages.wikidot.com/all-codes
E0712-invalidExceptionCaught Catching an exception which doesn’t inherit from BaseException Robustness http://pylint-messages.wikidot.com/all-codes
E1001-useOf_slots_OnOldStyleClass Use of __slots__ on an old style class Maintainability http://pylint-messages.wikidot.com/all-codes
E1002-useOfSuperOnOldStyleClass Use of super on an old style class Maintainability http://pylint-messages.wikidot.com/all-codes
E1003-badFirstArgumentToSuperMethod An argument other than the current class is given as first argument of the super() Accuracy http://pylint-messages.wikidot.com/all-codes
E1101-accessOfNonExistentMember Access of nonexistent member Robustness http://pylint-messages.wikidot.com/all-codes
E1103-accessingNonexistentMember Accessing nonexistent member Robustness http://pylint-messages.wikidot.com/all-codes
E1120-noValuePassedForParameterInFunctionCall Avoid function calls that have less arguments than those declared. Understandability http://pylint-messages.wikidot.com/all-codes
E1121-tooManyPositionalArgumentsForFunctionCall Avoid function calls that have more arguments than those declared. Understandability http://pylint-messages.wikidot.com/all-codes
E1122-duplicateArgumentNameInFunction Duplicate keyword argument in function call Accuracy http://pylint-messages.wikidot.com/all-codes
E1123-unexpectedKeywordArgumentInFunctionCall Passing unexpected keyword argument in function call Understandability http://pylint-messages.wikidot.com/all-codes
E1124-incorrectParameterPassed Avoid function calls from being passed an argument as both positional and keyword. Robustness http://pylint-messages.wikidot.com/all-codes
E1125-missingMandatoryKeywordArg Always pass required positional keyword arguments into function calls. Robustness http://pylint-messages.wikidot.com/all-codes
E1200-unsupportedLoggingFmt Avoid unsupported format characters from being used in logging operations. Understandability http://pylint-messages.wikidot.com/all-codes
E1201-avoidPartialFormatString Avoid partial format string from being used on logging operations. Understandability http://pylint-messages.wikidot.com/all-codes
E1205-tooManyArgumentsForLoggingFormatString Avoid logging operations that have more arguments than those declared in the format string. Understandability http://pylint-messages.wikidot.com/all-codes
E1206-notEnoughArgumentsForLoggingFormatString Avoid logging operations that have less arguments than those declared in the format string. Understandability http://pylint-messages.wikidot.com/all-codes
E1300-unsupportedConversionSpecifier Avoid unsupported conversion specifiers from being used in string format operations. Robustness http://pylint-messages.wikidot.com/all-codes
E1302-incorrectConversionSpecifierInStringFmt Avoid mixed named and unnamed conversion specifiers in string format operations. Robustness http://pylint-messages.wikidot.com/all-codes
E1303-expectedMappingForFormatString Use of mapping for format string operations that use named conversion specifiers is encouraged Accuracy http://pylint-messages.wikidot.com/all-codes
E1305-tooManyArgForFormatString Avoid string format operations that have more arguments than conversion specifiers declared. Robustness http://pylint-messages.wikidot.com/all-codes
E1310-suspiciousArgument Stripping with multiple chars doesn’t strip those chars as a string, but it removes all the occurences of each of them. Accuracy http://pylint-messages.wikidot.com/all-codes
R0201-methodCouldBeFunction Avoid the usage of classes when there are no references for it, suggesting that the method could be used as a static function instead Accuracy http://pylint-messages.wikidot.com/all-codes
R0401-cyclicImport A cyclic import between two or more modules is detected Maintainability http://pylint-messages.wikidot.com/all-codes
W0101-unreachableCode Avoid code after a return or raise statement, which will never be accessed. Maintainability http://pylint-messages.wikidot.com/all-codes
W0102-dangerousDefaultValAsArgument A mutable value as list or dictionary is detected in a default value for an argument. Robustness http://pylint-messages.wikidot.com/all-codes
W0104-statementHasNoEffect A statement doesn’t have (or at least seems to) any effect. Understandability http://pylint-messages.wikidot.com/all-codes
W0106-expressionAssignedToNothing Expression is assigned to nothing Understandability http://pylint-messages.wikidot.com/all-codes
W0107-unnecessaryPassStatement A ‘pass’ statement that can be avoided is encountered. Understandability http://pylint-messages.wikidot.com/all-codes
W0108-lambdaMayNotBeNecessary Avoid useless uses of lambda expressions. Maintainability http://pylint-messages.wikidot.com/all-codes
W0109-duplicateKeyInDictionary Duplicate key in dictionary Efficiency http://pylint-messages.wikidot.com/all-codes
W0110-replaceByComprehension Enforce list comprehensions for map/filter on lambda. Maintainability http://pylint-messages.wikidot.com/all-codes
W0120-elseClauseOnLoopWithoutBreak Else clause on loop without a break statement. Accuracy http://pylint-messages.wikidot.com/all-codes
W0141-blacklistedFunctionUsed A blacklisted built-in function is used (see the bad-function option). Usual blacklisted functions are the ones like map or filter, where Python now offers some cleaner alternative like list comprehension. Accuracy http://pylint-messages.wikidot.com/all-codes
W0142-readabilityError A function or method is called using *args or **kwargs to dispatch arguments. This doesn’t improve readability and should be used with care. Understandability http://pylint-messages.wikidot.com/all-codes
W0150-statementMaySwallowException Statement in finally block may swallow exception Accuracy http://pylint-messages.wikidot.com/all-codes
W0199-avoidAssertOnTuple Avoid calling assert on a 2-uple Robustness http://pylint-messages.wikidot.com/all-codes
W0201-attributeDefinedOutsideInit An instance attribute is defined outside the __init__ method. Robustness http://pylint-messages.wikidot.com/all-codes
W0211-avoidSelfOrClsAsFirstArgInStaticMethod Avoid the usage of self or cls as first argument of a static method Maintainability http://pylint-messages.wikidot.com/all-codes
W0212-invalidAccessToProtectedMember A protected member (i.e. class member with a name beginning with an underscore) is access outside the class or a descendant of the class where it’s defined. Accuracy http://pylint-messages.wikidot.com/all-codes
W0221-argumentNumbersDifferFromMethod A method has a different number of arguments than in the implemented interface or in an overridden method. Accuracy http://pylint-messages.wikidot.com/all-codes
W0222-signatureDifferFromMethod A method signature is different than in the implemented interface or in an overridden method. Maintainability http://pylint-messages.wikidot.com/all-codes
W0223-methodNotOverridden An abstract method (i.e. one that raises NotImplementedError) is not overridden in concrete class. Understandability http://pylint-messages.wikidot.com/all-codes
W0231-initNotCallFromBaseClass An ancestor class method has an __init__ method which is not called by a derived class. Understandability http://pylint-messages.wikidot.com/all-codes
W0232-classHasNotInitMethod A class has no __init__ method, and neither does its parent classes. Maintainability http://pylint-messages.wikidot.com/all-codes
W0233-initMethodCalledIncorrectly An __init__ method is called on a class which is not in the direct ancestors for the analysed class. Understandability http://pylint-messages.wikidot.com/all-codes
W0234-iterReturnNonIterator __iter__ returns non-iterator Accuracy http://pylint-messages.wikidot.com/all-codes
W0312-mixedTabsAndSpacesInAModule There are some mixed tabs and spaces in a module. Accuracy http://pylint-messages.wikidot.com/all-codes
W0401-wildcardImport Do not import everything from a module using star imports. Understandability http://pylint-messages.wikidot.com/all-codes
W0410-futureImportShouldBeFirstStatment __future__ imports need to be the first non docstring statement in a module in order to work. Accuracy http://pylint-messages.wikidot.com/all-codes
W0601-globalVariableUndefinedAtTheModuleLevel Do not use a global statement with a variable name that can’t be found. Accuracy http://pylint-messages.wikidot.com/all-codes
W0602-noAssignmentOfGlobalVar Do not use global statements with variables names which are not affected in the current scope. Robustness http://pylint-messages.wikidot.com/all-codes
W0604-usingGlobalStatementAtModuleLevel The global statement at module level is superfluous, since all the variables defined there are already globals. Maintainability http://pylint-messages.wikidot.com/all-codes
W0612-unusedVariable Avoid variables which are not used, which can be considered dead code. Maintainability http://pylint-messages.wikidot.com/all-codes
W0622-redefiningBuildinObject Do not define objects with the same name as a builtin, this will trip those reading the code and it will be harder to understand. Understandability http://pylint-messages.wikidot.com/all-codes
W0623-redefiningNameInExceptionHandler Avoid binding in an except clause to a name which already exists in the code. Accuracy http://pylint-messages.wikidot.com/all-codes
W0631-possibleUseOfUndefinedVariable An loop variable (i.e. defined by a for loop or a list comprehension or a generator expression) is used outside the loop. Accuracy http://pylint-messages.wikidot.com/all-codes
W0701-stringExceptionRaised Raising a string exception Robustness http://pylint-messages.wikidot.com/all-codes
W0703-catchingTooGeneralException Catching too general exception Accuracy http://pylint-messages.wikidot.com/all-codes
W0705-catchingAlreadyCaughtException An except clause which handles an exception that was previously caught in another except clause. Accuracy https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W0710-exceptionDoNotInheritFromStdException Exception doesn’t inherit from standard ‘Exception’ class Maintainability http://pylint-messages.wikidot.com/all-codes
W0711-binaryOperationException Exception to catch is the result of a binary operation Accuracy http://pylint-messages.wikidot.com/all-codes
W1300-incorrectDictionaryKeyFormat Do not pass dictionaries with non-string keys when doing old style formatting. Accuracy http://pylint-messages.wikidot.com/all-codes
E0303-useLenForNonNegativeInteger Used when a __len__ method returns something which is not a non-negative integer Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1604-userRaiseErrorClass Used when the alternate raise syntax ‘raise foo, bar’ is used instead of ‘raise foo(bar)’. Efficiency https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1609-importOnlyAllowedAtModuleLevel Used when the import star syntax is used somewhere else than the module level Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1700-yiedlnsideAsyncFunction Used when an yield or yield from statement is found inside an async function. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
I1101-cExtensionMemberUnavailable Used when a variable is accessed for non-existent member of C extension. Due to unavailability of source static analysis is impossible, but it may be performed by introspecting living objects in run-time Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R1708-avoidStopIterationInGenerator According to PEP479, the raise of StopIteration to end the loop of a generator may lead to hard to find bugs. This PEP specify that raise StopIteration has to be replaced by a simple return statement Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W0111-assignmentWillBeInvalidInFuture Used when assignment will become invalid in future Python release due to introducing new keyword Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W0123-avoidEvalFunction Used when you use the ‘eval’ function, to discourage its usage. Consider using ast.literal_eval for safely evaluating strings containing Python expressions from untrusted sources Security https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W0235-overriddenMethodIsUseless Used whenever we can detect that an overridden method is useless, relying on super() delegation to do the same thing as another method from the MRO. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W0640-variableDefinedInLoop A variable used in a closure is defined in a loop. This will result in all closures using the same value for the closed-over variable. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W0715-exceptionArgumentFmt Used when passing multiple arguments to an exception constructor, the first of them a string literal containing what appears to be placeholders intended for formatting Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1113-keywordArgBeforeVarPositionalArg When defining a keyword argument before variable positional arguments, one can end up in having multiple values passed for the aforementioned parameter in case the method is called with keyword arguments. Accuracy https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1202-useFormattingInLogging Used when a logging statement has a call form of ‘logging.(format_string.format(format_args…))’ Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1502-avoidUsingDataTimeInBooleanContxt Using datetime.time in a boolean context can hide subtle bugs when the time they represent matches midnight UTC. Accuracy https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1503-redundantUsedOfAssert The first argument of assertTrue and assertFalse is a condition. If a constant is passed as parameter, that condition will be always true Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1505-usingDeprecatedMethod The method is marked as deprecated and will be removed in a future version of Python. Consider looking for an alternative in the documentation. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1506-threadNeedsTargetFunction The warning is emitted when a threading.Thread class is instantiated without the target function being passed. By default, the first parameter is the group param, not the target param Accuracy https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1507-avoidCopyMethod os.environ is not a dict object but proxy object, so shallow copy has still effects on original object Efficiency https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1601-applyFunctionNotUsedInPython3 Used when the apply built-in function is referenced (missing from Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1602-basestringFunctionNotUsedInPython3 Used when the basestring built-in function is referenced (missing from Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1603-bufferFunctionNotUsedInPython3 Used when the buffer built-in function is referenced (missing from Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1604-cmpFunctionNotUsedInPython3 Used when the cmp built-in function is referenced (missing from Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1605-coerceFunctionNotUsedInPython3 Used when the coerce built-in function is referenced (missing from Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1606-execfileFunctionNotUsedInPython3 Used when the execfile built-in function is referenced (missing from Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1607-fileFunctionNotUsedInPython3 Used when the file built-in function is referenced (missing from Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1608-longFunctionNotUsedInPython3 Used when the long built-in function is referenced (missing from Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1609-raw_inputFunctionNotUsedInPython3 Used when the raw_input built-in function is referenced (missing from Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1610-reduceFunctionNotUsedInPython3 Used when the reduce built-in function is referenced (missing from Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1611-standardFunctionNotUsedInPython3 Used when the StandardError built-in function is referenced (missing from Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1612-unicodeFunctionNotUsedInPython3 Used when the unicode built-in function is referenced (missing from Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1613-xrangeFunctionNotUsedInPython3 Used when the xrange built-in function is referenced (missing from Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1614-__coerceMethodNotUsedInPython3 Used when a __coerce__ method is defined (method is not used by Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1615-__delsliceMethodNotUsedInPython3 Used when a __delslice__ method is defined (method is not used by Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1616-__getsliceMethodNotUsedInPython3 Used when a __getslice__ method is defined (method is not used by Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1617-__setsliceMethodNotUsedInPython3 Used when a __setslice__ method is defined (method is not used by Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1618-importMissing Used when an import is not accompanied by from __future__ import absolute_import (default behaviour in Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1619-possibleInvalidDivision Used for non-floor division w/o a float literal or from __future__ import division (Python 3 returns a float for int division unconditionally) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1620-callsNotPresentInPython3 Used for calls to dict.iterkeys(), itervalues() or iteritems() (Python 3 lacks these methods) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1621-methodNotPresentInPython3 Used for calls to dict.viewkeys(), viewvalues() or viewitems() (Python 3 lacks these methods) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1622-invalidNextMethodInPython3 Used when an object’s next() method is called (Python 3 uses the next() built- in function) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1623-invalidMetaclassUsedForPython3 Used when a metaclass is specified by assigning to __metaclass__ (Python 3 specifies the metaclass as a class statement argument) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1624-indexingExceptionsWillNotWorkOnPython3 Indexing exceptions will not work on Python 3. Use exception.args[index] instead. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1625-stringException Used when a string exception is raised. This will not work on Python 3. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1626-reloadMethodNotUsedInPython3 Used when the reload built-in function is referenced (missing from Python 3). Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1627-__octMethodNotUsedInPython3 Used when an __oct__ method is defined (method is not used by Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1628-__hexMethodNotUsedInPython3 Used when a __hex__ method is defined (method is not used by Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1629-__nonzeroMethodNotUsedInPython3 Used when a __nonzero__ method is defined (method is not used by Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1630-__cmpMethodNotUsedInPython3 Used when a __cmp__ method is defined (method is not used by Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1632-inputMethodNotUsedInPython3 Used when the input built-in is referenced (backwards-incompatible semantics in Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1633-roundMethodNotUsedInPython3 Used when the round built-in is referenced (backwards-incompatible semantics in Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1634-internMethodNotUsedInPython3 Used when the intern built-in is referenced (Moved to sys.intern in Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1635-unichrMethodNotUsedInPython3 Used when the unichr built-in is referenced (Use chr in Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1636-mapReferencedInNonIteratingContext Used when the map built-in is referenced in a non-iterating context (returns an iterator in Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1637-zipReferencedInNonIteratingContext Used when the zip built-in is referenced in a non-iterating context (returns an iterator in Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1638-rangeReferencedInNonIteratingContext Used when the range built-in is referenced in a non-iterating context (returns an iterator in Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1639-filterReferencedInNonIteratingContext Used when the filter built-in is referenced in a non-iterating context (returns an iterator in Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1640-cmpArgumentShoudBeAvoided Using the cmp argument for list.sort or the sorted builtin should be avoided, since it was removed in Python 3. Using either key or functools.cmp_to_key should be preferred. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1641-equalAndHashMethodImplementedTogether Used when a class implements __eq__ but not __hash__. In Python 2, objects get object.__hash__ as the default implementation, in Python 3 objects get None as their default __hash__ implementation if they also implement __eq__ Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1642-__div__methodNotUsedInPython3 Used when a __div__ method is defined. Using __truediv__ and setting__div__ = __truediv__ should be preferred.(method is not used by Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1643-__idiv__methodNotUsedInPython3 Used when an __idiv__ method is defined. Using __itruediv__ and setting__idiv__ = __itruediv__ should be preferred.(method is not used by Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1644-__rdiv__methodNotUsedInPython3 Used when a __rdiv__ method is defined. Using __rtruediv__ and setting__rdiv__ = __rtruediv__ should be preferred.(method is not used by Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1645-exceptionMessageRemovedInPython3 Used when the message attribute is accessed on an Exception. Use str(exception) instead Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1646-nonTextEncodingUsed Used when using str.encode or str.decode with a non-text encoding. Use codecs module to handle arbitrary codecs. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1647-sys.mainintRemovedInPython3 Used when accessing sys.maxint. Use sys.maxsize instead. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1648-moduleNotUsedInPython3 Used when importing a module that no longer exists in Python 3 Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1649-stringFunctionDeprecatedInPython3 Used when accessing a string function that has been deprecated in Python 3 Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1650-deprecatedDeleteCharsParameterUsed Used when using the deprecated deletechars parameters from str.translate. Use re.sub to remove the desired characters Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1651-usedDeprecatedFunctionOnItertoolsModule Used when accessing a function on itertools that has been removed in Python 3 Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1652-accessingADeprecatedFieldsOnTheTypesModule Used when accessing a field on types that has been removed in Python 3 Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1653-nextMethodDeprecatedInPython3 Used when a next method is defined that would be an iterator in Python 2 but is treated as a normal function in Python 3 Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1654-dict.itemsReferencedInNonIteratingContext Used when dict.items is referenced in a non-iterating context (returns an iterator in Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1655-dict.keysReferencedInNonIteratingContext Used when dict.keys is referenced in a non-iterating context (returns an iterator in Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1656-dict.valuesReferencedInNonIteratingContext Used when dict.values is referenced in a non-iterating context (returns an iterator in Python 3) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0112-AvoidMoreThanOneStarredVar Do not use more than one starred variable when unpacking. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0117-nonlocalNameFoundWithoutBInding Make sure that all nonlocals have a binding variable in the enclosing scopes. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0236-invalidObjectsInSlots Avoid using objects which shouldn’t appear in __slots__ definition. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0238-invalidSlotObjects Avoid using objects which are not suitable for defining __slots__ (only strings, iterables or sequences are permitted). Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0241-duplicateBasesForClass Avoid defining a class which has more than one of the same bases at the same inheritance level. Robustness https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0402-importError Import Error Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E0703-avoidRaiseFromSyntaxOnObjectsWithoutExceptions Avoid using the raise-from syntax with objects which aren’t exceptions. Robustness https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1127-sliceIdexNotAnInt A slice index for builtin containers needs to be an integer, None or an instance with __index__ method. Robustness https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1128-assigningToFunctionWhichReturnNone Avoid assignment done on a function call but the inferred function returns nothing but None. Robustness https://pylint.readthedocs.io/en/latest/technical_reference/features.html
E1132-functionCallWithRepeatedKeywordArg Don’t call a function with a repeated keyword argument. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W0124-avoidContxtManagerReturningMultipleVals Do not use context managers which returns multiple values and uses name binding with ‘as’ only for a part of those values. Robustness https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1307-invalidLookUpKeyInFormatSpecifier Don’t index objects which don’t support the index protocol when doing string formatting. Robustness https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R0101-tooManyNestedBlocks Used when a function or a method has too many nested blocks. This makes the code less understandable and maintainable. Understandability https://docs.pylint.org/en/1.6.0/features.html
R0102-simplifiableIfStatement Used when an if statement can be replaced with ‘bool(test)’. Understandability https://docs.pylint.org/en/1.6.0/features.html

Low level issues

Rule Description KPI URL
E0001-syntaxErrorForModule The code has syntax erros Understandability http://pylint-messages.wikidot.com/all-codes
R0801-duplicateLinesInFiles Similar lines Maintainability http://pylint-messages.wikidot.com/all-codes
R0901-tooManyAncestors Class has too many parent classes, try to reduce this to get a more simple (and so easier to use) class. Maintainability http://pylint-messages.wikidot.com/all-codes
R0902-tooManyInstanceAttributes Class has too many instance attributes, try to reduce this to get a more simple (and so easier to use) class. Maintainability http://pylint-messages.wikidot.com/all-codes
R0903-tooFewPublicMethods Classes aren’t meant to just store data, as you’re basically treating the class as a dictionary Maintainability http://pylint-messages.wikidot.com/all-codes
R0904-tooManyPublicMethods Class has too many public methods, try to reduce this to get a more simple (and so easier to use) class. Maintainability http://pylint-messages.wikidot.com/all-codes
R0911-tooManyReturnStatement Too many return statements Maintainability http://pylint-messages.wikidot.com/all-codes
R0912-tooManyBranches Too many branches Maintainability http://pylint-messages.wikidot.com/all-codes
R0913-tooManyArguments Too many arguments Maintainability http://pylint-messages.wikidot.com/all-codes
R0914-tooManyLocalVariables A method or function uses more than 15 variables in the namespace. Maintainability http://pylint-messages.wikidot.com/all-codes
R0915-tooManyStatements A function or method has too many statements. You should then split it in smaller functions / methods. Maintainability http://pylint-messages.wikidot.com/all-codes
R0921-abstractClassNotReferenced An abstract class is not used as ancestor anywhere. Maintainability http://pylint-messages.wikidot.com/all-codes
R0922-abstractClassNotUsedFrequently An abstract class is used less than X times as ancestor. Maintainability http://pylint-messages.wikidot.com/all-codes
R0923-interfaceNotImplemented An interface class has not been implemented. Understandability http://pylint-messages.wikidot.com/all-codes
R1703-ifStatementCanBeSimplified Suggest simplification of an if statement, which can be easier to understand after refactoring. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W0105-stringStatementHasNotEffect String statements which don’t form a docstring can be transformed into comments. Understandability http://pylint-messages.wikidot.com/all-codes
W0121-incorrectRaiseError Use raise ErrorClass(args) instead of raise ErrorClass, args. Understandability http://pylint-messages.wikidot.com/all-codes
W0301-uselessSemicolon A statement is endend by a semi-colon (‘;’), which isn’t necessary (that’s python, not C ;). Understandability http://pylint-messages.wikidot.com/all-codes
W0311-badIndentation An unexpected number of indentation’s tabulations or spaces has been found. Understandability http://pylint-messages.wikidot.com/all-codes
W0331-usedInvalidOpt Use of the <> operator. Use ‘!=’ instead. Understandability http://pylint-messages.wikidot.com/all-codes
W0332-longVarDeclaration A lower case ‘l’ is used to mark a long integer. You should use an upper case ‘L’ since the letter ‘l’ looks too much like the digit ‘1’. Understandability http://pylint-messages.wikidot.com/all-codes
W0333-useStrFunction The deprecated ‘“’ (backtick) operator is used instead of the str() function Understandability http://pylint-messages.wikidot.com/all-codes
W0402-useOfDeprecatedModule Uses of a deprecated module Accuracy http://pylint-messages.wikidot.com/all-codes
W0403-relativeImportFound An import relative to the package directory is detected. Understandability http://pylint-messages.wikidot.com/all-codes
W0404-reimportNotRequired Don’t import modules more than once. Resource Utilization http://pylint-messages.wikidot.com/all-codes
W0406-moduleImportItself Module imports itself Understandability http://pylint-messages.wikidot.com/all-codes
W0511-taskMarkerFound Task marker found Maintainability http://pylint-messages.wikidot.com/all-codes
W0512-cannotDecodeUsingEncoding Source line cannot be decoded using the specified source file encoding Understandability http://pylint-messages.wikidot.com/all-codes
W0603-usingGlobalStatement Using the global statement Understandability http://pylint-messages.wikidot.com/all-codes
W0611-unusedImport Do not leave unused imports lying around, they are dead code. Understandability http://pylint-messages.wikidot.com/all-codes
W0613-unusedArgument An argument is not used in the body of its function or method. Understandability http://pylint-messages.wikidot.com/all-codes
W0614-unusedImportFromWildcardImport Unused import from wildcard import Understandability http://pylint-messages.wikidot.com/all-codes
W0621-nameRedefinedFromOuterScope Redefining name from outer scope Understandability http://pylint-messages.wikidot.com/all-codes
W0632-possibleUnbalancedTuple Possible unbalanced tuple unpacking Understandability http://pylint-messages.wikidot.com/all-codes
W0633-unpackingNonSequence Attempting to unpack a non-sequence Understandability http://pylint-messages.wikidot.com/all-codes
W0704-exceptDoNothing Except doesn’t do anything Robustness http://pylint-messages.wikidot.com/all-codes
W0712-implicitExceptionsNotSupported Implicit unpacking of exceptions is not supported in Python 3 Understandability http://pylint-messages.wikidot.com/all-codes
W1001-propertyUsedOnOldStyleClass Use of ‘property’ on an old style class Understandability http://pylint-messages.wikidot.com/all-codes
W1111-functionCallOnlyReturnNone An assignment is done on a function call but the inferred function returns nothing but None. Understandability http://pylint-messages.wikidot.com/all-codes
W1201-formatStringInsteadOfConcat When using python’s built-in logging module you shouldn’t concatenate strings with values, and instead format the string. As if string.format() Understandability http://pylint-messages.wikidot.com/all-codes
W1301-unusedKeyInDictionary Don’t pass extra keys when doing string formatting with a dictionary. Accuracy http://pylint-messages.wikidot.com/all-codes
W1401-anomalousBacksEscape Anomalous backslash escape Maintainability http://pylint-messages.wikidot.com/all-codes
W1402-anomalousEscapeString Anomalous Unicode escape in byte string Maintainability http://pylint-messages.wikidot.com/all-codes
W1501-notAValidModeForOpen Make sure that the open builtin receives a correct mode. Accuracy http://pylint-messages.wikidot.com/all-codes
C0113-unneededNegation Used when a boolean expression contains an unneeded negation. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0122-useConstantOnLeftSideOfComparision Used when the constant is placed on the left side of a comparison. It is usually clearer in intent to place it in the right hand side of the comparison. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0201-avoidCallingKeysMethod Emitted when the keys of a dictionary are iterated through the .keys() method. It is enough to just iterate through the dictionary itself, as in ‘for key in dictionary’. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0205-slotsShouldBeNonStringIterable Used when a class __slots__ is a simple string, rather than an iterable. Accuracy https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R0123-possibleIncorrectComparision Used when comparing an object to a literal, which is usually what you do not want to do, since you can compare to a different literal than what was expected altogether. Accuracy https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R0916-tooManyBooleanExpressionsInIfStatement Used when an if statement contains too many boolean expressions Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R1701-mergeIsInstanceCalls Used when multiple consecutive isinstance calls can be merged into one. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R1702-tooManyNestedBlocks Used when a function or a method has too many nested blocks. This makes the code less understandable and maintainable. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R1704-localNameIsRedefiningArg Used when a local name is redefining an argument, which might suggest a potential error. This is taken in account only for a handful of name binding operations, such as for iteration, with statement assignment and exception handler assignment. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R1705-unnecessaryElseAfterReturn Used in order to highlight an unnecessary block of code following an if containing a return statement. As such, it will warn when it encounters an else following a chain of ifs, all of them containing a return statement. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R1706-oldTernarySyntax Used when one of known pre-python 2.5 ternary syntax is used. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R1707-avoidTrailingCommaTuple In Python, a tuple is actually created by the comma symbol, not by the parentheses. Unfortunately, one can actually create a tuple by misplacing a trailing comma, which can lead to potential weird bugs in your code. You should always use parentheses explicitly for creating a tuple. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R1709-booleanExpressionMayBeSimplified Emitted when redundant pre-python 2.5 ternary syntax is used. Portability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R1710-incorrectReturnExpression According to PEP8, if any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable) Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R1711-uselessReturn Emitted when a single ‘return’ or ‘return None’ statement is found at the end of function or method definition. This statement can safely be removed because Python will implicitly return None Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R1712-useTupleForSwappingVariables You do not have to use a temporary variable in order to swap variables. Using ‘tuple unpacking’ to directly swap variables makes the intention more clear. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0123-avoidExplicitTypeChecking Do not check explicitly the type of an object, use isinstance or feature checking instead. Efficiency https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0330-wrongIndentation Continued lines are badly indented. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R0202-useDecoratorInsteadOfClassMethod Use the decorator syntax (@) for creating a classmethod, do not call it explicitly. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R0203-useDecoratorInsteadOfStaticMethod A static method can easily be written by using the decorator syntax, which is cleaner and more obvious than calling static method directly. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W0125-avoidCondStmtWithConstantVal Prohibit a conditional statement with a constant value Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1302-invalidFormatString Make sure that the format strings are syntactically correct. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1303-missingKeywordArgumentForFormatString Pass all defined keyword arguments into a string formatting operation. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1304-unusedFormatArgument Prohibit formatting extra arguments, which are not used by the string format. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1305-avoidCombiningWhileStringFormatting Avoid combining automatic field numbering ({}) with manual field specification ({i}). Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
W1306-missingFormatAttributeInFormatSpecifier Avoid accessing a missing attribute in a string formatting field. Accuracy https://pylint.readthedocs.io/en/latest/technical_reference/features.html
R0204-redefinedVariableType Used when the type of a variable changes inside a method or a function. Understandability https://docs.pylint.org/en/1.6.0/features.html
C0102-blackListedName Used when the name is listed in the ‘bad-names’ black list. Understandability http://pylint-messages.wikidot.com/all-codes
C0103-invalidName The name doesn’t fit the naming convention associated to its type (constant, variable, class…). Understandability http://pylint-messages.wikidot.com/all-codes
C0111-missingDocstring Module, function, class or method has no docstring. Some special methods like __init__() don’t require a docstring. Understandability http://pylint-messages.wikidot.com/all-codes
C0112-emptyDocstring Module, function, class or method has an empty docstring. Understandability http://pylint-messages.wikidot.com/all-codes
C0121-missingAttribute An attribute required for modules is missing Understandability http://pylint-messages.wikidot.com/all-codes
C0200-useEnumerateInsteadOfRange Consider using enumerate instead of iterating with range and len Emitted when code that iterates with range and len is encountered. Such code can be simplified by using the enumerate builtin. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0202-useClsAsFirstArgumentInClass Used when a class method has a first argument named differently than the value specified in valid-classmethod-first-arg option (default to “cls”), recommended to easily differentiate them from regular instance methods. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0203-useMcsAsFirstArgumentInMethod Metaclass method should have ‘mcs’ as first argument Understandability http://pylint-messages.wikidot.com/all-codes
C0204-useMcsAsFirstArgumentInClass A metaclass class method has a first argument named differently than the value specified in the valid-metaclass-classmethod-first-arg option (defaults to mcs). Specifying the value mcs is recommended to easily differentiate such methods from regular instance methods. Understandability http://pylint-messages.wikidot.com/all-codes
C0301-lineTooLong A line is longer than the limit specified in the max-line-length option in Pylint Understandability http://pylint-messages.wikidot.com/all-codes
C0302-tooManyLinesInModule Too many lines in module, reducing its readability. Understandability http://pylint-messages.wikidot.com/all-codes
C0303-trailingWhitespace Prohibit whitespace on any line directly before the line end character(s). Understandability http://pylint-messages.wikidot.com/all-codes
C0304-newLineMissing A Python source file has no line end character(s) on its last line. Understandability http://pylint-messages.wikidot.com/all-codes
C0321-tooManyStmtOnSingleLine More than one statement is found on the same line. Understandability http://pylint-messages.wikidot.com/all-codes
C0322-OptNotPrecededBySpace Operator not preceded by a space Understandability http://pylint-messages.wikidot.com/all-codes
C0323-OptNotFollowedBySpace Operator not followed by a space Understandability http://pylint-messages.wikidot.com/all-codes
C0324-commaNotFollowedBySpace Comma not followed by a space Understandability http://pylint-messages.wikidot.com/all-codes
C0325-unnecessaryParensAfterKeyword Prohibit the use of unnecessary parenthesis to enforce Python conventions. Understandability http://pylint-messages.wikidot.com/all-codes
C0326-extraSpaces Prohibit use of extraneous whitespace in expressions and statements. Understandability http://pylint-messages.wikidot.com/all-codes
C1001-oldStyleClassDefined A class is defined using the old style. Understandability http://pylint-messages.wikidot.com/all-codes
I0001-builtInModuleNotChecked Used to inform that a built-in module has not been checked using the raw checkers. Maintainability http://pylint-messages.wikidot.com/all-codes
I0010-inlineOptionNotConsidered Used when an inline option is either badly formatted or can’t be used inside modules. Maintainability http://pylint-messages.wikidot.com/all-codes
I0011-locallyDisabling Used when an inline option disables a message or a messages category. Maintainability http://pylint-messages.wikidot.com/all-codes
I0012-locallyEnabling Used when an inline option enables a message or a messages category. Maintainability http://pylint-messages.wikidot.com/all-codes
I0013-ignoringEntireFile Used to inform that the file will not be checked. Maintainability http://pylint-messages.wikidot.com/all-codes
I0014-deprecatedDirectiveUsed Used to inform that a deprecated directive has been used. Maintainability http://pylint-messages.wikidot.com/all-codes
I0022-deprecatePragmaUsed Used to inform that a deprecated pragma has been used. Maintainability http://pylint-messages.wikidot.com/all-codes
C0305-trailingNewlines Used when there are trailing blank lines in a file. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0327-mixedLinesError Used when there are mixed (LF and CRLF) newline signs in a file. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0328-unexpectedLineEndingFmt Used when there is different newline than expected. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0401-incorrectSpellingInComment Used when a word in comment is not spelled correctly. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0402-incorrectSpellingInDocstring Used when a word in docstring is not spelled correctly. Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0403-invalidCharsInDocstring Used when a word in docstring cannot be checked by enchant. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0410-cyclicImport2 Used when a cyclic import between two or more modules is detected. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0411-incorrectImportOrder Used when PEP8 import order is not respected (standard imports first, then third-party libraries, then local imports) Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0412-importsNotGrouped Used when imports are not grouped by packages Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C0413-importsShouldBeAtTop Used when code and imports are mixed Understandability https://pylint.readthedocs.io/en/latest/technical_reference/features.html
C1801-lenUsedIncorrectly Used when Pylint detects that len(sequence) is being used inside a condition to determine if a sequence is empty. Instead of comparing the length to 0, rely on the fact that empty sequences are false. Efficiency https://pylint.readthedocs.io/en/latest/technical_reference/features.html
I0023-useSymbolicMessaage Used when a message is enabled or disabled by id. Maintainability https://pylint.readthedocs.io/en/latest/technical_reference/features.html

Bandit Code Issues

Bandit is an open-source static code analyzer that helps to detect security code issues in Python code. Visit their website for more detailed information on Bandit and the ruleset found below.

Bandit High Level Issues

RuleDescriptionExampleKPI
B401-blacklist_calls telnetlibMaintainability
B402-blacklist_callsftplibMaintainability
B411-blacklist_callsxmlrpclibMaintainability
B412-blacklist_callswsgiref.handlers.CGIHandler
twisted.web.twcgi.CGIScript
Maintainability
B413-blacklist_callsCrypto.Cipher
Crypto.Hash
Crypto.IO
Crypto.Protocol
Crypto.PublicKey
Crypto.Random
Crypto.Signature
Crypto.Util
Maintainability
B414-blacklist_callsCryptodome.Cipher
Cryptodome.Hash
Cryptodome.IO
Cryptodome.Protocol
Cryptodome.PublicKey
Cryptodome.Random
Cryptodome.Signature
Cryptodome.Util
Maintainability

Bandit Low Level Issues

RuleDescriptionexamplekpi
B101-assert_usedUse of assert detected. The enclosed code will be removed when
compiling to optimised byte code.
assert logged_in
display_assets()
Maintainability
B102-exec_usedUse of exec detected.exec("do evil")
exec "do evil"
Maintainability
B103-set_bad_file_permissionsProbable insecure usage of temp file/directory.os.chmod('/etc/hosts', 0o777)
os.chmod('/tmp/oh_hai', 0x1ff)
os.chmod('/etc/passwd', stat.S_IRWXU
Maintainability
B104-hardcoded_bind_all_interfacesPossible binding to all interfaces.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0', 31137))
s.bind(('192.168.0.1', 8080))
Maintainability
B105-hardcoded_password_stringPossible hardcoded password '(root)'def someFunction2(password):
if password == "root":
print("OK, logged in")
Maintainability
B106-hardcoded_password_funcargPossible hardcoded password: 'blerg'doLogin(password="blerg")Maintainability
B107-hardcoded_password_defaultPossible hardcoded
password: 'Admin'
def someFunction(user, password="Admin"):
print("Hi " + user)
Maintainability
B108-hardcoded_tmp_directoryinsecure usage of tmp file/directorytmp_dirs: ['/tmp', '/var/tmp', '/dev/shm']Maintainability
B110-try_except_passa pass in the except blocktry:
do_some_stuff()
except Exception:
pass
Maintainability
B112-try_except_continuea continue in the except blockwhile keep_going:
try:
do_some_stuff()
except Exception:
continue
Maintainability
B201-flask_debug_trueA Flask app appears to be run with debug=True, which exposes
the Werkzeug debugger and allows the execution of arbitrary code.
app.run(debug=True)Maintainability
B501-request_with_no_cert_validationRequests call with verify=False
disabling SSL certificate checks, security issue.
requests.get('https://gmail.com', verify=True)
requests.get('https://gmail.com', verify=False)
requests.post('https://gmail.com', verify=True)
Maintainability
B502-ssl_with_bad_versionssl.wrap_socket call with insecure SSL/TLS protocol version
identified, security issue
ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv3)
ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1)
Maintainability
B503-ssl_with_bad_defaultsFunction definition identified with insecure SSL/TLS protocol
version by default, possible security issue.
def open_ssl_socket(version=SSL.SSLv2_METHOD): passMaintainability
B504-ssl_with_no_versionssl.wrap_socket call with no SSL/TLS protocol version
specified, the default SSLv23 could be insecure, possible security
issue.
ssl.wrap_socket(Maintainability
B505-weak_cryptographic_keyDSA key sizes below 1024 bits are considered breakable.dsa.generate_private_key(512,
backends.default_backend())
rsa.generate_private_key(3,
Maintainability
B506-yaml_loaduse of yaml loadystr = yaml.dump({‘a’ : 1, ‘b’ : 2, ‘c’ : 3}) y = yaml.load(ystr) 6 yaml.dump(y)Maintainability
B507-ssh_no_host_key_verificationParamiko call with policy set
to automatically trust the unknown host key.
ssh_client = client.SSHClient()
ssh_client.set_missing_host_key_policy(client.AutoAddPolicy)
ssh_client.set_missing_host_key_policy(client.WarningPolicy)
Maintainability
B601-paramiko_callsPossible shell injection via Paramiko call, check inputs are
properly sanitized.
paramiko.exec_command('something; really; unsafe')Maintainability
B602-subprocess_popen_with_shell_equals_truesubprocess call with shell=True seems safe, but may be
changed in the future, consider rewriting without shell
subprocess.check_call(['/bin/ls', '-l'], shell=False)
subprocess.check_call('/bin/ls -l', shell=True)
Maintainability
B603-subprocess_without_shell_equals_truesubprocess call - check for execution of untrusted input.subprocess.check_output(['/bin/ls', '-l'])Maintainability
B604-any_other_function_with_shell_equals_trueFunction call with shell=True parameter identified, possible
security issue.
pop('/bin/gcc --version', shell=True)
Popen('/bin/gcc --version', shell=True)
Maintainability
B605-start_process_with_a_shellStarting a process with a shell: check for injection.os.system('/bin/echo hi')Maintainability
B606-start_process_with_no_shellStarting a process without a
shell.
os.spawnv(mode, path, args)
os.spawnve(mode, path, args, env)
os.spawnvp(mode, file, args)
Maintainability
B607-start_process_with_partial_pathStarting a process with a partial executable pathfrom subprocess import Popen as pop
pop('gcc --version', shell=False)
Maintainability
B608-hardcoded_sql_expressionsSQL injectioquery = "DELETE FROM foo WHERE id = '%s'" % identifier
query = "UPDATE foo SET value = 'b' WHERE id = '%s'" % identifier
Maintainability
B609-linux_commands_wildcard_injectionPossible wildcard injection in call: subprocess.Popeno.popen2('/bin/chmod *')
subp.Popen('/bin/chown *', shell=True)
Maintainability
B610-django_extra_usedPotential SQL injection on extra functionMaintainability
B611-django_rawsql_usedPotential SQL injection on RawSQL functionMaintainability
B701-jinja2_autoescape_falseUsing jinja2 templates with autoescape=False is dangerous and can
lead to XSS. Use autoescape=True to mitigate XSS vulnerabilities.
templateEnv = jinja2.Environment(autoescape=False,
loader=templateLoader)
Environment(loader=templateLoader,
load=templateLoader,
autoescape=False)
Maintainability
B702-use_of_mako_templatesMako templates allow HTML/JS rendering by default and are
inherently open to XSS attacks. Ensure variables in all templates are
properly sanitized via the 'n', 'h' or 'x' flags (depending on context).
mako.template.Template("hern")
template.Template("hern")
Maintainability
B703-django_mark_safePotential XSS on mark_safe functionMaintainability
B301-blacklist_callspickleImports : pickle.loads
pickle.load
pickle.Unpickler
cPickle.loads
cPickle.load
cPickle.Unpickler
dill.loads
dill.load
dill.Unpickler
shelve.open
shelve.DbfilenameShelf
Maintainability
B302-blacklist_callsmarshalImports : marshal.load
marshal.loads
Maintainability
B303-blacklist_callsmd5Imports : hashlib.md5
hashlib.sha1
Crypto.Hash.MD2.new
Crypto.Hash.MD4.new
Crypto.Hash.MD5.new
Crypto.Hash.SHA.new
Cryptodome.Hash.MD2.new
Cryptodome.Hash.MD4.new
Cryptodome.Hash.MD5.new
Cryptodome.Hash.SHA.new
cryptography.hazmat.primitives .hashes.MD5
cryptography.hazmat.primitives .hashes.SHA1
Maintainability
B304-blacklist_callsciphersImports : Crypto.Cipher.ARC2.new
Crypto.Cipher.ARC4.new
Crypto.Cipher.Blowfish.new
Crypto.Cipher.DES.new
Crypto.Cipher.XOR.new
Cryptodome.Cipher.ARC2.new
Cryptodome.Cipher.ARC4.new
Cryptodome.Cipher.Blowfish.new
Cryptodome.Cipher.DES.new
Cryptodome.Cipher.XOR.new
cryptography.hazmat.primitives .ciphers.algorithms.ARC4
cryptography.hazmat.primitives .ciphers.algorithms.Blowfish
cryptography.hazmat.primitives .ciphers.algorithms.IDEA
Maintainability
B305-blacklist_callscipher_modesImports : cryptography.hazmat.primitives .ciphers.modes.ECBMaintainability
B306-blacklist_callsmktemp_qImports : tempfile.mktempMaintainability
B307-blacklist_callsevalImports : evalMaintainability
B308-blacklist_callsmark_safeImports : django.utils.safestring.mark_safeMaintainability
B309-blacklist_callshttpsconnectionImports : httplib.HTTPSConnection
http.client.HTTPSConnection
six.moves.http_client .HTTPSConnection
Maintainability
B310-blacklist_callsurllib_urlopenImports : urllib.urlopen
urllib.request.urlopen
urllib.urlretrieve
urllib.request.urlretrieve
urllib.URLopener
urllib.request.URLopener
urllib.FancyURLopener
urllib.request.FancyURLopener
urllib2.urlopen
urllib2.Request
six.moves.urllib.request.urlopen
six.moves.urllib.request .urlretrieve
six.moves.urllib.request .URLopener
six.moves.urllib.request .FancyURLopener
Maintainability
B311-blacklist_callsrandomImports : random.random
random.randrange
random.randint
random.choice
random.uniform
random.triangular
Maintainability
B312-blacklist_callstelnetlibImports : telnetlib.*Maintainability
B313-blacklist_callsxml_bad_cElementTreeImports : xml.etree.cElementTree.parse
xml.etree.cElementTree.iterparse
xml.etree.cElementTree.fromstring
xml.etree.cElementTree.XMLParser
Maintainability
B314-blacklist_callsxml_bad_ElementTreeImports : xml.etree.ElementTree.parse
xml.etree.ElementTree.iterparse
xml.etree.ElementTree.fromstring
xml.etree.ElementTree.XMLParser
Maintainability
B315-blacklist_callsxml_bad_expatreaderImports : xml.sax.expatreader.create_parserMaintainability
B316-blacklist_callsxml_bad_expatbuilderImports : xml.dom.expatbuilder.parse
xml.dom.expatbuilder.parseString
Maintainability
B317-blacklist_callsxml_bad_saxImports : xml.sax.parse
xml.sax.parseString
xml.sax.make_parser
Maintainability
B318-blacklist_callsxml_bad_minidomImports : xml.dom.minidom.parse
xml.dom.minidom.parseString
Maintainability
B319-blacklist_callsxml_bad_pulldomImports : xml.dom.pulldom.parse
xml.dom.pulldom.parseString
Maintainability
B320-blacklist_callsxml_bad_etreeImports : lxml.etree.parse
lxml.etree.fromstring
lxml.etree.RestrictedElement
lxml.etree.GlobalParserTLS
lxml.etree.getDefaultParser
lxml.etree.check_docinfo
Maintainability
B321-blacklist_callsftplibImports : ftplib.*Maintainability
B322-blacklist_callsinputImports : inputMaintainability
B323-blacklist_callsunverified_contextImports : ssl._create_unverified_contextMaintainability
B325-blacklist_callstempnamImports : os.tempnam
os.tmpnam
Maintainability
B403-blacklist_callspickle
cPickle
dill
shelve
Maintainability
B404-blacklist_callssubprocessMaintainability
B405-blacklist_callsxml.etree.cElementTree
xml.etree.ElementTree
Maintainability
B406-blacklist_callsxml.saxMaintainability
B407-blacklist_callsxml.dom.expatbuilderMaintainability
B408-blacklist_callsxml.dom.minidomMaintainability
B409-blacklist_callsxml.dom.pulldomMaintainability
B410-blacklist_callslxmlMaintainability

JavaScript

The section below covers the JSLint and ESLint code checker issues.


JSLint code checker

JSLint is an open source static code analyzer which detects code issues and bugs in JavaScript programs. Visit their website for more detailed information on JSLint and the ruleset found below.


Critical level issues

Rule Description KPI URL
badConstructor The “Bad constructor” error is thrown when JSLint or JSHint encounters the new operator followed by a literal value. Maintainability http://linterrors.com/js/bad-constructor
earlyProgramEnd “Unexpected early end of program. This error is thrown when JSHint encounters missing closing paranthesis in a given piece of code.Consider the following example : console.log(“”January””.substring(//0,3); In this example ends of statement is commented out, which will potentially cause the problem. Why do I get this error? This error is raised to highlight a fatal JavaScript syntax error. Your code will not run unless you fix this issue.” Maintainability  
invalidRegularExpression Invalid regular expression. Maintainability  
missingClosingParenthesis “Missing ‘}’ to match ‘{‘ from line {a}. This error is thrown when JSHint encounters missing closing ‘}’ paranthesis in a given piece of code. Why do I get this error? This error is raised to highlight a fatal JavaScript syntax error. Your code will not run if you do not fix this error. “ Accuracy  
missingClosingBracket “Missing ‘]’ to match ‘[‘ from line {a}. This error is thrown when JSHint encounters missing closing ‘}’ paranthesis in a given piece of code. Why do I get this error? This error is raised to highlight a fatal JavaScript syntax error. Your code will not run if you do not fix this error. “ Accuracy  
expectedIdentifier Expected an identifier and instead saw ‘{a}’. Maintainability  

High level issues

Rule Description KPI URL
attemptToOverideConstant The “Attempting to override ‘{a}’ which is a constant” error is thrown when JSHint encounters an assignment expression with an identifer that has been declared in a constant variable statement. Maintainability http://linterrors.com/js/attempting-to-override-a-which-is-a-constant
badAssignment The “Bad assignment” error (and the alternative “Invalid left-hand side in assignment” error) are thrown when JSLint, JSHint or ESLint encounters an assignment expression in which the left-hand side is a call expression. Maintainability http://linterrors.com/js/bad-assignment
functionStatementsAreNotInvocable The “Function statements are not invocable. Wrap the whole function invocation in parens” error (and the alternative “Function declarations are not invocable” error) is thrown when JSLint and JSHint encounter a function declaration followed by a pair of parentheses. In the provided example we declare the demo function and then attempt to immediately invoke it. Maintainability http://linterrors.com/js/function-statements-are-not-invocable
notAFunction The “‘{a}’ is not a function” error is thrown when JSLint, JSHint or ESLint encounters an attempt to invoke the Math object as a function. JSLint and ESLint (but not JSHint) will also raise this warning when they encounter an attempt to invoke the JSON object as a function. Maintainability http://linterrors.com/js/a-is-not-a-function
unclosedComment The “Unclosed comment” error is thrown when JSLint or JSHint encounters a multiline comment that does not end with the character sequence */. Accuracy http://linterrors.com/js/unclosed-comment
unclosedMegaLiteral The “Unclosed mega literal” error is thrown when JSLint encounters an unclosed template string literal. JSHint raises the “Unclosed template literal” error in the same situation. Note that because template string literals are an ES2015 (ES6) feature this error should only appear when linting ES2015 code with the appropriate option set in the linter. In the provided example we attempt to assign an unclosed template string literal to a: Accuracy http://linterrors.com/js/unclosed-mega-literal
unclosedRegularExpression The “Unclosed regular expression” error is thrown when JSLint or JSHint encounters a regular expression literal with no closing / character. Accuracy http://linterrors.com/js/unclosed-regular-expression
unclosedString The “Unclosed string” error is thrown when JSLint or JSHint encounters a a string that is not closed before the next line break or the end of the program. There are numerous situations that could cause this. In this first example, we accidentally forget to close our string. Accuracy http://linterrors.com/js/unclosed-string
missingColon “The “”Missing ‘:’ on a case clause.”” error is thrown when JSLint or JSHint encounters that ‘:’ is missing after a case keyword in switch block.In the provided example we attempt to write a switch block with case statement: switch(value) { case ‘1’ console.log(‘never reach here’); break; } Why do I get this error? This error is raised to highlight a fatal JavaScript syntax error. Your code will not run if you do not fix this error. “ Understandability  
expectedOperator Expected an operator and instead saw ‘{a}’. Maintainability  
invalidForEachLoop Invalid for each loop. Make sure the expression syntax is correct. Accuracy  
variableACannotNamedB A {a} cannot be named ‘{b}’. Maintainability  
tooManyStatements Put statements in one function Maintainability  
cyclomaticComplexityTooHigh get rid of empty lines, early return Maintainability  

Medium level issues

Rule Description KPI URL
unexpectedParameterInGetterFunction The “Unexpected parameter in getter function” error, and the alternative “Unexpected identifier”, is thrown when JSLint, JSHint or ESLint encounters a named parameter in the signature of a property getter function. In the provided example we create an object x with a getter and setter. Maintainability http://linterrors.com/js/unexpected-parameter-a-in-get-b-function
avoidArguments The “Avoid arguments.{a}” error is thrown when JSLint, JSHint or ESLint encounters a reference to the callee or caller property of an arguments object. The text of this warning can therefore be either “Avoid arguments.callee” or “Avoid arguments.caller”. JSHint will only raise this warning if the noarg option is set to true. Maintainability http://linterrors.com/js/avoid-arguments
badForInVariable The “Bad for-in variable ‘{a}'” error (and the alternative “Creating global ‘for’ variable” and “Invalid left-hand side in for-in” errors) are thrown when JSLint, JSHint or ESLint encounters a for-in statement in which the initializer contains a literal value. JSLint and JSHint also raise this warning when it encounters a for-in statement in which the initializer contains an undefined variable reference. Maintainability http://linterrors.com/js/bad-for-in-variable
ConstHasAlreadyBeenDeclared The “const ‘{a}’ has already been declared” error is thrown when JSHint encounters a constant declaration with an identifier that has already been used in a previous constant declaration. Maintainability http://linterrors.com/js/const-a-has-already-been-declared
doNotAssignToTheExceptionParameter The “Do not assign to the exception parameter” error is thrown when JSLint, JSHint or ESLint encounters an assignment inside a catch block to the identifer associated with that block. In the example provided we attempt to assign a new value to the exception parameter e Maintainability http://linterrors.com/js/do-not-assign-to-the-exception-parameter
doNotMakeFunctionsWithinALoop The “Don’t make functions within a loop” error is thrown when JSLint, JSHint and ESLint encounter a function expression in a for, while or do statement body. In the provided example we attempt to add a click event listener to each element with a given class name. The event handler is intended to overwrite the contents of the clicked element with the value of i at a specific iteration of the loop Maintainability http://linterrors.com/js/dont-make-functions-within-a-loop
duplicateKey The “Duplicate key ‘{a}'” error, and the alternatives “Duplicate member ‘{a}'” and “Duplicate ‘{a}'”, is thrown when JSLint, JSHint or ESLint encounters an an object literal that contains more than one property with the same identifier. In the provided example we attempt to assign an object containing two properties with the identifier y to a variable x. Maintainability http://linterrors.com/js/duplicate-key-a
expectedAnIdentifier The “Expected an identifier and instead saw ‘{a}’ (a reserved word)” error is thrown when JSLint or JSHint encounters a reference to what should be an identifier but is actually a keyword that is reserved by the language. In the provided example we attempt to declare a variable with the identifier default which is a reserved word. Maintainability http://linterrors.com/js/expected-an-identifier-and-instead-saw-a-a-reserved-word
functionHasTooManyParameters The “Too many parameters per function. ({a})” error, and the alternative “This function has too many parameters ({a})”, is thrown when JSHint or ESLint encounters an attempt to a function signature with more named parameters than specified by the configuration. In JSHint the configuration is controlled by the maxparams option. In ESLint it’s max-params. Here’s an example in which we attempt to declare a function that takes 3 arguments. Maintainability http://linterrors.com/js/this-function-has-too-many-parameters
missingParenthesesInvokingAConstructor The “Missing ‘()’ invoking a constructor” error is thrown when JSLint, JSHint and ESLint encounter a new expression that is not immediately followed by a pair of parentheses. In the provided example we create an instance of the built-in Date constructor. Maintainability http://linterrors.com/js/missing-invoking-a-constructor
notDeclaredCorrectly The “Variable {a} was not declared correctly error (and the alternative “You might be leaking a variable ({a}) here” error) is thrown when JSLint and JSHint encounter more than one inline assignment. In this example, we attempt to assign a string literal to the variables x, y and z. Understandability http://linterrors.com/js/variable-a-was-not-declared-correctly
optionValidThis The “Option ‘validthis’ can’t be used in a global scope” error is thrown when JSHint encounters the validthis option in a global scope. Here’s a silly example in which we declare a function that is intended to be invoked in the context of an object. Maintainability http://linterrors.com/js/option-validthis-cant-be-used-in-a-global-scope
redefinition The “Redefinition of ‘{a}'” error is thrown when JSHint or ESLint encounters a variable declaration with an identifier that is the same as that of a built-in native object. In the provided example we attempt to declare a variable with the identifier String. Stability http://linterrors.com/js/redefinition-of-a
stopping The “Stopping. ({a}% scanned)” error is thrown when JSLint or JSHint encounters a JavaScript syntax error and cannot continue to reliably parse the program. JSHint will only raise this error if the passfail option is set to true. In the provided example we have half a variable statement which is invalid and cannot be parsed as a complete JavaScript program. Maintainability http://linterrors.com/js/stopping
trailingDecimalPointCanBeConfused The “A trailing decimal point can be confused with a dot” error is thrown when JSLint, JSHint and ESLint encounter a numeric literal followed by a . token which itself is not followed by a decimal integer literal. Here’s an example in which we attempt to assign the value 5.0 to the variable x. Understandability http://linterrors.com/js/a-trailing-decimal-point-can-be-confused-with-a-dot-a
unexpectedAssignmentExpression The “Unexpected assignment expression” error (and the alternative “Expected a conditional expression and instead saw an assignment” error) are thrown when JSLint, JSHint or ESLint encounters an assignment expression in an if, for or while statement initializer. In the provided example we have an if statement with an assignment expression where you would normally expect a conditional. Accuracy http://linterrors.com/js/unexpected-assignment-expression
usedBeforeItWasDefined The “‘{a}’ was used before it was defined” error (and the alternative “‘{a}’ is not defined” error) is thrown when JSLint, JSHint and ESLint encounter an identifier that has not been previously declared in a var statement or function declaration. Some very common examples of this error are those that refer to native environment objects:

 

 

 

 

 

 

1. “‘document’ was used before it was defined”
2. ‘window’ was used before it was defined”
3. ‘alert’ was used before it was defined”
4. ‘console’ was used before it was defined”
5. ‘require’ was used before it was defined”

In the provided example we attempt to set the value of the undeclared variable x and then attempt to use some native browser environment objects:

Maintainability http://linterrors.com/js/a-was-used-before-it-was-defined
withNotAllowedInStrictMode The “‘with’ is not allowed in strict mode” error, and the alternative “Strict mode code may not include a with statement”, is thrown when JSHint or ESLint encounters the with statement in code that is running in strict mode. Maintainability http://linterrors.com/js/with-is-not-allowed-in-strict-mode
wrapAnImmediateFunctionInvocation The “Wrap an immediate function invocation in parentheses” error is thrown when JSLint, JSHint and ESLint encounter an immediately invoked function expression that is not wrapped in parentheses. JSHint will only raise this warning if the immed option is set to true. In the provided example we assign the return value of the anonymous function the variable x. Maintainability http://linterrors.com/js/wrap-an-immediate-function-invocation-in-parentheses
undefinedInitialize const ‘{a}’ is initialized to ‘undefined’. Maintainability  
expectedvariableAMatchVariableB “Expected ‘{a}’ to match ‘{b}’ from line {c} and instead saw ‘{d}’  :   Error is thrown when JSHint encounters a fatal syntax error at a particular line. This is basically a parsing error and your code will not run unless you fix this error. The exact cause will depend on your program, but other errors are usually raised along side this one that should guide you to the problem with your code. Consider the following example : switch(oldPlugin.id) {} case ‘1’: In this example , JSHint we throw syntax error for ‘:’ saying Expected ‘}’ to match ‘{‘ from line 1 and instead saw ‘:'” Maintainability  
expectedOtherVariable “The “”Expected ‘{a}’ and instead saw ‘{b}’.”” error is thrown when JSLint or JSHint encounters unexpected behaviour in the code. In the provided example we attempt to write a switch block with case statement: switch(value) { case ‘1’ console.log(‘never reach here’); break; } In this case JSHint will give the error saying “”Expected ‘:’ and instead saw ‘if’ “” Why do I get this error? This error is raised to highlight a fatal JavaScript syntax error. Your code will not run if you do not fix this error. “ Maintainability  
lineBreakingError “Line breaking error ‘{a}’. JSLint does more than syntax checking: It enforces certain coding conventions. As a further defense against the semicolon insertion mechanism, JSLint expects long statements to be broken only after one of these punctuation characters or operators: , . ; : { } ( [ = < > ? ! + – * / % ~ ^ | & == != <= >= += -= *= /= %= ^= |= &= << >> || && === !== <<= >>= >>> >>>= JSLint does not expect to see a long statement broken after an identifier, a string, a number, closer, or a suffix operator: ) ] ++ — JSLint allows you to turn on the Tolerate sloppy line breaking (laxbreak) option. Semicolon insertion can mask copy/paste errors. If you always break lines after operators, then JSLint can do better at finding them. “ Accuracy  
missingVariable “Missing ‘{a}’. JSHint encounters this error when a keyword or token or operator is missing from the given statement. Consider the following example : var obj = {} In this example ‘;’ is missing in statement. JSHint will give warning saying ‘Missing semicolon’.” Maintainability  
unexpectedVariale “Unexpected ‘{a}’ error is thrown when JSHint encounters a fatal syntax error at a particular line. This is basically a parsing error and your code will not run unless you fix this error. The exact cause will depend on your program, but other errors are usually raised along side this one that should guide you to the problem with your code. Consider the following example : switch(oldPlugin.id) {} case ‘1’: In this example , JSHint we throw syntax error saying Parsing error : Unexpected token case” Maintainability  
illegalComma “Illegal comma. When do I get this error? The “”Extra comma. (it breaks older versions of IE)”” error (and the alternative “”Trailing comma”” and “”Unexpected ‘,’ errors””) are thrown when JSLint, JSHint and ESLint encounter a comma following the final element of an array literal or a comma following the final value in an object literal. Since version 2.0.0 JSHint will only raise this warning if the es3 option is set to true. Here’s an example: var x = {    prop1: 10,    prop2: 20, }; Why do I get this error? This error is raised to highlight a potential fatal syntax error.” Understandability  
expectedIntergerOrFalse Expected a small integer or ‘false’ and instead saw ‘{a}’. Maintainability  
yieldExpressions Yield expressions may only occur within generator functions. Maintainability  
declarationNotWithinBlock {a} declaration not directly within block. Maintainability  
declarationAllowedTopLevel {a} declarations are only allowed at the top level of module scope. Maintainability  
invalidMetaProperty Invalid meta property: ‘{a}.{b}’. Maintainability  
nonCallableValues Non-callable values cannot be used as the second operand to instanceof. Maintainability  
invalidPosition Yield expressions are only used with generator functions and should be called inside a function. Maintainability  
restParameterDoesNotSupportDefault We cannot have rest parameters and default value together. Accuracy  
superPropertyWithinMethodOnly Super property should be used inside a constructor before this. Maintainability  
superCallWithinClassMethodOnly Super property should be used inside a constructor before this. Maintainability  
usedBeforeDefined The “‘{a}’ was used before it was defined” error (and the alternative “‘{a}’ is not defined” error) is thrown when JSLint, JSHint and ESLint encounter an identifier that has not been previously declared in a var statement or function declaration. Some very common examples of this error are those that refer to native environment objects:

 

 

 

 

 

 

1. ‘document’ was used before it was defined”
2. ‘window’ was used before it was defined”
3. ‘alert’ was used before it was defined”
4. ‘console’ was used before it was defined”
5. ‘require’ was used before it was defined”

In the provided example we attempt to set the value of the undeclared variable x and then attempt to use some native browser environment objects.

Maintainability http://linterrors.com/js/a-was-used-before-it-was-defined
badOperand Bad operand is not allowed. Maintainability  
reassignmentOfA Reassignment of ‘{a}’, which is a {b}. Use ‘var’ or ‘let’ to declare bindings that may change. Maintainability  
badNumberA It can be a range error or type error Maintainability  
badInvocation when you try to invoke something which is not a function ex string. Maintainability  
expectedSingleParameter Expected a single parameter in set {a} function. Maintainability  
expectedBreakStatement The switch statement in JavaScript is one of the more error-prone constructs of the language thanks in part to the ability to “fall through” from one case to the next. Maintainability  
functionShouldContainOneYield This rule generates warnings for generator functions that do not have the yield keyword. Maintainability  

Low level issues

Rule Description KPI URL
allDebuggerStatementsShouldBeRemoved The “All ‘debugger’ statements should be removed” error, and the alternatives “Forgotten ‘debugger’ statement” and “Unexpected ‘debugger'”, is thrown when JSLint, JSHint or ESLint encounters a debugger statement. Maintainability http://linterrors.com/js/all-debugger-statements-should-be-removed
badEscapementOfEol The “Bad escapement of EOL. Use option multistr if needed” error, and the alternative “Multiline support is limited to browsers supporting ES5 only”, is thrown when JSHint or ESLint encounters a multiline string. JSHint will only issue this warning the the multistr option is not set to true. Maintainability http://linterrors.com/js/bad-escapement-of-eol-use-option-multistr-if-needed
useTheFunctionFormOfUseStrict The “Use the function form of ‘use strict'” error is thrown when JSLint encounters a strict mode directive in the outermost scope of the code. Maintainability http://linterrors.com/js/use-the-function-form-of-use-strict
useIsnanFunctionToCompareWithNan The “Use the isNaN function to compare with NaN” error is thrown when JSLint, JSHint and ESLint encounter a comparison in which one side is NaN. Maintainability http://linterrors.com/js/use-the-isnan-function-to-compare-with-nan
alreadyDefined The “{a} is already defined” error is thrown when JSLint or JSHint encounters a declaration with an identifier that has been used in a previous declaration. This applies to both variable and function declarations. However it only applies when the declarations appear within the scope of a function rather than the global scope. Maintainability http://linterrors.com/js/a-is-already-defined
betterWrittenInDotNotation The “[‘{a}’] is better written in dot notation” error is thrown when JSLint, JSHint or ESLint encounters an attempt to access a property using a string literal within a pair of square brackets when the property name is not a reserved word. Maintainability http://linterrors.com/js/a-is-better-written-in-dot-notation
bodyOfForInShouldBeWrapped The “The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype” error is thrown when JSLint encounters a for-in statement in which the first statement is not an if statement containing a call to the hasOwnProperty method. JSHint and ESLint are a little more leniant and do not enable this feature by default. They will only warn when they encounter a for-in statement in which the first statement is not an if statement, regardless of the condition of that if statement. Maintainability http://linterrors.com/js/the-body-of-a-for-in-should-be-wrapped-in-an-if-statement
combineWithPreviousVarStatement SLint will throw the “Combine this with the previous ‘var’ statement” error when it encounters multiple variable statements within a function. Maintainability http://linterrors.com/js/combine-this-with-the-previous-var-statement
confusingMinuses The “Confusing minuses” error is thrown when JSHint encounters an addition operator in which the right-hand-side expression is preceded by the unary – operator. Maintainability http://linterrors.com/js/confusing-minuses
confusingPluses The “Confusing pluses” error is thrown when JSHint encounters an addition operator in which the right-hand-side expression is preceded by the unary + operator. Maintainability http://linterrors.com/js/confusing-pluses
constructorNameShouldStartWithAnUppercaseLetter The “A constructor name should start with an uppercase letter” error is thrown when JSLint, JSHint or ESLint encounters an identifier, preceded by the new operator, whose first character is a lowercase letter. JSHint will only raise this warning when the newcap option is set to true. Maintainability http://linterrors.com/js/a-constructor-name-should-start-with-an-uppercase-letter
doNotUseAsAConstructor The “Do not use {a} as a constructor” error is thrown when JSLint, JSHint or ESLint encounters a call to String, Number, Boolean, Math or JSON preceded by the new operator. In the provided example we attempt to assign some values to variables by invoking these functions as constructors. Maintainability http://linterrors.com/js/do-not-use-a-as-a-constructor
doNotUseNewForSideEffects The “Do not use ‘new’ for side effects” error is thrown when JSLint, JSHint or ESLint encounters a function invocation preceded by the new operator when not part of an assignment or comparison expression. JSHint will only issue this warning if the nonew option is set to true. In the provided example we call the built-in Date function as a constructor but don’t assign the returned instance to anything. Maintainability http://linterrors.com/js/do-not-use-new-for-side-effects
doNotUseOctal The “Don’t use octal: ‘{a}’. Use ‘u…’ instead” error, and the alternative “Octal literals are not allowed in strict mode”, is thrown when JSLint, JSHint or ESLint encounters a string literal that contains the escape character followed by a digit between 0 and 7. JSHint and ESLint will only raise this warning when the relevant code is running in strict mode. In the provided example we attempt to assign a string containing an octal escape to a variable x. Maintainability http://linterrors.com/js/dont-use-octal-a-use-instead
doNotWrapFunctionLiteralsInParens The “Do not wrap function literals in parens unless they are to be immediately invoked” error (and the alternative “Wrapping non-IIFE function literals in parens is unnecessary” error) are thrown when JSLint, JSHint or ESLint encounters a function expression wrapped in parentheses with no following invoking parentheses. JSHint will throw this error in the same situation, but only if the immed option is set to true. In the provided example we assign a function expression to a variable x. Maintainability http://linterrors.com/js/do-not-wrap-function-literals-in-parens
emptyClass The “Empty class” error is thrown when JSLint, JSHint (only versions before 1.0.0) or ESLint encounters a regular expression literal containing an empty character class. The following example defines a regular expression including an empty character class. Maintainability http://linterrors.com/js/empty-class
ES5OptionIsSetPerDefault The “ES5 option is now set per default” error is thrown when JSHint (version 2.0.0 and above only) encounters the es5 option with a value of true. Here’s an example in which we set the es5 option so we can use reserved words as property identifers (which was not allowed in ES3). Understandability http://linterrors.com/js/es5-option-is-now-set-per-default
evalIsEvil The “eval is evil” error (and the alternative “eval can be harmful” error) is thrown when JSLint, JSHint or ESLint encounters a call to the eval function. Here’s an example in which we use eval to access an object property by a computed name. Efficiency http://linterrors.com/js/eval-is-evil
expectedAnAssignmentOrFunctionCall The “Expected an assignment or function call and instead saw an expression” error is thrown when JSLint, JSHint or ESLint encounters an expression with no effect. In the provided example we have a conditional expression that will evaluate to true but has no other effect on the program. Maintainability http://linterrors.com/js/expected-an-assignment-or-function-call
extendingPrototypeOfNativeObject The “Extending prototype of native object: ‘{a}'” error, and the alternative “{a} prototype is read only, properties should not be added” error, is thrown when JSHint (only versions 2.3.0 and above) or ESLint encounters *a assignment to a property of the prototype of a native object. JSHint will only raise this warning if the freeze option is set to true. The following example defines a reverse method on the native String prototype. Maintainability http://linterrors.com/js/extending-prototype-of-native-object
extraComma The “Extra comma. (it breaks older versions of IE)” error (and the alternative “Trailing comma” and “Unexpected ‘,’ errors”) are thrown when JSLint, JSHint and ESLint encounter a comma following the final element of an array literal or a comma following the final value in an object literal. Since version 2.0.0 JSHint will only raise this warning if the es3 option is set to true. Here’s an example. Maintainability http://linterrors.com/js/extra-comma
fnStatementsShouldNotBePlacedInBlocks The “Function statements should not be placed in blocks” error (and the alternative “Function declarations should not be placed in blocks” error) is thrown when JSLint or JSHint encounters a function declaration inside a block statement. In the provided example we attempt to declare the example function only if some condition is true. Maintainability http://linterrors.com/js/function-statements-should-not-be-placed-in-blocks
getOrSetAreEs5Features The “get/set are ES5 features” error, and the alternative “This is an ES5 feature”, is thrown when JSHint or JSLint encounters an object property getter or setter. In the provided example we create an object x with a getter and setter. The getter is intended to always return half of the set value. Understandability http://linterrors.com/js/get-set-are-es5-features
hasOwnProperty The “‘hasOwnProperty’ is a really bad name” error is thrown when JSHint encounters an assignment to an object property with the identifier hasOwnProperty. This applies to both object literals and to normal assignment statements. In the provided example we define an object with a property called hasOwnProperty. Maintainability http://linterrors.com/js/hasownproperty-is-a-really-bad-name
impliedEvalIsEvil The “Implied eval is evil. Pass a function instead of a string” error (and the alternative “Implied eval. Consider passing a function instead of a string” error) is thrown when JSLint, JSHint and ESLint encounter a call to setTimeout or setInterval in which the first argument is a string. Here’s an example that should pop up a browser alert after one second. Efficiency http://linterrors.com/js/implied-eval-is-evil-pass-a-function-instead-of-a-string
InvalidTypeOfValue The “Invalid typeof value ‘{a}'” error is thrown when JSHint encounters a comparison with a typeof expression on one side and an invalid string literal on the other. In the provided example we have a function that will return true if the argument is of type “bool”. Maintainability http://linterrors.com/js/invalid-typeof-value-a
leadingDecimalPointCanBeConfused The “A leading decimal point can be confused with a dot” error is thrown when JSLint, JSHint and ESLint encounter a numeric literal preceded by a . token which itself is not preceded by a decimal integer literal. Here’s an example in which we attempt to assign the value 0.5 to the variable x. Maintainability http://linterrors.com/js/a-leading-decimal-point-can-be-confused-with-a-dot-a
missingNameInFunctionStatement The “Missing name in function statement” error, and the alternative “Missing name in function declaration” error, is thrown when JSLint or JSHint encounters the function keyword, where it would normally be parsed as a statement, followed immediately by an opening parenthesis. In the provided example we attempt to define a function but forget to give it an identifier. Maintainability http://linterrors.com/js/missing-name-in-function-statement
missingRadixParameter The “Missing radix parameter” error is thrown when JSLint, JSHint or ESLint encounters a call to the parseInt function that only has one argument. As of JSHint 2.3.0 the warning will only be issued if the es3 option is set to true. Here’s an example. Maintainability http://linterrors.com/js/missing-radix-parameter
missingUseStrictStatement The “Missing ‘use strict’ statement” error is thrown when JSLint, JSHint and ESLint encounter a function that does not contain the strict mode directive, and none of whose ancestor scopes contain the strict mode directive. JSHint will only raise this warning if the strict option is set to true. Here’s an example of a function that does not run in strict mode. Maintainability http://linterrors.com/js/missing-use-strict-statement
mixedDoubleSingleQuotes The “Mixed double and single quotes” error is thrown when JSHint encounters string literal delimited by double or single quote characters when a string literal delimited by the other has already been found. It will only raise this warning if the quotmark option is set to true. In the provided example we attempt to assign string literals to the variables x and y. Conceptual Integrity http://linterrors.com/js/mixed-double-and-single-quotes
notALabel The “‘{a}’ is not a label” error, and the alternatives “‘{a}’ is not a statement label” and “Undefined label ‘{a}'”, is thrown when JSLint, JSHint or ESLint encounters a break or continue statement referencing a label that does not exist. In the provided example we try to break out of a for loop to the non-existent example label. Maintainability http://linterrors.com/js/a-is-not-a-label
notNecessaryToInitializeAsUndefined The “It is not necessary to initialize ‘{a}’ to ‘undefined'” error is thrown when JSLint, JSHint or ESLint encounters a variable statement in which the variable is explicitly initialised to undefined. Here’s an example in which we attempt to declare a variable x and assign undefined to it. Maintainability http://linterrors.com/js/it-is-not-necessary-to-initialize-a-to-undefined
onlyPropertiesShouldBeDeleted The “Only properties should be deleted” error, and the alternative “Variables should not be deleted” error, is thrown when JSLint, JSHint or ESLint encounters the delete operator followed by a single identifier. In the provided example we declare a variable x and then attempt to delete it. Maintainability http://linterrors.com/js/only-properties-should-be-deleted
outOfScope The “{a} used out of scope” error (and the alternative “{a} used outside of binding context” error) are thrown when JSLint, JSHint or ESLint encounters a reference to a variable declared in an inner block. In the provided example we declare the variable x in the body of an if statement and then attempt to return it from the enclosing function. Understandability http://linterrors.com/js/a-used-out-of-scope
readOnly The “Read only” error, and the alternative “{a} is a read-only native object”, is thrown when JSLint, JSHint or ESLint encounters assign a value to built-in native object. In the provided example we attempt to overwrite the native global String constructor function. Maintainability http://linterrors.com/js/read-only
regularExpressionLiteralCanBeConfused The “A regular expression literal can be confused with ‘/='” error is thrown when JSLint, JSHint (prior to version 1.0.0) or ESLint encounters a regular expression literal that begins with the = character. In the provided example we attempt to assign a regular expression literal to match the string “=1” to the variable x. Maintainability http://linterrors.com/js/a-regular-expression-literal-can-be-confused-with
returnStatementShouldNotContainAssignment The “Did you mean to return a conditional instead of an assignment?” error, and the alternative “Return statement should not contain assignment”, is thrown when JSHint or ESLint encounters a return statement containing an assignment expression. In the provided example we attempt to assign the result of an operation to result and also return the result of that assignment. Maintainability http://linterrors.com/js/did-you-mean-to-return-a-conditional
spacesAreHardToCount The “Spaces are hard to count. Use {a}” error is thrown when JSLint, ESLint or JSHint (prior to version 1.0.0) encounters a regular expression literal containing two or more consecutive space characters. In the provided example we define a regular expression that will match the string “three spaces” (there are three spaces between the two words). Maintainability http://linterrors.com/js/spaces-are-hard-to-count-use-a
statementLabel The “{a} is a statement label” error (and the alternative “Found identifier with the same name as label” error) are thrown when JSLint, JSHint or ESLint encounters a reference that shares an identifier with a label defined in the same scope. In the provided example there is a variable declared in the global execution context with the identifier x. Inside the test function, there is a for statement with a label that also has the identifier x. JSLint and JSHint throw this error when we attempt to refer to the x variable. Maintainability http://linterrors.com/js/a-is-a-statement-label
stringsMustUseSingleQuote The “Strings must use singlequote” and “Strings must use doublequote” errors are thrown when JSHint or ESLint encounters string literal delimited by double quote characters when the quotmark option is set to single or a string literal delimited by single quote characters when the quotmark option is set to double. In the provided example we attempt to assign a string literal to the variable x. Maintainability http://linterrors.com/js/strings-must-use-singlequote
theArrayLiteralNotationIsPreferrable The “The array literal notation [] is preferrable” error (and the alternative “Use the array literal notation []” error) are thrown when JSLint or JSHint encounter a call to the Array constructor preceded by the new operator with no arguments or more than one argument or a single argument that is not a number. Here’s an example. Maintainability http://linterrors.com/js/the-array-literal-notation-is-preferrable
theFunctionConstructorIsEval The “The Function constructor is eval” error (and the alternative “The Function constructor is a form of eval” error) is thrown when JSLint, JSHint or ESLint encounters a call to the Function constructor preceded by the new operator. Here’s a simple example which defines a function to add two numbers. Efficiency http://linterrors.com/js/the-function-constructor-is-eval
theObjectLiteralNotationIsPreferrable The “The object literal notation {} is preferrable” error (and the alternative “Use the object literal notation {}” and “Use the object literal notation {} or Object.create(null)” error) are thrown when JSLint, JSHint and ESLint encounter a call to the Object constructor preceded by the new operator. Maintainability http://linterrors.com/js/the-object-literal-notation-is-preferrable
unexpectedDanglingOfUnderscoreCharacter The “Unexpected dangling ‘_’ in ‘{a}'” error is thrown when JSLint, JSHint or ESLint encounters an identifier that begins or ends with the underscore character. JSHint will only raise this warning when the nomen option is set to true. ESLint only raises this warning for variable and function identifiers and not for object property identifiers. In the provided example we use several such identifiers. Maintainability http://linterrors.com/js/unexpected-dangling-_-in-a
unexpectedUseOfIncrementOrDecrementOperators. The “Unexpected ‘++'” error, and the alternative “Unary operator ‘++’ used”, is thrown when JSLint or ESLint encounters a use of the increment or decrement operators. In ESLint the warning is only raised if the no-plusplus option is set to 1. Maintainability http://linterrors.com/js/unexpected-plus-plus
unexpectedWith The “Unexpected ‘with'” error, and the alternatives “Don’t use ‘with'” and “Unexpected use of ‘with’ statement”, is thrown when JSLint, JSHint or ESLint encounters the with statement in code that is not running in strict mode. Maintainability http://linterrors.com/js/unexpected-with
unnecessarySemicolon The “Unnecessary semicolon” error is thrown when JSHint or ESLint encounters a semicolon following a block statement or function declaration. In the provided example we mistakenly include a semicolon after an if statement body (which is a block statement), and another after a function declaration. Maintainability http://linterrors.com/js/unnecessary-semicolon
unnecessaryUseStrict The “Unnecessary ‘use strict'” error (and the alternative “Unnecessary directive ‘{a}'” error) is thrown when JSLint, JSHint or ESLint encounters a “use strict” directive in code that is already running in strict mode. The following example features a factory function that runs in strict mode and returns another function that has its own strict mode directive. Maintainability http://linterrors.com/js/unnecessary-use-strict
unregisteredPropertyName The “Unregistered property name ‘{a}'” error (and the alternatives, “Unexpected /*property*/ ‘{a}'” and “Unexpected /*member ‘{a}'”) is thrown when JSLint or JSHint encounters a non-whitelisted property identifier. In the provided example we are attempting to create an object literal with a property named x. Maintainability http://linterrors.com/js/unregistered-property-name
unused The “Unused ‘{a}'” error, and the alternative “‘{a}’ is defined but never used”, is thrown when JSLint, JSHint or ESLint encounters an environment record binding with an identifier that is not referenced aside from its declaration. In JSHint the warning is only raised if the unused option is set to true. In the provided example there are various unused identifiers. Maintainability http://linterrors.com/js/unused-a
aIsNotDefined {a}’ is not defined. Maintainability https://github.com/jamesallardice/jslint-error-explanations/blob/master/message-articles/not-defined.md
valueMayBeOverwrittenInIE8 The “Value of ‘{a}’ may be overwritten in IE8 and earlier” error is thrown when JSHint or ESLint encounters a try…catch statement in which the catch identifier is the same as a variable or function identifer. The error is only raised when the identifer in question is declared in the same scope as the catch. In the provided example we declare a variable, a, and then use a as the identifier in the catch block. Maintainability http://linterrors.com/js/value-of-a-may-be-overwritten-in-ie8
badOption Bad option: ‘{a}’. Maintainability  
badOptionValue Bad option value. Maintainability  
jsonExpected Expected a JSON value. Maintainability  
neitherStringNorStringArray Input is neither a string nor an array of strings. Maintainability  
emptyInput Input is empty. Maintainability  
strictViolation Strict violation. Maintainability  
unbegunComment “The “”Unbegun comment”” error is thrown when JSLint or JSHint encounters a multiline comment that does not start with the character sequence /*. Here’s an example: This is a comment * but I forgot to * close it.*/ Why do I get this error? This error is raised to highlight a fatal JavaScript syntax error. Your code will not run unless you fix this issue. The ECMAScript 5 specification lists the following grammar for multiline comments (ES5 §7.4): MultiLineComment :: /* MultiLineCommentCharsopt */ We can see from the above quote that multiline comments must start with the /* characters. If you have an unbegun multiline comment a syntax error will be thrown when the interpreter reaches the end of the file. Here’s the above snippet once more, except we’ve closed the comment this time. “ Understandability  
unmatchedVariable Unmatched ‘{a}’. Maintainability  
missingPropertyName The “missing property name ‘{a}'” error (and the alternatives, “Unexpected /*property*/ ‘{a}'” and “Unexpected /*member ‘{a}'”) is thrown when we encounters a non-whitelisted property identifier. Understandability  
expectedStatement Expected to see a statement and instead saw a block. Maintainability  
eachValueOwnCaseLabel Each value should have its own case label. Maintainability  
UnrecoverableSyntaxError Unrecoverable syntax error. Accuracy  
tooManyErrors Too many errors. Accuracy  
yieldExpressionParenthesized Mozilla requires the yield expression to be parenthesized here. Maintainability  
classPropertyExpected Class properties must be methods. Expected ‘(‘ but instead saw ‘{a}’. Maintainability  
cannotSetAfterExecutable The ‘{a}’ option cannot be set after any executable code. Maintainability  
missingSemiColon “When do I get this error? The “”Missing semicolon”” error is thrown when JSHint or ESLint encounters a statement not immedietly followed by a semicolon. In the provided example we mistakenly not given a semicolon after variable declaration: function example() {    return true } Why do I get this error? This error is raised to highlight a lack of convention. Your code will work without error if you do not resolve this issue but you may be contravening coding styles and best practices.” Understandability  
incompatibleValues Incompatible values for the ‘{a}’ and ‘{b}’ linting options. Understandability  
dotFollowingNumber The “A dot following a number can be confused with a decimal point” error is thrown when JSHint encounters a numeric literal containing a decimal point as the left-hand-side of a member expression. In the provided example we attempt to assign the string representation of a number to a variable. Maintainability http://linterrors.com/js/a-dot-following-a-number-can-be-confused-with-a-decimal-point
lineBreakBeforeA Misleading line break before ‘{a}’; readers may interpret this as an expression boundary. Understandability  
unexpectedUseOfA unexpected use of a identifer token or keyword Maintainability  
confusingUseOfA make use of operator more clearly to get rid. Maintainability  
innerFunctionAtTopOfOuterFunction Inner functions should be listed at the top of the outer function.(function hoisting) Maintainability  
unreachableAfterB avoid early returns, no statement will excute after return. Maintainability  
labelAOnB If a loop contains no nested loops or switches, labeling the loop is unnecessary Maintainability  
missingSemiColonWarning All javascript statement should be terminated with semicolon(general rule) Understandability  
aIsNotAllowed using a object without declaring is not allowed Maintainability  
thisWillBeUndefined value of this in strict mode will be undefined Maintainability  
avoidEolEscaping JS didn’t support end-of-line escaping with until ES5 Maintainability  
badEscaping backslash character is used both for escaping special characters in string lierals and its used in escaping special characters in regular expressions Maintainability  
dontUseExtraZero number begin with zero and octal are disallowed in strict mode Maintainability  
unexpectedControlCharacter Unexpected control character in regular expression. Maintainability  
unexpectedEscapedCharacter Unexpected escaped character ‘{a}’ in regular expression. Maintainability  
javascriptUrl properly form href Maintainability  
unexpectedA There is a unexpected token keyword or variable. Maintainability  
weiredConstruction new keyword should be used when you need to have constructor function. Maintainability  
documentWriteCanFormEval document.write writes a DOM after it is considered to be complete Maintainability  
missingNewPrefixForConstructor function starting with capital letter should be constructor therefore to be called with new keyword Understandability  
blocksAreNested Blocks are nested too deeply. ({a}) Maintainability  
setterDefinedWithoutGetter Setter should be defined when there is a getter Maintainability  
unexpectedComma The “Extra comma. (it breaks older versions of IE)” error (and the alternative “Trailing comma” and “Unexpected ‘,’ errors”) are thrown. A comma following the final element of an array literal or a comma following the final value in an object literal. Understandability  
expectedString The “Expected a string and instead saw ‘{a}'” error is thrown when we encounters a comparison operator in which one of the operands is a typeof expression and the other operand is not a string literal. Maintainability  
keyMayProduceUnexpectedResult This error is raised to highlight code that may not work as you expect and could possibly cause a fatal JavaScript syntax error. In strict mode, your code will raise a syntax error. Otherwise, it will run without error but you will most likely get unexpected results. Maintainability  
characterMayGetDeleted This character may get silently deleted by one or more browsers. JSHint warns about unsafe characters when we include unicode characters, such as the “smart” quotes. Maintainability  
lineTooLong Line is too long. Maintainability  
propertyDeprecated When an object is created __proto__ is set to the original prototype property of the object’s constructor function. getPrototypeOf is the preferred method of getting “the prototype”. Maintainability  
availableInEs {a}’ is available in ES{b} (use ‘esversion: {b}’) or Mozilla JS extensions (use moz). It is available is ES6 and not in ES5. Maintainability  
identifierNotCamleCase Identifier ‘{a}’ is not in camel case. Understandability  
scriptUrl Using javascript: URLs is considered by some as a form of eval. Code passed in javascript: URLs has to be parsed and evaluated by the browser in the same way that eval is processed. Understandability  
stringsMustUseDoublequote Strings must use doublequote. Maintainability  
controlCharacterInString Control characters are special, invisible characters in the ASCII range 0-31. These characters are rarely used in JavaScript strings so a regular expression containing these characters is most likely a mistake. Maintainability  
avoidA ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let and const keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes Maintainability  
expectedASawB With this message, we are reporting that is has encountered one expression when it expected to see another.

One common cause of this message is when we encounters the equality operator ( ‘==’), and reports that it expects an identity operator (‘===’)

Maintainability  
availableOnlyInMozilla There are some expressions and statements which are only available with Mozilla JavaScript extensions (use moz option), for example ‘function closure expressions’, ‘let block’ etc. Maintainability  
availableOnlyInEs This expression is available in only ES6 and above. Use ES6 and above. For example ‘arrow’ functions. Maintainability  
alreadyDefinedInOuterScope In ECMAScript 2015, let will hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a “temporal dead zone” from the start of the block until the declaration is processed. Maintainability  
nonBreakingSpaces Multiple spaces in a row that are not used for indentation are typically mistakes. Understandability  
unnecessaryGroupingOperator Unnecessary grouping operator. Understandability  
unexpectedUseOfCommaOperator The comma operator includes multiple expressions where only one is expected. It evaluates each operand from left to right and returns the value of the last operand. However, this frequently obscures side effects, and its use is often an accident. Maintainability  
emptyArrayElements Arrays may contain empty slots, most frequently due to multiple commas being used in an array literal. Maintainability  
definedInFutureVersion {a}’ is defined in a future version of JavaScript. Use a different variable name to avoid migration issues. Maintainability  
invalidElementAfterRestElement It is good practice to have rest parameter at the end of parameter list. The rest parameters gather all remaining arguments, so the following has no sense. The …rest must always be last. Maintainability  
invalidParameterAfterRestParameter Rest parameter passed to function should end correctly, since a trailing comma after a spread rest property is a SyntaxError. Maintainability  
declarationsAreForbidden In ES6 use of`var` declarations are forbidden. Use `let` or `const` instead. Maintainability  
invalidForLoop For loop should be ran against non empty array or object. Maintainability  
optionOnlyAvailableWhenLinting The ‘{a}’ option is only available when linting ECMAScript {b} code. Maintainability  
mayNotBeSupported {a} may not be supported by non-browser environments. Maintainability  
mustBeInFunctionScope Variable used should be function scope Maintainability  
emptyDestructing Empty destructuring: this is unnecessary and can be removed. Maintainability  
regularParametersPosition Regular parameters should not come after default parameters. It is recommended to put default parameter as a last parameter. Maintainability  
functionExpressionShouldNotBeSecondOperand Function expressions should not be used as the second operand to instanceof. Maintainability  
emptyACanBeRemoved Empty block statements, while not technically errors, usually occur due to refactoring that wasn’t completed. They can cause confusion when reading code. Understandability  
emptyAReplacingWithImportB Empty {a}: consider replacing with `import ‘{b}’;`. Consider replacing empty with relevant block/expresssion. Maintainability  
commaWarnings Always put comma at the end of statement Understandability  

ESLint code checker

ESLint is an open source static code analyser for identifying and reporting errors in JavaScript programs. Visit their website for more detailed information on ESLint and the ruleset found below.


High level issues

Rule Description KPI URL
constructor-super Constructors of derived classes must call super(). Constructors of non derived classes must not call super(). If this is not observed, the JavaScript engine will raise a runtime error. This rule checks whether or not there is a valid super() call. Robustness https://eslint.org/docs/rules/constructor-super
for-direction A for loop with a stop condition that can never be reached, such as one with a counter that moves in the wrong direction, will run infinitely. While there are occasions when an infinite loop is intended, the convention is to construct such loops as while loops. More typically, an infinite for loop is a bug. Robustness https://eslint.org/docs/rules/for-direction
no-const-assign A constant expression (for example, a literal) as a test condition might be a typo or development trigger for a specific behavior. For example, the following code looks as if it is not ready for production. Maintainability https://eslint.org/docs/rules/no-constant-condition
no-control-regex Control characters are special, invisible characters in the ASCII range 0-31. These characters are rarely used in JavaScript strings so a regular expression containing these characters is most likely a mistake. Maintainability https://eslint.org/docs/rules/no-control-regex
no-debugger The debugger statement is used to tell the executing JavaScript environment to stop execution and start up a debugger at the current point in the code. This has fallen out of favor as a good practice with the advent of modern debugging and development tools. Production code should definitely not contain debugger, as it will cause the browser to stop executing code and open an appropriate debugger. Maintainability https://eslint.org/docs/rules/no-debugger
no-dupe-args If more than one parameter has the same name in a function definition, the last occurrence “shadows” the preceding occurrences. A duplicated name might be a typing error. Maintainability https://eslint.org/docs/rules/no-dupe-args
no-dupe-class-members If there are declarations of the same name in class members, the last declaration overwrites other declarations silently. It can cause unexpected behaviors. Maintainability https://eslint.org/docs/rules/no-dupe-class-members
no-dupe-keys Multiple properties with the same key in object literals can cause unexpected behavior in your application. Maintainability https://eslint.org/docs/rules/no-dupe-keys
no-global-assign JavaScript environments contain a number of built-in global variables, such as window in browsers and process in Node.js. In almost all cases, you don’t want to assign a value to these global variables as doing so could result in losing access to important functionality. For example, you probably don’t want to do this in browser code:

“window = {};”

While examples such as window are obvious, there are often hundreds of built-in global objects provided by JavaScript environments. It can be hard to know if you’re assigning to a global variable or not.

Robustness https://eslint.org/docs/rules/no-global-assign
no-obj-calls ECMAScript provides several global objects that are intended to be used as-is. Some of these objects look as if they could be constructors due their capitalization (such as Math and JSON) but will throw an error if you try to execute them as functions. Maintainability https://eslint.org/docs/rules/no-obj-calls
no-process-env The process.env object in Node.js is used to store deployment/configuration parameters. Littering it through out a project could lead to maintenance issues as it’s another kind of global dependency. As such, it could lead to merge conflicts in a multi-user setup and deployment issues in a multi-server setup. Instead, one of the best practices is to define all those parameters in a single configuration/settings file which could be accessed throughout the project. Robustness https://eslint.org/docs/rules/no-process-env
no-unreachable Because the return, throw, break, and continue statements unconditionally exit a block of code, any statements after them cannot be executed. Unreachable statements are usually a mistake. Efficiency https://eslint.org/docs/rules/no-unreachable

Medium level issues

Rule Description KPI URL
block-scoped-var The block-scoped-var rule generates warnings when variables are used outside of the block in which they were defined. This emulates C-style block scope. Analyzability https://eslint.org/docs/rules/block-scoped-var
callback-return The callback pattern is at the heart of most I/O and event-driven programming in JavaScript. To prevent calling the callback multiple times it is important to return anytime the callback is triggered outside of the main function body. Neglecting this technique often leads to issues where you do something more than once. For example, in the case of an HTTP request, you may try to send HTTP headers more than once leading Node.js to throw a Can’t render headers after they are sent to the client. error. Accuracy https://eslint.org/docs/rules/callback-return
default-case Some code conventions require that all switch statements have a default case, even if the default case is empty. The thinking is that it’s better to always explicitly state what the default behavior should be so that it’s clear whether or not the developer forgot to include the default behavior by mistake. Other code conventions allow you to skip the default case so long as there is a comment indicating the omission is intentional. Once again, the intent here is to show that the developer intended for there to be no default behavior. Robustness https://eslint.org/docs/rules/default-case
getter-return The get syntax binds an object property to a function that will be called when that property is looked up. It was first introduced in ECMAScript 5. Note that every getter is expected to return a value.

Maintainability https://eslint.org/docs/rules/getter-return
max-lines undefinedSome people consider large files a code smell. Large files tend to do a lot of things and can make it hard following what’s going. While there is not an objective maximum number of lines considered acceptable in a file, most people would agree it should not be in the thousands. Recommendations usually range from 100 to 500 lines. Understandability https://eslint.org/docs/rules/max-lines
no-await-in-loop Performing an operation on each element of an iterable is a common task. However, performing an await as part of each operation is an indication that the program is not taking full advantage of the parallelization benefits of async/await.

Usually, the code should be refactored to create all the promises at once, then get access to the results using Promise.all(). Otherwise, each successive operation will not start until the previous one has completed.

Maintainability https://eslint.org/docs/rules/no-await-in-loop
no-class-assign ClassDeclaration creates a variable, and we can modify the variable. But the modification is a mistake in most cases.

Maintainability https://eslint.org/docs/rules/no-class-assign
no-compare-neg-zero The rule should warn against code that tries to compare against -0, since that will not work as intended. That is, code like x === -0 will pass for both +0 and -0. The author probably intended Object.is(x, -0). Analyzability https://eslint.org/docs/rules/no-compare-neg-zero
no-cond-assign In conditional statements, it is very easy to mistype a comparison operator (such as ==) as an assignment operator (such as =). mThere are valid reasons to use assignment operators in conditional statements. However, it can be difficult to tell whether a specific assignment was intentional. Maintainability https://eslint.org/docs/rules/no-cond-assign
no-constant-condition We cannot modify variables that are declared using const keyword.
It will raise a runtime error. Under non ES2015 environment, it might be ignored merely.
Maintainability https://eslint.org/docs/rules/no-const-assign
no-delete-var The purpose of the delete operator is to remove a property from an object. Using the delete operator on a variable might lead to unexpected behavior. Maintainability https://eslint.org/docs/rules/no-delete-var
no-div-regex Require regex literals to escape division operators. Maintainability https://eslint.org/docs/rules/no-div-regex
no-duplicate-case If a switch statement has duplicate test expressions in case clauses, it is likely that a programmer copied a case clause but forgot to change the test expression. Maintainability https://eslint.org/docs/rules/no-duplicate-case
no-empty-character-class Because empty character classes in regular expressions do not match anything, they might be typing mistakes.

var foo = /^abc[]/;

Maintainability https://eslint.org/docs/rules/no-empty-character-class
no-empty-pattern When using destructuring, it’s possible to create a pattern that has no effect. This happens when empty curly braces are used to the right of an embedded object destructuring pattern. Maintainability https://eslint.org/docs/rules/no-empty-pattern
no-eval JavaScript’s eval() function is potentially dangerous and is often misused. Using eval() on untrusted code can open a program up to several different injection attacks. The use of eval() in most contexts can be substituted for a better, alternative approach to a problem. Security https://eslint.org/docs/rules/no-eval
no-ex-assign If a catch clause in a try statement accidentally (or purposely) assigns another value to the exception parameter, it impossible to refer to the error from that point on. Since there is no arguments object to offer alternative access to this data, assignment of the parameter is absolutely destructive. Robustness https://eslint.org/docs/rules/no-ex-assign
no-extra-boolean-cast In contexts such as an if statement’s test where the result of the expression will already be coerced to a Boolean, casting to a Boolean via double negation (!!) or a Boolean call is unnecessary. Maintainability https://eslint.org/docs/rules/no-extra-boolean-cast
no-fallthrough The switch statement in JavaScript is one of the more error-prone constructs of the language thanks in part to the ability to “fall through” from one case to the next. That works fine when you don’t want a fallthrough, but what if the fallthrough is intentional, there is no way to indicate that in the language. It’s considered a best practice to always indicate when a fallthrough is intentional using a comment which matches the //falls through regular expression. Maintainability https://eslint.org/docs/rules/no-fallthrough
no-func-assign JavaScript functions can be written as a FunctionDeclaration function foo() { … } or as a FunctionExpression var foo = function() { … };. While a JavaScript interpreter might tolerate it, overwriting/reassigning a function written as a FunctionDeclaration is often indicative of a mistake or issue. Maintainability https://eslint.org/docs/rules/no-func-assign
no-invalid-regexp An invalid pattern in a regular expression literal is a SyntaxError when the code is parsed, but an invalid string in RegExp constructors throws a SyntaxError only when the code is executed. Maintainability https://eslint.org/docs/rules/no-invalid-regexp
no-irregular-whitespace Invalid or irregular whitespace causes issues with ECMAScript 5 parsers and also makes code harder to debug in a similar nature to mixed tabs and spaces.

Various whitespace characters can be inputted by programmers by mistake for example from copying or keyboard shortcuts. Pressing Alt + Space on macOS adds in a non breaking space character for example.

Known issues these spaces cause:
1.  Zero Width Space
1a.  Is NOT considered a separator for tokens and is often parsed as an Unexpected token ILLEGAL
1b. Is NOT shown in modern browsers making code repository software expected to resolve the visualization
2. Line Separator
2a. Is NOT a valid character within JSON which would cause parse errors

Maintainability https://eslint.org/docs/rules/no-irregular-whitespace
no-labels Labeled statements in JavaScript are used in conjunction with break and continue to control flow around multiple loops. While convenient in some cases, labels tend to be used only rarely and are frowned upon by some as a remedial form of flow control that is more error prone and harder to understand. Maintainability https://eslint.org/docs/rules/no-labels
no-loop-func Writing functions within loops tends to result in errors due to the way the function creates a closure around the loop. For example: Maintainability https://eslint.org/docs/rules/no-loop-func
no-mixed-requires In the Node.js community it is often customary to separate initializations with calls to require modules from other variable declarations, sometimes also grouping them by the type of module. This rule helps you enforce this convention. Maintainability https://eslint.org/docs/rules/no-mixed-requires
no-native-reassign JavaScript environments contain a number of built-in global variables, such as window in browsers and process in Node.js. In almost all cases, you don’t want to assign a value to these global variables as doing so could result in losing access to important functionality. For example, you probably don’t want to do this in browser code:

“window = {};”

While examples such as window are obvious, there are often hundreds of built-in global objects provided by JavaScript environments. It can be hard to know if you’re assigning to a global variable or not.

Maintainability https://eslint.org/docs/rules/no-native-reassign
no-new-symbol Symbol is not intended to be used with the new operator, but to be called as a function. Maintainability https://eslint.org/docs/rules/no-new-symbol
no-plusplus Because the unary ++ and — operators are subject to automatic semicolon insertion, differences in whitespace can change semantics of source code.

// i = 11, j = 20
var i = 10;
var j = 20;

i ++
j

// i = 10, j = 21
var i = 10;
var j = 20;

i
++
j

Robustness https://eslint.org/docs/rules/no-plusplus
no-process-exit The process.exit() method in Node.js is used to immediately stop the Node.js process and exit. This is a dangerous operation because it can occur in any method at any point in time, potentially stopping a Node.js application completely when an error occurs.

If you are using process.exit() only for specifying the exit code, you can set process.exitCode (introduced in Node.js 0.11.8) instead.

Robustness https://eslint.org/docs/rules/no-process-exit
no-prototype-builtins In ECMAScript 5.1, Object.create was added, which enables the creation of objects with a specified [[Prototype]]. Object.create(null) is a common pattern used to create objects that will be used as a Map. This can lead to errors when it is assumed that objects will have properties from Object.prototype. This rule prevents calling Object.prototype methods directly from an object. Maintainability https://eslint.org/docs/rules/no-prototype-builtins
no-redeclare In JavaScript, it’s possible to redeclare the same variable name using var. This can lead to confusion as to where the variable is actually declared and initialized. Maintainability https://eslint.org/docs/rules/no-redeclare
no-regex-spaces Regular expressions can be very complex and difficult to understand, which is why it’s important to keep them as simple as possible in order to avoid mistakes. One of the more error-prone things you can do with a regular expression is to use more than one space. It’s better to use only one space and then specify how many spaces are expected. Maintainability https://eslint.org/docs/rules/no-regex-spaces
no-self-assign Self assignments have no effect, so probably those are an error due to incomplete refactoring. Those indicate that what you should do is still remaining. Maintainability https://eslint.org/docs/rules/no-self-assign
no-sequences The comma operator includes multiple expressions where only one is expected. It evaluates each operand from left to right and returns the value of the last operand. However, this frequently obscures side effects, and its use is often an accident. Maintainability https://eslint.org/docs/rules/no-sequences
no-shadow Shadowing is the process by which a local variable shares the same name as a variable in its containing scope. Maintainability https://eslint.org/docs/rules/no-shadow
no-shadow-restricted-names ES5 §15.1.1 Value Properties of the Global Object (NaN, Infinity, undefined) as well as strict mode restricted identifiers eval and arguments are considered to be restricted names in JavaScript. Defining them to mean something else can have unintended consequences and confuse others reading the code. Maintainability https://eslint.org/docs/rules/no-shadow-restricted-names
no-sparse-arrays Sparse arrays contain empty slots, most frequently due to multiple commas being used in an array literal, such as:

var items = [,,];

While the items array in this example has a length of 2, there are actually no values in items[0] or items[1]. The fact that the array literal is valid with only commas inside, coupled with the length being set and actual item values not being set, make sparse arrays confusing for many developers.

The confusion around sparse arrays defined in this manner is enough that it’s recommended to avoid using them unless you are certain that they are useful in your code.

Maintainability https://eslint.org/docs/rules/no-sparse-arrays
no-this-before-super In the constructor of derived classes, if this/super are used before super() calls, it raises a reference error. This rule checks this/super keywords in constructors, then reports those that are before super(). Maintainability https://eslint.org/docs/rules/no-this-before-super
no-undef This rule can help you locate potential ReferenceErrors resulting from misspellings of variable and parameter names, or accidental implicit globals (for example, from forgetting the var keyword in a for loop initializer). Maintainability https://eslint.org/docs/rules/no-undef
no-undef-init The undefined variable in JavaScript is actually a property of the global object. As such, in ECMAScript 3 it was possible to overwrite the value of undefined. While ECMAScript 5 disallows overwriting undefined, it’s still possible to shadow undefined. Because undefined can be overwritten or shadowed, reading undefined can give an unexpected value. (This is not the case for null, which is a keyword that always produces the same value.) To guard against this, you can avoid all uses of undefined, which is what some style guides recommend and what this rule enforces.

Those style guides then also recommend:
1. Variables that should be undefined are simply left uninitialized. (All uninitialized variables automatically get the value of undefined in JavaScript.)
2. Checking if a value is undefined should be done with typeof.
3. Using the void operator to generate the value of undefined if necessary.

As an alternative, you can use the no-global-assign and no-shadow-restricted-names rules to prevent undefined from being shadowed or assigned a different value. This ensures that undefined will always hold its original, expected value.

Maintainability https://eslint.org/docs/rules/no-undefined
no-unexpected-multiline Semicolons are usually optional in JavaScript, because of automatic semicolon insertion (ASI). You can require or disallow semicolons with the semi rule.

The rules for ASI are relatively straightforward: As once described by Isaac Schlueter, a newline character always ends a statement, just like a semicolon, except where one of the following is true:
1. The statement has an unclosed paren, array literal, or object literal or ends in some other way that is not a valid way to end a statement. (For instance, ending with . or ,.)
2. The line is — or ++ (in which case it will decrement/increment the next token.)
3. It is a for(), while(), do, if(), or else, and there is no {
4.The next line starts with [, (, +, *, /, -, ,, ., or some other binary operator that can only be found between two tokens in a single expression.

In the exceptions where a newline does not end a statement, a typing mistake to omit a semicolon causes two unrelated consecutive lines to be interpreted as one expression. Especially for a coding style without semicolons, readers might overlook the mistake. Although syntactically correct, the code might throw exceptions when it is executed.

Maintainability https://eslint.org/docs/rules/no-unexpected-multiline
no-unmodified-loop-condition Variables in a loop condition often are modified in the loop.
If not, it’s possibly a mistake.
Robustness https://eslint.org/docs/rules/no-unmodified-loop-condition
no-unsafe-finally JavaScript suspends the control flow statements of try and catch blocks until the execution of finally block finishes. So, when return, throw, break, or continue is used in finally, control flow statements inside try and catch are overwritten, which is considered as unexpected behavior. Maintainability https://eslint.org/docs/rules/no-unsafe-finally
no-unused-labels Labels that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such labels take up space in the code and can lead to confusion by readers. Maintainability https://eslint.org/docs/rules/no-unused-labels
no-useless-escape Escaping non-special characters in strings, template literals, and regular expressions doesn’t have any effect. Maintainability https://eslint.org/docs/rules/no-useless-escape
require-yield This rule generates warnings for generator functions that do not have the yield keyword. Maintainability https://eslint.org/docs/rules/require-yield
strict A strict mode directive is a “use strict” literal at the beginning of a script or function body. It enables strict mode semantics.

When a directive occurs in global scope, strict mode applies to the entire script. When a directive occurs at the beginning of a function body, strict mode applies only to that function, including all contained functions. In the CommonJS module system, a hidden function wraps each module and limits the scope of a “global” strict mode directive. In ECMAScript modules, which always have strict mode semantics, the directives are unnecessary.

Maintainability https://eslint.org/docs/rules/strict
use-isnan In JavaScript, NaN is a special value of the Number type. It’s used to represent any of the “not-a-number” values represented by the double-precision 64-bit format as specified by the IEEE Standard for Binary Floating-Point Arithmetic.

Because NaN is unique in JavaScript by not being equal to anything, including itself, the results of comparisons to NaN are confusing. Therefore, use Number.isNaN() or global isNaN() functions to test whether a value is NaN.

Maintainability https://eslint.org/docs/rules/use-isnan
valid-typeof For a vast majority of use cases, the result of the typeof operator is one of the following string literals: “undefined”, “object”, “boolean”, “number”, “string”, “function” and “symbol”. It is usually a typing mistake to compare the result of a typeof operator to other string literals. Maintainability https://eslint.org/docs/rules/valid-typeof

Low level issues

Rule Description KPI URL
accessor-pairs It’s a common mistake in JavaScript to create an object with just a setter for a property but never have a corresponding getter defined for it. Without a getter, you cannot read the property, so it ends up not being used. Maintainability https://eslint.org/docs/rules/accessor-pairs
array-bracket-newline A number of style guides require or disallow line breaks inside of array brackets. Understandability https://eslint.org/docs/rules/array-bracket-newline
array-bracket-spacing A number of style guides require or disallow spaces between array brackets and other tokens. This rule applies to both array literals and destructuring assignments (ECMAScript 6). Understandability https://eslint.org/docs/rules/array-bracket-spacing
array-callback-return Array has several methods for filtering, mapping, and folding. If we forget to write return statement in a callback of those, it’s probably a mistake. Accuracy https://eslint.org/docs/rules/array-callback-return
array-element-newline A number of style guides require or disallow line breaks between array elements. Understandability https://eslint.org/docs/rules/array-element-newline
arrow-body-style Arrow functions have two syntactic forms for their function bodies. They may be defined with a block body (denoted by curly braces) () => { … } or with a single expression () => …, whose value is implicitly returned. Understandability https://eslint.org/docs/rules/arrow-body-style
arrow-parens Arrow functions can omit parentheses when they have exactly one parameter. In all other cases the parameter(s) must be wrapped in parentheses. This rule enforces the consistent use of parentheses in arrow functions. Understandability https://eslint.org/docs/rules/arrow-parens
arrow-spacing This rule normalize style of spacing before/after an arrow function’s arrow(=>). Understandability https://eslint.org/docs/rules/arrow-spacing
block-spacing This rule enforces consistent spacing inside an open block token and the next token on the same line. This rule also enforces consistent spacing inside a close block token and previous token on the same line. Understandability https://eslint.org/docs/rules/block-spacing
brace-style Brace style is closely related to indent style in programming and describes the placement of braces relative to their control statement and body. There are probably a dozen, if not more, brace styles in the world. The one true brace style is one of the most common brace styles in JavaScript, in which the opening brace of a block is placed on the same line as its corresponding statement or declaration.While no style is considered better than the other, most developers agree that having a consistent style throughout a project is important for its long-term maintainability. Understandability https://eslint.org/docs/rules/brace-style
camelcase When it comes to naming variables, style guides generally fall into one of two camps: camelcase (variableName) and underscores (variable_name). This rule focuses on using the camelcase approach. If your style guide calls for camelCasing your variable names, then this rule is for you! Understandability https://eslint.org/docs/rules/camelcase
capitalized-comments Comments are useful for leaving information for future developers. In order for that information to be useful and not distracting, it is sometimes desirable for comments to follow a particular style. One element of comment formatting styles is whether the first word of a comment should be capitalized or lowercase. In general, no comment style is any more or less valid than any others, but many developers would agree that a consistent style can improve a project’s maintainability. Understandability https://eslint.org/docs/rules/capitalized-comments
class-methods-use-this If a class method does not use this, it can sometimes be made into a static function. If you do convert the method into a static function, instances of the class that call that particular method have to be converted to a static call as well (MyClass.callStaticMethod()) Maintainability https://eslint.org/docs/rules/class-methods-use-this
comma-dangle Trailing commas in object literals are valid according to the ECMAScript 5 (and ECMAScript 3!) spec. However, IE8 (when not in IE8 document mode) and below will throw an error when it encounters trailing commas in JavaScript. Trailing commas simplify adding and removing items to objects and arrays, since only the lines you are modifying must be touched. Another argument in favor of trailing commas is that it improves the clarity of diffs when an item is added or removed from an object or array. Understandability https://eslint.org/docs/rules/comma-dangle
comma-spacing Spacing around commas improve readability of a list of items. Although most of the style guidelines for languages prescribe adding a space after a comma and not before it, it is subjective to the preferences of a project. Understandability https://eslint.org/docs/rules/comma-spacing
comma-style The Comma Style rule enforces styles for comma-separated lists. There are two comma styles primarily used in JavaScript:
1. The standard style, in which commas are placed at the end of the current line
2. Comma First style, in which commas are placed at the start of the next line

One of the justifications for using Comma First style is that it can help track missing and trailing commas. These are problematic because missing commas in variable declarations can lead to the leakage of global variables and trailing commas can lead to errors in older versions of IE.

Understandability https://eslint.org/docs/rules/comma-style
complexity Cyclomatic complexity measures the number of linearly independent paths through a program’s source code. This rule allows setting a cyclomatic complexity threshold. Maintainability https://eslint.org/docs/rules/complexity
computed-property-spacing While formatting preferences are very personal, a number of style guides require or disallow spaces between computed properties in the following situations: Understandability https://eslint.org/docs/rules/computed-property-spacing
consistent-return Unlike statically-typed languages which enforce that a function returns a specified type of value, JavaScript allows different code paths in a function to return different types of values.

A confusing aspect of JavaScript is that a function returns undefined if any of the following are true:
1. it does not execute a return statement before it exits
2. it executes return which does not specify a value explicitly
3. it executes return undefined
4. it executes return void followed by an expression (for example, a function call)
5.it executes return followed by any other expression which evaluates to undefined

If any code paths in a function return a value explicitly but some code path do not return a value explicitly, it might be a typing mistake, especially in a large function. In the following example:
1. a code path through the function returns a Boolean value true
2.  another code path does not return a value explicitly, therefore returns undefined implicitly

Maintainability https://eslint.org/docs/rules/consistent-return
consistent-this It is often necessary to capture the current execution context in order to make it available subsequently. There are many commonly used aliases for this such as that, self or me. It is desirable to ensure that whichever alias the team agrees upon is used consistently throughout the application. Understandability https://eslint.org/docs/rules/consistent-this
curly JavaScript allows the omission of curly braces when a block contains only one statement. However, it is considered by many to be best practice to never omit curly braces around blocks, even when they are optional, because it can lead to bugs and reduces code clarity. There are, however, some who prefer to only use braces when there is more than one statement to be executed. Maintainability https://eslint.org/docs/rules/curly
dot-location JavaScript allows you to place newlines before or after a dot in a member expression. Consistency in placing a newline before or after the dot can greatly increase readability. Understandability https://eslint.org/docs/rules/dot-location
dot-notation In JavaScript, one can access properties using the dot notation (foo.bar) or square-bracket notation (foo[“bar”]). However, the dot notation is often preferred because it is easier to read, less verbose, and works better with aggressive JavaScript minimizers. Understandability https://eslint.org/docs/rules/dot-notation
eol-last Trailing newlines in non-empty files are a common UNIX idiom. Benefits of trailing newlines include the ability to concatenate or append to files as well as output files to the terminal without interfering with shell prompts. Maintainability https://eslint.org/docs/rules/eol-last
eqeqeq It is considered good practice to use the type-safe equality operators === and !== instead of their regular counterparts == and !=. The reason for this is that == and != do type coercion which follows the rather obscure Abstract Equality Comparison Algorithm.
For instance, the following statements are all considered true:

1. [] == false
2. [] == ![]
3. 3 == “03”

If one of those occurs in an innocent-looking statement such as a == b the actual problem is very difficult to spot.

Robustness https://eslint.org/docs/rules/eqeqeq
func-call-spacing When calling a function, developers may insert optional whitespace between the function’s name and the parentheses that invoke it. Understandability https://eslint.org/docs/rules/func-call-spacing
func-name-matching This rule requires function names to match the name of the variable or property to which they are assigned. The rule will ignore property assignments where the property name is a literal that is not a valid identifier in the ECMAScript version specified in your configuration (default ES5). Understandability https://eslint.org/docs/rules/func-name-matching
func-names A pattern that’s becoming more common is to give function expressions names to aid in debugging.

Foo.prototype.bar = function bar() {};

Adding the second bar in the above example is optional.  If you leave off the function name then when the function throws an exception you are likely to get something similar to anonymous function in the stack trace.  If you provide the optional name for a function expression then you will get the name of the function expression in the stack trace.

Maintainability https://eslint.org/docs/rules/func-names
func-style There are two ways of defining functions in JavaScript: function declarations and function expressions. Declarations contain the function keyword first, followed by a name and then its arguments and the function body/

The primary difference between function declarations and function expressions is that declarations are hoisted to the top of the scope in which they are defined, which allows you to write code that uses the function before its declaration.

For function expressions, you must define the function before it is used, otherwise it causes an error.

Due to these different behaviors, it is common to have guidelines as to which style of function should be used. There is really no correct or incorrect choice here, it is just a preference.

Understandability https://eslint.org/docs/rules/func-style
function-paren-newline Many style guides require or disallow newlines inside of function parentheses. Understandability https://eslint.org/docs/rules/function-paren-newline
generator-star-spacing Generators are a new type of function in ECMAScript 6 that can return multiple values over time. These special functions are indicated by placing an * after the function keyword. To keep a sense of consistency when using generators this rule enforces a single position for the *. Maintainability https://eslint.org/docs/rules/generator-star-spacing
global-require In Node.js, module dependencies are included using the require() function, such as:

var fs = require(“fs”);

While require() may be called anywhere in code, some style guides prescribe that it should be called only in the top level of a module to make it easier to identify dependencies. For instance, it’s arguably harder to identify dependencies when they are deeply nested inside of functions and other statements:

function foo() {
if (condition) {
var fs = require(“fs”);
}
}

Since require() does a synchronous load, it can cause performance problems when used in other locations. Further, ES6 modules mandate that import and export statements can only occur in the top level of the module’s body.

Maintainability https://eslint.org/docs/rules/global-require
guard-for-in Looping over objects with a for in loop will include properties that are inherited through the prototype chain. This behavior can lead to unexpected items in your for loop. Note that simply checking foo.hasOwnProperty(key) is likely to cause an error in some cases; see no-prototype-builtins. Maintainability https://eslint.org/docs/rules/guard-for-in
handle-callback-err In Node.js, a common pattern for dealing with asynchronous behavior is called the callback pattern. This pattern expects an Error object or null as the first argument of the callback. Forgetting to handle these errors can lead to some really strange behavior in your application. Robustness https://eslint.org/docs/rules/handle-callback-err
id-blacklist Bad names can lead to hard-to-decipher code. Generic names, such as data, don’t infer much about the code and the values it receives. This rule allows you to configure a blacklist of bad identifier names, that you don’t want to see in your code. Maintainability https://eslint.org/docs/rules/id-blacklist
id-length Very short identifier names like e, x, _t or very long ones like hashGeneratorResultOutputContainerObject can make code harder to read and potentially less maintainable. To prevent this, one may enforce a minimum and/or maximum identifier length. Understandability https://eslint.org/docs/rules/id-length
id-match Naming things consistently in a project is an often underestimated aspect of code creation. When done correctly, it can save your team hours of unnecessary head scratching and misdirections. This rule allows you to precisely define and enforce the variables and function names on your team should use. No more limiting yourself to camelCase, snake_case, PascalCase or oHungarianNotation. Id-match has all your needs covered! Understandability https://eslint.org/docs/rules/id-match
implicit-arrow-linebreak An arrow function body can contain an implicit return as an expression instead of a block body. It can be useful to enforce a consistent location for the implicitly returned expression. Understandability https://eslint.org/docs/rules/implicit-arrow-linebreak
indent There are several common guidelines which require specific indentation of nested blocks and statements.

These are the most common scenarios recommended in different style guides:
1. Two spaces, not longer and no tabs: Google, npm, Node.js, Idiomatic, Felix
2. Tabs: jQuery
3. Four spaces: Crockford

Understandability https://eslint.org/docs/rules/indent
indent-legacy ESLint 4.0.0 introduced a rewrite of the indent rule, which now reports more errors than it did in previous versions. To ease the process of migrating to 4.0.0, the indent-legacy rule was introduced as a snapshot of the indent rule from ESLint 3.x. If your build is failing after the upgrade to 4.0.0, you can disable indent and enable indent-legacy as a quick fix. Eventually, you should switch back to the indent rule to get bugfixes and improvements in future versions. Understandability https://eslint.org/docs/rules/indent-legacy
init-declarations In JavaScript, variables can be assigned during declaration, or at any point afterwards using an assignment statement. For example, in the following code, foo is initialized during declaration, while bar is initialized later. Maintainability https://eslint.org/docs/rules/init-declarations
jsx-quotes JSX attribute values can contain string literals, which are delimited with single or double quotes.

 

Unlike string literals in JavaScript, string literals within JSX attributes can’t contain escaped quotes. If you want to have e.g. a double quote within a JSX attribute value, you have to use single quotes as string delimiter.

 

Maintainability https://eslint.org/docs/rules/jsx-quotes
key-spacing This rule enforces spacing around the colon in object literal properties. It can verify each property individually, or it can ensure horizontal alignment of adjacent properties in an object literal. Understandability https://eslint.org/docs/rules/key-spacing
keyword-spacing Keywords are syntax elements of JavaScript, such as function and if. These identifiers have special meaning to the language and so often appear in a different color in code editors. As an important part of the language, style guides often refer to the spacing that should be used around keywords. For example, you might have a style guide that says keywords should be always surrounded by spaces, which would mean if-else statements must look like this:

if (foo) {
// …
} else {
// …
}

Of course, you could also have a style guide that disallows spaces around keywords.

Understandability https://eslint.org/docs/rules/keyword-spacing
line-comment-position Line comments can be positioned above or beside code. This rule helps teams maintain a consistent style.

// above comment
var foo = “bar”; // beside comment

Maintainability https://eslint.org/docs/rules/line-comment-position
linebreak-style When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that different line endings are written by either of the mentioned (might especially happen when using the windows and mac versions of SourceTree together).

The linebreaks (new lines) used in windows operating system are usually carriage returns (CR) followed by a line feed (LF) making it a carriage return line feed (CRLF) whereas Linux and Unix use a simple line feed (LF). The corresponding control sequences are “n” (for LF) and “rn” for (CRLF).

Many versioning systems (like git and subversion) can automatically ensure the correct ending. However to cover all contingencies, you can activate this rule.

Understandability https://eslint.org/docs/rules/linebreak-style
lines-around-comment Many style guides require empty lines before or after comments. The primary goal of these rules is to make the comments easier to read and improve readability of the code. Understandability https://eslint.org/docs/rules/lines-around-comment
lines-around-directive Directives are used in JavaScript to indicate to the execution environment that a script would like to opt into a feature such as “strict mode”. Directives are grouped together in a directive prologue at the top of either a file or function block and are applied to the scope in which they occur. Maintainability https://eslint.org/docs/rules/lines-around-directive
lines-between-class-members This rule improves readability by enforcing lines between class members. It will not check empty lines before the first member and after the last member, since that is already taken care of by padded-blocks. Understandability https://eslint.org/docs/rules/lines-between-class-members
max-depth Many developers consider code difficult to read if blocks are nested beyond a certain depth. Understandability https://eslint.org/docs/rules/max-depth
max-len Very long lines of code in any language can be difficult to read. In order to aid in readability and maintainability many coders have developed a convention to limit lines of code to X number of characters (traditionally 80 characters). Understandability https://eslint.org/docs/rules/max-len
max-nested-callbacks Many JavaScript libraries use the callback pattern to manage asynchronous operations. A program of any complexity will most likely need to manage several asynchronous operations at various levels of concurrency. A common pitfall that is easy to fall into is nesting callbacks, which makes code more difficult to read the deeper the callbacks are nested. Understandability https://eslint.org/docs/rules/max-nested-callbacks
max-params Functions that take numerous parameters can be difficult to read and write because it requires the memorization of what each parameter is, its type, and the order they should appear in. As a result, many coders adhere to a convention that caps the number of parameters a function can take. Understandability https://eslint.org/docs/rules/max-params
max-statements The max-statements rule allows you to specify the maximum number of statements allowed in a function. Understandability https://eslint.org/docs/rules/max-statements
max-statements-per-line A line of code containing too many statements can be difficult to read. Code is generally read from the top down, especially when scanning, so limiting the number of statements allowed on a single line can be very beneficial for readability and maintainability. Understandability https://eslint.org/docs/rules/max-statements-per-line
multiline-comment-style Many style guides require a particular style for comments that span multiple lines. For example, some style guides prefer the use of a single block comment for multiline comments, whereas other style guides prefer consecutive line comments. Understandability https://eslint.org/docs/rules/multiline-comment-style
multiline-ternary undefinedJavaScript allows operands of ternary expressions to be separated by newlines, which can improve the readability of your program. Understandability https://eslint.org/docs/rules/multiline-ternary
new-cap The new operator in JavaScript creates a new instance of a particular type of object. That type of object is represented by a constructor function. Since constructor functions are just regular functions, the only defining characteristic is that new is being used as part of the call. Native JavaScript functions begin with an uppercase letter to distinguish those functions that are to be used as constructors from functions that are not. Many style guides recommend following this pattern to more easily determine which functions are to be used as constructors. Maintainability https://eslint.org/docs/rules/new-cap
new-parens JavaScript allows the omission of parentheses when invoking a function via the new keyword and the constructor has no arguments. However, some coders believe that omitting the parentheses is inconsistent with the rest of the language and thus makes code less clear. Maintainability https://eslint.org/docs/rules/new-parens
newline-after-var As of today there is no consistency in separating variable declarations from the rest of the code. Some developers leave an empty line between var statements and the rest of the code. Maintainability https://eslint.org/docs/rules/newline-after-var
newline-before-return There is no hard and fast rule about whether empty lines should precede return statements in JavaScript. However, clearly delineating where a function is returning can greatly increase the readability and clarity of the code. Maintainability https://eslint.org/docs/rules/newline-before-return
newline-per-chained-call Chained method calls on a single line without line breaks are harder to read, so some developers place a newline character after each method call in the chain to make it more readable and easy to maintain. Understandability https://eslint.org/docs/rules/newline-per-chained-call
no-alert JavaScript’s alert, confirm, and prompt functions are widely considered to be obtrusive as UI elements and should be replaced by a more appropriate custom UI implementation. Furthermore, alert is often used while debugging code, which should be removed before deployment to production. Maintainability https://eslint.org/docs/rules/no-alert
no-array-constructor Use of the Array constructor to construct a new array is generally
discouraged in favor of array literal notation because of the single-argument
pitfall and because the Array global may be redefined. The exception is when
the Array constructor is used to intentionally create sparse arrays of a
specified size by giving the constructor a single numeric argument.
Maintainability https://eslint.org/docs/rules/no-array-constructor
no-bitwise The use of bitwise operators in JavaScript is very rare and often & or | is simply a mistyped && or ||, which will lead to unexpected behavior.

var x = y | z;

Maintainability https://eslint.org/docs/rules/no-bitwise
no-buffer-constructor In Node.js, the behavior of the Buffer constructor is different depending on the type of its argument. Passing an argument from user input to Buffer() without validating its type can lead to security vulnerabilities such as remote memory disclosure and denial of service. As a result, the Buffer constructor has been deprecated and should not be used. Use the producer methods Buffer.from, Buffer.alloc, and Buffer.allocUnsafe instead. Maintainability https://eslint.org/docs/rules/no-buffer-constructor
no-caller The use of arguments.caller and arguments.callee make several code optimizations impossible. They have been deprecated in future versions of JavaScript and their use is forbidden in ECMAScript 5 while in strict mode.

function foo() {
var callee = arguments.callee;
}

Maintainability https://eslint.org/docs/rules/no-caller
no-case-declarations This rule disallows lexical declarations (let, const, function and class)
in case/default clauses. The reason is that the lexical declaration is visible
in the entire switch block but it only gets initialized when it is assigned, which
will only happen if the case where it is defined is reached.

To ensure that the lexical declaration only applies to the current case clause
wrap your clauses in blocks.

Maintainability https://eslint.org/docs/rules/no-case-declarations
no-catch-shadow In IE 8 and earlier, the catch clause parameter can overwrite the value of a variable in the outer scope, if that variable has the same name as the catch clause parameter. Maintainability https://eslint.org/docs/rules/no-catch-shadow
no-confusing-arrow Arrow functions (=>) are similar in syntax to some comparison operators (>, <, <=, and >=). This rule warns against using the arrow function syntax in places where it could be confused with a comparison operator. Even if the arguments of the arrow function are wrapped with parens, this rule still warns about it unless allowParens is set to true. Understandability https://eslint.org/docs/rules/no-confusing-arrow
no-console In JavaScript that is designed to be executed in the browser, it’s considered a best practice to avoid using methods on console. Such messages are considered to be for debugging purposes and therefore not suitable to ship to the client. In general, calls using console should be stripped before being pushed to production. Maintainability https://eslint.org/docs/rules/no-console
no-continue The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration. When used incorrectly it makes code less testable, less readable and less maintainable. Structured control flow statements such as if should be used instead. Maintainability https://eslint.org/docs/rules/no-continue
no-duplicate-imports Using a single import statement per module will make the code clearer because you can see everything being imported from that module on one line. In the following example the module import on line 1 is repeated on line 3. These can be combined to make the list of imports more succinct.

import { merge } from ‘module’;
import something from ‘another-module’;
import { find } from ‘module’;

Maintainability https://eslint.org/docs/rules/no-duplicate-imports
no-else-return If an if block contains a return statement, the else block becomes unnecessary. Its contents can be placed outside of the block. Maintainability https://eslint.org/docs/rules/no-else-return
no-empty Empty block statements, while not technically errors, usually occur due to refactoring that wasn’t completed. They can cause confusion when reading code. Maintainability https://eslint.org/docs/rules/no-empty
no-empty-function Empty functions can reduce readability because readers need to guess whether it’s intentional or not. So writing a clear comment for empty functions is a good practice.

function foo() {
// do nothing.
}

Especially, the empty block of arrow functions might be confusing developers.
It’s very similar to an empty object literal.

list.map(() => {}); // This is a block, would return undefined.
list.map(() => ({})); // This is an empty object.

Maintainability https://eslint.org/docs/rules/no-empty-function
no-eq-null Comparing to null without a type-checking operator (== or !=), can have unintended results as the comparison will evaluate to true when comparing to not just a null, but also an undefined value. Maintainability https://eslint.org/docs/rules/no-eq-null
no-extend-native In JavaScript, you can extend any object, including builtin or “native” objects. Sometimes people change the behavior of these native objects in ways that break the assumptions made about them in other parts of the code. Maintainability https://eslint.org/docs/rules/no-extend-native
no-extra-bind The bind() method is used to create functions with specific this values and, optionally, binds arguments to specific values. When used to specify the value of this, it’s important that the function actually use this in its function body. Sometimes during the course of code maintenance, the this value is removed from the function body. In that case, you can end up with a call to bind() that doesn’t accomplish anything. Maintainability https://eslint.org/docs/rules/no-extra-bind
no-extra-label If a loop contains no nested loops or switches, labeling the loop is unnecessary. You can achieve the same result by removing the label and using break or continue without a label. Probably those labels would confuse developers because they expect labels to jump to further. Maintainability https://eslint.org/docs/rules/no-extra-label
no-extra-parens This rule restricts the use of parentheses to only where they are necessary. Maintainability https://eslint.org/docs/rules/no-extra-parens
no-extra-semi Typing mistakes and misunderstandings about where semicolons are required can lead to semicolons that are unnecessary. While not technically an error, extra semicolons can cause confusion when reading code. Maintainability https://eslint.org/docs/rules/no-extra-semi
no-floating-decimal Float values in JavaScript contain a decimal point, and there is no requirement that the decimal point be preceded or followed by a number. Although not a syntax error, this format for numbers can make it difficult to distinguish between true decimal numbers and the dot operator. For this reason, some recommend that you should always include a number before and after a decimal point to make it clear the intent is to create a decimal number. Maintainability https://eslint.org/docs/rules/no-floating-decimal
no-implicit-coercion In JavaScript, there are a lot of different ways to convert value types.
Some of them might be hard to read and understand.
Maintainability https://eslint.org/docs/rules/no-implicit-coercion
no-implicit-globals When working with browser scripts, developers often forget that variable and function declarations at the top-level scope become global variables on the window object. As opposed to modules which have their own scope. Globals should be explicitly assigned to window or self if that is the intent. Otherwise variables intended to be local to the script should be wrapped in an IIFE. Maintainability https://eslint.org/docs/rules/no-implicit-globals
no-implied-eval It’s considered a good practice to avoid using eval() in JavaScript. There are security and performance implications involved with doing so, which is why many linters (including ESLint) recommend disallowing eval(). However, there are some other ways to pass a string and have it interpreted as JavaScript code that have similar concerns.

The first is using setTimeout(), setInterval() or execScript() (Internet Explorer only), both of which can accept a string of JavaScript code as their first argument. For example:

“setTimeout(“alert(‘Hi!’);”, 100);”

This is considered an implied eval() because a string of JavaScript code is passed in to be interpreted. The same can be done with setInterval() and execScript(). Both interpret the JavaScript code in  the global scope. For  both setTimeout() and setInterval(), the first argument can also be a function, and that is considered safer and is more performant:

“setTimeout(function() {
alert(“Hi!”);
}, 100);”

The best practice is to always use a function for the first argument of setTimeout() and setInterval() (and avoid execScript()).

Maintainability https://eslint.org/docs/rules/no-implied-eval
no-inline-comments Some style guides disallow comments on the same line as code. Code can become difficult to read if comments immediately follow the code on the same line. On the other hand, it is sometimes faster and more obvious to put comments immediately following code. Understandability https://eslint.org/docs/rules/no-inline-comments
no-inner-declarations In JavaScript, prior to ES6, a function declaration is only allowed in the first level of a program or the body of another function, though parsers sometimes erroneously accept them elsewhere. This only applies to function declarations; named or anonymous function expressions can occur anywhere an expression is permitted. Maintainability https://eslint.org/docs/rules/no-inner-declarations
no-invalid-this Under the strict mode, this keywords outside of classes or class-like objects might be undefined and raise a TypeError. Maintainability https://eslint.org/docs/rules/no-invalid-this
no-iterator The __iterator__ property was a SpiderMonkey extension to JavaScript that could be used to create custom iterators that are compatible with JavaScript’s for in and for each constructs. However, this property is now obsolete, so it should not be used. You should use ECMAScript 6 iterators and generators instead. Maintainability https://eslint.org/docs/rules/no-iterator
no-label-var This rule aims to create clearer code by disallowing the bad practice of creating a label that shares a name with a variable that is in scope. Maintainability https://eslint.org/docs/rules/no-label-var
no-lone-blocks In JavaScript, prior to ES6, standalone code blocks delimited by curly braces do not create a new scope and have no use. In ES6, code blocks may create a new scope if a block-level binding (let and const), a class declaration or a function declaration (in strict mode) are present. A block is not considered redundant in these cases. Maintainability https://eslint.org/docs/rules/no-lone-blocks
no-lonely-if If an if statement is the only statement in the else block, it is often clearer to use an else if form. Maintainability https://eslint.org/docs/rules/no-lonely-if
no-magic-numbers Magic numbers’ are numbers that occur multiple time in code without an explicit meaning. They should preferably be replaced by named constants. Maintainability https://eslint.org/docs/rules/no-magic-numbers
no-mixed-operators Enclosing complex expressions by parentheses clarifies the developer’s intention, which makes the code more readable. This rule warns when different operators are used consecutively without parentheses in an expression.

Note: It is expected for this rule to emit one error for each mixed operator in a pair. As a result, for each two consecutive mixed operators used, a distinct error will be displayed, pointing to where the specific operator that breaks the rule is used.

Maintainability https://eslint.org/docs/rules/no-mixed-operators
no-mixed-spaces-and-tabs Most code conventions require either tabs or spaces be used for indentation. As such, it’s usually an error if a single line of code is indented with both tabs and spaces. Understandability https://eslint.org/docs/rules/no-mixed-spaces-and-tabs
no-multi-assign Chaining the assignment of variables can lead to unexpected results and be difficult to read. Maintainability https://eslint.org/docs/rules/no-multi-assign
no-multi-spaces Multiple spaces in a row that are not used for indentation are typically mistakes. Multiple spaces such as this are generally frowned upon in favor of single spaces. Maintainability https://eslint.org/docs/rules/no-multi-spaces
no-multi-str It’s possible to create multiline strings in JavaScript by using a slash before a newline. Some consider this to be a bad practice as it was an undocumented feature of JavaScript that was only formalized later. Understandability https://eslint.org/docs/rules/no-multi-str
no-multiple-empty-lines Some developers prefer to have multiple blank lines removed, while others feel that it helps improve readability. Whitespace is useful for separating logical sections of code, but excess whitespace takes up more of the screen. Understandability https://eslint.org/docs/rules/no-multiple-empty-lines
no-negated-condition Negated conditions are more difficult to understand. Code can be made more readable by inverting the condition instead.

This rule disallows negated conditions in either of the following:
1. if statements which have an else branch
2. ternary expressions

Maintainability https://eslint.org/docs/rules/no-negated-condition
no-negated-in-lhs Negated conditions are more difficult to understand. Code can be made more readable by inverting the condition instead. Maintainability https://eslint.org/docs/rules/no-negated-in-lhs
no-nested-ternary Nesting ternary expressions can make code more difficult to understand. Maintainability https://eslint.org/docs/rules/no-nested-ternary
no-new The goal of using new with a constructor is typically to create an object of a particular type and store that object in a variable. Maintainability https://eslint.org/docs/rules/no-new
no-new-func It’s possible to create functions in JavaScript using the Function constructor This is considered by many to be a bad practice due to the difficulty in debugging and reading these types of functions. Maintainability https://eslint.org/docs/rules/no-new-func
no-new-object The Object constructor is used to create new generic objects in JavaScript. Many prefer to always use the object literal syntax and never use the Object constructor.

While there are no performance differences between the two approaches, the byte savings and conciseness of the object literal form is what has made it the de facto way of creating new objects.

Maintainability https://eslint.org/docs/rules/no-new-object
no-new-require The require function is used to include modules that exist in separate files, such as:
var appHeader = require(‘app-header’);

Some modules return a constructor which can potentially lead to code such as:
var appHeader = new require(‘app-header’);

Unfortunately, this introduces a high potential for confusion since the code author likely meant to write:
var appHeader = new (require(‘app-header’));

For this reason, it is usually best to disallow this particular expression.

Maintainability https://eslint.org/docs/rules/no-new-require
no-new-wrappers There are three primitive types in JavaScript that have wrapper objects: string, number, and boolean. These are represented by the constructors String, Number, and Boolean, respectively. The primitive wrapper types are used whenever one of these primitive values is read, providing them with object-like capabilities such as methods. Behind the scenes, an object of the associated wrapper type is created and then destroyed, which is why you can call methods on primitive values.

Although possible, there aren’t any good reasons to use these primitive wrappers as constructors. They tend to confuse other developers more than anything else because they seem like they should act as primitives, but they do not.

The first problem is that primitive wrapper objects are, in fact, objects. That means typeof will return “object” instead of “string”, “number”, or “boolean”. The second problem comes with boolean objects. Every object is truthy, that means an instance of Boolean always resolves to true even when its actual value is false.

For these reasons, it’s considered a best practice to avoid using primitive wrapper types with new.

Maintainability https://eslint.org/docs/rules/no-new-wrappers
no-octal Octal literals are numerals that begin with a leading zero. Because the leading zero which identifies an octal literal has been a source of confusion and error in JavaScript code, ECMAScript 5 deprecates the use of octal numeric literals. Maintainability https://eslint.org/docs/rules/no-octal
no-octal-escape As of the ECMAScript 5 specification, octal escape sequences in string literals are deprecated and should not be used. Unicode escape sequences should be used instead. Maintainability https://eslint.org/docs/rules/no-octal-escape
no-param-reassign Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments object. Often, assignment to function parameters is unintended and indicative of a mistake or programmer error.

This rule can be also configured to fail when function parameters are modified. Side effects on parameters can cause counter-intuitive execution flow and make errors difficult to track down.

Maintainability https://eslint.org/docs/rules/no-param-reassign
no-path-concat In Node.js, the __dirname and __filename global variables contain the directory path and the file path of the currently executing script file, respectively. Sometimes, developers try to use these variables to create paths to other files. However, there are a few problems with this. First, you can’t be sure what type of system the script is running on. Node.js can be run on any computer, including Windows, which uses a different path separator. It’s very easy, therefore, to create an invalid path using string concatenation and assuming Unix-style separators. There’s also the possibility of having double separators, or otherwise ending up with an invalid path.

In order to avoid any confusion as to how to create the correct path, Node.js provides the path module. This module uses system-specific information to always return the correct value.

Maintainability https://eslint.org/docs/rules/no-path-concat
no-proto __proto__ property has been deprecated as of ECMAScript 3.1 and shouldn’t be used in the code. Use getPrototypeOf method instead. Maintainability https://eslint.org/docs/rules/no-proto
no-restricted-globals Disallowing usage of specific global variables can be useful if you want to allow a set of global variables by enabling an environment, but still want to disallow some of those. For instance, early Internet Explorer versions exposed the current DOM event as a global variable event, but using this variable has been considered as a bad practice for a long time. Restricting this will make sure this variable isn’t used in browser code. Maintainability https://eslint.org/docs/rules/no-restricted-globals
no-restricted-imports Imports are an ES6/ES2015 standard for making the functionality of other modules available in your current module. In CommonJS this is implemented through the require() call which makes this ESLint rule roughly equivalent to its CommonJS counterpart no-restricted-modules.

Why would you want to restrict imports?
1. Some imports might not make sense in a particular environment. For example, Node.js’ fs module would not make sense in an environment that didn’t have a file system.
2. Some modules provide similar or identical functionality, think lodash and underscore. Your project may have standardized on a module. You want to make sure that the other alternatives are not being used as this would unnecessarily bloat the project and provide a higher maintenance cost of two dependencies when one would suffice.

Maintainability https://eslint.org/docs/rules/no-restricted-imports
no-restricted-modules A module in Node.js is a simple or complex functionality organized in a JavaScript file which can be reused throughout the Node.js
application. The keyword require is used in Node.js/CommonJS to import modules into an application. This way you can have dynamic loading where the loaded module name isn’t predefined /static, or where you conditionally load a module only if it’s “truly required”.

Why would you want to restrict a module?
Disallowing usage of specific Node.js modules can be useful if you want to limit the available methods a developer can use. For example, you can block usage of the fs module if you want to disallow file system access.

Maintainability https://eslint.org/docs/rules/no-restricted-modules
no-restricted-properties Certain properties on objects may be disallowed in a codebase. This is useful for deprecating an API or restricting usage of a module’s methods. For example, you may want to disallow using describe.only when using Mocha or telling people to use Object.assign instead of _.extend. Maintainability https://eslint.org/docs/rules/no-restricted-properties
no-restricted-syntax JavaScript has a lot of language features, and not everyone likes all of them. As a result, some projects choose to disallow the use of certain language features altogether. For instance, you might decide to disallow the use of try-catch or class, or you might decide to disallow the use of the in operator.

Rather than creating separate rules for every language feature you want to turn off, this rule allows you to configure the syntax elements you want to restrict use of. These elements are represented by their ESTree node types. For example, a function declaration is represented by FunctionDeclaration and the with statement is represented by WithStatement. You may find the full list of AST node names you can use on GitHub and use the online parser to see what type of nodes your code consists of.

You can also specify AST selectors to restrict, allowing much more precise control over syntax patterns.

Maintainability https://eslint.org/docs/rules/no-restricted-syntax
no-return-assign One of the interesting, and sometimes confusing, aspects of JavaScript is that assignment can happen at almost any point. Because of this, an errant equals sign can end up causing assignment when the true intent was to do a comparison. This is especially true when using a return statement. Understandability https://eslint.org/docs/rules/no-return-assign
no-return-await Inside an async function, return await is useless. Since the return value of an async function is always wrapped in Promise.resolve, return await doesn’t actually do anything except add extra time before the overarching Promise resolves or rejects. This pattern is almost certainly due to programmer ignorance of the return semantics of async functions. Maintainability https://eslint.org/docs/rules/no-return-await
no-script-url Using javascript: URLs is considered by some as a form of eval. Code passed in javascript: URLs has to be parsed and evaluated by the browser in the same way that eval is processed. Maintainability https://eslint.org/docs/rules/no-script-url
no-self-compare Comparing a variable against itself is usually an error, either a typo or refactoring error. It is confusing to the reader and may potentially introduce a runtime error.

The only time you would compare a variable against itself is when you are testing for NaN. However, it is far more appropriate to use typeof x === ‘number’ && isNaN(x) or the Number.isNaN ES2015 function for that use case rather than leaving the reader of the code to determine the intent of self comparison.

Maintainability https://eslint.org/docs/rules/no-self-compare
no-spaced-func It’s possible to have whitespace between the name of a function and the parentheses that execute it, such patterns tend to look more like errors. Maintainability https://eslint.org/docs/rules/no-spaced-func
no-sync In Node.js, most I/O is done through asynchronous methods. However, there are often synchronous versions of the asynchronous methods. For example, fs.exists() and fs.existsSync(). In some contexts, using synchronous operations is okay (if, as with ESLint, you are writing a command line utility). However, in other contexts the use of synchronous operations is considered a bad practice that should be avoided. For example, if you are running a high-travel web server on Node.js, you should consider carefully if you want to allow any synchronous operations that could lock up the server. Maintainability https://eslint.org/docs/rules/no-sync
no-tabs Some style guides don’t allow the use of tab characters at all, including within comments. Maintainability https://eslint.org/docs/rules/no-tabs
no-template-curly-in-string ECMAScript 6 allows programmers to create strings containing variable or expressions using template literals, instead of string concatenation, by writing expressions like ${variable} between two backtick quotes (`). It can be easy to use the wrong quotes when wanting to use template literals, by writing “${variable}”, and end up with the literal value “${variable}” instead of a string containing the value of the injected expressions. Maintainability https://eslint.org/docs/rules/no-template-curly-in-string
no-ternary The ternary operator is used to conditionally assign a value to a variable. Some believe that the use of ternary operators leads to unclear code. Maintainability https://eslint.org/docs/rules/no-ternary
no-throw-literal It is considered good practice to only throw the Error object itself or an object using the Error object as base objects for user-defined exceptions.
The fundamental benefit of Error objects is that they automatically keep track of where they were built and originated.

This rule restricts what can be thrown as an exception. When it was first created, it only prevented literals from being thrown (hence the name), but it has now been expanded to only allow expressions which have a possibility of being an Error object.

Maintainability https://eslint.org/docs/rules/no-throw-literal
no-trailing-spaces Sometimes in the course of editing files, you can end up with extra whitespace at the end of lines. These whitespace differences can be picked up by source control systems and flagged as diffs, causing frustration for developers. While this extra whitespace causes no functional issues, many code conventions require that trailing spaces be removed before check-in. Maintainability https://eslint.org/docs/rules/no-trailing-spaces
no-undefined In JavaScript, a variable that is declared and not initialized to any value automatically gets the value of undefined. Maintainability https://eslint.org/docs/rules/no-undef-init
no-underscore-dangle As far as naming conventions for identifiers go, dangling underscores may be the most polarizing in JavaScript. Dangling underscores are underscores at either the beginning or end of an identifier.

There is actually a long history of using dangling underscores to indicate “private” members of objects in JavaScript (though JavaScript doesn’t have truly private members, this convention served as a warning). This began with SpiderMonkey adding nonstandard methods such as __defineGetter__(). The intent with the underscores was to make it obvious that this method was special in some way. Since that time, using a single underscore prefix has become popular as a way to indicate “private” members of objects.

Whether or not you choose to allow dangling underscores in identifiers is purely a convention and has no effect on performance, readability, or complexity. It’s purely a preference.

Maintainability https://eslint.org/docs/rules/no-underscore-dangle
no-unneeded-ternary It’s a common mistake in JavaScript to use a conditional expression to select between two Boolean values instead of using ! to convert the test to a Boolean.

Another common mistake is using a single variable as both the conditional test and the consequent. In such cases, the logical OR can be used to provide the same functionality.

Maintainability https://eslint.org/docs/rules/no-unneeded-ternary
no-unsafe-negation Just as developers might type -a + b when they mean -(a + b) for the negative of a sum, they might type !key in object by mistake when they almost certainly mean !(key in object) to test that a key is not in an object. !obj instanceof Ctor is similar. Maintainability https://eslint.org/docs/rules/no-unsafe-negation
no-unused-expressions An unused expression which has no effect on the state of the program indicates a logic error.

For example, n + 1; is not a syntax error, but it might be a typing mistake where a programmer meant an assignment statement n += 1; instead.

Maintainability https://eslint.org/docs/rules/no-unused-expressions
no-unused-vars Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Suc