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
- Select the Code checkers configuration option from the repository context menu of the desired repository.
- On the Code checkers configuration page, on the left side navigation pane, by default, code issues are enabled except few.
- 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).
- For a specific selected checker, rules will be displayed.
- Move the cursor on the desired rule to view the More info button. More info will display a detailed description and examples.
- Users can search rules manually by typing in the search text box.
- 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.
- 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.
- 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 :
- Go to the Component Explorer present at the top navigation bar next to the duplication tab.
- From the Suppressed Issues tab, click on the unsuppress icon.
Suppression details can be seen on click of suppressed issue .
Suppression Review Workflow
This feature is only available for enterprise customers.
- 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:
File | Severity | Line | Description | Rule | Tag |
---|---|---|---|---|---|
src/main/java/com/mariten/kanatools/KanaConverter.java | Low | 26 | This issue is having low criticality. | Custom Rule | {"CWE":"146"};{"MISRA":"444"};{"CWE":"123"} |
src/main/java/com/mariten/kanatools/KanaConverter.java | High | 33 | This issue is having High criticality. | Rule-01 | Tag1 |
src/main/java/com/mariten/kanatools/KanaConverter.java | low | 45 | This issue is having low criticality. | custom Rule 3 | {"CWE":"231"};{"CWE":"867"} |
src/main/java/com/mariten/kanatools/KanaConverter.java | Medium | 25 | This issue is having medium criticality. | custom Rule-04 | {"CWE":"453"} |
src/main/java/com/mariten/kanatools/KanaConverter.java | Medium | 39 | This issue is having medium criticality. | custom Rule 5 | NewTag;TagTest1 |
src/main/java/com/mariten/kanatools/KanaConverter.java | Critical | 43 | Critical | custome Rule 8 | NewTag;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
- 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. - 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. - 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.
- 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
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
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 |
core.StackAddressEscape | Check that addresses to stack memory do not escape the function | char const *p; void test() { char const str[] = “string”; p = str; // warn } | Robustness |
core.uninitialized.ArraySubscript | Check for uninitialized values used as array subscripts | void test() { int i, a[10]; int x = a[i]; // warn: array subscript is undefined } | Robustness |
cplusplus.NewDelete | Check 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.NewDeleteLeaks | Check for memory leaks. Traces memory managed by new/delete. | void test() { int *p = new int; } // warn | Resource Utilization |
cplusplus.SelfAssignment | Checks C++ copy and move assignment operators for self assignment | Resource Utilization | |
optin.cplusplus.VirtualCall | Check virtual function calls during construction or destruction | Robustness | |
osx.coreFoundation.CFRetainRelease | Check for null arguments to CFRetain/CFRelease/CFMakeCollectable | void test(CFTypeRef p) { if (!p) CFRetain(p); // warn } | Robustness |
osx.coreFoundation.containers.OutOfBounds | Checks for index out-of-bounds when using ‘CFArray’ API | void test() { CFArrayRef A = CFArrayCreate(0, 0, 0, &kCFTypeArrayCallBacks); CFArrayGetValueAtIndex(A, 0); // warn } | Robustness |
osx.coreFoundation.containers.PointerSizedValues | Warns if ‘CFArray’, ‘CFDictionary’, ‘CFSet’ are created with non-pointer-size values | void test() { int x[] = { 1 }; CFArrayRef A = CFArrayCreate(0, (const void **)x, 1, &kCFTypeArrayCallBacks); // warn } | 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 |
security.FloatLoopCounter | Warn 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.UncheckedReturn | Warn on uses of functions whose return values must be always checked | void test() { setuid(1); // warn } | Maintainability |
unix.Malloc | Check 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.MismatchedDeallocator | Check for mismatched deallocators. | // C, C++ void test() { int *p = (int *)malloc(sizeof(int)); delete p; // warn } | Robustness |
alpha.valist.Uninitialized | Experimental: Check for usages of uninitialized (or already released) va_lists. | Robustness | |
alpha.valist.Unterminated | Experimental: Check for va_lists which are not released by a va_end call. | Robustness |
High-level issues
Rule | Description | Example | KPI |
---|---|---|---|
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.CallAndMessageUnInitRefArg | Experimental: 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.CastSize | Experimental: Check when casting a malloc’ed type T, whether the size is a multiple of the size of T | void test() { int *x = (int *)malloc(11); // warn } | Accuracy |
alpha.core.CastToStruct | Experimental: Check for cast from non-struct pointer to struct pointer | struct s {}; void test(int *p) { struct s *ps = (struct s *) p; // warn } | Accuracy |
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.FixedAddr | Experimental: Check for assignment of a fixed address to a pointer | void test() { int *p; p = (int *) 0x10000; // warn } | Maintainability |
alpha.core.IdenticalExpr | Experimental: 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.PointerArithm | Experimental: Check for pointer arithmetic on locations other than array elements | void test() { int x; int *p; p = &x + 1; // warn } | Maintainability |
alpha.core.PointerSub | Experimental: Check for pointer subtractions on two pointers pointing to different memory chunks | void test() { int x, y; int d = &y – &x; // warn } | Accuracy |
alpha.core.SizeofPtr | Experimental: Warn about unintended use of sizeof() on pointer expressions | struct s {}; int test(struct s *p) { return sizeof(p); // warn: sizeof(ptr) can produce an unexpected result } | Accuracy |
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.cplusplus.IteratorPastEnd | Experimental: Check iterators used past end | class A { public: A() { f(); // warn } virtual void f(); } | Robustness |
alpha.deadcode.UnreachableCode | Experimental: Check unreachable code | int test() { int x = 1; while(x); return x; // warn } | Maintainability |
alpha.security.ArrayBound | Experimental: Warn about buffer overflows (older checker) | void test() { char *s = “”; char c = s[1]; // warn } | Robustness |
alpha.security.ArrayBoundV2 | Experimental: Warn about buffer overflows | void test() { int buf[100]; int *p = buf; p = p + 99; p[1] = 1; // warn } | Robustness |
alpha.security.MallocOverflow | Experimental: Check for overflows in the arguments to malloc() | void test(int n) { void *p = malloc(n * sizeof(int)); // warn } | Robustness |
alpha.security.ReturnPtrRange | Experimental: Check for an out-of-bound pointer being returned to callers | static int A[10]; int *test() { int *p = A + 10; return p; // warn } | Robustness |
alpha.security.taint.TaintPropagation | Experimental: Generate taint information used by other checkers | void test() { char x = getchar(); // ‘x’ marked as tainted system(&x); // warn: untrusted data is passed to a system call } | Robustness |
alpha.unix.BlockInCriticalSection | Experimental: Check for calls to blocking functions inside a critical section | Robustness | |
alpha.unix.Chroot | Experimental: Check improper use of chroot | void f(); void test() { chroot(“/usr/local”); f(); // warn: no call of chdir(“/”) immediately after chroot } | Robustness |
alpha.unix.cstring.BufferOverlap | Experimental: Checks for overlap in two buffer arguments | void test() { int a[4] = {0}; memcpy(a + 2, a + 1, 8); // warn } | Maintainability |
alpha.unix.cstring.NotNullTerminated | Experimental: Check for arguments which are not null-terminating strings | void test() { int y = strlen((char *)&test); // warn } | Accuracy |
alpha.unix.cstring.OutOfBounds | Experimental: Check for out-of-bounds access in string functions | void test(char *y) { char x[4]; if (strlen(y) == 4) strncpy(x, y, 5); // warn } | Robustness |
alpha.unix.PthreadLock | Experimental: Simple lock -> unlock checker | pthread_mutex_t mtx; void test() { pthread_mutex_lock(&mtx); pthread_mutex_lock(&mtx); // warn: this lock has already been acquired } | Robustness |
alpha.unix.SimpleStream | Experimental: Check for misuses of stream APIs | void test() { FILE *F = fopen(“myfile.txt”, “w”); } // warn: opened file is never closed | Resource Utilization |
alpha.unix.Stream | Experimental: Check stream handling functions | void test() { FILE *p = fopen(“foo”, “r”); } // warn: opened file is never closed | Resource Utilization |
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 |
core.UndefinedBinaryOperatorResult | Check for undefined results of binary operators | void test() { int x; int y = x + 1; // warn: left operand is garbage } | Accuracy |
core.uninitialized.Assign | Check for assigning uninitialized values | void test() { int x; x |= 1; // warn: left expression is unitialized } | Accuracy |
core.uninitialized.Branch | Check for uninitialized values used as branch conditions | void test() { int x; if (x) // warn return; } | Accuracy |
core.uninitialized.CapturedBlockVariable | Check for blocks that capture uninitialized values | void test() { int x; ^{ int y = x; }(); // warn } | Accuracy |
core.uninitialized.UndefReturn | Check for uninitialized values being returned to the caller | int test() { int x; return x; // warn } | Accuracy |
core.VLASize | Check for declarations of variable length arrays of undefined or zero size | void test() { int x; int vla1[x]; // warn: garbage as size } | Accuracy |
osx.coreFoundation.CFError | Check usage of CFErrorRef* parameters | void test(CFErrorRef *error) { // warn: function accepting CFErrorRef* should have a // non-void return } | Understandability |
osx.coreFoundation.CFNumber | Check for proper uses of CFNumber APIs | CFNumberRef test(unsigned char x) { return CFNumberCreate(0, kCFNumberSInt16Type, &x); // warn: 8 bit integer is used to initialize a 16 bit integer } | Understandability |
osx.SecKeychainAPI | Check for proper uses of Secure Keychain APIs | void test() { unsigned int *ptr = 0; UInt32 length; SecKeychainItemFreeContent(ptr, &length); // warn: trying to free data which has not been allocated } | Robustness |
security.insecureAPI.getpw | Warn on uses of the ‘getpw’ function | void test() { char buff[1024]; getpw(2, buff); // warn } | Maintainability |
security.insecureAPI.gets | Warn on uses of the ‘gets’ function | void test() { char buff[1024]; gets(buff); // warn } | Maintainability |
security.insecureAPI.mkstemp | Warn when ‘mkstemp’ is passed fewer than 6 X’s in the format string | void test() { mkstemp(“XX”); // warn } | Maintainability |
security.insecureAPI.mktemp | Warn on uses of the ‘mktemp’ function | void test() { char *x = mktemp(“/tmp/zxcv”); // warn: insecure, use mkstemp } | Maintainability |
security.insecureAPI.rand | Warn on uses of the ‘rand’, ‘random’, and related functions | void test() { random(); // warn } | Maintainability |
security.insecureAPI.strcpy | Warn 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.vfork | Warn on uses of the ‘vfork’ function | void test() { vfork(); // warn } | Maintainability |
unix.API | Check 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.BadSizeArg | Check the size argument passed into C string functions for common erroneous patterns | void test() { char dest[3]; strncat(dest, “***”, sizeof(dest)); // warn: potential buffer overflow } | Robustness |
unix.cstring.NullArg | Check for null pointers being passed as arguments to C string functions | int test() { return strlen(0); // warn } | Robustness |
unix.MallocSizeof | Check for dubious malloc arguments involving sizeof | void test() { long *p = malloc(sizeof(short)); // warn: result is converted to ‘long *’, which is // incompatible with operand type ‘short’ free(p); } | Accuracy |
unix.Vfork | Check for proper usage of vfork | int 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 Address | Function 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 parameter | int* 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
Rule | Description | Example | KPI |
---|---|---|---|
alpha.valist.CopyToSelf | Experimental: Check for va_lists which are copied onto itself. | Maintainability | |
apiModeling.google.GTest | Model gtest assertion APIs | Maintainability | |
core.builtin.BuiltinFunctions | Evaluate compiler builtin functions (e.g., alloca()) | Maintainability | |
core.builtin.NoReturnFunctions | Evaluate “panic” functions that are known to not return to the caller | Maintainability | |
core.DynamicTypePropagation | Generate dynamic type information | Maintainability | |
deadcode.DeadStores | Check for values stored to variables that are never read afterwards | void test() { int x; x = 1; // warn } | Resource Utilization |
optin.mpi.MPI-Checker | Checks MPI code | void 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.API | Check for proper uses of various Apple APIs | void test() { dispatch_once_t pred = 0; dispatch_once(&pred, ^(){}); // warn: dispatch_once uses local } | Maintainability |
unix.StdCLibraryFunctions | Improve modeling of the C standard library functions | Maintainability | |
dynamic-cast | Implementations 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:
Non-Compliant code: Base* b1 = new Base; | Robustness |
shallow copy assignment | Shallow 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 construct | Shallow 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
Rule | Description | Example | KPI |
---|---|---|---|
debug.AnalysisOrder | Print callbacks that are called during analysis in order | Maintainability | |
debug.ConfigDumper | Dump config table | Maintainability | |
debug.DumpBugHash | Dump the bug hash for all statements. | Maintainability | |
debug.DumpCallGraph | Display Call Graph | Maintainability | |
debug.DumpCalls | Print calls as they are traversed by the engine | Maintainability | |
debug.DumpCFG | Display Control-Flow Graphs | Maintainability | |
debug.DumpDominators | Print the dominance tree for a given CFG | Maintainability | |
debug.DumpLiveVars | Print results of live variable analysis | Maintainability | |
debug.DumpTraversal | Print branch conditions as they are traversed by the engine | Maintainability | |
debug.ExprInspection | Check the analyzer’s understanding of expressions | Maintainability | |
debug.Stats | Emit warnings with analyzer statistics | Maintainability | |
debug.TaintTest | Mark tainted symbols as such. | Maintainability | |
debug.ViewCallGraph | View Call Graph using GraphViz | Maintainability | |
debug.ViewCFG | View Control-Flow Graphs using GraphViz | Maintainability | |
debug.ViewExplodedGraph | View Exploded Graphs using GraphViz | Maintainability | |
llvm.Conventions | Check code for LLVM codebase conventions | Maintainability | |
llvm.Conventions | Check code for LLVM codebase conventions | Maintainability | |
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; Non-Complaint Code: int x = -1; | Maintainability |
char signedness | Specify 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: | 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. | | Maintainability |
hidden parameter | A function declares a variable with the same name as a parameter, which is then "hidden". | Complaint Code: | Maintainability |
hidden parameter | A function declares a variable with the same name as a parameter, which is then "hidden". | Complaint Code: | Maintainability |
deactivated code | Code segments that are permanently disabled by the preprocessor. Indication of inactive code. Only cases with condition would be OK. | Non-complaint code:
| Maintainability |
Assignment Operator Non-Const Arg | Assignment operator must not have non-const argument. | Non-complaint code:
| Robustness |
Assignment Operator Returns Void | Assignment operator must return a valid object. Return type should not be void. | Non-Complaint code:class Alpha { Complaint Code: | Robustness |
Assignment Operator Non-Const Return | Assignment operator must return const qualified valid object. | Non-Complaint code:class Alpha { Complaint Code: | 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
Rule | Description | KPI |
---|---|---|
arrayIndexOutOfBounds | Array ‘array[2]’ index array[1][1] out of bounds. | Robustness |
assignBoolToPointer | Boolean value assigned to pointer. | Robustness |
autoVariables | Dangerous 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 |
autovarInvalidDeallocation | The deallocation of an auto-variable results in undefined behaviour. You should only free memory that has been allocated dynamically. | Robustness |
boostForeachError | BOOST_FOREACH caches the end() iterator. It’s undefined behavior if you modify the container inside. | Robustness |
bufferAccessOutOfBounds | Buffer is accessed out of bounds: buffer | Resource Utilization |
coutCerrMisusage | Invalid usage of output stream: ‘<< std::cout'. | Robustness |
deadpointer | Dead pointer usage. Pointer ‘pointer’ is dead if it has been assigned ‘&x’ at line 0. | Robustness |
deallocDealloc | Deallocating a deallocated pointer: varname | Robustness |
deallocret | Returning/dereferencing ‘p’ after it is deallocated / released | Robustness |
deallocuse | Dereferencing ‘varname’ after it is deallocated / released | Robustness |
doubleFree | Memory pointed to by ‘varname’ is freed twice. | Resource Utilization |
eraseDereference | The iterator ‘iter’ is invalid before being assigned. Dereferencing or comparing it with another iterator is invalid operation. | Robustness |
floatConversionOverflow | Undefined behaviour: float (1e+100) conversion overflow. | Resource Utilization |
insecureCmdLineArgs | Buffer overrun possible for long command line arguments. | Resource Utilization |
integerOverflow | Signed integer overflow for expression ”. | Resource Utilization |
invalidFunctionArg | Invalid func_name() argument nr 1 | Understandability |
invalidFunctionArgBool | Invalid func_name() argument nr 1. A non-boolean value is required. | Understandability |
invalidIterator1 | Invalid iterator: iterator | Understandability |
invalidIterator2 | After push_back|push_front|insert() the iterator ‘iterator’ may be invalid. | Understandability |
invalidPointer | Invalid pointer ‘pointer’ after push_back(). | Understandability |
invalidScanfFormatWidth | Width 5 given in format string (no. 10) is larger than destination buffer ‘[0]’ use %-1s to prevent overflowing it. | Resource Utilization |
IOWithoutPositioning | Read and write operations without a call to a positioning function (fseek fsetpos or rewind) or fflush in between result in undefined behaviour. | Resource Utilization |
iterators | Same iterator is used with different containers ‘container1’ and ‘container2’. | Resource Utilization |
leakNoVarFunctionCall | Allocation with funcName funcName doesn’t release it. | Resource Utilization |
leakReturnValNotUsed | Return value of allocation function ‘funcName’ is not stored. | Maintainability |
mallocOnClassError | Memory 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 |
memleak | Memory leak: varname | Resource Utilization |
memleakOnRealloc | Common realloc mistake: ‘varname’ nulled but not freed upon failure | Resource Utilization |
memsetClass | Using ‘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 |
memsetClassReference | Using ‘memfunc’ on class that contains a reference. | Resource Utilization |
mismatchAllocDealloc | Mismatching allocation and deallocation: varname | Resource Utilization |
mismatchingContainers | Iterators of different containers are used together. | Robustness |
mismatchSize | The allocated size sz is not a multiple of the underlying type’s size. | Resource Utilization |
negativeArraySize | Declaration of array ” with negative size is undefined behaviour | Maintainability |
negativeIndex | Array index -1 is out of bounds. | Maintainability |
negativeMemoryAllocationSize | Memory allocation size is negative.Negative allocation size has no specified behaviour. | Resource Utilization |
nullPointer | Null pointer dereference | Robustness |
nullPointerArithmetic | Overflow in pointer arithmetic NULL pointer is subtracted. | Robustness |
operatorEqMissingReturnStatement | No ‘return’ statement in non-void function causes undefined behavior. | Robustness |
outOfBounds | index is out of bounds: Supplied size 2 is larger than actual size 1. | Robustness |
pointerArithBool | Converting 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 message | Understandability |
raceAfterInterlockedDecrement | Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead. | Robustness |
readWriteOnlyFile | Read operation on a file that was opened only for writing. | Maintainability |
resourceLeak | Resource leak: varname | Resource Utilization |
returnAddressOfAutoVariable | Address of an auto-variable returned. | Robustness |
returnAddressOfFunctionParameter | Address 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 |
returnLocalVariable | Pointer to local array variable returned. | Robustness |
returnReference | Reference to auto variable returned. | Robustness |
returnTempReference | Reference to temporary returned. | Robustness |
selfInitialization | Member variable ‘var’ is initialized by itself. | Robustness |
shiftNegative | Shifting by a negative value is undefined behaviour | Robustness |
shiftTooManyBits | Shifting 32-bit value by 64 bits is undefined behaviour | Robustness |
shiftTooManyBitsSigned | Shifting signed 32-bit value by 31 bits is undefined behaviour | Robustness |
sprintfOverlappingData | The 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 |
stlBoundaries | Iterator 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 |
stlcstr | Dangerous usage of c_str(). The c_str() return value is only valid until its string is deleted. | Robustness |
stlOutOfBounds | When i==foo.size() foo[i] is out of bounds. | Robustness |
stringLiteralWrite | Modifying string literal directly or indirectly is undefined behaviour. | Robustness |
strPlusChar | Unusual pointer arithmetic. A value of type ‘char’ is added to a string literal. | Robustness |
throwInNoexceptFunction | Exception thrown in function declared not to throw exceptions. | Understandability |
uninitdata | Memory is allocated but not initialized: varname | Resource Utilization |
uninitstring | Dangerous usage of ‘varname’ (strncpy doesn’t always null-terminate it). | Robustness |
uninitStructMember | Uninitialized struct member: a.b | Robustness |
uninitvar | Uninitialized variable: varname | Robustness |
unknownEvaluationOrder | Expression ‘x = x++;’ depends on order of evaluation of side effects | Robustness |
useAutoPointerArray | Object 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 |
useAutoPointerContainer | An 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 |
useAutoPointerMalloc | Object 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 |
useClosedFile | Used file that is not opened. | Robustness |
va_end_missing | va_list ‘vl’ was opened but not closed by va_end(). | Resource Utilization |
va_list_usedBeforeStarted | va_list ‘vl’ used before va_start() was called. | Maintainability |
va_start_referencePassed | Using reference ‘arg1’ as parameter for va_start() results in undefined behaviour. | Robustness |
va_start_subsequentCalls | va_start() or va_copy() called subsequently on ‘vl’ without va_end() in between. | Maintainability |
virtualDestructor | Class ‘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 |
writeReadOnlyFile | Write operation on a file that was opened only for reading. | Robustness |
wrongPipeParameterSize | The 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 |
wrongPrintfScanfArgNum | printf format string requires 3 parameters but only 2 are given. | Maintainability |
zerodiv | Division by zero. | Robustness |
High level issues
Rule | Description | KPI |
---|---|---|
accessForwarded | Access of forwarded variable v. | Robustness |
accessMoved | Access of moved variable v. | Robustness |
argumentSize | The array ‘array’ is too small the function ‘function’ expects a bigger one. | Maintainability |
arrayIndexOutOfBoundsCond | Array ‘x[10]’ accessed at index 20 which is out of bounds. Otherwise condition ‘y==20’ is redundant. | Robustness |
assertWithSideEffect | Non-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 |
assignmentInAssert | Variable ‘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 |
badBitmaskCheck | Result of operator ‘|’ is always true if one operand is non-zero. Did you intend to use ‘&’? | Accuracy |
bufferNotZeroTerminated | The 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 |
charBitOp | When 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 |
charLiteralWithCharPtrCompare | Char literal compared with pointer ‘foo’. Did you intend to dereference it? | Accuracy |
checkCastIntToCharAndBack | When 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 |
clarifyStatement | A 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 |
compareBoolExpressionWithInt | Comparison of a boolean expression with an integer other than 0 or 1. | Accuracy |
comparisonFunctionIsAlwaysTrueOrFalse | The 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 |
constStatement | Redundant code: Found a statement that begins with type constant. | Maintainability |
copyCtorAndEqOperator | The class ‘class’ has ‘operator=’ but lack of ‘copy constructor’. | Maintainability |
derefInvalidIterator | Make sure to check that the iterator is valid before dereferencing it – not after. | Maintainability |
divideSizeof | Division 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 |
duplInheritedMember | The class ‘class’ defines member variable with name ‘variable’ also defined in its parent class ‘class’. | Understandability |
exceptDeallocThrow | Exception thrown in invalid state ‘p’ points at deallocated memory. | Robustness |
exceptThrowInDestructor | The 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 |
funcArgOrderDifferent | Function ‘function’ argument order different: declaration ” definition ” | Accuracy |
ignoredReturnValue | Return value of function malloc() is not used. | Maintainability |
incompleteArrayFill | The 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 |
incorrectLogicOperator | Logical 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 |
incorrectStringBooleanError | Conversion of string literal Hello World” to bool always evaluates to true.” | Understandability |
incorrectStringCompare | String 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 |
invalidscanf | scanf() 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 |
invalidTestForOverflow | Invalid test for overflow ‘x + u < x'. Condition is always false unless there is overflow and overflow is UB. | Accuracy |
leakUnsafeArgAlloc | Unsafe allocation. If funcName() throws memory could be leaked. Use make_shared() instead. | Resource Utilization |
literalWithCharPtrCompare | String literal compared with variable ‘foo’. Did you intend to use strcmp() instead? | Robustness |
mallocOnClassWarning | Memory 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 |
memsetValueOutOfRange | The 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 |
memsetZeroBytes | memset() 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 |
moduloAlwaysTrueFalse | Comparison of modulo result is predetermined because it is always less than 1. | Understandability |
multiplySizeof | Multiplying sizeof() with sizeof() indicates a logic error. | Understandability |
nullPointerDefaultArg | Possible null pointer dereference if the default parameter value is used: pointer | Robustness |
nullPointerRedundantCheck | Either the condition is redundant or there is possible null pointer dereference: pointer. | Robustness |
operatorEqToSelf | operator=’ 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 |
operatorEqVarError | Member variable ‘classname::’ is not assigned a value in ‘classname::operator=’. | Robustness |
oppositeInnerCondition | Opposite conditions in nested ‘if’ blocks lead to a dead code block. | Maintainability |
pointerSize | Size 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 |
possibleBufferAccessOutOfBounds | Possible 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 |
publicAllocationError | Possible leak in public function. The pointer ‘varname’ is not deallocated before it is allocated. | Resource Utilization |
redundantAssignInSwitch | Variable ‘var’ is reassigned a value before the old one has been used. ‘break;’ missing? | Maintainability |
redundantCopyInSwitch | Buffer ‘var’ is being written before its old content has been used. ‘break;’ missing? | Maintainability |
seekOnAppendedFile | Repositioning operation performed on a file opened in append mode has no effect. | Maintainability |
selfAssignment | Redundant assignment of ‘varname’ to itself. | Maintainability |
signConversion | Suspicious code: sign conversion of var in calculation even though var can have a negative value | Accuracy |
signedCharArrayIndex | Signed ‘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 |
sizeArgumentAsChar | The size argument is given as a char constant. | Maintainability |
sizeofCalculation | Found calculation inside sizeof(). | Understandability |
sizeofDivisionMemfunc | Division by result of sizeof(). memset() expects a size in bytes did you intend to multiply instead? | Accuracy |
sizeofsizeof | Calling 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 |
sizeofwithnumericparameter | It 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 |
sizeofwithsilentarraypointer | Using ‘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 |
staticStringCompare | The compared strings ‘str1’ and ‘str2’ are always unequal. Therefore the comparison is unnecessary and looks suspicious. | Understandability |
stlIfFind | Suspicious condition. The result of find() is an iterator but it is not properly checked. | Robustness |
StlMissingComparison | The 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 |
stringCompare | The compared strings ‘varname1’ and ‘varname2’ are identical. This could be a logic bug. | Maintainability |
strncatUsage | At 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.c | Robustness |
suspiciousCase | Using 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 |
suspiciousEqualityComparison | Found suspicious equality comparison. Did you intend to assign a value instead? | Accuracy |
suspiciousSemicolon | Suspicious use of ; at the end of ” statement. | Accuracy |
terminateStrncpy | If 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 |
thisSubtraction | Suspicious pointer subtraction. Did you intend to write ‘->’? | Accuracy |
uninitMemberVar | Member variable ‘classname::varname’ is not initialized in the constructor. | Robustness |
unusedLabelSwitch | Label ” is not used. Should this be a ‘case’ of the enclosing switch()? | Understandability |
useAutoPointerCopy | std::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 |
uselessAssignmentPtrArg | Assignment of function parameter has no effect outside the function. Did you forget dereferencing it? | Accuracy |
uselessCallsCompare | std::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 |
uselessCallsEmpty | Ineffective call of function ’empty()’. Did you intend to call ‘clear()’ instead? | Resource Utilization |
uselessCallsRemove | The 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 |
wrongmathcall | Passing value ‘#’ to #() leads to implementation-defined result. | Understandability |
wrongPrintfScanfParameterPositionError | printf: referencing parameter 2 while 1 arguments given | Understandability |
zerodivcond | Either the condition is redundant or there is division by zero at line 0. | Robustness |
Medium level issues
Rule | Description | KPI |
---|---|---|
arithOperationsOnVoidPointer | varname’ 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 |
AssignmentAddressToInteger | Assigning 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 |
AssignmentIntegerToAddress | Assigning 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 |
CastAddressToIntegerAtReturn | Returning 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 |
CastIntegerToAddressAtReturn | Returning 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 |
fflushOnInputStream | fflush() called on input stream ‘stdin’ may result in undefined behaviour on non-linux systems. | Portability |
functionStatic | The 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 |
invalidPointerCast | Casting between float* and double* which have an incompatible binary data representation. | Portability |
memsetClassFloat | Using 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 |
memsetFloat | The 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 |
passedByValue | Parameter ‘parametername’ is passed by value. It could be passed as a (const) reference which is usually faster and recommended in C++. | Efficiency |
pointerOutOfBounds | Undefined 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 overflow | Portability |
postfixOperator | Prefix ++/– 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 |
redundantCopy | Buffer ‘var’ is being written before its old content has been used. | Maintainability |
redundantCopyLocalConst | The 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 |
shiftNegativeLHS | Shifting a negative value is technically undefined behaviour | Robustness |
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 |
sizeofVoid | 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 |
stlcstrParam | The 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 |
stlcstrReturn | The 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 |
stlIfStrFind | Either 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 |
stlSize | Checking 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 |
unknownSignCharArrayIndex | char’ type used as array index. Values greater that 127 will be treated depending on whether ‘char’ is signed or unsigned on target platform. | Robustness |
useInitializationList | When 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 |
uselessCallsSubstr | Ineffective call of function ‘substr’ because it returns a copy of the object. Use operator= instead. | Accuracy |
uselessCallsSwap | The ‘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 |
varFuncNullUB | Passing 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 ap | Robustness |
misra-c2012-1.3 | There shall be no occurrence of undefined or critical unspecified behavior | Robustness |
misra-c2012-2.1 | A project shall not contain unreachable code | Robustness |
misra-c2012-2.2 | There shall be no dead code | Robustness |
misra-c2012-2.4 | A project should not contain unused tag declarations | Robustness |
misra-c2012-2.6 | A function should not contain unused label declarations | Robustness |
misra-c2012-3.1 | The character sequences /* an // shall not be used within a comment | Robustness |
misra-c2012-4.1 | Octal and hexadecimal escape sequences shall be terminated | Robustness |
misra-c2012-5.1 | External identifiers shall be distinct | Robustness |
misra-c2012-5.3 | An identifier declared in an inner scope shall not hide an identifier declared in an outer scope | Robustness |
misra-c2012-5.4 | Macro identifiers shall be distinct | Robustness |
misra-c2012-5.5 | Identifiers shall be distinct from macro names | Robustness |
misra-c2012-7.1 | Octal constants shall not be used | Robustness |
misra-c2012-7.3 | The lowercase character ‘l’ shall not be used in a literal suffix | Robustness |
misra-c2012-8.3 | All declarations of an object or function shall use the same names and type qualifiers | Robustness |
misra-c2012-8.11 | When an array with external linkage is declared, its size should be explicitly specified | Robustness |
misra-c2012-8.12 | Within an enumerator list, the value of an implicitly-specified enumeration constant shall be unique | Robustness |
misra-c2012-8.14 | The restrict type qualifier shall not be used | Robustness |
misra-c2012-9.1 | The value of an object with automatic storage duration shall not be read before it has been set | Robustness |
misra-c2012-9.5 | Where designated initializers are used to initialize an array object the size of the array shall be specified explicitly | Robustness |
misra-c2012-10.4 | Both operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type category | Robustness |
misra-c2012-10.6 | The value of a composite expression shall not be assigned to an object with wider essential type | Robustness |
misra-c2012-10.8 | The value of a composite expression shall not be cast to a different essential type category or a wider essential type | Robustness |
misra-c2012-11.3 | A cast shall not be performed between a pointer to object type and a pointer to a different object type | Robustness |
misra-c2012-11.4 | A conversion should not be performed between a pointer to object and an integer type | Robustness |
misra-c2012-11.5 | A conversion should not be performed from pointer to void into pointer to object | Robustness |
misra-c2012-11.6 | A cast shall not be performed between pointer to void and an arithmetic type | Robustness |
misra-c2012-11.7 | A cast shall not be performed between pointer to object and a noninteger arithmetic type | Robustness |
misra-c2012-11.8 | A cast shall not remove any const or volatile qualification from the type pointed to by a pointer | Robustness |
misra-c2012-11.9 | The macro NULL shall be the only per mitted form of integer null pointer constant | Robustness |
misra-c2012-12.1 | The precedence of operators within expressions should be made explicit | Robustness |
misra-c2012-12.2 | The 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 operand | Robustness |
misra-c2012-12.3 | The comma operator should not be used | Robustness |
misra-c2012-12.4 | Evaluation of constant expressions should not lead to unsigned integer wrap-around | Robustness |
misra-c2012-13.1 | Initializer lists shall not contain persistent side effects | Robustness |
misra-c2012-13.2 | The value of an expression and its persistent side effects shall be the same under all permitted evaluation orders | Robustness |
misra-c2012-13.3 | A full expression containing an increment (++) or decrement (–) operator should have no other potential side effects other than that caused by the increment or decrement operator | Robustness |
misra-c2012-13.4 | The result of an assignment operator should not be used | Robustness |
misra-c2012-13.5 | The right-hand operand of a logical && or || operator shall not contain persistent side effects | Robustness |
misra-c2012-13.6 | The operand of the sizeof operator shall not contain any expression which has potential side effects | Robustness |
misra-c2012-14.1 | A loop counter shall not have essentially floating type | Robustness |
misra-c2012-14.2 | A for loop shall be well-formed | Robustness |
misra-c2012-14.4 | The controlling expression of an if statement and the controlling expression of an iteration- statement shall have essentially Boolean type | Robustness |
misra-c2012-15.1 | The goto statement should not be used | Robustness |
misra-c2012-15.2 | The goto statement shall jump to a label declared later in the same function | Robustness |
misra-c2012-15.3 | Any label referenced by a goto statement shall be declared in the same block, or in any block enclosing the goto statement | Robustness |
misra-c2012-15.5 | A function should have a single point of exit at the end | Robustness |
misra-c2012-15.6 | The body of an iteration-statement or a selection-statement shall be a compound-statement | Robustness |
misra-c2012-15.7 | All if … else if constructs shall be terminated with an else statement | Robustness |
misra-c2012-16.2 | A switch label shall only be used when the most closely-enclosing compound statement is the body of a switch statement | Robustness |
misra-c2012-16.3 | An unconditional break statement shall terminate every switch-clause | Robustness |
misra-c2012-16.4 | Every switch statement shall have a default label | Robustness |
misra-c2012-16.5 | A default label shall appear as either the first or the last switch label of a switch statement | Robustness |
misra-c2012-16.6 | Every switch statement shall have at least two switch-clauses | Robustness |
misra-c2012-16.7 | A switch-expression shall not have essentially Boolean type | Robustness |
misra-c2012-17.1 | The features of shall not be used | Robustness |
misra-c2012-17.5 | The function argument corresponding to a parameter declared to have an array type shall have an appropriate number of elements | Robustness |
misra-c2012-17.6 | The declaration of an array parameter shall not contain the static keyword between the [ ] | Robustness |
misra-c2012-17.8 | A function parameter should not be modified | Robustness |
misra-c2012-18.1 | A pointer resulting from arithmetic on a pointer operand shall address an element of the same array as that pointer operand | Robustness |
misra-c2012-18.5 | Declarations should contain no more than two levels of pointer nesting | Robustness |
misra-c2012-18.6 | The address of an object with automatic storage shall not be copied to another object that persists after the first object has ceased to exist | Robustness |
misra-c2012-18.8 | Variable-length array types shall not be used | Robustness |
misra-c2012-19.2 | The union keyword should not be used | Robustness |
misra-c2012-20.1 | #include directives should only be preceded by preprocessor directives or comments | Robustness |
misra-c2012-20.2 | The ‘, ” or characters and the /* or // character sequences shall not occur in a header fi le name | Robustness |
misra-c2012-20.3 | The #include directive shall be followed by either a or “filename” sequence | Robustness |
misra-c2012-20.4 | A macro shall not be defined with the same name as a keyword | Robustness |
misra-c2012-20.5 | #undef should not be used | Robustness |
misra-c2012-21.3 | The memory allocation and deallocation functions of shall not be used | Robustness |
misra-c2012-21.4 | The standard header file shall not be used | Robustness |
misra-c2012-21.5 | The standard header file shall not be used | Robustness |
misra-c2012-21.7 | The atof, atoi, atol and atoll functions of shall not be used | Robustness |
misra-c2012-21.8 | The library functions abort, exit, getenv and system of shall not be used | Robustness |
misra-c2012-21.9 | The library functions bsearch and qsort of shall not be used | Robustness |
misra-c2012-21.11 | The standard header file shall not be used | Robustness |
misra-c2012-22.1 | All resources obtained dynamically by means of Standard Library functions shall be explicitly released | Robustness |
misra-c2012-22.2 | A block of memory shall only be freed if it was allocated by means of a Standard Library function | Robustness |
misra-c2012-22.4 | There shall be no attempt to write to a stream which has been opened as read-only | Robustness |
misra-c2012-22.6 | The value of a pointer to a FILE shall not be used after the associated stream has been closed | Robustness |
Low level issues
Rule | Description | KPI |
---|---|---|
arrayIndexThenCheck | Defensive 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 |
assignBoolToFloat | Boolean value assigned to floating point variable. | Maintainability |
assignIfError | Mismatching assignment and comparison comparison ” is always false. | Maintainability |
bitwiseOnBoolean | Boolean variable ‘varname’ is used in bitwise operation. Did you mean ‘&&’? | Maintainability |
catchExceptionByValue | The exception is caught by value. It could be caught as a (const) reference which is usually recommended in C++. | Robustness |
clarifyCalculation | Suspicious 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 |
clarifyCondition | Suspicious condition (assignment + comparison); Clarify expression with parentheses. | Maintainability |
commaSeparatedReturn | Comma 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 |
comparisonError | The 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 |
comparisonOfBoolWithBoolError | The variable ‘var_name’ is of type ‘bool’ and comparing ‘bool’ value using relational (< > <= or >=) operator could cause unexpected results. | Maintainability |
comparisonOfFuncReturningBoolError | The 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 |
comparisonOfTwoFuncsReturningBoolError | The 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 |
copyCtorPointerCopying | Value of pointer ‘var’ which points to allocated memory is copied in copy constructor instead of allocating new memory. | Maintainability |
cstyleCast | C-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 |
duplicateBranch | Finding 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 |
duplicateBreak | Consecutive return break continue goto or throw statements are unnecessary. The second statement can never be executed and so should be removed. | Maintainability |
duplicateExpression | Finding 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 |
duplicateExpressionTernary | Finding the same expression in both branches of ternary operator is suspicious as the same code is executed regardless of the condition. | Maintainability |
exceptRethrowCopy | Rethrowing 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 |
funcArgNamesDifferent | Function ‘function’ argument 2 names different: declaration ‘A’ definition ‘B’. | Understandability |
functionConst | The 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 |
incrementboolean | The 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 |
initializerList | Member 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 |
knownConditionTrueFalse | Condition ‘x’ is always true | Understandability |
mismatchingBitAnd | Mismatching bitmasks. Result is always 0 (X = Y & 0xf0; Z = X & 0x1; => Z=0). | Understandability |
multiCondition | Expression is always false because ‘else if’ condition matches previous condition at line 1. | Understandability |
nanInArithmeticExpression | Using NaN/Inf in a computation. Although nothing bad really happens it is suspicious. | Maintainability |
noConstructor | The 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 |
noCopyConstructor | class ‘class’ does not have a copy constructor which is recommended since the class contains a pointer to allocated memory. | Robustness |
noExplicitConstructor | Class ‘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 |
operatorEq | The 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 |
operatorEqShouldBeLeftUnimplemented | operator=’ should either return reference to ‘this’ instance or be declared private and left unimplemented. | Accuracy |
pointerLessThanZero | A pointer cannot be negative so it is either pointless or an error to check if it is. | Maintainability |
pointerPositive | A pointer cannot be negative so it is either pointless or an error to check if it is not. | Maintainability |
reademptycontainer | Reading from empty STL container ‘var’ | Understandability |
redundantAssignment | Variable ‘var’ is reassigned a value before the old one has been used. | Maintainability |
redundantCondition | Redundant condition: If x > 11 the condition x > 10 is always true. | Maintainability |
redundantIfRemove | Redundant checking of STL container element existence before removing it. It is safe to call the remove method on a non-existing element. | Maintainability |
redundantPointerOp | Redundant pointer operation on ‘varname’ – it’s already a pointer. | Maintainability |
truncLongCastAssignment | int 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 |
truncLongCastReturn | int 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 |
unassignedVariable | Variable ‘varname’ is not assigned a value. | Maintainability |
unhandledExceptionSpecification | Unhandled exception specification when calling function foo(). Either use a try/catch around the function call or add a exception specification for funcname() also. | Maintainability |
unpreciseMathCall | Expression ‘1 – erf(x)’ can be replaced by ‘erfc(x)’ to avoid loss of precision. | Maintainability |
unreachableCode | Statements following return break continue goto or throw will never be executed. | Maintainability |
unreadVariable | Variable ‘varname’ is assigned a value that is never used. | Understandability |
unsafeClassCanLeak | The 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 |
unsignedLessThanZero | The unsigned variable ‘varname’ will never be negative so it is either pointless or an error to check if it is. | Maintainability |
unsignedPositive | Unsigned variable ‘varname’ can’t be negative so it is unnecessary to test it. | Maintainability |
unusedAllocatedMemory | Variable ‘varname’ is allocated memory that is never used. | Resource Utilization |
unusedFunction | The function ‘funcName’ is never used. | Understandability |
unusedLabel | Label ” is not used. | Understandability |
unusedPrivateFunction | Unused private function: ‘classname::funcname’ | Understandability |
unusedScopedObject | Instance of ‘varname’ object is destroyed immediately. | Understandability |
unusedStructMember | struct member ‘structname::variable’ is never used. | Understandability |
unusedVariable | Unused variable: varname | Understandability |
uselessAssignmentArg | Assignment of function parameter has no effect outside the function. | Understandability |
variableScope | The 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
Rule | Description | Example | KPI |
---|---|---|---|
ArithmeticExpressionsMustDeclarePrecedence | This statement contains a complex arithmetic expression which omits parenthesis around operations | Non-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 |
AvoidExceptionsInsideStaticConstructors | If any exception is thrown from within a static constructor, the type is unusable for the lifetime of the program | Cause: 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 Complaint Code: public class MyClass | Robustness |
ConditionalExpressionsMustDeclarePrecedence | A C# statement contains a complex conditional expression which omits parenthesis around operations | Cause: 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)) 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 |
EmptyCatchBlock | An empty catch block suppress all errors and shouldn’t be used | Analyzability | |
RegexExpressionIsIncorrect | The regular expression is invalid and will fail at run-time | Cause: The regular expression pattern is invalid and will fail at run-time. Non-complaint Code: string input = “/content/Somefile.cs”; Complaint code: string input = “/content/Somefile.cs”; | Robustness |
VirtualMethodCalledOnConstructor | If 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 run | Non-complaint Code:public class VirtualMethodOnConstructorTests 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 |
VulnerableEncryption | Secure 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 | Security |
WeakEncryption | Weak 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 | Security |
High level issues
Rule | Description | Example | KPI |
---|---|---|---|
AllocationOfReferenceTypeEnumerator | Non-ValueType enumerator may result in an heap allocation. | Non-complaint Code: IList iListData = new[] { 123, 32, 4 }; Complaint Code: int[] intData = new[] { 123, 32, 4 }; | Efficiency |
ArrayAllocationForParamsParameter | Unnecessary array allocation will occur even if no parameter is passed in for the params parameter. | Non-complaint Code:class Test Complaint Code: class Test | Efficiency |
CodeAnalysisSuppressionMustHaveJustification | The 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 |
DisposablesShouldCallSuppressFinalize | 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. | 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 Compliant code: public class MyClass : System.IDisposable | Robustness |
DoNotChangeLoopVariables | Don’t change a loop variable inside a for loop. | Robustness | |
DontConcatenateStringsInLoops | Don’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 = “”; Complaint code: var values = “”; | Efficiency |
MakeFieldReadonly | A 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 Complaint code: class Class1 | Maintainability |
NonOverriddenVirtualMethodCallOnValueType | Non-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; | Efficiency |
RemoveEmptyFinalizers | An 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 Complaint code: public class MyClass | Resource Utilization |
SwitchWithoutDefaultClause | Consider adding default case to the switch | Non-complaint code:switch (value) Complaint code: switch (value) | Robustness |
Invalid Logging Class Name | Consider 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 ICloneable | Consider 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
Rule | Description | Example | KPI |
---|---|---|---|
CatchBlocksShouldRethrow | Any 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 Complaint Code: try | Analyzability |
CompilerWarningLevelIsSetTooLow | Build with the highest warning level | Cause: 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 |
DisposeFieldsProperly | This class has a disposable field and is not disposing it. | Non-Complaint Code:internal class D : System.IDisposable Compliant code: class Class1 : System.IDisposable | Maintainability |
DoNotHideInheritedMembers | On hiding an inherited member, the derived version of the member replaces the base class version | Cause: 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 Non-compliant code: public class B | 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 Compliant code: class Employee | Understandability |
FieldsMustBePrivate | Make the field private and add a property to expose the field outside of the class | Cause: 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 |
HardCodedStringsAndMagicNumbers | Hard coded values should be moved to resources for better maintainability | Cause: 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() Compliant code: public void MyMethod() | 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 Compliant code: class Class1 | Maintainability |
RedundantFieldAssignment | Consider not assigning the default value to a field for performance optimisation | Cause: It’s recommended not to assign the default value to a field as a performance optimization. Non-complaint code: class SampleClass Complaint code: class SampleClass | Efficiency |
ThrowDoesNothing | If 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 parameters | Cause: 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 { } Complaint code: You will have two choices, you can rethrow the original exception as-is: try { } | Analyzability |
UseConfigureAwaitFalseOnAwaitedTask | Consider using ConfigureAwait(false) on the awaited task | Non-complaint code:public async Task TestAsync() Complaint code: public async Task TestAsync() | Robustness |
UseOfRegexIsMatchMightBeImproved | Instantiating the Regex object multiple times might be bad for performance. Consider using the static IsMatch method from Regex class and/or compile the regex | Cause: 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) Complaint code: public static bool TestRegex(string parameterValue) | Efficiency |
UseStaticMethod | If 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 Complaint code: public class Program | Robustness |
UseSwitch | Multiple ‘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) Complaint code: public void DoThis(string s) | Efficiency |
LogErrorInCatch | The log level inside Catch block should be Error | Cause A log level less than an Error is not recommended within a Catch Block especially when there is an exception. Non-complaint code: try Non-complaint code: try | 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 //CODE FIX: public abstract class 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 |
Understandability |
CallExtensionMethodAsExtension | Consider simplifying a call to some static methods by using their Extension method implementation. | //Example For Issue Occurrence:
public void DoThis() //CODE FIX: public void DoThis() |
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: //CODE FIX: |
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) //CODE FIX: void Class1(string 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 |
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) //CODE FIX: if (true) |
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]; //CODE FIX: var a = new int[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() //CODE FIX: private bool CheckAll() |
Maintainability |
ReturnInterfacesToCollections | Return an IEnumerable or ICollection instead of a concrete collection class. | //Example For Issue Occurrence:
List M() //CODE FIX: ICollection M() |
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() //CODE FIX: void Test() |
Resource Utilization |
SimplifyExpression | This expression can be more simplified | //Example For Issue Occurrence:
bool foo= true; //CODE FIX: bool foo= true; |
Maintainability |
TerminateAsyncMethodWithAsyncKeyword | Asynchronous method name should end with ‘Async’ | //Example For Issue Occurrence:
public static async Task Foo() //CODE FIX: public static async Task FooAsync() |
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 public MyClass() { } private void MyMethod() //CODE FIX: public class MyClass 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() //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]; |
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) //CODE FIX: var x = items.Select((object f) => |
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; //CODE FIX: Code c; |
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) //CODE FIX: public void Method(string value) |
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; //CODE FIX: decimal pricePerOunce = 17.36m; |
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; //CODE FIX: var result = true; |
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
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
Rule | Description | Example | KPI |
---|---|---|---|
optin.osx.cocoa.localizability.EmptyLocalizationContextChecke | Check 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 alloc | Maintainability |
osx.cocoa.Loops | Improved modeling of loops using Cocoa collection types | Maintainability | |
osx.cocoa.NonNilReturnValue | Model the APIs that are guaranteed to return a non-nil value | Maintainability | |
osx.cocoa.NSAutoreleasePool | Warn for suboptimal uses of NSAutoreleasePool in Objective-C GC mode | void test() { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [pool release]; // warn } | Maintainability |
osx.cocoa.UnusedIvars | Warn about private ivars that are never used | @interface MyObj : NSObject { @private id x; // warn } @end @implementation MyObj @end | Maintainability |
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
Rule | Description | Example | KPI | Tags |
---|---|---|---|---|
Compile Regex Once | Pattern 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 { Compliant code: Class Foo { | Efficiency | |
Disabled Spring Securitys CSRF | CSRF 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 Compliant code: @Configuration | Security | |
Resource Leak | Resource 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 { Compliant code: class Demo { | Resource Utilization | |
Weak Cipher Algorithm | Use 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 Compliant code:
| 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 { Compliant code: class Demo { | Resource Utilization | |
Non Private Field In Synchronized Block | Non-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 { Compliant code class NonPrivateFieldAccessInSynchronizedBlock { | Robustness, Security | |
Database Should Be Password Protected | Database 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 { Compliant code class CipherExample { | Security | |
Should Not Use getRequestedSessionId API | This 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 |
| Security | |
Web Application Contains Main Method | This 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 |
``` | 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 |
| Security | |
Potential Command Injection | Avoid 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') |
| 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 |
| Security | |
Accessing Android external storage is security-sensitive | Files 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 |
| Security | |
Using unsafe Jackson deserialization configuration is security-sensitive | JThe 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 |
| Security | |
Setting JavaBean properties is security-sensitive | The 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 |
| Security | |
Run Should Not Be Called Directly | The 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 { Compliant code class Demo { | Functionality, Efficiency | |
Exclude SpringBootApplication And ComponentScan From The Default Package | Exclude "SpringBootApplication" and "@ComponentScan" from the default package. | Non-compliant code import org.springframework.boot.SpringApplication; Compliant code package javacodechecker; | Efficiency | spring |
High level issues
Rule | Description | Example | KPI |
---|---|---|---|
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 { Compliant code class SecureRandomGenerator { | Security |
Security Sensitive Regex | Regular 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 | 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 { Compliant code class Demo { | 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 { Compliant code public class LoggingClass extends BaseChecker { | 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 { Compliant code public void process2() { | Analyzability |
Complex Regex Pattern | Avoid 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 { | Efficiency |
Empty Catch Block | Empty 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 { // compliant code public void process2() { | Analyzability |
Empty Catch Block | Empty 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 { // compliant code public void process2() { | Analyzability |
Sensitive Info Logged | Logger 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 { Compliant code class Demo { | Security |
Main Should Not Throw Anything | The 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: Compliant code public static void main(String[] args) { | Functionality |
Avoid Synchronized At Method Level | Avoid 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:
Compliant code public class SynchronizedCounter { | Efficiency |
Shortcircuit Logic Should Be Used In Boolean Contexts | Using non-short-curcuit logic is a mistake it can also cause serious problem error. | Non-compliant code:
Compliant code
| Efficiency |
Medium level issues
Rule | Description | Example | KPI |
---|---|---|---|
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 { Compliant code: class Demo { | Robustness |
Preserve Stack Trace In Logs | Preserve stack trace in logs. This will help to analyse the logs in case of any exception. | Non-compliant code:class Demo { Compliant code: class Demo { | Analyzability |
Read Only Transaction | Spring 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 { Compliant Code: class Demo { | Robustness |
Unusual REST Practice | The 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 { Compliant code class Demo { | Maintainability |
Variables Should Not Be Self Assigned | Self-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 { Compliant code class Demo { | Functionality |
Externalizable Must Have No Arguments Constructor | Externalizable interface cannot be deserialized without a non-argument constructor,so non-argument constructor must be implemented. | Non-compliant code public class Car implements Externalizable { Compliant code public class Car implements Externalizable { | Efficiency |
Getters And Setters Should Access The Expected Fields | Getter 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 { Compliant code private boolean active; | Functionality |
RunFinalizersOnExit Should Not Be Called | Remove 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) { Compliant code public static void main(String [] args) { | Efficiency |
Big Integer Instantiation | Use 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"); Compliant code BigInteger bigInteger = BigInteger.ONE; | Efficiency |
Maps With Enum Values Replace With EnumMap | If 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 { Compliant code public class MyClass { | Functionality |
Mismatch Regex Boundaries Should Not Be Used | In 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 String | Avoid 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 { Compliant Code class Demo { | Functionality |
Empty String Should Not Be Used | Concatenating 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 Block | Exception 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 { Compliant Code try { | Functionality |
Low level issues
Rule | Description | Example | KPI |
---|---|---|---|
Log Level Info In Catch Block | The 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 { Compliant code: class Demo { | Analyzability |
Non Thread Safe Field Declaration | A 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 { Compliant code: class Demo { | Robustness |
Info level issues
Rule | Description | Example | KPI |
---|---|---|---|
String Concatenation In Logging | Instead 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 { Compliant code: class Demo { | Efficiency |
Tightly Coupled Class | A 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 { Compliant code: class Demo { | 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
Rule | Description | Example | KPI |
---|---|---|---|
ControlStatementBraces | Enforce 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 |
IdenticalCatchBranches | Identical 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 |
LinguisticNaming | This 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 |
LocalVariableNamingConventions | Configurable 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]; |
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]; |
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: |
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) { 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); |
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. |
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. |
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. |
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: |
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 Solution: @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) |
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 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 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: |
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”) 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:. |
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: The XML code above will cause the creation of a file with the content “Hello World!”. Vulnerable Code: 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: |
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
Rule | Description | Example | KPI |
---|---|---|---|
B401-blacklist_calls | telnetlib | Maintainability | |
B402-blacklist_calls | ftplib | Maintainability | |
B411-blacklist_calls | xmlrpclib | Maintainability | |
B412-blacklist_calls | wsgiref.handlers.CGIHandler twisted.web.twcgi.CGIScript | Maintainability | |
B413-blacklist_calls | Crypto.Cipher Crypto.Hash Crypto.IO Crypto.Protocol Crypto.PublicKey Crypto.Random Crypto.Signature Crypto.Util | Maintainability | |
B414-blacklist_calls | Cryptodome.Cipher Cryptodome.Hash Cryptodome.IO Cryptodome.Protocol Cryptodome.PublicKey Cryptodome.Random Cryptodome.Signature Cryptodome.Util | Maintainability |
Bandit Low Level Issues
Rule | Description | example | kpi |
---|---|---|---|
B101-assert_used | Use of assert detected. The enclosed code will be removed when compiling to optimised byte code. | assert logged_in display_assets() | Maintainability |
B102-exec_used | Use of exec detected. | exec("do evil") exec "do evil" | Maintainability |
B103-set_bad_file_permissions | Probable 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_interfaces | Possible 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_string | Possible hardcoded password '(root)' | def someFunction2(password): if password == "root": print("OK, logged in") | Maintainability |
B106-hardcoded_password_funcarg | Possible hardcoded password: 'blerg' | doLogin(password="blerg") | Maintainability |
B107-hardcoded_password_default | Possible hardcoded password: 'Admin' | def someFunction(user, password="Admin"): print("Hi " + user) | Maintainability |
B108-hardcoded_tmp_directory | insecure usage of tmp file/directory | tmp_dirs: ['/tmp', '/var/tmp', '/dev/shm'] | Maintainability |
B110-try_except_pass | a pass in the except block | try: do_some_stuff() except Exception: pass | Maintainability |
B112-try_except_continue | a continue in the except block | while keep_going: try: do_some_stuff() except Exception: continue | Maintainability |
B201-flask_debug_true | A 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_validation | Requests 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_version | ssl.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_defaults | Function definition identified with insecure SSL/TLS protocol version by default, possible security issue. | def open_ssl_socket(version=SSL.SSLv2_METHOD): pass | Maintainability |
B504-ssl_with_no_version | ssl.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_key | DSA key sizes below 1024 bits are considered breakable. | dsa.generate_private_key(512, backends.default_backend()) rsa.generate_private_key(3, | Maintainability |
B506-yaml_load | use of yaml load | ystr = yaml.dump({‘a’ : 1, ‘b’ : 2, ‘c’ : 3}) y = yaml.load(ystr) 6 yaml.dump(y) | Maintainability |
B507-ssh_no_host_key_verification | Paramiko 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_calls | Possible shell injection via Paramiko call, check inputs are properly sanitized. | paramiko.exec_command('something; really; unsafe') | Maintainability |
B602-subprocess_popen_with_shell_equals_true | subprocess 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_true | subprocess call - check for execution of untrusted input. | subprocess.check_output(['/bin/ls', '-l']) | Maintainability |
B604-any_other_function_with_shell_equals_true | Function 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_shell | Starting a process with a shell: check for injection. | os.system('/bin/echo hi') | Maintainability |
B606-start_process_with_no_shell | Starting 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_path | Starting a process with a partial executable path | from subprocess import Popen as pop pop('gcc --version', shell=False) | Maintainability |
B608-hardcoded_sql_expressions | SQL injectio | query = "DELETE FROM foo WHERE id = '%s'" % identifier query = "UPDATE foo SET value = 'b' WHERE id = '%s'" % identifier | Maintainability |
B609-linux_commands_wildcard_injection | Possible wildcard injection in call: subprocess.Popen | o.popen2('/bin/chmod *') subp.Popen('/bin/chown *', shell=True) | Maintainability |
B610-django_extra_used | Potential SQL injection on extra function | Maintainability | |
B611-django_rawsql_used | Potential SQL injection on RawSQL function | Maintainability | |
B701-jinja2_autoescape_false | Using 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_templates | Mako 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_safe | Potential XSS on mark_safe function | Maintainability | |
B301-blacklist_calls | pickle | Imports : 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_calls | marshal | Imports : marshal.load marshal.loads | Maintainability |
B303-blacklist_calls | md5 | Imports : 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_calls | ciphers | Imports : 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_calls | cipher_modes | Imports : cryptography.hazmat.primitives .ciphers.modes.ECB | Maintainability |
B306-blacklist_calls | mktemp_q | Imports : tempfile.mktemp | Maintainability |
B307-blacklist_calls | eval | Imports : eval | Maintainability |
B308-blacklist_calls | mark_safe | Imports : django.utils.safestring.mark_safe | Maintainability |
B309-blacklist_calls | httpsconnection | Imports : httplib.HTTPSConnection http.client.HTTPSConnection six.moves.http_client .HTTPSConnection | Maintainability |
B310-blacklist_calls | urllib_urlopen | Imports : 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_calls | random | Imports : random.random random.randrange random.randint random.choice random.uniform random.triangular | Maintainability |
B312-blacklist_calls | telnetlib | Imports : telnetlib.* | Maintainability |
B313-blacklist_calls | xml_bad_cElementTree | Imports : xml.etree.cElementTree.parse xml.etree.cElementTree.iterparse xml.etree.cElementTree.fromstring xml.etree.cElementTree.XMLParser | Maintainability |
B314-blacklist_calls | xml_bad_ElementTree | Imports : xml.etree.ElementTree.parse xml.etree.ElementTree.iterparse xml.etree.ElementTree.fromstring xml.etree.ElementTree.XMLParser | Maintainability |
B315-blacklist_calls | xml_bad_expatreader | Imports : xml.sax.expatreader.create_parser | Maintainability |
B316-blacklist_calls | xml_bad_expatbuilder | Imports : xml.dom.expatbuilder.parse xml.dom.expatbuilder.parseString | Maintainability |
B317-blacklist_calls | xml_bad_sax | Imports : xml.sax.parse xml.sax.parseString xml.sax.make_parser | Maintainability |
B318-blacklist_calls | xml_bad_minidom | Imports : xml.dom.minidom.parse xml.dom.minidom.parseString | Maintainability |
B319-blacklist_calls | xml_bad_pulldom | Imports : xml.dom.pulldom.parse xml.dom.pulldom.parseString | Maintainability |
B320-blacklist_calls | xml_bad_etree | Imports : lxml.etree.parse lxml.etree.fromstring lxml.etree.RestrictedElement lxml.etree.GlobalParserTLS lxml.etree.getDefaultParser lxml.etree.check_docinfo | Maintainability |
B321-blacklist_calls | ftplib | Imports : ftplib.* | Maintainability |
B322-blacklist_calls | input | Imports : input | Maintainability |
B323-blacklist_calls | unverified_context | Imports : ssl._create_unverified_context | Maintainability |
B325-blacklist_calls | tempnam | Imports : os.tempnam os.tmpnam | Maintainability |
B403-blacklist_calls | pickle cPickle dill shelve | Maintainability | |
B404-blacklist_calls | subprocess | Maintainability | |
B405-blacklist_calls | xml.etree.cElementTree xml.etree.ElementTree | Maintainability | |
B406-blacklist_calls | xml.sax | Maintainability | |
B407-blacklist_calls | xml.dom.expatbuilder | Maintainability | |
B408-blacklist_calls | xml.dom.minidom | Maintainability | |
B409-blacklist_calls | xml.dom.pulldom | Maintainability | |
B410-blacklist_calls | lxml | Maintainability |
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” 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” 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: |
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 i ++ // i = 10, j = 21 i |
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: 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: 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: 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: |
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 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() { 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: |
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) { 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 |
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() { |
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 |
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’; |
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() { Especially, the empty block of arrow functions might be confusing developers. list.map(() => {}); // This is a block, would return undefined. |
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() { 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: |
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: Unfortunately, this introduces a high potential for confusion since the code author likely meant to write: 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? |
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? |
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. Such variables take up space in the code and can lead to confusion by readers. | Maintainability | https://eslint.org/docs/rules/no-unused-vars |
no-use-before-define | In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it’s possible to use identifiers before their formal declarations in code. This can be confusing and some believe it is best to always declare variables and functions before using them.
In ES6, block-level bindings (let and const) introduce a “temporal dead zone” where a ReferenceError will be thrown with any attempt to access the variable before its declaration. |
Maintainability | https://eslint.org/docs/rules/no-use-before-define |
no-useless-call | The function invocation can be written by Function.prototype.call() and Function.prototype.apply().
But Function.prototype.call() and Function.prototype.apply() are slower than the normal function invocation. |
Maintainability | https://eslint.org/docs/rules/no-useless-call |
no-useless-computed-key | It’s unnecessary to use computed properties with literals such as: var foo = {[“a”]: “b”}; | Maintainability | https://eslint.org/docs/rules/no-useless-computed-key |
no-useless-concat | It’s unnecessary to concatenate two strings together, such as: var foo = “a” + “b”; This code is likely the result of refactoring where a variable was removed from the concatenation (such as “a” + b + “b”). In such a case, the concatenation isn’t important and the code can be rewritten as: var foo = “ab”; |
Maintainability | https://eslint.org/docs/rules/no-useless-concat |
no-useless-constructor | ES2015 provides a default class constructor if one is not specified. As such, it is unnecessary to provide an empty constructor or one that simply delegates into its parent class. | Maintainability | https://eslint.org/docs/rules/no-useless-constructor |
no-useless-rename | ES2015 allows for the renaming of references in import and export statements as well as destructuring assignments. This gives programmers a concise syntax for performing these operations while renaming these references. | Maintainability | https://eslint.org/docs/rules/no-useless-rename |
no-useless-return | A return; statement with nothing after it is redundant, and has no effect on the runtime behavior of a function. This can be confusing, so it’s better to disallow these redundant statements. | Maintainability | https://eslint.org/docs/rules/no-useless-return |
no-var | 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 | https://eslint.org/docs/rules/no-var |
no-void | The void operator takes an operand and returns undefined: void expression will evaluate expression and return undefined. It can be used to ignore any side effects expression may produce. | Maintainability | https://eslint.org/docs/rules/no-void |
no-warning-comments | Developers often add comments to code which is not complete or needs review. Most likely you want to fix or review the code, and then remove the comment, before you consider the code to be production ready. | Understandability | https://eslint.org/docs/rules/no-warning-comments |
no-whitespace-before-property | JavaScript allows whitespace between objects and their properties. However, inconsistent spacing can make code harder to read and can lead to errors. | Maintainability | https://eslint.org/docs/rules/no-whitespace-before-property |
no-with | The with statement is potentially problematic because it adds members of an object to the current scope, making it impossible to tell what a variable inside the block actually refers to. | Maintainability | https://eslint.org/docs/rules/no-with |
nonblock-statement-body-position | When writing if, else, while, do-while, and for statements, the body can be a single statement instead of a block. It can be useful to enforce a consistent location for these single statements. | Maintainability | https://eslint.org/docs/rules/nonblock-statement-body-position |
object-curly-newline | A number of style guides require or disallow line breaks inside of object braces and other tokens. | Understandability | https://eslint.org/docs/rules/object-curly-newline |
object-curly-spacing | While formatting preferences are very personal, a number of style guides require or disallow spaces between curly braces in the following situations. | Understandability | https://eslint.org/docs/rules/object-curly-spacing |
object-property-newline | This rule permits you to restrict the locations of property specifications in object literals. You may prohibit any part of any property specification from appearing on the same line as any part of any other property specification. You may make this prohibition absolute, or, by invoking an object option, you may allow an exception, permitting an object literal to have all parts of all of its property specifications on a single line. | Maintainability | https://eslint.org/docs/rules/object-property-newline |
object-shorthand | ECMAScript 6 provides a concise form for defining object literal methods and properties. This syntax can make defining complex object literals much cleaner. | Maintainability | https://eslint.org/docs/rules/object-shorthand |
one-var | Variables can be declared at any point in JavaScript code using var, let, or const. There are many styles and preferences related to the declaration of variables, and one of those is deciding on how many variable declarations should be allowed in a single function.
There are two schools of thought in this regard: The single-declaration school of thought is based in pre-ECMAScript 6 behaviors, where there was no such thing as block scope, only function scope. Since all var statements are hoisted to the top of the function anyway, some believe that declaring all variables in a single declaration at the top of the function removes confusion around scoping rules. |
Maintainability | https://eslint.org/docs/rules/one-var |
one-var-declaration-per-line | Some developers declare multiple var statements on the same line, others prefer to declare one var per line. Keeping to one of these styles across a project’s codebase can help with maintaining code consistency. | Maintainability | https://eslint.org/docs/rules/one-var-declaration-per-line |
operator-assignment | JavaScript provides shorthand operators that combine variable assignment and some simple mathematical operations. For example, x = x + 4 can be shortened to x += 4. | Maintainability | https://eslint.org/docs/rules/operator-assignment |
operator-linebreak | When a statement is too long to fit on a single line, line breaks are generally inserted next to the operators separating expressions. | Maintainability | https://eslint.org/docs/rules/operator-linebreak |
padded-blocks | Some style guides require block statements to start and end with blank lines. The goal is to improve readability by visually separating the block content and the surrounding code. Since it’s good to have a consistent code style, you should either always write padded blocks or never do it. | Maintainability | https://eslint.org/docs/rules/padded-blocks |
padding-line-between-statements | This rule requires or disallows blank lines between the given 2 kinds of statements. Properly blank lines help developers to understand the code. | Maintainability | https://eslint.org/docs/rules/padding-line-between-statements |
prefer-arrow-callback | Arrow functions can be an attractive alternative to function expressions for callbacks or function arguments.
For example, arrow functions are automatically bound to their surrounding scope/context. This provides an alternative to the pre-ES6 standard of explicitly binding function expressions to achieve similar behavior. Additionally, arrow functions are: |
Maintainability | https://eslint.org/docs/rules/prefer-arrow-callback |
prefer-const | If a variable is never reassigned, using the const declaration is better.
const declaration tells readers, “this variable is never reassigned,” reducing cognitive load and improving maintainability. |
Maintainability | https://eslint.org/docs/rules/prefer-const |
prefer-destructuring | With JavaScript ES6, a new syntax was added for creating variables from an array index or object property, called destructuring. This rule enforces usage of destructuring instead of accessing a property through a member expression. | Maintainability | https://eslint.org/docs/rules/prefer-destructuring |
prefer-numeric-literals | The parseInt() and Number.parseInt() functions can be used to turn binary, octal, and hexadecimal strings into integers. As binary, octal, and hexadecimal literals are supported in ES6, this rule encourages use of those numeric literals instead of parseInt() or Number.parseInt(). | Maintainability | https://eslint.org/docs/rules/prefer-numeric-literals |
prefer-promise-reject-errors | It is considered good practice to only pass instances of the built-in Error object to the reject() function for user-defined errors in Promises. Error objects automatically store a stack trace, which can be used to debug an error by determining where it came from. If a Promise is rejected with a non-Error value, it can be difficult to determine where the rejection occurred. | Maintainability | https://eslint.org/docs/rules/prefer-promise-reject-errors |
prefer-reflect | This rule was deprecated in ESLint v3.9.0 and will not be replaced. The original intent of this rule now seems misguided as we have come to understand that Reflect methods are not actually intended to replace the Object counterparts the rule suggests, but rather exist as low-level primitives to be used with proxies in order to replicate the default behavior of various previously existing functionality. | Maintainability | https://eslint.org/docs/rules/prefer-reflect |
prefer-rest-params | There are rest parameters in ES2015. We can use that feature for variadic functions instead of the arguments variable. arguments does not have methods of Array.prototype, so it’s a bit of an inconvenience. |
Maintainability | https://eslint.org/docs/rules/prefer-rest-params |
prefer-spread | Before ES2015, one must use Function.prototype.apply() to call variadic functions. In ES2015, one can use the spread operator to call variadic functions. | Maintainability | https://eslint.org/docs/rules/prefer-spread |
prefer-template | In ES2015 (ES6), we can use template literals instead of string concatenation. | Maintainability | https://eslint.org/docs/rules/prefer-template |
quote-props | Object literal property names can be defined in two ways: using literals or using strings. In many cases, it doesn’t matter if you choose to use an identifier instead of a string or vice-versa. Even so, you might decide to enforce a consistent style in your code.
There are, however, some occasions when you must use quotes: |
Maintainability | https://eslint.org/docs/rules/quote-props |
quotes | JavaScript allows you to define strings in one of three ways: double quotes, single quotes, and backticks (as of ECMAScript 6). Each of these lines creates a string and, in some cases, can be used interchangeably. The choice of how to define strings in a codebase is a stylistic one outside of template literals (which allow embedded of expressions to be interpreted). Many codebases require strings to be defined in a consistent manner. | Maintainability | https://eslint.org/docs/rules/quotes |
radix | When using the parseInt() function it is common to omit the second argument, the radix, and let the function try to determine from the first argument what type of number it is. By default, parseInt() will autodetect decimal and hexadecimal (via 0x prefix). Prior to ECMAScript 5, parseInt() also autodetected octal literals, which caused problems because many developers assumed a leading 0 would be ignored.
This confusion led to the suggestion that you always use the radix parameter to parseInt() to eliminate unintended consequences. ECMAScript 5 changed the behavior of parseInt() so that it no longer autodetects octal literals and instead treats them as decimal literals. However, the differences between hexadecimal and decimal interpretation of the first parameter causes many developers to continue using the radix parameter to ensure the string is interpreted in the intended way. On the other hand, if the code is targeting only ES5-compliant environments passing the radix 10 may be redundant. In such a case you might want to disallow using such a radix. |
Maintainability | https://eslint.org/docs/rules/radix |
require-await | Async functions which have no await expression may be the unintentional result of refactoring. | Maintainability | https://eslint.org/docs/rules/require-await |
require-jsdoc | JSDoc is a JavaScript API documentation generator. It uses specially-formatted comments inside of code to generate API documentation automatically. Some style guides require JSDoc comments for all functions as a way of explaining function behavior. | Understandability | https://eslint.org/docs/rules/require-jsdoc |
rest-spread-spacing | ES2015 introduced the rest and spread operators, which expand an iterable structure into its individual parts. There is currently a proposal to add object rest and spread properties to the spec. As with other operators, whitespace is allowed between the rest or spread operator and the expression it is operating on, which can lead to inconsistent spacing within a codebase. | Maintainability | https://eslint.org/docs/rules/rest-spread-spacing |
semi | JavaScript is unique amongst the C-like languages in that it doesn’t require semicolons at the end of each statement. In many cases, the JavaScript engine can determine that a semicolon should be in a certain spot and will automatically add it. This feature is known as automatic semicolon insertion (ASI) and is considered one of the more controversial features of JavaScript.
On the first line, the JavaScript engine will automatically insert a semicolon, so this is not considered a syntax error. The JavaScript engine still knows how to interpret the line and knows that the line end indicates the end of the statement. In the debate over ASI, there are generally two schools of thought. The first is that we should treat ASI as if it didn’t exist and always include semicolons manually. The rationale is that it’s easier to always include semicolons than to try to remember when they are or are not required, and thus decreases the possibility of introducing an error. However, the ASI mechanism can sometimes be tricky to people who are using semicolons. Effectively, a semicolon is inserted after the return statement, causing the code below it (a labeled literal inside a block) to be unreachable. This rule and the no-unreachable rule will protect your code from such cases. On the other side of the argument are those who says that since semicolons are inserted automatically, they are optional and do not need to be inserted manually. However, the ASI mechanism can also be tricky to people who don’t use semicolons. In this example, a semicolon will not be inserted after the first line, causing a run-time error (because an empty object is called as if it’s a function). The no-unexpected-multiline rule can protect your code from such cases. Although ASI allows for more freedom over your coding style, it can also make your code behave in an unexpected way, whether you use semicolons or not. Therefore, it is best to know when ASI takes place and when it does not, and have ESLint protect your code from these potentially unexpected cases. In short, as once described by Isaac Schlueter, a n character always ends a statement (just like a semicolon) unless 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 ,.) |
Maintainability | https://eslint.org/docs/rules/semi |
semi-spacing | JavaScript allows you to place unnecessary spaces before or after a semicolon.
Disallowing or enforcing space around a semicolon can improve the readability of your program. |
Maintainability | https://eslint.org/docs/rules/semi-spacing |
semi-style | Generally, semicolons are at the end of lines. However, in semicolon-less style, semicolons are at the beginning of lines. This rule enforces that semicolons are at the configured location. | Maintainability | https://eslint.org/docs/rules/semi-style |
sort-imports | The import statement is used to import members (functions, objects or primitives) that have been exported from an external module. Using a specific member syntax. The import statement can also import a module without exported bindings. Used when the module does not export anything, but runs it own code or changes the global context object. When declaring multiple imports, a sorted list of import declarations make it easier for developers to read the code and find necessary imports later. This rule is purely a matter of style. | Understandability | https://eslint.org/docs/rules/sort-imports |
sort-keys | When declaring multiple properties, some developers prefer to sort property names alphabetically to be able to find necessary property easier at the later time. Others feel that it adds complexity and becomes burden to maintain. | Understandability | https://eslint.org/docs/rules/sort-keys |
sort-vars | When declaring multiple variables within the same block, some developers prefer to sort variable names alphabetically to be able to find necessary variable easier at the later time. Others feel that it adds complexity and becomes burden to maintain. | Understandability | https://eslint.org/docs/rules/sort-vars |
space-before-blocks | Consistency is an important part of any style guide. While it is a personal preference where to put the opening brace of blocks, it should be consistent across a whole project. Having an inconsistent style distracts the reader from seeing the important parts of the code. |
Maintainability | https://eslint.org/docs/rules/space-before-blocks |
space-before-function-paren | When formatting a function, whitespace is allowed between the function name or function keyword and the opening paren. Named functions also require a space between the function keyword and the function name, but anonymous functions require no whitespace. Style guides may require a space after the function keyword for anonymous functions, while others specify no whitespace. Similarly, the space after a function name may or may not be required. | Understandability | https://eslint.org/docs/rules/space-before-function-paren |
space-in-parens | Some style guides require or disallow a whitespace immediately after the initial // or /* of a comment. Whitespace after the // or /* makes it easier to read text in comments. On the other hand, commenting out code is easier without having to put a whitespace right after the // or /*. | Maintainability | https://eslint.org/docs/rules/spaced-comment |
space-infix-ops | While formatting preferences are very personal, a number of style guides require spaces around operators. The proponents of these extra spaces believe it make the code easier to read and can more easily highlight potential errors. | Understandability | https://eslint.org/docs/rules/space-infix-ops |
space-unary-ops | Some style guides require or disallow spaces inside of parentheses. | Understandability | https://eslint.org/docs/rules/space-in-parens |
spaced-comment | Some style guides require or disallow spaces before or after unary operators. This is mainly a stylistic issue, however, some JavaScript expressions can be written without spacing which makes it harder to read and maintain. | Understandability | https://eslint.org/docs/rules/space-unary-ops |
switch-colon-spacing | Spacing around colons improves readability of case/default clauses. | Maintainability | https://eslint.org/docs/rules/switch-colon-spacing |
symbol-description | The Symbol function may have optional description. Using description promotes easier debugging: when a symbol is logged the description is used. It may facilitate identifying symbols when one is observed during debugging. | Maintainability | https://eslint.org/docs/rules/symbol-description |
template-curly-spacing | We can embed expressions in template strings with using a pair of ${ and }. This rule can force usage of spacing within the curly brace pair according to style guides. | Maintainability | https://eslint.org/docs/rules/template-curly-spacing |
template-tag-spacing | With ES6, it’s possible to create functions called tagged template literals where the function parameters consist of a template literal’s strings and expressions. When using tagged template literals, it’s possible to insert whitespace between the tag function and the template literal. | Maintainability | https://eslint.org/docs/rules/template-tag-spacing |
unicode-bom | The Unicode Byte Order Mark (BOM) is used to specify whether code units are big endian or little endian. That is, whether the most significant or least significant bytes come first. UTF-8 does not require a BOM because byte ordering does not matter when characters are a single byte. Since UTF-8 is the dominant encoding of the web, we make “never” the default option. | Maintainability | https://eslint.org/docs/rules/unicode-bom |
valid-jsdoc | JSDoc generates application programming interface (API) documentation from specially-formatted comments in JavaScript code. If comments are invalid because of typing mistakes, then documentation will be incomplete. If comments are inconsistent because they are not updated when function definitions are modified, then readers might become confused. | Maintainability | https://eslint.org/docs/rules/valid-jsdoc |
vars-on-top | The vars-on-top rule generates warnings when variable declarations are not used serially at the top of a function scope or the top of a program. By default variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter. This rule forces the programmer to represent that behavior by manually moving the variable declaration to the top of its containing scope. |
Maintainability | https://eslint.org/docs/rules/vars-on-top |
wrap-iife | You can immediately invoke function expressions, but not function declarations. A common technique to create an immediately-invoked function expression (IIFE) is to wrap a function declaration in parentheses. The opening parentheses causes the contained function to be parsed as an expression, rather than a declaration. | Maintainability | https://eslint.org/docs/rules/wrap-iife |
wrap-regex | When a regular expression is used in certain situations, it can end up looking like a division operator. | Maintainability | https://eslint.org/docs/rules/wrap-regex |
yield-star-spacing | This rule enforces spacing around the * in yield* expressions. | Maintainability | https://eslint.org/docs/rules/yield-star-spacing |
yoda | Yoda conditions are so named because the literal value of the condition comes first while the variable comes second. For example, the following is a Yoda condition:
if (“red” === color) { // … } This is called a Yoda condition because it reads as, “if red equals the color”, similar to the way the Star Wars character Yoda speaks. Compare to the other way of arranging the operands: if (color === “red”) { // .. } This typically reads, “if the color equals red”, which is arguably a more natural way to describe the comparison. Proponents of Yoda conditions highlight that it is impossible to mistakenly use = instead of == because you cannot assign to a literal value. Doing so will cause a syntax error and you will be informed of the mistake early on. This practice was therefore very common in early programming where tools were not yet available. Opponents of Yoda conditions point out that tooling has made us better programmers because tools will catch the mistaken use of = instead of == (ESLint will catch this for you). Therefore, they argue, the utility of the pattern doesn’t outweigh the readability hit the code takes while using Yoda conditions. |
Maintainability | https://eslint.org/docs/rules/yoda |
TypeScript
The section below covers the TSLint code checker issues.
TSLint code checker
TSLint is an open source static code analyser which checks code for readability, maintainability, and functionality errors in TypeScript programs. Visit their website for more detailed information on TSLint and the ruleset found below.
Critical level issue
Rule | Description | KPI | URL |
---|---|---|---|
cyclomatic-complexity | Cyclomatic complexity is a code metric which indicates the level of complexity in a function. High cyclomatic complexity indicates confusing code which may be prone to errors or difficult to modify. | Refactoring | https://palantir.github.io/tslint/rules/trailing-comma |
ban-types | Bans specific types from being used. Does not ban the corresponding runtime objects from being used. | Robustness | |
encoding | Enforces UTF-8 file encoding. | Portability |
High level issue
Rule | Description | KPI | URL |
---|---|---|---|
no-internal-module | Using module leads to a confusion of concepts with external modules. Use the newer namespace keyword instead. | Maintainability | https://palantir.github.io/tslint/rules/ban-types |
no-inferred-empty-object-type | Disallow type inference of {} (empty object type) at function and constructor call sites | Maintainability | https://palantir.github.io/tslint/rules/no-internal-module |
no-unsafe-finally | When used inside finally blocks, control flow statements, such as return, continue, break and throws override any other control flow statements in the same try/catch scope. This is confusing and unexpected behavior. | Maintainability | https://palantir.github.io/tslint/rules/no-unsafe-finally |
no-mergeable-namespace | Disallows mergeable namespaces in the same file. | Maintainability | https://palantir.github.io/tslint/rules/no-mergeable-namespace |
max-classes-per-file | Ensures that files have a single responsibility so that that classes each exist in their own files | Maintainability | https://palantir.github.io/tslint/rules/no-duplicate-variable |
max-file-line-count | Limiting the number of lines allowed in a file allows files to remain small, single purpose, and maintainable. | Maintainability | https://palantir.github.io/tslint/rules/triple-equals |
no-duplicate-variable | A variable can be reassigned if necessary – there’s no good reason to have a duplicate variable declaration. | Robustness | https://palantir.github.io/tslint/rules/curly |
use-isnan | NaN !== NaN, comparisons with regular operators will produce unexpected results. So, instead of if (myVar === NaN), do if (isNaN(myVar)). | Robustness | https://palantir.github.io/tslint/rules/no-duplicate-super |
triple-equals | Requires === and !== in place of == and !=. | Robustness | https://palantir.github.io/tslint/rules/no-import-side-effect |
file-header | Enforces a certain header comment for all files, matched by a regular expression. | Maintainability | https://palantir.github.io/tslint/rules/ban |
no-invalid-template-strings | Warns on use of ${ in non-template strings. | Maintainability | https://palantir.github.io/tslint/rules/no-unnecessary-class |
unified-signatures | Warns for any two overloads that could be unified into one by using a union or an optional/rest parameter. | Maintainability | |
no-parameter-reassignment | Disallows reassigning parameters. | Robustness | |
curly | if (foo === bar) foo++; bar++; In the code above, the author almost certainly meant for both foo++ and bar++ to be executed only if foo === bar. However, he forgot braces and bar++ will be executed no matter what. This rule could prevent such a mistake. | Understandability | |
no-duplicate-super | The second call to “super()” will fail at runtime. | Accuracy | |
no-eval | eval() is dangerous as it allows arbitrary code execution with full privileges. There are alternatives for most of the use cases for eval(). | Robustness | https://palantir.github.io/tslint/rules/await-promise |
radix | From MDN: Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10. | Maintainability | https://palantir.github.io/tslint/rules/interface-name |
no-floating-promises | Unhandled Promises can cause unexpected behavior, such as resolving at unexpected times. | Robustness | https://palantir.github.io/tslint/rules/no-use-before-declare |
no-object-literal-type-assertion | Always prefer const x: T = { … }; to const x = { … } as T;. The type assertion in the latter case is either unnecessary or hides an error. The compiler will warn for excess properties with this syntax, but not missing required fields. For example: const x: { foo: number } = {} will fail to compile, but const x = {} as { foo: number } will succeed. | Maintainability | https://palantir.github.io/tslint/rules/newline-before-return |
no-debugger | In general, debugger statements aren’t appropriate for production code. | Accuracy | https://palantir.github.io/tslint/rules/prefer-conditional-expression |
no-unnecessary-initializer | Forbids a “var”/”let” statement or destructuring initializer to be initialized to “undefined”. | Accuracy | https://palantir.github.io/tslint/rules/align |
switch-default | Require a default case in all switch statements. | Robustness | https://palantir.github.io/tslint/rules/space-before-function-paren |
no-angle-bracket-type-assertion | Both formats of type assertions have the same effect, but only as type assertions work in .tsx files. This rule ensures that you have a consistent type assertion style across your codebase. | Understandability | https://palantir.github.io/tslint/rules/space-within-parens |
object-literal-shorthand | Enforces/disallows use of ES6 object literal shorthand. | Understandability | https://palantir.github.io/tslint/rules/no-boolean-literal-compare |
adjacent-overload-signatures | Improves readability and organization by grouping naturally related items together. | Understandability | https://palantir.github.io/tslint/rules/no-trailing-whitespace |
no-unsafe-any | Warns when using an expression of type ‘any’ in a dynamic way. Uses are only allowed if they would work for {} | null | undefined. Type casts and tests are allowed. Expressions that work on all values (such as “” + x) are allowed. | Accuracy | https://palantir.github.io/tslint/rules/no-irregular-whitespace |
no-this-assignment | Assigning a variable to this instead of properly using arrow lambdas may be a symptom of pre-ES6 practices or not manging scope well. | Accuracy | https://palantir.github.io/tslint/rules/no-duplicate-imports |
no-unbound-method | Warns when a method is used as outside of a method call. | Accuracy | https://palantir.github.io/tslint/rules/member-ordering |
no-return-await | An async function always wraps the return value in a Promise. Using return await just adds extra time before the overreaching promise is resolved without changing the semantics. | Efficiency | |
no-import-side-effect | Imports with side effects may have behavior which is hard for static verification. | Robustness | |
interface-over-type-literal | Interfaces are generally preferred over type literals because interfaces can be implemented, extended and merged. | Maintainability | |
callable-types | Style | Maintainability | https://palantir.github.io/tslint/rules/no-switch-case-fall-through |
no-non-null-assertion | Using non-null assertion cancels the benefits of the strict null checking mode. | Accuracy | https://palantir.github.io/tslint/rules/no-arg |
deprecation | Deprecated APIs should be avoided, and usage updated. | Maintainability | https://palantir.github.io/tslint/rules/no-string-throw |
ban | Bans the use of specific functions or global methods. | Maintainability | https://palantir.github.io/tslint/rules/no-parameter-properties |
no-reference | Using /// comments to load other files is outdated. Use ES6-style imports to reference other files. | Maintainability | https://palantir.github.io/tslint/rules/no-sparse-arrays |
no-duplicate-switch-case | Prevents duplicate cases in switch statements. | Accuracy | https://palantir.github.io/tslint/rules/no-unnecessary-type-assertion |
no-unnecessary-class | Users who come from a Java-style OO language may wrap their utility functions in an extra class, instead of putting them at the top level. | Maintainability | https://palantir.github.io/tslint/rules/binary-expression-operand-order |
no-disable-auto-sanitization | Do not disable auto-sanitization of HTML because this opens up your page to an XSS attack. Specifically, do not use the execUnsafeLocalFunction or setInnerHTMLUnsafefunctions. | Security | https://palantir.github.io/tslint/rules/no-invalid-this |
no-duplicate-parameter-names | This rule is now enforced by the TypeScript compiler. Do not write functions or methods with duplicate parameter names | Robustness | https://palantir.github.io/tslint/rules/no-dynamic-delete |
no-http-string | Do not use strings that start with ‘http:’. URL strings should start with ‘https:’. Http strings can be a security problem and indicator that your software may suffer from cookie-stealing attacks. Since version 1.0, this rule takes a list of regular expressions as a parameter. Any string matching that regular expression will be ignored. For example, to allow http connections to example.com and examples.com, configure your rule like this: “no-http-string”: [true, “http://www.example.com/?.*”, “http://www.examples.com/?.*”] | Security | https://palantir.github.io/tslint/rules/no-unnecessary-callback-wrapper |
no-octal-literal | Do not use octal literals or escaped octal sequences. Octals in JS have historically been a non-standard extension to the standard (in ES5, which introduces strict mode, they’re in Annex B, which is a collection of non-standard features that most implementations support: except it defines octals in a way incompatible with what websites require), and strict mode made an attempt to disallow all non-standard extensions | Maintainability | |
no-with-statement | Do not use with statements. Assign the item to a new variable instead. Use of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues. The with statement forces the specified object to be searched first for all name lookups. Therefore all identifiers that aren’t members of the specified object will be found more slowly in a ‘with’ block. Where performance is important, ‘with’ should only be used to encompass code blocks that access members of the specified object. | Maintainability | |
non-literal-require | Detect require() function calls for something that is not a string literal. For security reasons, it is best to only require() string literals. Otherwise, it is perhaps possible for an attacker to somehow change the value and download arbitrary Javascript into your page. | Security | |
possible-timing-attack | Avoid timing attacks by not making direct string comparisons to sensitive data. Do not compare against variables named password, secret, api, apiKey, token, auth, pass, or hash. For more info see Using Node.js Event Loop for Timing Attacks | Security |
Medium level issue
Rule | Description | KPI | URL |
---|---|---|---|
no-console | In general, console methods aren’t appropriate for production code. | Resource Utilization | https://palantir.github.io/tslint/rules/cyclomatic-complexity |
no-magic-numbers | Magic numbers should be avoided as they often lack documentation, forcing them to be stored in variables gives them implicit documentation.When no list of allowed values is specified, -1, 0 and 1 are allowed by default. | Maintainability | https://palantir.github.io/tslint/rules/encoding |
no-var-keyword | Disallows usage of the var keyword. Use let or const instead. | Maintainability | https://palantir.github.io/tslint/rules/no-inferred-empty-object-type |
typeof-compare | Makes sure result of typeof is compared to correct string values | Maintainability | https://palantir.github.io/tslint/rules/use-isnan |
no-switch-case-fall-through | Fall though in switch statements is often unintentional and a bug. | Accuracy | https://palantir.github.io/tslint/rules/no-invalid-template-strings |
no-arg | Using arguments.callee makes various performance optimizations impossible. See MDN for more details on why to avoid arguments.callee. | Efficiency | https://palantir.github.io/tslint/rules/unified-signatures |
arrow-return-shorthand | Suggests to convert () => { return x; } to () => x. | Understandability | https://palantir.github.io/tslint/rules/no-floating-promises |
no-var-requires | Disallows the use of require statements except in import statements.In other words, the use of forms such as var module = require(“module”) are banned. Instead use ES6 style imports or import foo = require(‘foo’) imports. | Maintainability | https://palantir.github.io/tslint/rules/no-object-literal-type-assertion |
no-submodule-imports | Submodules of some packages are treated as private APIs and the import paths may change without deprecation periods. It’s best to stick with top-level package exports. | Maintainability | https://palantir.github.io/tslint/rules/no-debugger |
no-inferrable-types | Explicit types where they can be easily inferred by the compiler make code more verbose. | Robustness | https://palantir.github.io/tslint/rules/no-unnecessary-initializer |
no-redundant-jsdoc | Forbids JSDoc which duplicates TypeScript functionality. | Maintainability | https://palantir.github.io/tslint/rules/adjacent-overload-signatures |
use-default-type-parameter | Warns if an explicitly specified type argument is the default for that type parameter. | Maintainability | https://palantir.github.io/tslint/rules/no-return-await |
no-shadowed-variable | Shadowing a variable masks access to it and obscures to what value an identifier actually refers. | Robustness | https://palantir.github.io/tslint/rules/interface-over-type-literal |
no-string-throw | Flags throwing plain strings or concatenations of strings because only Errors produce proper stack traces. | Maintainability | https://palantir.github.io/tslint/rules/no-non-null-assertion |
no-string-literal | If –noImplicitAny is turned off, property access via a string literal will be ‘any’ if the property does not exist. | Robustness | https://palantir.github.io/tslint/rules/no-duplicate-switch-case |
forin | for (let key in someObject) { if (someObject.hasOwnProperty(key)) { // code here } } Prevents accidental iteration over properties inherited from an object’s prototype. See MDN’s for…in documentation for more information about for…in loops. | Maintainability | |
no-parameter-properties | Parameter properties can be confusing to those new to TS as they are less explicit than other ways of declaring and initializing class members. | Understandability | |
variable-name | Checks variable names for various errors. | Understandability | |
match-default-export-name | Requires that a default import have the same name as the declaration it imports. Does nothing for anonymous default exports. | Understandability | https://palantir.github.io/tslint/rules/max-line-length |
no-any | Using any as a type declaration nullifies the compile-time benefits of the type system. | Robustness | https://palantir.github.io/tslint/rules/arrow-parens |
prefer-switch | Prefer a switch statement to an if statement with simple === comparisons. | Maintainability | https://palantir.github.io/tslint/rules/new-parens |
switch-final-break | Checks whether the final clause of a switch statement ends in break; | Robustness | https://palantir.github.io/tslint/rules/one-variable-per-declaration |
no-sparse-arrays | Missing elements are probably an accidentally duplicated comma. | Robustness | https://palantir.github.io/tslint/rules/semicolon |
ban-comma-operator | Using the comma operator can create a potential for many non-obvious bugs or lead to misunderstanding of code. | Understandability | https://palantir.github.io/tslint/rules/no-consecutive-blank-lines |
no-unnecessary-type-assertion | Warns if a type assertion does not change the type of an expression. | Understandability | https://palantir.github.io/tslint/rules/prefer-function-over-method |
no-conditional-assignment | Assignments in conditionals are often typos: for example if (var1 = var2) instead of if (var1 == var2). They also can be an indicator of overly clever code which decreases maintainability. | Accuracy | https://palantir.github.io/tslint/rules/completed-docs |
prefer-for-of | A for(… of …) loop is easier to implement and read when the index is not needed. | Understandability | https://palantir.github.io/tslint/rules/linebreak-style |
binary-expression-operand-order | In a binary expression, a literal should always be on the right-hand side if possible. For example, prefer “x + 1” over “1 + x”. | Understandability | https://palantir.github.io/tslint/rules/no-default-export |
promise-function-async | Ensures that each function is only capable of 1) returning a rejected promise, or 2) throwing an Error object. In contrast, non-async Promise-returning functions are technically capable of either. This practice removes a requirement for consuming code to handle both cases. | Maintainability | https://palantir.github.io/tslint/rules/whitespace |
no-implicit-dependencies | Disallows importing transient dependencies and modules installed above your package’s root directory. | Maintainability | https://palantir.github.io/tslint/rules/ordered-imports |
no-unnecessary-qualifier | Warns when a namespace qualifier (A.x) is unnecessary. | Accuracy | https://palantir.github.io/tslint/rules/strict-boolean-expressions |
no-for-in-array | Disallows iterating over an array with a for-in loop. A for-in loop (for (var k in o)) iterates over the properties of an Object. While it is legal to use for-in loops with array types, it is not common. for-in will iterate over the indices of the array as strings, omitting any “holes” in the array. More common is to use for-of, which iterates over the values of an array. If you want to iterate over the indices, alternatives include: array.forEach((value, index) => { … }); for (const [index, value] of array.entries()) { … } for (let i = 0; i < array.length; i++) { … } | Accuracy | https://palantir.github.io/tslint/rules/no-empty |
prefer-const | If a variable is only assigned to once when it is declared, it should be declared using ‘const’. | Understandability | https://palantir.github.io/tslint/rules/object-literal-sort-keys |
object-literal-key-quotes | Object literal property names can be defined in two ways: using literals or using strings. For example, these two objects are equivalent: var object1 = { property: true }; var object2 = { ‘property’ : true }; In many cases, it doesn’t matter if you choose to use an identifier instead of a string or vice-versa. Even so, you might decide to enforce a consistent style in your code. This rules lets you enforce consistent quoting of property names. Either they should always be quoted (default behavior) or quoted only as needed (‘as-needed’). | Understandability | https://palantir.github.io/tslint/rules/comment-format |
typedef | Requires type definitions to exist. | Understandability | |
class-name | Makes it easy to differentiate classes from regular variables at a glance. | Understandability | |
prefer-readonly | Marking never-modified variables as readonly helps enforce the code’s intent of keeping them as never-modified. It can also help prevent accidental changes of members not meant to be changed. | Accuracy | |
no-null-keyword | Instead of having the dual concepts of null andundefined in a codebase, this rule ensures that only undefined is used. | Understandability | |
no-namespace | ES6-style external modules are the standard way to modularize code. Using module {} and namespace {} are outdated ways to organize TypeScript code. | Maintainability | |
prefer-template | Prefer a template expression over string literal concatenation. | Understandability | |
member-access | Explicit visibility declarations can make code more readable and accessible for those new to TS. | Understandability | |
no-construct | There is little reason to use String, Number, or Boolean as constructors. In almost all cases, the regular function-call version is more appropriate. More details are available on StackOverflow. | Understandability | |
return-undefined | Prefer return; in void functions and return undefined; in value-returning functions. | Accuracy | |
no-reference-import | Don’t if you import foo anyway. | Maintainability | |
import-blacklist | Some libraries allow importing their submodules instead of the entire module. This is good practise as it avoids loading unused modules. | Efficiency | |
no-bitwise | Bitwise operators are often typos – for example bool1 & bool2 instead of bool1 && bool2. They also can be an indicator of overly clever code which decreases maintainability. | Accuracy | |
prefer-object-spread | Object spread allows for better type checking and inference. | Maintainability | |
restrict-plus-operands | When adding two variables, operands must both be of type number or of type string. | Accuracy | |
no-invalid-this | See the rule’s author;s rationale here. | Maintainability | https://palantir.github.io/tslint/rules/typeof-compare |
no-misused-new | Warns on apparent attempts to define constructors for interfaces or new for classes. | Accuracy | https://palantir.github.io/tslint/rules/no-var-requires |
newline-per-chained-call | This style helps to keep code “vertical”, avoiding the need for side-scrolling in IDEs or text editors. | Understandability | https://palantir.github.io/tslint/rules/no-inferrable-types |
no-unused-variable | In addition to avoiding compilation errors, this rule may still be useful if you wish to have tslint automatically remove unused imports, variables, functions, and private class members, when using TSLint’s –fix option. | Maintainability | https://palantir.github.io/tslint/rules/no-redundant-jsdoc |
no-dynamic-delete | Deleting dynamically computed keys is dangerous and not well optimized. | Accuracy | https://palantir.github.io/tslint/rules/use-default-type-parameter |
quotemark | Requires single or double quotes for string literals. | Accuracy | https://palantir.github.io/tslint/rules/no-string-literal |
no-unused-expression | Detects potential errors where an assignment or function call was intended. | Maintainability | https://palantir.github.io/tslint/rules/forin |
label-position | Labels in JavaScript only can be used in conjunction with break or continue, constructs meant to be used for loop flow control. While you can theoretically use labels on any block statement in JS, it is considered poor code structure to do so. |
Maintainability | https://palantir.github.io/tslint/rules/match-default-export-name |
no-empty-interface | An empty interface is equivalent to its supertype (or {}). | Maintainability | https://palantir.github.io/tslint/rules/no-any |
only-arrow-functions | Traditional functions don’t bind lexical scope, which can lead to unexpected behavior when accessing “this”. | Accuracy | https://palantir.github.io/tslint/rules/prefer-switch |
no-require-imports | Prefer the newer ES6-style imports over require(). | Maintainability | Checks whether the final clause of a switch statement ends in break; |
no-unnecessary-callback-wrapper | Replaces x => f(x) with just f. To catch more cases, enable only-arrow-functions and arrow-return-shorthand too. | Accuracy | https://palantir.github.io/tslint/rules/ban-comma-operator |
no-void-expression | Requires expressions of type void to appear in statement position. | Maintainability | https://palantir.github.io/tslint/rules/no-conditional-assignment |
array-type | Requires using either “T[]” or “Array” for arrays. | Maintainability | https://palantir.github.io/tslint/rules/prefer-for-of |
Prefer-method-signature | Prefer foo(): void over foo: () => void in interfaces and types. | Maintainability | https://palantir.github.io/tslint/rules/promise-function-async |
chai-prefer-contains-to-index-of | Avoid Chai assertions that invoke indexOf and compare for a -1 result. It is better to use the chai .contain() assertion API instead because the failure message will be more clearer if the test fails. | Efficiency | https://palantir.github.io/tslint/rules/no-implicit-dependencies |
chai-vague-errors | Avoid Chai assertions that result in vague errors. For example, asserting expect(something).to.be.true will result in the failure message “Expected true received false”. This is a vague error message that does not reveal the underlying problem. It is especially vague in TypeScript because stack trace line numbers often do not match the source code. A better pattern to follow is the xUnit Patterns Assertion Message pattern. The previous code sample could be better written as expect(something).to.equal(true, ‘expected something to have occurred’); | Maintainability | https://palantir.github.io/tslint/rules/no-unnecessary-qualifier |
export-name | The name of the exported module must match the filename of the source file. This is case-sensitive but ignores file extension. Since version 1.0, this rule takes a list of regular expressions as a parameter. Any export name matching that regular expression will be ignored. For example, to allow an exported name like myChartOptions, then configure the rule like this: “export-name”: [true, “myChartOptionsg”] | Maintainability | https://palantir.github.io/tslint/rules/no-for-in-array |
function-name | Applies a naming convention to function names and method names. You can configure the naming convention by passing parameters. Please note, the private-method-regex does take precedence over the static-method-regex, so a private static method must match the private-method-regex. The default values are: [ true, { “method-regex”: “^[a-z][wd]+$”, “private-method-regex”: “^[a-z][wd]+$”, “protected-method-regex”: “^[a-z][wd]+$”, “static-method-regex”: “^[A-Z_d]+$”, “function-regex”: “^[a-z][wd]+$” } This rule has some overlap with the tslint variable-name rule; however, the rule here is more configurable.] | Maintainability | https://palantir.github.io/tslint/rules/prefer-const |
import-name | The name of the imported module must match the name of the thing being imported. For example, it is valid to name imported modules the same as the module name: import Service = require(‘x/y/z/Service’) and import Service from ‘x/y/z/Service’. But it is invalid to change the name being imported, such as: import MyCoolService = require(‘x/y/z/Service’) and import MyCoolService from ‘x/y/z/Service’. Since version 2.0.9 it is possible to configure this rule with a list of exceptions. For example, to allow underscore to be imported as _, add this configuration: ‘import-name’: [ true, { ‘underscore’: ‘_’ }] | Maintainability | https://palantir.github.io/tslint/rules/object-literal-key-quotes |
insecure-random | Do not use insecure sources for random bytes. Use a secure random number generator instead. Bans all uses of Math.random and crypto.pseudoRandomBytes. Better alternatives are crypto.randomBytes and window.crypto.getRandomValues. References: * CWE 330 * MDN Math.random * Node.js crypto.randomBytes() * window.crypto.getRandomValues() | Accuracy | https://palantir.github.io/tslint/rules/typedef |
jquery-deferred-must-complete | When a JQuery Deferred instance is created, then either reject() or resolve() must be called on it within all code branches in the scope. | Maintainability | https://palantir.github.io/tslint/rules/class-name |
max-func-body-length | Avoid long functions. The line count of a function body must not exceed the value configured within this rule’s options. You can setup a general max function body length applied for every function/method/arrow function e.g. [true, 30] or set different maximum length for every type e.g. [true, { “func-body-length”: 10 , “func-expression-body-length”: 10 , “arrow-body-length”: 5, “method-body length”: 15, “ctor-body-length”: 5 }]. To specify a function name whose parameters you can ignore for this rule, pass a regular expression as a string(this can be useful for Mocha users to ignore the describe() function). Since version 2.0.9, you can also ignore single- and multi-line comments from the total function length, eg. [true, { “ignore-comments”: true }] | Maintainability | https://palantir.github.io/tslint/rules/prefer-readonly |
mocha-no-side-effect-code | All test logic in a Mocha test case should be within Mocha lifecycle method and not defined statically to execute when the module loads. Put all assignments and initialization statements in a before(), beforeEach(), beforeAll(), after(), afterEach(), afterAll(), or it() function. Code executed outside of these lifecycle methods can throw exceptions before the test runner is initialized and can result in errors or even test runner crashes. This rule can be configured with a regex to ignore certain initializations. For example, to ignore any calls to RestDataFactory configure the rule with: [true, { ignore: ‘^RestDataFactory..*’ }] | Accuracy | https://palantir.github.io/tslint/rules/member-access |
no-backbone-get-set-outside-model | Avoid using model.get(‘x’) and model.set(‘x’, value) Backbone accessors outside of the owning model. This breaks type safety and you should define getters and setters for your attributes instead. | Maintainability | https://palantir.github.io/tslint/rules/return-undefined |
no-banned-terms | Do not use banned terms: caller, callee, eval, arguments. These terms refer to functions or properties that should not be used, so it is best practice to simply avoid them. | Understandability | https://palantir.github.io/tslint/rules/no-reference-import |
no-document-domain | Do not write to document.domain. Scripts setting document.domain to any value should be validated to ensure that the value is on a list of allowed sites. Also, if your site deals with PII in any way then document.domain must not be set to a top-level domain (for example, live.com) but only to an appropriate subdomain (for example, billing.live.com). If you are absolutely sure that you want to set document.domain then add a tslint suppression comment for the line. For more information see the Phase 4 Verification page of the Microsoft SDL | Security | https://palantir.github.io/tslint/rules/no-misused-new |
no-duplicate-case | This rule can be replaced with TSLint’s no-duplicate-switch-case. Do not use duplicate case labels in switch statements. Similar to the ESLint no-duplicate-caserule | Maintainability | https://palantir.github.io/tslint/rules/no-unused-variable |
no-empty-interfaces | Do not use empty interfaces. They are compile-time only artifacts and they serve no useful purpose | Maintainability | https://palantir.github.io/tslint/rules/quotemark |
no-exec-script | Do not use the execScript functions. window.execScript is not crossing browsers, only IE supports it. | Robustness | https://palantir.github.io/tslint/rules/label-position |
no-inner-html | Do not write values to innerHTML, outerHTML, or set HTML using the JQuery html() function. Writing values to innerHTML can expose your website to XSS injection attacks. All strings must be escaped before being rendered to the page. | Security | https://palantir.github.io/tslint/rules/array-type |
no-invalid-regexp | Do not use invalid regular expression strings in the RegExp constructor. Similar to the ESLint no-invalid-regexp rule | Maintainability | https://palantir.github.io/tslint/rules/prefer-method-signature |
no-missing-visibility-modifiers | This rule is in the TSLint product as member-access. Class members (both fields and methods) should have visibility modifiers specified. THe Principle of Least Visibility guides us to prefer private methods and fields when possible. If a developer forgets to add a modifier then TypeScript assumes the element should be public, which is the wrong default choice. | Maintainability | |
no-multiple-var-decl | Deprecated – This rule is now part of the base TSLint product as the rule named ‘one-variable-per-declaration’. Do not use comma separated variable declarations | Maintainability | |
no-regex-spaces | Do not use multiple spaces in a regular expression literal. Similar to the ESLint no-regex-spaces rule | Maintainability | |
no-relative-imports | Do not use relative paths when importing external modules or ES6 import declarations. The advantages of removing all relative paths from imports is that 1) the import name will be consistent across all files and subdirectories so searching for usages is much easier. 2) Moving source files to different folders will not require you to edit your import statements. 3) It will be possible to copy and paste import lines between files regardless of the file location. And 4) version control diffs will be simplified by having overall fewer edits to the import lines. | Maintainability | |
no-reserved-keywords | Do not use reserved keywords as names of local variables, fields, functions, or other identifiers. Since version 2.0.9 this rule accepts a parameter called allow-quoted-properties. If true, interface properties in quotes will be ignored. This can be a useful way to avoid verbose suppress-warning comments for generated d.ts files. This rule has some overlap with the tslint variable-name rule, however, the rule here finds more keywords and more usages. | Maintainability | |
no-stateless-class | Deprecated – This rule can be replaced with TSLint’s no-unnecessary-class. A stateless class represents a failure in the object oriented design of the system. A class without state is better modeled as a module or given some state. A stateless class is defined as a class with only static members and no parent class. | Maintainability | |
no-suspicious-comment | Do not use suspicious comments, such as BUG, HACK, FIXME, LATER, LATER2, TODO. We recommend that you run this rule before each release as a quality checkpoint. Reference: CWE-546 Suspicious Comment | Robustness | |
no-typeof-undefined | Do not use the idiom typeof x === ‘undefined’. You can safely use the simpler x === undefined or perhaps x == null if you want to check for either null or undefined. | Accuracy | |
no-unnecessary-bind | Do not bind ‘this’ as the context for a function literal or lambda expression. If you bind ‘this’ as the context to a function literal, then you should just use a lambda without the bind. If you bind ‘this’ as the context to a lambda, then you can remove the bind call because ‘this’ is already the context for lambdas. Works for Underscore methods as well. | Accuracy | |
no-unnecessary-field-initialization | Do not unnecessarily initialize the fields of a class to values they already have. For example, there is no need to explicitly set a field to undefined in the field’s initialization or in the class’ constructor. Also, if a field is initialized to a constant value (null, a string, a boolean, or some number) then there is no need to reassign the field to this value within the class constructor. | Resource Utilization | |
no-unnecessary-override | Do not write a method that only calls super() on the parent method with the same arguments. You can safely remove methods like this and Javascript will correctly dispatch the method to the parent object. | Resource Utilization | |
no-unsupported-browser-code | Avoid writing browser-specific code for unsupported browser versions. Browser versions are specified in the rule configuration options, eg: [true, [ “IE 11”, “Firefox > 40”, “Chrome >= 45” ] ]. Browser-specific blocks of code can then be designated with a single-line comment, like so: // Browser specific: IE 10, or with a jsdoc like this: @browserspecific chrome 40. | Understandability | |
no-useless-files | Avoid keeping files around that only contain commented out code, are completely empty, or only contain whitespace characters | Resource Utilization | |
no-var-self | Deprecated – This rule can be replaced with TSLint’s no-this-assignment. Do not use var self = this; instead, manage scope with arrow functions/lambdas. Self variables are a common practice in JavaScript but can be avoided in TypeScript. By default the rule bans any assignments of the this reference. If you want to enforce a naming convention or allow some usages then configure the rule with a regex. By default the rule is configured with (?!) which matches nothing. You can pass ^self$ to allow variables named self or pass ^(?!self$) to allow anything other than self, for example | Maintainability | |
prefer-array-literal | Use array literal syntax when declaring or instantiating array types. For example, prefer the Javascript form of string[] to the TypeScript form Array. Prefer ‘[]’ to ‘new Array()’. Prefer ‘[4, 5]’ to ‘new Array(4, 5)’. Prefer ‘[undefined, undefined]’ to ‘new Array(4)’. Since 2.0.10, this rule can be configured to allow Array type parameters. To ignore type parameters, configure the rule with the values: [ true, { ‘allow-type-parameters’: true } ] This rule has some overlap with the TSLint array-type rule, however, the version here catches more instances. | Maintainability | |
promise-must-complete | When a Promise instance is created, then either the reject() or resolve() parameter must be called on it within all code branches in the scope. For more examples see the feature request. This rule has some overlap with the tslint no-floating-promises rule, but they are substantially different. | Maintainability | |
react-a11y-aria-unsupported-elements | For accessibility of your website, enforce that elements that do not support ARIA roles, states, and properties do not have those attributes. | Maintainability | |
react-a11y-event-has-role | For accessibility of your website, Elements with event handlers must have explicit role or implicit role. | Maintainability | |
react-a11y-image-button-has-alt | For accessibility of your website, enforce that inputs element with type=”image” must have non-empty alt attribute. | Maintainability | |
react-a11y-img-has-alt | Enforce that an img element contains the alt attribute or role=’presentation’ for a decorative image. All images must have alt text to convey their purpose and meaning to screen reader users. Besides, the alt attribute specifies an alternate text for an image, if the image cannot be displayed. This rule accepts as a parameter a string array for tag names other than img to also check. For example, if you use a custom tag named ‘Image’ then configure the rule with: [true, [‘Image’]] | Maintainability | |
react-a11y-lang | For accessibility of your website, HTML elements must have a lang attribute and the attribute must be a valid language code. | Maintainability | |
react-a11y-meta | For accessibility of your website, HTML meta elements must not have http-equiv=”refresh”. | Maintainability | |
react-a11y-props | For accessibility of your website, enforce all aria-* attributes are valid. Elements cannot use an invalid aria-* attribute. This rule will fail if it finds an aria-* attribute that is not listed in WAI-ARIA states and properties. | Maintainability | |
react-a11y-proptypes | For accessibility of your website, enforce the type of aria state and property values are correct. | Maintainability | |
react-a11y-role-has-required-aria-props | For accessibility of your website, elements with aria roles must have all required attributes according to the role. | Maintainability | |
react-a11y-role-supports-aria-props | For accessibility of your website, enforce that elements with explicit or implicit roles defined contain only aria-* properties supported by that role. Many aria attributes (states and properties) can only be used on elements with particular roles. Some elements have implicit roles, such as , which will be resolved to role=’link’. A reference for the implicit roles can be found at Default Implicit ARIA Semantics. | Maintainability | |
react-a11y-role | For accessibility of your website, elements with aria roles must use a valid, non-abstractaria role. A reference to role defintions can be found at WAI-ARIA roles. | Maintainability | |
react-a11y-tabindex-no-positive | For accessibility of your website, enforce tabindex value is not greater than zero. Avoid positive tabindex attribute values to synchronize the flow of the page with keyboard tab order. | Maintainability | |
react-a11y-titles | For accessibility of your website, HTML title elements must not be empty, must be more than one word, and must not be more than 60 characters long. | Maintainability | |
react-anchor-blank-noopener | For security reasons, anchor tags with target=”_blank” should also include rel=”noopener noreferrer”. In order to restrict the behavior window.opener access, the original page needs to add a rel=”noopener” attribute to any link that has target=”_blank”. However, Firefox does not support that tag, so you should actually use rel=”noopener noreferrer” for full coverage. For more info see: The target=”_blank” vulnerability by example | Maintainability | |
react-iframe-missing-sandbox | React iframes must specify a sandbox attribute. If specified as an empty string, this attribute enables extra restrictions on the content that can appear in the inline frame. The value of the attribute can either be an empty string (all the restrictions are applied), or a space-separated list of tokens that lift particular restrictions. You many not use both allow-scripts and allow-same-origin at the same time, as that allows the embedded document to programmatically remove the sandbox attribute in some scenarios. | Maintainability | |
react-no-dangerous-html | Do not use React’s dangerouslySetInnerHTML API. This rule finds usages of the dangerouslySetInnerHTML API (but not any JSX references). For more info see the react-no-dangerous-html Rule wiki page. | Security | |
react-this-binding-issue | Several errors can occur when using React and React.Component subclasses. When using React components you must be careful to correctly bind the ‘this’ reference on any methods that you pass off to child components as callbacks. For example, it is common to define a private method called ‘onClick’ and then specify onClick={this.onClick} as a JSX attribute. If you do this then the ‘this’ reference will be undefined when your private method is invoked. The React documentation suggests that you bind the ‘this’ reference on all of your methods within the constructor: this.onClick = this.onClick.bind(this);. This rule will create a violation if 1) a method reference is passed to a JSX attribute without being bound in the constructor. And 2) a method is bound multiple times in the constructor. Another issue that can occur is binding the ‘this’ reference to a function within the render() method. For example, many people will create an anonymous lambda within the JSX attribute to avoid the ‘this’ binding issue: onClick={() => { this.onClick(); }}. The problem with this is that a new instance of an anonymous function is created every time render() is invoked. When React compares virutal DOM properties within shouldComponentUpdate() then the onClick property will look like a new property and force a re-render. You should avoid this pattern because creating function instances within render methods breaks any logic within shouldComponentUpdate() methods. This rule creates violations if 1) an anonymous function is passed as a JSX attribute. And 2) if a function instantiated in local scope is passed as a JSX attribute. This rule can be configured via the “allow-anonymous-listeners” parameter. If you want to suppress violations for the anonymous listener scenarios then configure that rule like this: “react-this-binding-issue”: [ true, { ‘allow-anonymous-listeners’: true } ] | Maintainability | |
underscore-consistent-invocation | Enforce a consistent usage of the _ functions. By default, invoking underscore functions should begin with wrapping a variable in an underscore instance: _(list).map(…). An alternative is to prefer using the static methods on the _ variable: _.map(list, …). The rule accepts single parameter called ‘style’ which can be the value ‘static’ or ‘instance’: [true, { “style”: “static” }] | Maintainability | |
use-named-parameter | Do not reference the arguments object by numerical index; instead, use a named parameter. This rule is similar to JSLint’s Use a named parameter rule. | Maintainability | |
valid-typeof | Deprecated – This rule is now enforced by the TypeScript compiler. Ensures that the results of typeof are compared against a valid string. This rule aims to prevent errors from likely typos by ensuring that when the result of a typeof operation is compared against a string, that the string is a valid value. Similar to the valid-typeof ESLint rule. | Accuracy |
Low level issue
Rule | Description | KPI | URL |
---|---|---|---|
import-spacing | Ensures proper spacing between import statement keywords | Understandability | https://palantir.github.io/tslint/rules/max-classes-per-file |
interface-name | Makes it easy to differentiate interfaces from regular classes at a glance. | Understandability | https://palantir.github.io/tslint/rules/max-file-line-count |
indent | Using only one of tabs or spaces for indentation leads to more consistent editor behavior, cleaner diffs in version control, and easier programmatic manipulation. | Understandability | https://palantir.github.io/tslint/rules/file-header |
max-line-length | Limiting the length of a line of code improves code readability. It also makes comparing code side-by-side easier and improves compatibility with various editors, IDEs, and diff viewers. | Maintainability | https://palantir.github.io/tslint/rules/no-parameter-reassignment |
arrow-parens | Maintains stylistic consistency with other arrow function definitions. | Understandability | https://palantir.github.io/tslint/rules/no-eval |
no-use-before-declare | This rule is primarily useful when using the var keyword since the compiler will automatically detect if a block-scoped let and const variable is used before declaration. Since most modern TypeScript doesn’t use var, this rule is generally discouraged and is kept around for legacy purposes. It is slow to compute, is not enabled in the built-in configuration presets, and should not be used to inform TSLint design decisions. | Robustness | https://palantir.github.io/tslint/rules/radix |
newline-before-return | Helps maintain a readable style in your codebase. | Understandability | https://palantir.github.io/tslint/rules/switch-default |
prefer-conditional-expression | This reduces duplication and can eliminate an unnecessary variable declaration. | Efficiency | https://palantir.github.io/tslint/rules/no-angle-bracket-type-assertion |
new-parens | Maintains stylistic consistency with other function calls. | Understandability | https://palantir.github.io/tslint/rules/object-literal-shorthand |
align | Helps maintain a readable, consistent style in your codebase. | Understandability | https://palantir.github.io/tslint/rules/no-unbound-method |
space-before-function-paren | Require or disallow a space before function parenthesis | Understandability | https://palantir.github.io/tslint/rules/callable-types |
space-within-parens | Enforces spaces within parentheses or disallow them. Empty parentheses () are always allowed. | Understandability | https://palantir.github.io/tslint/rules/deprecation |
one-variable-per-declaration | Disallows multiple variable definitions in the same declaration statement. | Understandability | https://palantir.github.io/tslint/rules/no-reference |
typedef-whitespace | Determines if a space is required or not before the colon in a type specifier. | Understandability | https://palantir.github.io/tslint/rules/strict-type-predicates |
semicolon | Enforces consistent semicolon usage at the end of every statement. | Understandability | https://palantir.github.io/tslint/rules/import-spacing |
trailing-comma | Requires or disallows trailing commas in array and object literals, destructuring assignments, function typings, named imports and exports and function parameters. | Understandability | https://palantir.github.io/tslint/rules/indent |
no-consecutive-blank-lines | Helps maintain a readable style in your codebase. | Understandability | https://palantir.github.io/tslint/rules/typedef-whitespace |
prefer-function-over-method | Warns for class methods that do not use “this”. | Accuracy | https://palantir.github.io/tslint/rules/eofline |
no-boolean-literal-compare | Warns on comparison to a boolean literal, as in x === true. | Robustness | https://palantir.github.io/tslint/rules/type-literal-delimiter |
completed-docs | Enforces documentation for important items be filled out. | Understandability | https://palantir.github.io/tslint/rules/jsdoc-format |
linebreak-style | Enforces a consistent linebreak style. | Understandability | https://palantir.github.io/tslint/rules/one-line |
no-default-export | Named imports/exports promote clarity. In addition, current tooling differs on the correct way to handle default imports/exports. Avoiding them all together can help avoid tooling bugs and conflicts. | Understandability | https://palantir.github.io/tslint/rules/number-literal-format |
no-trailing-whitespace | Keeps version control diffs clean as it prevents accidental whitespace from being committed. | Understandability | |
eofline | It is a standard convention to end files with a newline. | Understandability | |
whitespace | Helps maintain a readable, consistent style in your codebase. | Understandability | |
no-irregular-whitespace | Disallow irregular whitespace within a file, including strings and comments. | Understandability | |
ordered-imports | Requires that import statements be alphabetized and grouped. Enforce a consistent ordering for ES6 imports: Named imports must be alphabetized (i.e. import {A, B, C} from foo;) The exact ordering can be controlled by the named-imports-order option. “longName as name” imports are ordered by ‘longName’. Import sources must be alphabetized within groups, i.e.: import * as foo from “a” ; import * as bar from “b” ; Groups of imports are delineated by blank lines. You can use these to group imports however you like, e.g. by first- vs. third-party or thematically or can you can enforce a grouping of third-party, parent directories and the current directory. | Understandability | |
type-literal-delimiter | Checks that type literal members are separated by semicolons. Enforces a trailing semicolon for multiline type literals. | Understandability | |
jsdoc-format | Helps maintain a consistent, readable style for JSDoc comments. | Understandability | |
one-line | Requires the specified tokens to be on the same line as the expression preceding them. | Understandability | |
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. | Understandability | https://palantir.github.io/tslint/rules/no-console |
member-ordering | A consistent ordering for class members can make classes easier to read, navigate, and edit. | Maintainability | https://palantir.github.io/tslint/rules/no-magic-numbers |
strict-boolean-expressions | Restricts the types allowed in boolean expressions. By default only booleans are allowed. The following nodes are checked: Arguments to the !, &&, and || operators The condition in a conditional expression (cond ? x : y) Conditions for if, for, while, and do-while statements. | Understandability | https://palantir.github.io/tslint/rules/no-var-keyword |
number-literal-format | Checks that decimal literals should begin with ‘0.’ instead of just ‘.’, and should not end with a trailing ‘0’. | Understandability | https://palantir.github.io/tslint/rules/arrow-return-shorthand/ |
no-empty | Empty blocks are often indicators of missing code. | Accuracy | https://palantir.github.io/tslint/rules/no-submodule-imports |
object-literal-sort-keys | Useful in preventing merge conflicts | Maintainability | https://palantir.github.io/tslint/rules/no-shadowed-variable |
comment-format | Helps maintain a consistent, readable style in your codebase. | Understandability | https://palantir.github.io/tslint/rules/variable-name |
missing-jsdoc | All files must have a top level JSDoc comment. A JSDoc comment starts with /** (not one more or one less asterisk) and a JSDoc at the ‘top-level’ appears without leading spaces. Trailing spaces are acceptable but not recommended. | Understandability | https://palantir.github.io/tslint/rules/no-null-keyword |
missing-optional-annotation | Deprecated – This rule is now enforced by the TypeScript compiler. A parameter that follows one or more parameters marked as optional is not itself marked optional | Understandability | https://palantir.github.io/tslint/rules/no-namespace |
mocha-avoid-only | Do not invoke Mocha’s describe.only, it.only or context.only functions. These functions are useful ways to run a single unit test or a single test case during your build, but please be careful to not push these methods calls to your version control repositiory because it will turn off any of the other tests. | Testability | https://palantir.github.io/tslint/rules/prefer-template |
mocha-unneeded-done | A function declares a MochaDone parameter but only resolves it synchronously in the main function. The MochaDone parameter can be safely removed from the parameter list. | Maintainability | https://palantir.github.io/tslint/rules/no-construct |
no-constant-condition | Do not use constant expressions in conditions. Similar to the ESLint no-constant-conditionrule. Since version 2.0.14, this rule accepts a parameter called checkLoops which defaults to true. If set to false then loops are not checked for conditionals. For example, disable loop checking with [ true, { ‘checkLoops’: false } ] | Maintainability | https://palantir.github.io/tslint/rules/import-blacklist |
no-control-regex | Do not use control characters in regular expressions . Similar to the ESLint no-control-regex rule | Maintainability | https://palantir.github.io/tslint/rules/no-bitwise |
no-cookies | Do not use cookies | Maintainability | https://palantir.github.io/tslint/rules/prefer-object-spread |
no-delete-expression | Do not delete expressions. Only properties should be deleted | Maintainability | https://palantir.github.io/tslint/rules/restrict-plus-operands |
no-document-write | Do not use document.write. A serious problems: document.write does not work in XHTML. document.write does not directly modify the DOM, preventing further manipulation. document.write executed after the page has finished loading will overwrite the page, or write a new page, or not work. document.write executes where encountered: it cannot inject at a given node point. document.write is effectively writing serialised text which is not the way the DOM works conceptually, and is an easy way to create bugs (.innerHTML has the same problem) | Maintainability | https://palantir.github.io/tslint/rules/newline-per-chained-call |
no-empty-line-after-opening-brace | Avoid an empty line after an opening brace. | Maintainability | https://palantir.github.io/tslint/rules/no-unused-expression |
no-for-in | Avoid use of for-in statements. They can be replaced by Object.keys | Maintainability | https://palantir.github.io/tslint/rules/no-empty-interface |
no-function-constructor-with-string-args | Do not use the version of the Function constructor that accepts a string argument to define the body of the function. | Maintainability | https://palantir.github.io/tslint/rules/only-arrow-functions |
no-function-expression | Do not use function expressions; use arrow functions (lambdas) instead. In general, lambdas are simpler to use and avoid the confusion about what the ‘this’ references points to. Function expressions that contain a ‘this’ reference are allowed and will not create a failure. | Understandability | https://palantir.github.io/tslint/rules/no-require-imports |
no-increment-decrement | Avoid use of increment and decrement operators particularly as part of complicated expressions | Maintainability | https://palantir.github.io/tslint/rules/no-void-expression |
no-jquery-raw-elements | Do not create HTML elements using JQuery and string concatenation. It is error prone and can hide subtle defects. Instead use the JQuery element API. | Resource Utilization | |
no-multiline-string | Do not declare multiline strings. | Maintainability | |
no-single-line-block-comment | Avoid single line block comments and use single line comments instead. Block comments do not nest properly and have no advantages over normal single-line comments | Understandability | |
no-string-based-set-immediate | Do not use the version of setImmediate that accepts code as a string argument. However, it is acceptable to use the version of setImmediate where a direct reference to a function is provided as the callback argument | Maintainability | |
no-string-based-set-interval | Do not use the version of setInterval that accepts code as a string argument. However, it is acceptable to use the version of setInterval where a direct reference to a function is provided as the callback argument | Maintainability | https://msdn.microsoft.com/en-us/library/cc307418.aspx |
no-string-based-set-timeout | Do not use the version of setTimeout that accepts code as a string argument. However, it is acceptable to use the version of setTimeout where a direct reference to a function is provided as the callback argument | Maintainability | |
no-unexternalized-strings | Ensures that double quoted strings are passed to a localize call to provide proper strings for different locales. The rule can be configured using an object literal as document in the feature request | Maintainability | |
no-unnecessary-local-variable | Do not declare a variable only to return it from the function on the next line. It is always less code to simply return the expression that initializes the variable. | Resource Utilization | |
no-unnecessary-semicolons | Remove unnecessary semicolons | Maintainability | |
prefer-type-cast | Prefer the tradition type casts instead of the new ‘as-cast’ syntax. For example, prefer myVariable instead of myVariable as string. Rule ignores any file ending in .tsx. If you prefer the opposite and want to see the as type casts, then enable the tslint rule named ‘no-angle-bracket-type-assertion’ | Accuracy | |
react-a11y-anchors | For accessibility of your website, anchor element link text should be at least 4 characters long. Links with the same HREF should have the same link text. Links that point to different HREFs should have different link text. Links with images and text content, the alt attribute should be unique to the text content or empty. An an anchor element’s href prop value must not be just #. References: WCAG Rule 38: Link text should be as least four 4 characters long WCAG Rule 39: Links with the same HREF should have the same link text WCAG Rule 41: Links that point to different HREFs should have different link text WCAG Rule 43: Links with images and text content, the alt attribute should be unique to the text content or empty |
Understandability | |
react-tsx-curly-spacing | Consistently use spaces around the brace characters of JSX attributes. You can either allow or ban spaces between the braces and the values they enclose. One of the two following options are required: * “always” enforces a space inside of curly braces (default) * “never” disallows spaces inside of curly braces By default, braces spanning multiple lines are not allowed with either setting. If you want to allow them you can specify an additional allowMultiline property with the value false. Examples: * “react-tsx-curly-spacing”: [true, “always”] * “react-tsx-curly-spacing”: [true, “never”] * “react-tsx-curly-spacing”: [true, “never”, {“allowMultiline”: false}] References * eslint-plugin-react jsx-curly-spacing rule * tslint-react jsx-curly-spacing rule | Maintainability | https://github.com/Microsoft/tslint-microsoft-contrib/wiki/react-no-dangerous-html-Rule |
react-unused-props-and-state | Remove unneeded properties defined in React Props and State interfaces. Any interface named Props or State is defined as a React interface. All fields in these interfaces must be referenced. This rule can be configured with regexes to match custom Props and State interface names. Example for including all interfaces ending with Props or State: [ true, { ‘props-interface-regex’: ‘Props$’, ‘state-interface-regex’: ‘State$’ } ] | Resource Utilization | |
await-promise | While it is valid TypeScript to await a non-Promise-like value (it will resolve immediately), this pattern is often a programmer error and the resulting semantics can be unintuitive. | Maintainability | https://palantir.github.io/tslint/rules/no-unsafe-any |
strict-type-predicates | Warns for type predicates that are always true or always false. Works for ‘typeof’ comparisons to constants (e.g. ‘typeof foo === “string”’), and equality comparison to ‘null’/’undefined’. (TypeScript won’t let you compare ‘1 === 2’, but it has an exception for ‘1 === undefined’.) Does not yet work for ‘instanceof’. Does not warn for ‘if (x.y)’ where ‘x.y’ is always truthy. For that, see strict-boolean-expressions. This rule requires strictNullChecks to work properly. | Maintainability | https://palantir.github.io/tslint/rules/no-this-assignment |
GO
The section below covers the Go Meta Linters, Gosec, and Staticcheck issues.
Go Meta Linter Issues
Go Meta Linter is an open source static code analyzer that concurrently runs a variety of different linters and normalizes their output to a standard format. Visit their website for more detailed information on Go Meta Linter and the ruleset found below.
High level issues
Rule | Description | KPI | URL |
---|---|---|---|
golint-omitValueFromRange | should omit values from range; this loop is equivalent to ‘for range …’ | Accuracy | https://github.com/golang/lint/blob/master/lint.go |
golint-omit2ndValueFromRange | should omit 2nd value from range; this loop is equivalent to ‘for %s %s range …’ | Accuracy | https://github.com/golang/lint/blob/master/lint.go |
golint-replaceSprintf | should replace (fmt.Sprintf(…)) with .Errorf(…) | Understandability | https://github.com/golang/lint/blob/master/lint.go |
vet-unsafeptr | Likely incorrect uses of unsafe.Pointer to convert integers to pointers. A conversion from uintptr to unsafe.Pointer is invalid if it implies that there is a uintptr-typed word in memory that holds a pointer value, because that word will be invisible to stack copying and to the garbage collector. | Accuracy | https://golang.org/cmd/vet/#hdr-Misuse_of_unsafe_Pointers |
Medium level issues
Rule | Description | KPI | URL |
---|---|---|---|
golint-errorShouldBeLastReturn | error should be the last type when returning multiple items | Robustness | https://github.com/golang/lint/blob/master/lint.go |
golint-annoyingUseExportedType | exported function returns unexported type, which can be annoying to use. | Robustness | https://github.com/golang/lint/blob/master/lint.go |
golint-ifBlockReturn | if block ends with a return statement, so drop this else and outdent its block | Accuracy | https://github.com/golang/lint/blob/master/lint.go |
golint-receiverNameShouldBeConsistent | receiver name should be consistent with previous receiver name | Robustness | https://github.com/golang/lint/blob/master/lint.go |
golint-receiverNameShouldBeReflection | receiver name should be a reflection of its identity; don’t use generic names such as “this” or “self” | Robustness | https://github.com/golang/lint/blob/master/lint.go |
golint-receiverNameShouldNotBeUnderscore | receiver name should not be an underscore, omit the name if it is unused | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-dropAssignment | should drop = from declaration of var. it is the zero value | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-blankImport | a blank import should be only in a main or test package, or have a comment justifying it | Efficiency | https://github.com/golang/lint/blob/master/lint.go |
golint-contextContextFirstArg | context.Context should be the first parameter of a function | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-avoidUnitSpecificSuffix | don’t use unit-specific suffix Sec | Robustness | https://github.com/golang/lint/blob/master/lint.go |
golint-packageCommentDetached | package comment is detached; there should be no blank lines between it and the package statement | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-packageNameStutters | Package name stutters. Consider using other names | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-avoidBasicTypeAsKey | should not use basic type as key in context.WithValue | Robustness | https://github.com/golang/lint/blob/master/lint.go |
vet-printfFormatting | Suspicious calls to functions in the Printf family, including any functions with these names, disregarding case:
Print Printf Println The -printfuncs flag can be used to redefine this list. If the function name ends with an ‘f’, the function is assumed to take a format descriptor string in the manner of fmt.Printf. If not, vet complains about arguments that look like format descriptor strings. It also checks for errors such as using a Writer as the first argument of Printf. |
Understandability | https://golang.org/cmd/vet/#hdr-Printf_family |
vet-unreachableCode | Unreachable code | Robustness | https://golang.org/cmd/vet/#hdr-Unreachable_code |
vet-shadow | Variables that may have been unintentionally shadowed. | Maintainability | https://golang.org/cmd/vet/#hdr-Shadowed_variables |
vet-copyingLock | Locks that are erroneously passed by value. | Robustness | https://golang.org/cmd/vet/#hdr-Copying_locks |
vet-boolCondError | Mistakes involving boolean operators. | Accuracy | https://golang.org/cmd/vet/#hdr-Boolean_conditions |
vet-httpresponseUsedIncorrectly | Mistakes deferring a function call on an HTTP response before checking whether the error returned with the response was nil | Accuracy | https://golang.org/cmd/vet/#hdr-HTTP_responses_used_incorrectly |
vet-lostcancel | The cancelation function returned by context.WithCancel, WithTimeout, and WithDeadline must be called or the new context will remain live until its parent context is cancelled. (The background context is never cancelled.) | Robustness | https://golang.org/cmd/vet/#hdr-Failure_to_call_the_cancelation_function_returned_by_WithCancel |
vet-rangeloops | Incorrect uses of range loop variables in closures. | Accuracy | https://golang.org/cmd/vet/#hdr-Range_loop_variables |
vet-shiftIncorrect | Shifts equal to or longer than the variable’s length. | Accuracy | https://golang.org/cmd/vet/#hdr-Shifts |
vet-unusedresult | Calls to well-known functions and methods that return a value that is discarded. By default, this includes functions like fmt.Errorf and fmt.Sprintf and methods like String and Error. The flags -unusedfuncs and -unusedstringmethods control the set | Robustness | https://golang.org/cmd/vet/#hdr-Unused_result_of_certain_function_calls |
gocyclo-cyclomaticComplexity | High cyclomatic complexity | Efficiency | https://github.com/alecthomas/gocyclo |
errcheck-returnValueNotChecked | Running errcheck on a package will report all function calls that have unchecked errors. | Accuracy | https://github.com/kisielk/errcheck |
gotype-indexOutOfBounds | Index out of bounds | Robustness | https://godoc.org/golang.org/x/tools/cmd/gotype |
gotype-incorrectConversion | Incorrect conversion of variable | Accuracy | https://godoc.org/golang.org/x/tools/cmd/gotype |
gotype-unusedVar | Variables declared but not used | Maintainability | https://godoc.org/golang.org/x/tools/cmd/gotype |
Low level issues
Rule | Description | KPI | URL |
---|---|---|---|
golint-formComment | Comment on exported type should be of the valid form | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-allCaps | don’t use ALL_CAPS in Go names; use CamelCase | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-underscoreInPackageName | don’t use an underscore in package name | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-leadingK | don’t use leading k in Go names | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-avoidUnderscoresInGoName | don’t use underscores in Go names | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-errorEndString | error strings should not be capitalized or end with punctuation or a newline | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-errorVarName | error variable should have name of the form errFoo. | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-incorrectPackageComment | package comment should be of the form “NamePackage…”. | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-avoidSpaceInPackageComment | package comment should not have leading space | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-havePackageComment | should have a package comment, unless it’s in another file for this package | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-commentExportedType | comment on exported type should be of the form “Type …” (with optional leading article) |
Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-exportedShouldHaveComment | exported [type|var|method|struct] should have comment or be unexported | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-exportedDeclaration | exported * should have its own declaration | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-dotImports | should not use dot imports | Resource Utilization | https://github.com/golang/lint/blob/master/lint.go |
golint-mixedCapsError | don’t use MixedCaps in package name | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-omitType | should omit type from declaration of var. it will be inferred from the right-hand side | Accuracy | https://github.com/golang/lint/blob/master/lint.go |
golint-initialisms | Improper variable name | Understandability | https://github.com/golang/lint/blob/master/lint.go |
golint-replaceLintIncDec | Use increment or decrement operator | Maintainability | https://github.com/golang/lint/blob/master/lint.go |
golint-structFieldInitialisms | Struct field initialized incorrectly | Understandability | https://github.com/golang/lint/blob/master/lint.go |
vet-asmdecl | Mismatches between assembly files and Go function declarations. | Understandability | https://golang.org/cmd/vet/#hdr-Assembly_declarations |
vet-uselessAssignment | Check for useless assignments. | Maintainability | https://golang.org/cmd/vet/#hdr-Useless_assignments |
vet-atomicMistakes | Common mistaken usages of the sync/atomic package | Maintainability | https://golang.org/cmd/vet/#hdr-Atomic_mistakes |
vet-buildTags | Badly formed or misplaced +build tags. | Understandability | https://golang.org/cmd/vet/#hdr-Build_tags |
vet-cgocallInvalid | Detect some violations of the cgo pointer passing rules. | Understandability | https://golang.org/cmd/vet/#hdr-Invalid_uses_of_cgo |
vet-composites | Composite struct literals that do not use the field-keyed syntax. | Understandability | https://golang.org/cmd/vet/#hdr-Unkeyed_composite_literals |
vet-nonstandardMethodSignature | Non-standard signatures for methods with familiar names, including:
Format GobEncode GobDecode MarshalJSON MarshalXML |
Understandability | https://golang.org/cmd/vet/#hdr-Methods |
vet-nilfunc | Comparisons between functions and nil | Maintainability | https://golang.org/cmd/vet/#hdr-Nil_function_comparison |
vet-structtags | Struct tags that do not follow the format understood by reflect.StructTag.Get. Well-known encoding struct tags (json, xml) used with unexported fields. | Accuracy | https://golang.org/cmd/vet/#hdr-Struct_tags |
vet-testsExamples | Mistakes involving tests including functions with incorrect names or signatures and example tests that document identifiers not in the package | Understandability | https://golang.org/cmd/vet/#hdr-Tests_and_documentation_examples |
structcheck-unusedStructField | Unused struct field | Maintainability | https://github.com/opennota/check |
ineffassign-ineffectualAssignment | Detect ineffectual assignments in Go code | Maintainability | https://github.com/gordonklaus/ineffassign |
gotype-importNotUsed | Check if imports are not used | Maintainability | https://godoc.org/golang.org/x/tools/cmd/gotype |
gotype-invalidOpr | invalid operation | Accuracy | https://godoc.org/golang.org/x/tools/cmd/gotype |
gotype-undeclaredName | Undeclared name | Understandability | https://godoc.org/golang.org/x/tools/cmd/gotype |
gotype-invalidOperand | Invalid Operand | Understandability | https://godoc.org/golang.org/x/tools/cmd/gotype |
gotype-incorrectUseOfArg | Incorrect use of variable as argument | Robustness | https://godoc.org/golang.org/x/tools/cmd/gotype |
gotype-varNotDeclared | Var not declared by package | Understandability | https://godoc.org/golang.org/x/tools/cmd/gotype |
Gosec Linter Issues
Gosec Linters are configured to run specifically against the supplied input files by excluding certain file paths and produce reports in different formats. Visit their website for more detailed information on Gosec Linter and the ruleset found below.
Gosec critical level issues
Rule | Description | Example | KPI |
---|---|---|---|
G101-LookForHardCodedCredentials | Do not use hardcoded passwords anywhere in the source code.The use of hard-coded passwords increases the possibility of password guessing tremendously. Hardcoded password is nothing but a plaintext password used in the application source code as it is one of the easiest ways to use password for authentication as required to connect and communicate with database or other systems. Variables are considered to look like a password if they have match any one of: 1)“password†2)“pass†3)“passwd†4)“pwd†5)“secret†6)“token†| //non-compliant package main import "fmt" func main() { username := "admin" var password = "f62e5bcda4fae4f82370da0c6f20697b8f8447ef" //non-compliant code (Consider storing passwords in a configuration file and restrict access to that file.) fmt.Println("Doing something with: ", username, password) } //compliant code package main import "fmt" func main() { username := "admin" password:= getEncryptedPass() fmt.Println("Never use hardcoded passwords.") } | Security |
G402-LookForBadTLSConnectionSettings | Look for bad TLS connection settings.When a certificate is invalid or malicious, it might allow an attacker to spoof a trusted entity by interfering in the communication path between the host and client. The software might connect to a malicious host while believing it is a trusted host, or the software might be deceived into accepting spoofed data that appears to originate from a trusted host. | "//non-compliant code package main import ( ""crypto/tls"" ""fmt"" ) func main() { TLSClientConfig: &tls.Config{InsecureSkipVerify} }" | Security |
Gosec high level issues
Rule | Description | Example | KPI | |
---|---|---|---|---|
G102-BindToAllInterfaces | Binding to all network interfaces can potentially open up a service to traffic on unintended interfaces, that may not be properly documented or secured. This check looks for a string pattern “0.0.0.0†that may indicate a hardcoded binding to all network interfaces.This exposes the running instance to any attackers reachable via the interface they didn't expect to be listening on. For example: If a user wants to run a setup locally or on any other instance, they may specify to run on "localhost"(or any other specified ip). But if "0.0.0.0" is used, it makes the port accessible on all network interfaces. | //non-compliant code package main import ( "log" "net" ) func main() { l, err := net.Listen("tcp", "0.0.0.0:2000") //non-compliant if err != nil { log.Fatal(err) } defer l.Close() } // compliant code package main import ( "log" "net" ) func main() { l, err := net.Listen("tcp", "123.123.12.1:2000") //compliant if err != nil { log.Fatal(err) } defer l.Close() } | Security | - [Source](https://github.com/securego/gosec#available-rules) - [OWASP Top 10 2007 Category A6](https://www.martellosecurity.com/kb/mitre/cwe/717/) - Information Leakage and Improper Error Handling - [CWE-200](http://cwe.mitre.org/data/definitions/200.html) - Exposure of Sensitive Information to an Unauthorized Actor - [CWE-605](https://cwe.mitre.org/data/definitions/605.html) - Multiple Binds to the Same Port |
G103-AuditTheUseOfUnsafeBlock | Do not import package "unsafe".Using the "unsafe" package in Go gives flexibility to the attacker of your application.The pointer arithmetic is one of the examples from the unsafe package which can be used for data leak, memory corruption or even execution of attackers own script.Also the "unsafe" package is not protected by "Go 1 compatibility guidelines". | //non-compliant code package main import ( "fmt" "unsafe" ) type Fake struct{} func (Fake) Good() {} func main() { unsafeM := Fake{} unsafeM.Good() fmt.Printf("unsafe package is imported.") //compliant code package main import ( "fmt" ) type Fake struct{} func (Fake) Good() {} func main() { fmt.Printf("Do not import packaged unsafe.") | Security | - [Source](https://github.com/securego/gosec#available-rules) - [CWE-242](https://cwe.mitre.org/data/definitions/242.html) - Use of Inherently Dangerous Function |
G104-AuditErrorsNotChecked | A really useful feature of Golang is the ability to return a tuple of a result and an error value from a function. There is a rule in Golang that the result of a function is unsafe until you check the error value. Many security exploits can be performed when the error value is not checked.Go code uses error values to indicate an abnormal state. | //non-compliant package main import ( "fmt" ) func a() error { return fmt.Errorf("This is an error") } func main() { a() } //compliant code package main import ( "fmt" ) func a() error { return fmt.Errorf("This is an error") } func main() { err := a() if(err != nil){ fmt.Println("Checked Error!") } } | Security | - [Source](https://github.com/securego/gosec#available-rules) - [CWE-703](https://cwe.mitre.org/data/definitions/703.html) - Improper Check or Handling of Exceptional Conditions |
G106-AuditTheUseOfssh-InsecureIgnoreHostKey | Audit the use of ssh.InsecureIgnoreHostKey.InsecureIgnoreHostKey is used to accept any host key. It should not be used for production code. Go team provided the "knownhosts" subpackage in their crypto SSH package.Using new with a known_hosts file a code can be written more `efficiently and securely. | //non-compliant code package main import ( "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/agent" ) func main() { // generate key hkCallback := ssh.InsecureIgnoreHostKey() } //compliant code package main import ( "golang.org/x/crypto/ssh/knownhosts" ) func main() { hkCallback, err = knownhosts.New(tf.Name()) if err != nil { return nil, err } } | Security | - [CWE-322](https://cwe.mitre.org/data/definitions/322.html) - Key Exchange without Entity Authentication |
G108-ProfilingEndpointAutomaticallyExposedOn-debug-pprof | Profiling endpoint automatically exposed on /debug/pprof. This can lead to following Security issues: 1) Function names and file paths are revealed. 2) Profiling data may reveal business sensitive information (for example traffic to a web server) 3) Profiling degrades performance, providing a vector for a DoS attack Depending on your application, leaving a debugging server may not necessarily be a critical security hole. At a minimum it’s inadvisable, but it could be much worse. | //non compliant code package main import ( "fmt" "log" "net/http" _ "net/http/pprof" // here be dragons ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") }) log.Fatal(http.ListenAndServe(":8080", nil)) } //compliant code package main import ( "fmt" "log" "net/http" ) func main() { // Pprof server. professor.Launch("localhost:8081") // Application server. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") }) log.Fatal(http.ListenAndServe(":8080", nil)) } | Security | |
G110-PotentialDoSvulnerabilityviadecompressionbomb | Potential DoS vulnerability via decompression bomb | //non-compliant code package main import ( "bytes" "compress/gzip" "fmt" "io" "log" "os" "time" ) func Example_writerReader() { var buf bytes.Buffer zw := gzip.NewWriter(&buf) // Setting the Header fields is optional. zw.Name = "a-new-hope.txt" zw.Comment = "an epic space opera by George Lucas" zw.ModTime = time.Date(1977, time.May, 25, 0, 0, 0, 0, time.UTC) _, err := zw.Write([]byte("A long time ago in a galaxy far, far away...")) if err != nil { log.Fatal(err) zr, err := gzip.NewReader(&buf) if err != nil { log.Fatal(err) } fmt.Printf("Name: %s\nComment: %s\nModTime: %s\n\n", zr.Name, zr.Comment, zr.ModTime.UTC()) if _, err := io.Copy(os.Stdout, zr); err != nil { log.Fatal(err) } }} | Security | |
G305-FileTraversalWhenExtractingZip-tar-archive | A path traversal attack (also known as directory traversal) aims to access files and directories that are stored outside the web root folder. By manipulating variables that reference files with “dot-dot-slash (../)†sequences and its variations or by using absolute file paths, it may be possible to access arbitrary files and directories stored on file system including application source code or configuration and critical system files. Extracting some malicious file will result in traversing out of the target folder, ending up overwriting important files. | //non-compliant code package main import ( "archive/zip" "fmt" "path/filepath" ) func main(src string, dst string) ([]string, error) { fmt.Printf("Unzip dataset %s\n", src) var fileNames []string // Open zip file r, err := zip.OpenReader(src) if err != nil { return fileNames, err } defer r.Close() // Extract files for _, f := range r.File { // Open file filePath := filepath.Join(dst, f.Name) fmt.println(filepath) } } | Security | - [CWE-22](https://cwe.mitre.org/data/definitions/22.html) - Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') |
G401-DetectTheUsageOfDES-RC4-MD5orSHA1 | Detect the usage of DES, RC4, MD5 or SHA1 | //non-compliant code package main import ( "crypto/sha1" "fmt" ) func main() { h = sha1.New() } | Security | - [CWE-326](https://cwe.mitre.org/data/definitions/326.html) - Inadequate Encryption Strength |
G404-InsecureRandomNumberSource_rand | Use "crypto/rand" instead of "math/rand". "math/rand" implements a large selection of pseudo-random number generators whereas "crypto/rand" implements a cryptographically secure pseudo-random number generator with a limited interface. | //non-compliant code package main import ( "fmt" "math/rand" "time" ) func main() { fmt.Print(rand.Intn(100), ",") } //compliant code package main import ( "fmt" "crypto/rand" "time" ) func main() { fmt.Print(rand.Intn(100), ",") } | Security | - [CWE-338](https://cwe.mitre.org/data/definitions/338.html) - Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG) |
G501-Importblocklist-crypto-md5 | Do not import crypto/md5.Package md5 implements the MD5 hash algorithm as defined in RFC 1321. MD5 is cryptographically broken and should not be used for secure applications. | //non-compliant code package main import ( "fmt" "crypto/md5" ) func main() { fmt.Printf("Imported crypto/md5") } //compliant code package main import ( "fmt" ) func main() { fmt.Printf("Do not import crypto/md5") } | Security | - [CWE-327](https://cwe.mitre.org/data/definitions/327.html) - Use of a Broken or Risky Cryptographic Algorithm - [OWASP Top 10 2017 Category A3](https://owasp.org/www-project-top-ten/OWASP_Top_Ten_2017/Top_10-2017_A3-Sensitive_Data_Exposure) - Sensitive Data Exposure |
G502-Importblocklist-crypto-des | Package des implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3. DES is cryptographically broken and should not be used for secure applications. | //non-compliant code package main import ( "fmt" "crypto/des" ) func main() { fmt.Printf("Imported crypto/des") } //compliant code package main import ( "fmt" ) func main() { fmt.Printf("Do not import crypto/des") } | Security | - [CWE-327](https://cwe.mitre.org/data/definitions/327.html) - Use of a Broken or Risky Cryptographic Algorithm - [OWASP Top 10 2017 Category A3](https://owasp.org/www-project-top-ten/OWASP_Top_Ten_2017/Top_10-2017_A3-Sensitive_Data_Exposure) - Sensitive Data Exposure |
G503-Importblocklist-crypto-rc4 | Import blocklist: crypto/rc4 | //non-compliant code package main import ( "fmt" "crypto/rc4" ) func main() { fmt.Printf("Imported crypto/rc4") } //compliant code package main import ( "fmt" "crypto/rc4" ) func main() { fmt.Printf("Do not import crypto/rc4") } | Security | |
G504-Importblocklist-net-http-cgi | Import blocklist: net/http/cgi | //non-compliant code package main import ( "fmt" "net/http/cgi" ) func main() { fmt.Printf("Imported net/http/cgi") } //compliant code package main import ( "fmt" "net/http/cgi" ) func main() { fmt.Printf("Do not import net/http/cgi") } | Security | |
G505-Importblocklist-crypto-sha1 | Do not import crypto/sha1. It is a SHA-1 used to calculate an alphanumeric string that serves as the cryptographic representation of a file or a piece of data.This can serve as a digital signature. It is supposed to be unique and non-reversible.If a weakness is found in a hash function that allows for two files to have the same digest, the function is considered cryptographically broken, because digital fingerprints generated with it can be forged and cannot be trusted. | //non-compliant code package main import ( "fmt" "crypto/sha1" ) func main() { fmt.Printf("Imported crypto/sha1") } //compliant code package main import ( "fmt" ) func main() { fmt.Printf("Do not import crypto/sha1") } | Security | - [Source](https://github.com/securego/gosec#available-rules) - [CWE-327](https://cwe.mitre.org/data/definitions/327.html) - Use of a Broken or Risky Cryptographic Algorithm - [OWASP Top 10 2017 Category A3](https://owasp.org/www-project-top-ten/OWASP_Top_Ten_2017/Top_10-2017_A3-Sensitive_Data_Exposure) - Sensitive Data Exposure |
Gosec medium level issues
Rule | Description | Example | KPI | |
---|---|---|---|---|
G107-UrlProvidedToHTTPRequestAsTaintInput | Getting a URL from an untrusted source like user input, gives the ability of an attacker to redirect your application to bad websites and perform additional attacks. One of the examples is the http.Get() function issues a GET to the specified URL and if the result is appropriate GET will follow the redirect after calling Client's CheckRedirect function. That means that the attacker can send your application to various places.This problem leads to SSRF attacks via http requests with variable url. | //non-compliant code package main import ( "fmt" "io/ioutil" "net/http" ) var url string = "http://www.google.com" func main() { resp, err := http.Get(url) if err != nil { panic(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } fmt.Printf("%s", body) } //compliant code package main import ( "fmt" "net/http" ) const url = "https://127.0.0.1" func main() { resp, err := http.Get(url) if err != nil { fmt.Println(err) } fmt.Println(resp.Status) } | Security | - [Source](https://github.com/securego/gosec#available-rules) - [CWE-88](https://cwe.mitre.org/data/definitions/88.html) - Improper Neutralization of Argument Delimiters in a Command ('Argument Injection') - [OWASP Top 10 2013 Category A10](https://blog.detectify.com/2016/08/15/owasp-top-10-unvalidated-redirects-and-forwards-10/) - Unvalidated Redirects and Forwards |
G109-PotentialIntegerOverflowMadeByStrconv-Atoiresultconversiontoint16-32 | Potential Integer overflow made by strconv.Atoi result conversion to int16/32.The strconv.Atoi function parses an int - a machine dependent integer type, which, for 64-bit targets will be int64. There are places throughout the codebase where the result returned from strconv.Atoi is later converted to a smaller type: int16 or int32. This may overflow with a certain input. | //non-compliant code package main import ( "fmt" "strconv" ) func updatePodPorts(params map[string]string, podSpec *v1.PodSpec) (err error) { port := -1 hostPort := -1 if len(params["port"]) > 0 { port, err = strconv.Atoi(params["port"]) // <-- this should parse port as strconv.ParseUint(params["port"], 10, 16) if err != nil { return err } } // (...) // Don't include the port if it was not specified. if len(params["port"]) > 0 { podSpec.Containers[0].Ports = []v1.ContainerPort{ { ContainerPort: int32(port), // <-- this should later just be uint16(port) }, } } //compliant code package main import ( "fmt" "strconv" ) func updatePodPorts(params map[string]string, podSpec *v1.PodSpec) (err error) { port := -1 hostPort := -1 if len(params["port"]) > 0 { port, err = strconv.ParseUint(params["port"], 10, 16) if err != nil { return err } } // (...) // Don't include the port if it was not specified. if len(params["port"]) > 0 { podSpec.Containers[0].Ports = []v1.ContainerPort{ { ContainerPort: uint16(port), }, } } | Security | |
G201-SQLqueryconstructionusingformatstring | Do not use packages like "fmt" in technologies like SQL or HTML. SQL injection is one of the top security issues developers make and the consequences of this can be severe. Using the format string function in the fmt Golang package to dynamically create an SQL query can easily create a possibility for SQL injection. The reason is that the format string function doesn't escape special characters like ' and it's easy to add second SQL command in the format string. | /non-compliant code package main import ( "database/sql" "fmt" "os" ) func main(){ db, err := sql.Open("sqlite3", ":memory:") if err != nil { panic(err) } q := fmt.Sprintf("SELECT * FROM foo where name = '%s'", os.Args[1]) rows, err := db.Query(q) if err != nil { panic(err) } defer rows.Close() } //compliant code package main import ( "database/sql" ) const staticQuery = "SELECT * FROM foo WHERE age < 32" func main(){ db, err := sql.Open("sqlite3", ":memory:") if err != nil { panic(err) } rows, err := db.Query(staticQuery) if err != nil { panic(err) } defer rows.Close() } | Security | |
G202-SQLQueryConstructionuSingStringConcatenation | Do not construct SQL queries using string concatenation.Instead use the database/sql. By using the database/sql package along with argument placeholders, you are able to construct SQL statements that are automatically escaped properly. There is no need to construct the SQL statement manually, but instead provide arguments that can be easily escaped. The underlying driver for database/sql will be aware of special characters which needs to be handled and will escape them, preventing any nefarious SQL from running. | //non-compliant code package main import ( "database/sql" ) var staticQuery = "SELECT * FROM foo WHERE age < " func main() { db, err := sql.Open("sqlite3", ":memory:") if err != nil { panic(err) } var gender string = "M" rows, err := db.Query("SELECT * FROM foo WHERE gender = " + gender) if err != nil { panic(err) } defer rows.Close() } //compliant code package main import ( "database/sql" "bufio" ) func main(){ db, err := sql.Open("sqlite3", ":memory:") if err != nil { panic(err) } in := bufio.NewReader(os.Stdin) name, err := in.ReadString('\n') if err != nil { panic(err) } rows, err := db.Query("SELECT * FROM foo WHERE name = ?", name) if err != nil { panic(err) } defer rows.Close() } | Security | - [Source](https://github.com/securego/gosec#available-rules) - [CWE-89](https://cwe.mitre.org/data/definitions/89.html) - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') |
G204-AuditUseOfCommandExecution | Audit use of command execution. Go-audit is an alternative to auditd with better logging. It exports logs in JSON and combines multiple events, with same root cause, into one event for easy analysis. | //non-compliant code for _, files := range protoFilesMap { for _, relProtoFile := range files { args := []string{ "--go_out", pwd, } args = append(args, relProtoFile) cmd := exec.Command(protoc, args...) cmd.Env = append(cmd.Env, os.Environ()...) } | Security | |
G301-PoorFilePermissionsUsedWhenCreatingADirectory | Do not use poor file permissions when creating a directory. Directory permission should be 0750 or less while creating a it. | //non-compliant code package main import ( "log" "os" ) func main() { _, err := os.Stat("test") if os.IsNotExist(err) { errDir := os.MkdirAll("test", 0755) if errDir != nil { log.Fatal(err) } } } //compliant code package main import ( "log" "os" ) func main() { _, err := os.Stat("test") if os.IsNotExist(err) { errDir := os.MkdirAll("test", 0750) if errDir != nil { log.Fatal(err) } } } | Security | - [CWE-276](https://cwe.mitre.org/data/definitions/276.html) - Incorrect Default Permissions |
G302-PoorFilePermissionsUsedWithchmod | Do not use poor file permissions for a file with chmod. Use file permimssion 0600 or less. | //non-compliant code package main import ( "log" "os" "time" ) func main() { // Test File existence. _, err := os.Stat("test.txt") if err != nil { if os.IsNotExist(err) { log.Fatal("File does not exist.") } } log.Println("File exist.") // Change permissions Linux. err = os.Chmod("test.txt", 0777) if err != nil { log.Println(err) } //compliant code package main import ( "log" "os" "time" ) func main() { // Test File existence. _, err := os.Stat("test.txt") if err != nil { if os.IsNotExist(err) { log.Fatal("File does not exist.") } } log.Println("File exist.") // Change permissions Linux. err = os.Chmod("test.txt", 0600) if err != nil { log.Println(err) } | Security | - [CWE-276](https://cwe.mitre.org/data/definitions/276.html) - Incorrect Default Permissions |
G303-CreatingTempFileUsingaPredictablePath | Creating tempfile using a predictable path | Security | ||
G304-FilePathprovidedastaintinput | File path provided as taint input | //non-compliant code package main import ( "os" "fmt" "path/filepath" ) func (v upgradeCommand) verifyChecksum(source, checksum string) error { var ( err error h hash.Hash ) checksumFile, err := os.Open(checksum) if err != nil { return err } } | Security | - [CWE-22](https://cwe.mitre.org/data/definitions/22.html) - Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') |
G306-PoorFilePermissionsUsedWhenWritingToANewFile | DO not use Poor file permissions when writing to a new file. Expected permission is 0600 or less for writing in a new file. | //non compliant code package main import ( "fmt" "io/ioutil" "os" "path/filepath" ) func main() { dname, err := ioutil.TempDir("", "sampledir") check(err) fmt.Println("Temp dir name:", dname) defer os.RemoveAll(dname) fname := filepath.Join(dname, "file1") err = ioutil.WriteFile(fname, []byte{1, 2}, 0777) check(err) } //compliant code package main import ( "fmt" "io/ioutil" "os" "path/filepath" ) func main() { dname, err := ioutil.TempDir("", "sampledir") check(err) fmt.Println("Temp dir name:", dname) defer os.RemoveAll(dname) fname := filepath.Join(dname, "file1") err = ioutil.WriteFile(fname, []byte{1, 2}, 0600) check(err) } | Security | - [CWE-276](https://cwe.mitre.org/data/definitions/276.html) - Incorrect Default Permissions |
G307-DeferringaMethodWhichReturnsAnError | Deferring a method which returns an error | //non-compliant code package main import ( "os" "fmt" ) func main() { checksumFile, err := os.Open(checksum) if err != nil { return err } defer checksumFile.Close() } | Security | |
G403-EnsureMinimumRSAkeyLengthOf2048Bits | Ensure minimum RSA key length of 2048 bits. RSA encryption is more computationally expensive than typical symmetric ciphers such as AES. The key generation and decryption operations in particular are relatively expensive operations. Guidelines on RSA key length : 1) For relatively low level of security and running modest hardware, choose an RSA key length of at least 2048 bits. 2) For dedicated hardware and/or achieve good security, consider a key size of 4096 bits. 3) If long-term high security is required, ensure that system could be reconfigured at a later date to use a higher key length. | //non-compliant code package main import ( "crypto/rand" "crypto/rsa" "fmt" "os" ) func main() { // generate key privatekey, err := rsa.GenerateKey(rand.Reader, 1024) if err != nil { fmt.Printf("Cannot generate RSA key\n") os.Exit(1) } } //compliant code package main import ( "crypto/rand" "crypto/rsa" "fmt" "os" ) func main() { // generate key privatekey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { fmt.Printf("Cannot generate RSA key\n") os.Exit(1) } } | Security | - [CWE-310](https://cwe.mitre.org/data/definitions/310.html) - Cryptographic Issues |
G601-ImplicitMemoryAliasingOfItemsFromARangeStatement | Implicit memory aliasing of items from a range statement | //non-compliant code package main func main() { var a [5]int for i, k := range a { fmt.Println(&k) // non compliant } } //compliant code package main func main() { var a [5]int for i, k := range a { fmt.Println(&a[i]) // non compliant } } | Security |
Gosec low level issues
Rule | Description | Example | KPI |
---|---|---|---|
G203-UseOfUnescapedDataInHTMLTemplates | Use of unescaped data in HTML templates. Package template (html/template) implements data-driven templates for generating HTML output safe against code injection. It provides the same interface as package text/template and should be used instead of text/template whenever the output is HTML. "html/template" provides automatic, context-sensitive escaping safe against code injection.HTML templates treat data values as plain text which should be encoded so they can be safely embedded in an HTML document. The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts.If the output is not HTML, use text/template instead which does not escape data. | "import ""html/template"" func unescape(s string) template.HTML { return template.HTML(s) }" | Security |
Staticcheck Linter Issues
Static Linter is an open-source static code analyzer that finds bugs and performance-related issues. Visit their website for more detailed information on Go Meta Linter and the ruleset found below.
Staticcheck high level issues
rule | Description | example | KPI | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
S1023-Omit redundant control flow | Omit redundant control flowFunctions that have no return value do not need a return statement as the final statement of the function. Switches in Go do not have automatic fallthrough, unlike languages like C. It is not necessary to have a break statement as the final statement in a case block. | Functionality | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
S1029-Range over the string directly | Ranging over a string will yield byte offsets and runes. If the offset isn't used, this is functionally equivalent to converting the string to a slice of runes and ranging over that. Ranging directly over the string will be more performant, however, as it avoids allocating a new slice, the size of which depends on the length of the string. | //non-compliant code for _, r := range []rune(s) {} //compliant code for _, r := range s {} | Functonality, Efficiency | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1000-Invalid regular expression | Invalid regular expression | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1001-Invalid template | Invalid template | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1002-Invalid format in time.Parse | Invalid format in time.Parse | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1003-Unsupported argument to functions in encoding/binary | The encoding/binary package can only serialize types with known sizes. This precludes the use of the int and uint types, as their sizes differ on different architectures. Furthermore, it doesn't support serializing maps, channels, strings, or functions. | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1005-Invalid first argument to exec.Command | os/exec runs programs directly (using variants of the fork and exec system calls on Unix systems). This shouldn't be confused with running a command in a shell. The shell will allow for features such as input redirection, pipes, and general scripting. The shell is also responsible for splitting the user's input into a program name and its arguments. | //non-compliant code ls / /tmp //compliant code exec.Command("ls", "/", "/tmp") | Robustness | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1007-Invalid URL in net/url.Parse | Invalid URL in net/url.Parse | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1010-(*regexp.Regexp).FindAll called with n == 0, which will always return zero results | If n >= 0, the function returns at most n matches/submatches. To return all results, specify a negative number. | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1011-Various methods in the strings package expect valid UTF-8, but invalid input is provided | Various methods in the strings package expect valid UTF-8, but invalid input is provided | Functionality | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1013-io.Seeker.Seek is being called with the whence constant as the first argument, but it should be the second | io.Seeker.Seek is being called with the whence constant as the first argument, but it should be the second | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1014-Non-pointer value passed to Unmarshal or Decode | Non-pointer value passed to Unmarshal or Decode | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1020-Using an invalid host:port pair with a net.Listen-related function | Using an invalid host:port pair with a net.Listen-related function | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1021-Using bytes.Equal to compare two net.IP | A net.IP stores an IPv4 or IPv6 address as a slice of bytes. The length of the slice for an IPv4 address, however, can be either 4 or 16 bytes long, using different ways of representing IPv4 addresses. In order to correctly compare two net.IPs, the net.IP.Equal method should be used, as it takes both representations into account. | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1023-Modifying the buffer in an io.Writer implementation | Write must not modify the slice data, even temporarily. | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1026-Cannot marshal channels or functions | Cannot marshal channels or functions | Robustness, Functionality | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1027-Atomic access to 64-bit variable must be 64-bit aligned | On ARM, x86-32, and 32-bit MIPS, it is the caller's responsibility to arrange for 64-bit alignment of 64-bit words accessed atomically. The first word in a variable or in an allocated struct, array, or slice can be relied upon to be 64-bit aligned. You can use the structlayout tool to inspect the alignment of fields in a struct. | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1029-Inappropriate key in call to context.WithValue | The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of WithValue should define their own types for keys. To avoid allocating when assigning to an interface{}, context keys often have concrete type struct{}. Alternatively, exported context key variables' static type should be a pointer or interface. | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA1030-Invalid argument in call to a strconv function | This check validates the format, number base and bit size arguments of the various parsing and formatting functions in strconv. | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA2000-sync.WaitGroup.Add called inside the goroutine, leading to a race condition | sync.WaitGroup.Add called inside the goroutine, leading to a race condition | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA2002-Called testing.T.FailNow or SkipNow in a goroutine, which isn't allowed | Called testing.T.FailNow or SkipNow in a goroutine, which isn't allowed | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA2003-Deferred Lock right after locking, likely meant to defer Unlock instead | Deferred Lock right after locking, likely meant to defer Unlock instead | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA3000-TestMain doesn't call os.Exit, hiding test failures | Test executables (and in turn 'go test') exit with a non-zero status code if any tests failed. When specifying your own TestMain function, it is your responsibility to arrange for this, by calling os.Exit with the correct code. The correct code is returned by (*testing.M).Run, so the usual way of implementing TestMain is to end it with os.Exit(m.Run()). | Functionality | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA4012-Comparing a value against NaN even though no value is equal to NaN | Comparing a value against NaN even though no value is equal to NaN | Conceptual Integrity, Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA5002-The empty for loop (for {}) spins and can block the scheduler | The empty for loop (for {}) spins and can block the scheduler | Robustness, Conceptual Integrity | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA5003-Defers in infinite loops will never execute | Defers in infinite loops will never execute | Robustness, Conceptual Integrity | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA5005-The finalizer references the finalized object, preventing garbage collection | A finalizer is a function associated with an object that runs when the garbage collector is ready to collect said object, that is when the object is no longer referenced by anything. If the finalizer references the object, however, it will always remain as the final reference to that object, preventing the garbage collector from collecting the object. The finalizer will never run, and the object will never be collected, leading to a memory leak. That is why the finalizer should instead use its first argument to operate on the object. That way, the number of references can temporarily go to zero before the object is being passed to the finalizer. | Efficiency, Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA5007-Infinite recursive call | A function that calls itself recursively needs to have an exit condition. Otherwise it will recurse forever, until the system runs out of memory. This issue can be caused by simple bugs such as forgetting to add an exit condition. It can also happen "on purpose". Some languages have tail call optimization which makes certain infinite recursive calls safe to use. Go, however, does not implement TCO, and as such a loop should be used instead. | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA5008-Invalid struct tag | Invalid struct tag | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA5009-Invalid Printf call | Invalid Printf call | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA5010-Impossible type assertion | Some type assertions can be statically proven to be impossible. This is the case when the method sets of both arguments of the type assertion conflict with each other, for example by containing the same method with different signatures. The Go compiler already applies this check when asserting from an interface value to a concrete type. If the concrete type misses methods from the interface, or if function signatures don't match, then the type assertion can never succeed. This check applies the same logic when asserting from one interface to another. If both interface types contain the same method but with different signatures, then the type assertion can never succeed, either. | Robustness, Conceptual Integrity | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA5011-Possible nil pointer dereference | A pointer is being dereferenced unconditionally, while also being checked against nil in another place. This suggests that the pointer may be nil and dereferencing it may panic. This is commonly a result of improperly ordered code or missing return statements. Staticcheck tries to deduce which functions abort control flow. | //non-comliant code func Log(msg string, level int) { fmt.Println(msg) if level == levelFatal { os.Exit(1) } } func Fatal(msg string) { Log(msg, levelFatal) } func fn(x *int) { if x == nil { Fatal("unexpected nil pointer") } fmt.Println(*x) } //compliant code func Log(msg string, level int) { fmt.Println(msg) if level == levelFatal { os.Exit(1) } } func Fatal(msg string) { Log(msg, levelFatal) panic("unreachable") } func fn(x *int) { if x == nil { Fatal("unexpected nil pointer") } fmt.Println(*x) } | Robustess | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA6002-Storing non-pointer values in sync.Pool allocates memory | A sync.Pool is used to avoid unnecessary allocations and reduce the amount of work the garbage collector has to do. When passing a value that is not a pointer to a function that accepts an interface, the value needs to be placed on the heap, which means an additional allocation. Slices are a common thing to put in sync.Pools, and they're structs with 3 fields (length, capacity, and a pointer to an array). In order to avoid the extra allocation, one should store a pointer to the slice instead. | Efficieny | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA6005-Inefficient string comparison with strings.ToLower or strings.ToUpper | Converting two strings to the same case and comparing them like so if strings.ToLower(s1) == strings.ToLower(s2) { ... } is significantly more expensive than comparing them with strings.EqualFold(s1, s2). This is due to memory usage as well as computational complexity. strings.ToLower will have to allocate memory for the new strings, as well as convert both strings fully, even if they differ on the very first byte. strings.EqualFold, on the other hand, compares the strings one character at a time. It doesn't need to create two intermediate strings and can return as soon as the first non-matching character has been found. | Robustness | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SA9001-Defers in range loops may not run when you expect them to | Defers in range loops may not run when you expect them to | Conceptual Integrity, Robustness |
Staticcheck medium level issues
Rule | Description | Example | KPI |
---|---|---|---|
S1000-Use plain channel send or receive instead of single-case select | Select statements with a single case can be replaced with a simple send or receive. | //non-compliant code select { case x := <-ch: fmt.Println(x) } //compliant code x := <-ch fmt.Println(x) | Functionality |
S1003-Replace call to strings.Index with strings.Contains | Replace call to strings.Index with strings.Contains | //non-compliant code if strings.Index(x, y) != -1 {} //compliant code if strings.Contains(x, y) {} | Functionality, Robustness |
S1004-Replace call to bytes.Compare with bytes.Equal | Replace call to bytes.Compare with bytes.Equal | //non-compliant code if bytes.Compare(x, y) == 0 {} //compliant code if bytes.Equal(x, y) {} | Functionality, Robustness |
S1007-Simplify regular expression by using raw string literal | Raw string literals use ` instead of " and do not support any escape sequences. This means that the backslash (\) can be used freely, without the need of escaping. Since regular expressions have their own escape sequences, raw strings can improve their readability. | //non-compliant code regexp.Compile("\\A(\\w+) profile: total \\d+\\n\\z") //compliant code regexp.Compile(`\A(\w+) profile: total \d+\n\z`) | Maintainability, Functionality |
S1008-Simplify returning boolean expression | Simplify returning boolean expression | //non-compliant code if return true } return false //compliant code if return true } return false | Maintainability |
S1009-Omit redundant nil check on slices | The len function is defined for all slices, even nil ones, which have a length of zero. It is not necessary to check if a slice is not nil before checking that its length is not zero. | //non-compliant code if x != nil && len(x) != 0 {} //compliant code if len(x) != 0 {} | Functionality, Conceptual Integrity |
S1010-Omit default slice index | When slicing, the second index defaults to the length of the value, making s[n:len(s)] and s[n:] equivalent. | Functionality | |
S1011-Use a single append to concatenate two slices | Use a single append to concatenate two slices | //non-compliant code for _, e := range y { x = append(x, e) } //compliant code x = append(x, y...) | Functonality, Efficiency |
S1016-Use a type conversion instead of manually copying struct fields | Two struct types with identical fields can be converted between each other. In older versions of Go, the fields had to have identical struct tags. Since Go 1.8, however, struct tags are ignored during conversions. It is thus not necessary to manually copy every field individually. | //non-compliant code var x T1 y := T2{ Field1: x.Field1, Field2: x.Field2, } //compliant code var x T1 y := T2(x) | Functonality, Efficiency |
S1017-Replace manual trimming with strings.TrimPrefix | Instead of using strings.HasPrefix and manual slicing, use the strings.TrimPrefix function. If the string doesn't start with the prefix, the original string will be returned. Using strings.TrimPrefix reduces complexity, and avoids common bugs, such as off-by-one mistakes. | //non-compliant code if strings.HasPrefix(str, prefix) { str = str[len(prefix):] } //compliant code str = strings.TrimPrefix(str, prefix) | Functionality |
S1018-Use copy for sliding elements | copy() permits using the same source and destination slice, even with overlapping ranges. This makes it ideal for sliding elements in a slice. | //non-compliant code for i := 0; i < n; i++ { bs[i] = bs[offset+i] } //compliant code copy(bs[:n], bs[offset:]) | Functionality |
S1019-Simplify make call by omitting redundant arguments | The make function has default values for the length and capacity arguments. For channels and maps, the length defaults to zero. Additionally, for slices the capacity defaults to the length. | Functionality | |
S1024-Replace x.Sub(time.Now()) with time.Until(x) | The time.Until helper has the same effect as using x.Sub(time.Now()) but is easier to read. | //non-compliant code x.Sub(time.Now()) //compliant code time.Until(x) | Functionality |
S1025-Don't use fmt.Sprintf("%s", x) unnecessarily | In many instances, there are easier and more efficient ways of getting a value's string representation. Whenever a value's underlying type is a string already, or the type has a String method, they should be used directly. | //non-compliant code fmt.Sprintf("%s", x) fmt.Sprintf("%s", y) fmt.Sprintf("%s", z) //compliant code x string(y) z.String() | Functionality |
S1028-Simplify error construction with fmt.Errorf | Simplify error construction with fmt.Errorf | //non-compliant code errors.New(fmt.Sprintf(...)) //compliant code fmt.Errorf(...) | Functionality |
S1030-Use bytes.Buffer.String or bytes.Buffer.Bytes | bytes.Buffer has both a String and a Bytes method. It is almost never necessary to use string(buf.Bytes()) or []byte(buf.String()) – simply use the other method. The only exception to this are map lookups. Due to a compiler optimization, m[string(buf.Bytes())] is more efficient than m[buf.String()]. | Functionality | |
S1035-Redundant call to net/http.CanonicalHeaderKey in method call on net/http.Header | The methods on net/http.Header, namely Add, Del, Get and Set, already canonicalize the given header name. | Functionality | |
S1037-Elaborate way of sleeping | Using a select statement with a single case receiving from the result of time.After is a very elaborate way of sleeping that can much simpler be expressed with a simple call to time.Sleep. | Functionality | |
S1040-Type assertion to current type | The type assertion 'x.(SomeInterface)', when 'x' already has type 'SomeInterface', can only fail if 'x' is nil. Usually, this is left-over code from when 'x' had a different type and you can safely delete the type assertion. If you want to check that 'x' is not nil, consider being explicit and using an actual 'if x == nil' comparison instead of relying on the type assertion panicking. | Functionality | |
SA1004-Suspiciously small untyped constant in time.Sleep | The time.Sleep function takes a time.Duration as its only argument. Durations are expressed in nanoseconds. Thus, calling time.Sleep(1) will sleep for 1 nanosecond. This is a common source of bugs, as sleep functions in other languages often accept seconds or milliseconds. The time package provides constants such as time.Second to express large durations. These can be combined with arithmetic to express arbitrary durations, for example '5 * time.Second' for 5 seconds. If you truly meant to sleep for a tiny amount of time, use 'n * time.Nanosecond' to signal to Staticcheck that you did mean to sleep for some amount of nanoseconds. | Robustness | |
SA1006-Printf with dynamic first argument and no further arguments | Printf with dynamic first argument and no further arguments Using fmt.Printf with a dynamic first argument can lead to unexpected output. The first argument is a format string, where certain character combinations have special meaning. | Robustness | |
SA1008-Non-canonical key in http.Header map | Keys in http.Header maps are canonical, meaning they follow a specific combination of uppercase and lowercase letters. Methods such as http.Header.Add and http.Header.Del convert inputs into this canonical form before manipulating the map. When manipulating http.Header maps directly, as opposed to using the provided methods, care should be taken to stick to canonical form in order to avoid inconsistencies. | //non-compliant code h := http.Header{} h["etag"] = []string{"1234"} h.Add("etag", "5678") fmt.Println(h) //compliant code h := http.CanonicalHeaderKey{} h["etag"] = []string{"1234"} h.Add("etag", "5678") fmt.Println(h) | Functionality |
SA1012-A nil context.Context is being passed to a function, consider using context.TODO instead | A nil context.Context is being passed to a function, consider using context.TODO instead | Maintainability | |
SA1015-Using time.Tick in a way that will leak. Consider using time.NewTicker, and only use time.Tick in tests, commands and endless functions | Using time.Tick in a way that will leak. Consider using time.NewTicker, and only use time.Tick in tests, commands and endless functions | Robustness | |
SA1016-Trapping a signal that cannot be trapped | Not all signals can be intercepted by a process. Speficially, on UNIX-like systems, the syscall.SIGKILL and syscall.SIGSTOP signals are never passed to the process, but instead handled directly by the kernel. It is therefore pointless to try and handle these signals. | Functionality | |
SA1017-Channels used with os/signal.Notify should be buffered | The os/signal package uses non-blocking channel sends when delivering signals. If the receiving end of the channel isn't ready and the channel is either unbuffered or full, the signal will be dropped. To avoid missing signals, the channel should be buffered and of the appropriate size. For a channel used for notification of just one signal value, a buffer of size 1 is sufficient. | Maintainability, Efficiency | |
SA1019-Using a deprecated function, variable, constant or field | Using a deprecated function, variable, constant or field | Maintainability | |
SA1024-A string cutset contains duplicate characters | The strings.TrimLeft and strings.TrimRight functions take cutsets, not prefixes. A cutset is treated as a set of characters to remove from a string. For example, strings.TrimLeft("42133word", "1234")) will result in the string "word" – any characters that are 1, 2, 3 or 4 are cut from the left of the string. In order to remove one string from another, use strings.TrimPrefix instead. | Functionality | |
SA1025-It is not possible to use (*time.Timer).Reset's return value correctly | It is not possible to use (*time.Timer).Reset's return value correctly | Fuctionality, Robustness | |
SA1028-sort.Slice can only be used on slices | The first argument of sort.Slice must be a slice. | Functionality | |
SA2001-Empty critical section, did you mean to defer the unlock? | Empty critical sections of the kind mu.Lock() mu.Unlock() are very often a typo, and the following was intended instead: mu.Lock() defer mu.Unlock() Do note that sometimes empty critical sections can be useful, as a form of signaling to wait on another goroutine. Many times, there are simpler ways of achieving the same effect. When that isn't the case, the code should be amply commented to avoid confusion. Combining such comments with a //lint:ignore directive can be used to suppress this rare false positive. | Functionality | |
SA3001-Assigning to b.N in benchmarks distorts the results | The testing package dynamically sets b.N to improve the reliability of benchmarks and uses it in computations to determine the duration of a single operation. Benchmark code must not alter b.N as this would falsify results. | Robustness | |
SA4004-The loop exits unconditionally after one iteration | The loop exits unconditionally after one iteration | Functionality | |
SA4006-A value assigned to a variable is never read before being overwritten. Forgotten error check or dead code? | A value assigned to a variable is never read before being overwritten. Forgotten error check or dead code? | Conceptual Integrity | |
SA4008-The variable in the loop condition never changes, are you incrementing the wrong variable? | The variable in the loop condition never changes, are you incrementing the wrong variable? | Conceptual Integrity | |
SA4009-A function argument is overwritten before its first use | A function argument is overwritten before its first use | Conceptual Integrity | |
SA4010-The result of append will never be observed anywhere | The result of append will never be observed anywhere | Conceptual Integrity | |
SA4011-Break statement with no effect. Did you mean to break out of an outer loop? | Break statement with no effect. Did you mean to break out of an outer loop? | Conceptual Integrity | |
SA5000-Assignment to nil map | Assignment to nil map | if len(slice) < 0 { fmt.Println("unreachable code") } | Functionality, Conceptual Integrity |
SA5001-Defering Close before checking for a possible error | Defering Close before checking for a possible error | Conceptual Integrity | |
SA5004-for { select { ... with an empty default branch spins | for { select { ... with an empty default branch spins | Conceptual Integrity | |
SA5012-Passing odd-sized slice to function expecting even size | Some functions that take slices as parameters expect the slices to have an even number of elements. Often, these functions treat elements in a slice as pairs. For example, strings.NewReplacer takes pairs of old and new strings, and calling it with an odd number of elements would be an error. | Robustness | |
SA6000-Using regexp.Match or related in a loop, should use regexp.Compile | Using regexp.Match or related in a loop, should use regexp.Compile | COnceptual INtegrity | |
SA6001-Missing an optimization opportunity when indexing maps by byte slices | Map keys must be comparable, which precludes the use of byte slices. This usually leads to using string keys and converting byte slices to strings. Normally, a conversion of a byte slice to a string needs to copy the data and causes allocations. The compiler, however, recognizes m[string(b)] and uses the data of b directly, without copying it, because it knows that the data can't change during the map lookup. | //non-comliant code k := string(b) println(m[k]) println(m[k]) //compliant code println(m[string(b)]) println(m[string(b)]) | Functionality, Conceptual Integrity |
SA6003-Converting a string to a slice of runes before ranging over it | You may want to loop over the runes in a string. Instead of converting the string to a slice of runes and looping over that, you can loop over the string itself. | //non-comliant code for _, r := range s {} //compliant code for _, r := range []rune(s) {} | Functionality |
SA9002-Using a non-octal os.FileMode that looks like it was meant to be in octal. | Using a non-octal os.FileMode that looks like it was meant to be in octal. | Maintainability | |
SA9005-Trying to marshal a struct with no public fields nor custom marshaling | The encoding/json and encoding/xml packages only operate on exported fields in structs, not unexported ones. It is usually an error to try to (un)marshal structs that only consist of unexported fields. This check will not flag calls involving types that define custom marshaling behavior, e.g. via MarshalJSON methods. It will also not flag empty structs. | Conceptual Integrity, Functionality | |
SA9006-Dubious bit shifting of a fixed size integer value | Bit shifting a value past its size will always clear the value. For instance: v := int8(42) v >>= 8 will always result in 0. This check flags bit shifiting operations on fixed size integer values only. That is, int, uint and uintptr are never flagged to avoid potential false positives in somewhat exotic but valid bit twiddling tricks: // Clear any value above 32 bits if integers are more than 32 bits. func f(i int) int { v := i >> 32 v = v << 32 return i-v } | Robustness | |
ST1008-A function's error value should be its last return value | A function's error value should be its last return value. | Functionality | |
ST1016-Use consistent method receiver names | Use consistent method receiver names | Functionality | |
ST1019-Importing the same package multiple times | Go allows importing the same package multiple times, as long as different import aliases are being used. That is, the following bit of code is valid: import ( "fmt" fumpt "fmt" format "fmt" _ "fmt" ) However, this is very rarely done on purpose. Usually, it is a sign of code that got refactored, accidentally adding duplicate import statements. It is also a rarely known feature, which may contribute to confusion. | Functionaility |
Staticcheck low level issues
Rule | Description | Example | KPI | |
---|---|---|---|---|
S1001-Replace for loop with call to copy | Use copy() for copying elements from one slice to another. | //non-compliant code for i, x := range src { dst[i] = x } //compliant code copy(dst, src) | Functionality, Efficiency | low |
S1002-Omit comparison with boolean constant | Omit comparison with boolean constant | //non-compliant code if x == true {} //compliant code if x {} | Functionality | low |
S1005-Drop unnecessary use of the blank identifier | In many cases, assigning to the blank identifier is unnecessary. | //non-compliant code for _ = range s {} x, _ = someMap[key] _ = <-ch //compliant code for range s{} x = someMap[key] <-ch | Functionality | low |
S1006-Use for { ... } for infinite loops | For infinite loops, using for { ... } is the most idiomatic choice. | Functionality | low | |
S1012-Replace time.Now().Sub(x) with time.Since(x) | Replace time.Now().Sub(x) with time.Since(x) | //non-compliant code time.Now().Sub(x) //compliant code time.Since(x) | Functionality | low |
S1020-Omit redundant nil check in type assertion | Omit redundant nil check in type assertion | //non-compliant code if _, ok := i.(T); ok && i != nil {} //compliant code if _, ok := i.(T); ok {} | Functionality | low |
S1021-Merge variable declaration and assignment | Merge variable declaration and assignment | //non-compliant code var x uint x = 1 //compliant code var x uint = 1 | Functionality | low |
S1031-Omit redundant nil check around loop | Omit redundant nil check around loop | Functionality | low | |
S1032-Use sort.Ints(x), sort.Float64s(x), and sort.Strings(x) | The sort.Ints, sort.Float64s and sort.Strings functions are easier to read than sort.Sort(sort.IntSlice(x)), sort.Sort(sort.Float64Slice(x)) and sort.Sort(sort.StringSlice(x)). | //non-compliant code sort.Sort(sort.StringSlice(x)) //compliant code sort.Strings(x) | Functionality | low |
S1033-Unnecessary guard around call to delete | Calling delete on a nil map is a no-op. | Functionality | low | |
S1034-Use result of type assertion to simplify cases | Use result of type assertion to simplify cases | Maintainability | low | |
S1036-Unnecessary guard around map access | When accessing a map key that doesn't exist yet, one receives a zero value. Often, the zero value is a suitable value, for example when using append or doing integer math. | //non-compliant code if _, ok := m["foo"]; ok { m["foo"] = append(m["foo"], "bar") } else { m["foo"] = []string{"bar"} } //compliant code m["foo"] = append(m["foo"], "bar") | Functionality | low |
S1038-Unnecessarily complex way of printing formatted string | Instead of using fmt.Print(fmt.Sprintf(...)), one can use fmt.Printf(...). | Functionality | low | |
S1039-Unnecessary use of fmt.Sprint | Calling fmt.Sprint with a single string argument is unnecessary and identical to using the string directly. | Functionality | low | |
SA1018-strings.Replace called with n == 0, which does nothing | With n == 0, zero instances will be replaced. To replace all instances, use a negative number, or use strings.ReplaceAll. | Funtionality | low | |
SA4000-Boolean expression has identical expressions on both sides | Boolean expression has identical expressions on both sides | Functionality | low | |
SA4001-&*x gets simplified to x, it does not copy x | &*x gets simplified to x, it does not copy x | Functionality | low | |
SA4003-Comparing unsigned values against negative values is pointless | Comparing unsigned values against negative values is pointless | Functionality | low | |
SA4013-Negating a boolean twice (!!b) is the same as writing b. This is either redundant, or a typo. | Negating a boolean twice (!!b) is the same as writing b. This is either redundant, or a typo. | Functionality | low | |
SA4014-An if/else if chain has repeated conditions and no side-effects; if the condition didn't match the first time, it won't match the second time, either | An if/else if chain has repeated conditions and no side-effects; if the condition didn't match the first time, it won't match the second time, either | Maintainability | low | |
SA4015-Calling functions like math.Ceil on floats converted from integers doesn't do anything useful | Calling functions like math.Ceil on floats converted from integers doesn't do anything useful | Conceptual Integrity, Functionality | low | |
SA4016-Certain bitwise operations, such as x ^ 0, do not do anything useful | Certain bitwise operations, such as x ^ 0, do not do anything useful | Functionality | low | |
SA4017-A pure function's return value is discarded, making the call pointless | A pure function's return value is discarded, making the call pointless | Functionality | low | |
SA4018-Self-assignment of variables | Self-assignment of variables | Conceptual Integrity, Functionality | low | |
SA4019-Multiple, identical build constraints in the same file | Multiple, identical build constraints in the same file | Functionality, Conceptual Integrity | low | |
SA4020-Unreachable case clause in a type switch | In a type switch like the following type T struct{} func (T) Read(b []byte) (int, error) { return 0, nil } var v interface{} = T{} switch v.(type) { case io.Reader: // ... case T: // unreachable } the second case clause can never be reached because T implements io.Reader and case clauses are evaluated in source order. | //non-comliant code type T struct{} func (T) Read(b []byte) (int, error) { return 0, nil } var v interface{} = T{} switch v.(type) { case io.Reader: // ... case T: // unreachable } | Functionality | low |
SA4021-x = append(y) is equivalent to x = y | x = append(y) is equivalent to x = y | Functionality, Conceptual Integrity | low | |
SA4022-Comparing the address of a variable against nil | Code such as 'if &x == nil' is meaningless, because taking the address of a variable always yields a non-nil pointer. | Functionality, Conceptual Integrity | low | |
SA4023-Impossible comparison of interface value with untyped nil | Under the covers, interfaces are implemented as two elements, a type T and a value V. V is a concrete value such as an int, struct or pointer, never an interface itself, and has type T. For instance, if we store the int value 3 in an interface, the resulting interface value has, schematically, (T=int, V=3). The value V is also known as the interface's dynamic value, since a given interface variable might hold different values V (and corresponding types T) during the execution of the program. An interface value is nil only if the V and T are both unset, (T=nil, V is not set), In particular, a nil interface will always hold a nil type. If we store a nil pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (T=*int, V=nil). Such an interface value will therefore be non-nil even when the pointer value V inside is nil. It's a good idea for functions that return errors always to use the error type in their signature (as we did above) rather than a concrete type such as *MyError, to help guarantee the error is created correctly. As an example, os.Open returns an error even though, if not nil, it's always of concrete type *os.PathError. Similar situations to those described here can arise whenever interfaces are used. Just keep in mind that if any concrete value has been stored in the interface, the interface will not be nil. | //non-compliant code func returnsError() error { var p *MyError = nil if bad() { p = ErrBad } return p // Will always return a non-nil error. } //compliant code func returnsError() error { if bad() { return ErrBad } return nil } | Functionality, Conceptual Integrity | low |
SA4024-Checking for impossible return value from a builtin function | Return values the len and cap builtins cannot be negative. | //non-compliant code func returnsError() error { var p *MyError = nil if bad() { p = ErrBad } return p // Will always return a non-nil error. } //compliant code func returnsError() error { if bad() { return ErrBad } return nil } | Conceptual Integrity | low |
SA9003-Empty body in an if or else branch | Empty body in an if or else branch | Maintainability | low | |
SA9004-Only the first constant has an explicit type | n a constant declaration such as the following: const ( First byte = 1 Second = 2 ) the constant Second does not have the same type as the constant First. This construct shouldn't be confused with const ( First byte = iota Second ) where First and Second do indeed have the same type. The type is only passed on when no explicit value is assigned to the constant. When declaring enumerations with explicit values it is therefore important not to write const ( EnumFirst EnumType = 1 EnumSecond = 2 EnumThird = 3 ) This discrepancy in types can cause various confusing behaviors and bugs. | //non-comliant code package pkg const ( EnumFirst uint8 = 1 EnumSecond = 2 ) func fn(useFirst bool) { x := EnumSecond if useFirst { x = EnumFirst } } | Conceptual Integrity | low |
ST1000-Incorrect or missing package comment | Packages must have a package comment that is formatted according to the guidelines laid out in | Maintainability | low | |
ST1001-Dot imports are discouraged | Dot imports that aren't in external test packages are discouraged. The dot_import_whitelist option can be used to whitelist certain imports. | Maintainability | low | |
ST1003-Poorly chosen identifier | Identifiers, such as variable and package names, follow certain rules. | Maintainability | low | |
ST1005-Incorrectly formatted error string | Error strings should not be capitalized (unless beginning with proper nouns or acronyms) or end with punctuation, since they are usually printed following other context. That is, use fmt.Errorf("something bad") not fmt.Errorf("Something bad"), so that log.Printf("Reading %s: %v", filename, err) formats without a spurious capital letter mid-message. | Maintainability, Robustness | low | |
ST1006-Poorly chosen receiver name | The name of a method's receiver should be a reflection of its identity; often a one or two letter abbreviation of its type suffices (such as "c" or "cl" for "Client"). Don't use generic names such as "me", "this" or "self", identifiers typical of object-oriented languages that place more emphasis on methods as opposed to functions. The name need not be as descriptive as that of a method argument, as its role is obvious and serves no documentary purpose. It can be very short as it will appear on almost every line of every method of the type; familiarity admits brevity. Be consistent, too: if you call the receiver "c" in one method, don't call it "cl" in another. | Maintainability | low | |
ST1011-Poorly chosen name for variable of type time.Duration | time.Duration values represent an amount of time, which is represented as a count of nanoseconds. An expression like 5 * time.Microsecond yields the value 5000. It is therefore not appropriate to suffix a variable of type time.Duration with any time unit, such as Msec or Milli. | Maintainability | low | |
ST1012-Poorly chosen name for error variable | Error variables that are part of an API should be called errFoo or ErrFoo. | Maintainability | low | |
ST1013-Should use constants for HTTP error codes, not magic numbers | HTTP has a tremendous number of status codes. While some of those are well known (200, 400, 404, 500), most of them are not. The net/http package provides constants for all status codes that are part of the various specifications. It is recommended to use these constants instead of hard-coding magic numbers, to vastly improve the readability of your code. | Maintainability | low | |
ST1015-A switch's default case should be the first or last case | A switch's default case should be the first or last case | Maintainability, Functionality | low | |
ST1017-Don't use Yoda conditions | Don't use Yoda conditionsYoda conditions are conditions of the kind 'if 42 == x', where the literal is on the left side of the comparison. These are a common idiom in languages in which assignment is an expression, to avoid bugs of the kind 'if (x = 42)'. In Go, which doesn't allow for this kind of bug, we prefer the more idiomatic 'if x == 42'. | Maintainability | low | |
ST1018-Avoid zero-width and control characters in string literals | Avoid zero-width and control characters in string literals | //non-compliant import ( "fmt" fumpt "fmt" format "fmt" _ "fmt" ) | Maintainability | low |
ST1020-The documentation of an exported function should start with the function's name | Doc comments work best as complete sentences, which allow a wide variety of automated presentations. The first sentence should be a one-sentence summary that starts with the name being declared. If every doc comment begins with the name of the item it describes, you can use the doc subcommand of the go tool and run the output through grep. | Maintainability | low | |
ST1021-The documentation of an exported type should start with type's name | Doc comments work best as complete sentences, which allow a wide variety of automated presentations. The first sentence should be a one-sentence summary that starts with the name being declared. If every doc comment begins with the name of the item it describes, you can use the doc subcommand of the go tool and run the output through grep. | Maintainability | low | |
ST1022-The documentation of an exported variable or constant should start with variable's name | Doc comments work best as complete sentences, which allow a wide variety of automated presentations. The first sentence should be a one-sentence summary that starts with the name being declared. If every doc comment begins with the name of the item it describes, you can use the doc subcommand of the go tool and run the output through grep. | Maintainability | low |
PHP
The section below covers PHPMD and PHPCS code checker issues.
PHPMD Code Checker
PHP Mess Detector (PHPMD) is an open source code checker that aims to be a PHP equivalent of the well known Java tool PMD. Visit their website for more detailed information on PHPMD and the ruleset found below.
Critical level issues
Rule | Description | KPI | URL |
---|---|---|---|
EvalExpression | An eval-expression is untestable, a security risk and bad practice. Therefore it should be avoided. Consider to replace the eval-expression with regular code. | Security | https://phpmd.org/rules/design.html |
High level issues
Rule | Description | KPI | URL |
---|---|---|---|
ExitExpression | An exit-expression within regular code is untestable and therefore it should be avoided. Consider to move the exit-expression into some kind of startup script where an error/exception code is returned to the calling environment. | Robustness | https://phpmd.org/rules/design.html |
GotoStatement | Goto makes code harder to read and it is nearly impossible to understand the control flow of an application that uses this language construct. Therefore it should be avoided. Consider to replace Goto with regular control structures and separate methods/function, which are easier to read. | Robustness | https://phpmd.org/rules/design.html |
NumberOfChildren | A class with an excessive number of children is an indicator for an unbalanced class hierarchy. You should consider to refactor this class hierarchy. | Robustness | https://phpmd.org/rules/design.html |
DepthOfInheritance | A class with many parents is an indicator for an unbalanced and wrong class hierarchy. You should consider to refactor this class hierarchy. | Robustness | https://phpmd.org/rules/design.html |
CouplingBetweenObjects | A class with too many dependencies has negative impacts on several quality aspects of a class. This includes quality criteria like stability, maintainability and understandability | Robustness | https://phpmd.org/rules/design.html |
DevelopmentCodeFragment | Functions like var_dump(), print_r() etc. are normally only used during development and therefore such calls in production code are a good indicator that they were just forgotten. | Robustness | https://phpmd.org/rules/design.html |
Medium level issues
Rule | Description | KPI | URL |
---|---|---|---|
CyclomaticComplexity | Complexity is determined by the number of decision points in a method plus one for the method entry. The decision points are ‘if’, ‘while’, ‘for’, and ‘case labels’. Generally, 1-4 is low complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high complexity. | Maintainability | https://phpmd.org/rules/codesize.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. | Maintainability | https://phpmd.org/rules/codesize.html |
ExcessiveMethodLength | Violations of this rule usually indicate that the method is doing too much. Try to reduce the method size by creating helper methods and removing any copy/pasted code. | Maintainability | https://phpmd.org/rules/codesize.html |
ExcessiveClassLength | Long Class files are indications that the class may be trying to do too much. Try to break it down, and reduce the size to something manageable. | Maintainability | https://phpmd.org/rules/codesize.html |
ExcessiveClassComplexity | The Weighted Method Count (WMC) of a class is a good indicator of how much time and effort is required to modify and maintain this class. The WMC metric is defined as the sum of complexities of all methods declared in a class. A large number of methods also means that this class has a greater potential impact on derived classes. | Robustness | https://phpmd.org/rules/codesize.html |
UnusedPrivateField | Detects when a private field is declared and/or assigned a value, but not used. | Maintainability | https://phpmd.org/rules/unusedcode.html#UnusedPrivateField |
UnusedLocalVariable | Detects when a local variable is declared and/or assigned, but not used. | Maintainability | https://phpmd.org/rules/unusedcode.html#UnusedLocalVariable |
UnusedPrivateMethod | Unused Private Method detects when a private method is declared but is unused. | Maintainability | https://phpmd.org/rules/unusedcode.html#UnusedPrivateMethod |
UnusedFormalParameter | Avoid passing parameters to methods or constructors and then not using those parameters. | Maintainability | https://phpmd.org/rules/unusedcode.html#UnusedFormalParameter |
Low level issues
Rule | Description | KPI | URL |
---|---|---|---|
BooleanArgumentFlag | A boolean flag argument is a reliable indicator for a violation of the Single Responsibility Principle (SRP). You can fix this problem by extracting the logic in the boolean flag into its own class or method. | Maintainability | https://phpmd.org/rules/cleancode.html |
ElseExpression | An if expression with an else branch is never necessary. You can rewrite the conditions in a way that the else is not necessary and the code becomes simpler to read. To achieve this use early return statements. To achieve this you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations. | Maintainability | https://phpmd.org/rules/cleancode.html |
StaticAccess | Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods | Maintainability | https://phpmd.org/rules/cleancode.html |
ExcessiveParameterList | Long parameter lists can indicate that a new object should be created to wrap the numerous parameters. Basically, try to group the parameters together. | Understandability | https://phpmd.org/rules/codesize.html |
ExcessivePublicCount | A large number of public methods and attributes declared in a class can indicate the class may need to be broken up as increased effort will be required to thoroughly test it. | Understandability | https://phpmd.org/rules/codesize.html |
TooManyFields | Classes that have too many fields could be redesigned to have fewer fields, possibly through some nested object grouping of some of the information. For example, a class with city/state/zip fields could instead have one Address field. | Understandability | https://phpmd.org/rules/codesize.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. By default it ignores methods starting with ‘get’ or ‘set’. The default was changed from 10 to 25 in PHPMD 2.3. | Understandability | https://phpmd.org/rules/codesize.html |
TooManyPublicMethods | A class with too many public methods is probably a good suspect for refactoring, in order to reduce its complexity and find a way to have more fine grained objects. By default it ignores methods starting with ‘get’ or ‘set’. | Understandability | https://phpmd.org/rules/codesize.html |
Superglobals | Accessing a super-global variable directly is considered a bad practice. These variables should be encapsulated in objects that are provided by a framework, for instance | Maintainability | https://phpmd.org/rules/controversial.html |
CamelCaseClassName | It is considered best practice to use the CamelCase notation to name classes. | Maintainability | https://phpmd.org/rules/controversial.html |
CamelCasePropertyName | It is considered best practice to use the camelCase notation to name attributes. | Maintainability | https://phpmd.org/rules/controversial.html |
CamelCaseMethodName | It is considered best practice to use the camelCase notation to name methods. | Maintainability | https://phpmd.org/rules/controversial.html |
CamelCaseParameterName | It is considered best practice to use the camelCase notation to name parameters | Maintainability | https://phpmd.org/rules/controversial.html |
CamelCaseVariableName | It is considered best practice to use the camelCase notation to name variables. | Maintainability | https://phpmd.org/rules/controversial.html |
ShortVariable | Detects when a field, local, or parameter has a very short name. | Understandability | https://phpmd.org/rules/naming.html |
LongVariable | Detects when a field, formal or local variable is declared with a long name. | Understandability | https://phpmd.org/rules/naming.html |
ShortMethodName | Detects when very short method names are used. | Understandability | https://phpmd.org/rules/naming.html |
ConstructorWithNameAsEnclosingClass | A constructor method should not have the same name as the enclosing class, consider to use the PHP 5 __construct method. | Understandability | https://phpmd.org/rules/naming.html |
ConstantNamingConventions | Class/Interface constant names should always be defined in uppercase. | Understandability | https://phpmd.org/rules/naming.html |
BooleanGetMethodName | Looks for methods named ‘getX()’ with ‘boolean’ as the return type. The convention is to name these methods ‘isX()’ or ‘hasX()’. | Understandability | https://phpmd.org/rules/naming.html |
PHPCS Code Checker
PHP_CodeSniffer is an open source code checker that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard. Visit their website for more detailed information on PHPCS and the ruleset found below.
High level issues
Rule | Description | KPI | |
---|---|---|---|
no-throw | Discourage use of “throw” statement for error flagging | security | |
no-tx-origin | Discourage use of “tx.origin” global variable | security | |
enforce-explicit-visibility | Encourage user to explicitly specify visibility of function | security | |
no-block-members | Discourage use of members “blockhash” & “timestamp” (and alias “now”) of “block” global variable List of members to warn against [“blockhash”, “timestamp”] | security | |
no-call-value | Discourage use of .call.value()() | security | |
no-assign-params | Disallow assigning to function parameters | security | |
no-fixed | Disallow fixed point types | security | |
no-inline-assembly | Discourage use of inline assembly | security | |
no-low-level-calls | Discourage the use of low-level functions – call(), callcode() & delegatecall() List of functions to warn against [“call”, “callcode”, “delegatecall”] | security | |
no-modify-for-iter-var | Discourage user to modify a for loop iteration counting variable in the loop body | security | |
no-send | Discourage the use of unsafe method “send” | security | |
no-sha3 | Encourage use of “keccak256()” over “sha3()” function | security | |
no-unreachable-code | Disallow unreachable code | security |
Medium level issues
Rule | Description | KPI | |
---|---|---|---|
pragma-on-top | Ensure a) A PRAGMA directive exists and b) its on top of the file | Understandability | |
no-constant | Ensure that view is used over deprecated constant in function declarations | Portability | |
no-experimental | Ensure that experimental features are not used in production | Robustness |
Low level issues
Rule | Description | KPI | |
---|---|---|---|
imports-on-top | Ensure that all import statements are on top of the file | Understandability | |
variable-declarations | Ensure that names “l”, “O” & “I” are not used for variables | Understandability | |
array-declarations | Ensure that array declarations do not have space between the type and brackets | style | |
operator-whitespace | Ensure that operators are surrounded by a single space on either side | style | |
conditionals-whitespace | Ensure that there is exactly one space between conditional operators and parenthetic blocks | style | |
comma-whitespace | Ensure that there is no whitespace or comments between comma delimited elements and commas | style | |
semicolon-whitespace | Ensure that there is no whitespace or comments before semicolons | style | |
function-whitespace | Ensure function calls and declaration have (or do not have) whitespace in appropriate locations | style | |
lbrace | Ensure that every if, for, while and do statement is followed by an opening curly brace “{“on the same line | style | |
mixedcase | Ensure that all variable, function and parameter names follow the mixedCase naming convention | Understandability | |
camelcase | Ensure that contract, library, modifier and struct names follow CamelCase notation | Understandability | |
uppercase | Ensure that all constants (and only constants) contain only upper case letters and underscore | Understandability | |
no-empty-blocks | Ensure that no empty blocks {} exist | Understandability | |
no-unused-vars | Flag all the variables that were declared but never used | Understandability | |
quotes | Ensure that all strings use only 1 style – either double quotes or single quotes | style | |
blank-lines | Ensure that there is exactly a 2-line gap between Contract and Funtion declarations | style | |
indentation | Ensure consistent indentation of 4 spaces per level | style | |
arg-overflow | In the case of 4+ elements in the same line require they are instead put on a single line each | style | |
whitespace | Specify where whitespace is suitable and where it is not | stylfy | |
function-order | Ensure order of functions in a contract: constructor, fallback, external, public, internal, private | Understandability | |
emit | Ensure that emit statement is used to trigger a solidity event | style | |
value-in-payable | Ensure “msg.value” is only used in functions with the “payable” modifier | Accuracy | |
max-len | Ensure that a line of code does not exceed the specified number of characters | style | |
error-reason | Ensure that error message is provided for revert and require statements | Understandability | |
visibility-first | Ensure that the visibility modifier for a function should come before any custom modifiers | Understandability | |
linebreak-style | Ensure consistent linebreak style | style |
Kotlin
The section below covers Detekt code checker issues.
Detekt code checker
Detekt is an open source static code analysis tool for the Kotlin programming language. It operates on the abstract syntax tree provided by the Kotlin compiler. Visit their website for more detailed information on Detekt and the ruleset found below.
Medium level issues
Rule | Description | KPI | url |
---|---|---|---|
InstanceOfCheckForException | This rule reports catch blocks which check for the type of an exception via is checks or casts. Instead of catching generic exception types and then checking for specific exception types the code should use multiple catch blocks. These catch blocks should then catch the specific exceptions. | Robustness | https://arturbosch.github.io/detekt/exceptions.html#instanceofcheckforexception |
IteratorHasNextCallsNextMethod | Verifies implementations of the Iterator interface. The hasNext() method of an Iterator implementation should not have any side effects. This rule reports implementations that call the next() method of the Iterator inside the hasNext() method. | Robustness | https://arturbosch.github.io/detekt/potential-bugs.html#iteratorhasnextcallsnextmethod |
NestedClassesVisibility | Nested classes are often used to implement functionality local to the class it is nested in. Therefore it should not be public to other parts of the code. Prefer keeping nested classes private. | Security | https://arturbosch.github.io/detekt/style.html#nestedclassesvisibility |
PrintStackTrace | This rule reports code that tries to print the stacktrace of an exception. Instead of simply printing a stacktrace a better logging solution should be used. | Security | https://arturbosch.github.io/detekt/exceptions.html#printstacktrace |
RethrowCaughtException | This rule reports all exceptions that are caught and then later re-thrown without modification. It ignores caught exception that are rethrown if there is work done before that. | Robustness | https://arturbosch.github.io/detekt/exceptions.html#rethrowcaughtexception |
SpreadOperator | Using a spread operator causes a full copy of the array to be created before calling a method. This has a very high performance penalty. Benchmarks showing this performance penalty can be seen here: https://sites.google.com/a/athaydes.com/renato-athaydes/posts/kotlinshiddencosts-benchmarks | Efficiency | https://arturbosch.github.io/detekt/performance.html#spreadoperator |
SwallowedException | Exceptions should not be swallowed. This rule reports all instances where exceptions are caught and not correctly passed into a newly thrown exception. | Analyzability | https://arturbosch.github.io/detekt/exceptions.html#swallowedexception |
ThrowingExceptionFromFinally | This rule reports all cases where exceptions are thrown from a finally block. Throwing exceptions from a finally block should be avoided as it can lead to confusion and discarded exceptions. | Maintainability | https://arturbosch.github.io/detekt/exceptions.html#throwingexceptionfromfinally |
ThrowingExceptionInMain | This rule reports all exceptions that are thrown in a main method. An exception should only be thrown if it can be handled by a higher function. | Robustness | https://arturbosch.github.io/detekt/exceptions.html#throwingexceptioninmain |
TooGenericExceptionThrown | This rule reports thrown exceptions that have a type that is too generic. It should be preferred to throw specific exceptions to the case that has currently occurred. | Robustness | https://arturbosch.github.io/detekt/exceptions.html#toogenericexceptionthrown |
UnreachableCode | Reports unreachable code. Code can be unreachable because it is behind return, throw, continue or break expressions. This unreachable code should be removed as it serves no purpose. | Robustness | https://arturbosch.github.io/detekt/potential-bugs.html#unreachablecode |
Low level issues
Rule | Description | KPI | url |
---|---|---|---|
ClassNaming | Reports when class names which do not follow the specified naming convention are used. | https://arturbosch.github.io/detekt/naming.html#classnaming | |
CollapsibleIfStatements | This rule detects if statements which can be collapsed. This can reduce nesting and help improve readability. However it should be carefully considered if merging the if statements actually does improve readability or if it hides some edge-cases from the reader. | Understandability | https://arturbosch.github.io/detekt/style.html#collapsibleifstatements |
CommentOverPrivateFunction | This rule reports comments and documentation that has been added to private functions. These comments get reported because they probably explain the functionality of the private function. However private functions should be small enough and have an understandable name so that they are self-explanatory and do not need this comment in the first place. Instead of simply removing this comment to solve this issue prefer to split up the function into smaller functions with better names if necessary. Giving the function a better, more descriptive name can also help in solving this issue. |
https://arturbosch.github.io/detekt/comments.html#commentoverprivatefunction | |
CommentOverPrivateProperty | This rule reports comments and documentation above private properties. This can indicate that the property has a confusing name or is not in a small enough context to be understood. Private properties should be named in a self-explanatory way and readers of the code should be able to understand why the property exists and what purpose it solves without the comment. Instead of simply removing the comment to solve this issue prefer renaming the property to a more self-explanatory name. If this property is inside a bigger class it could make senes to refactor and split up the class. This can increase readability and make the documentation obsolete. |
https://arturbosch.github.io/detekt/comments.html#commentoverprivateproperty | |
ComplexCondition | Complex conditions make it hard to understand which cases lead to the condition being true or false. To improve readability and understanding of complex conditions consider extracting them into well-named functions or variables and call those instead. | Understandability | https://arturbosch.github.io/detekt/complexity.html#complexcondition |
ComplexInterface | Complex interfaces which contain too many functions and/or properties indicate that this interface is handling too many things at once. Interfaces should follow the single-responsibility principle to also encourage implementations of this interface to not handle too many things at once. Threshold for complex interface is 10. Large interfaces should be split into smaller interfaces which have a clear responsibility and are easier to understand and implement. | Maintainability | https://arturbosch.github.io/detekt/complexity.html#complexinterface |
ComplexMethod | Complex methods are hard to understand and read. It might not be obvious what side-effects a complex method has. Prefer splitting up complex methods into smaller methods that are in turn easier to understand. Smaller methods can also be named much clearer which leads to improved readability of the code. Threadhold is 10 | Maintainability | https://arturbosch.github.io/detekt/complexity.html#complexmethod |
DataClassContainsFunctions | This rule reports functions inside data classes which have not been whitelisted as a conversion function. Data classes should mainly be used to store data. This rule assumes that they should not contain any extra functions aside functions that help with converting objects from/to one another. Data classes will automatically have a generated equals, toString and hashCode function by the compiler. | https://arturbosch.github.io/detekt/style.html#dataclasscontainsfunctions | |
DuplicateCaseInWhenExpression | Flags duplicate case statements in when expressions. If a when expression contains the same case statement multiple times they should be merged. Otherwise it might be easy to miss one of the cases when reading the code, leading to unwanted side effects. | Robustness | https://arturbosch.github.io/detekt/potential-bugs.html#duplicatecaseinwhenexpression |
EmptyCatchBlock | Reports empty catch blocks. Empty blocks of code serve no purpose and should be removed. | Analyzability | https://arturbosch.github.io/detekt/empty-blocks.html#emptycatchblock |
EmptyClassBlock | Reports empty classes. Empty blocks of code serve no purpose and should be removed. | Maintainability | https://arturbosch.github.io/detekt/empty-blocks.html#emptyclassblock |
EmptyDefaultConstructor | Reports empty default constructors. Empty blocks of code serve no purpose and should be removed. | Maintainability | https://arturbosch.github.io/detekt/empty-blocks.html#emptydefaultconstructor |
EmptyDoWhileBlock | Reports empty do/while loops. Empty blocks of code serve no purpose and should be removed. | Maintainability | https://arturbosch.github.io/detekt/empty-blocks.html#emptydowhileblock |
EmptyElseBlock | Reports empty else blocks. Empty blocks of code serve no purpose and should be removed. | Maintainability | https://arturbosch.github.io/detekt/empty-blocks.html#emptyelseblock |
EmptyFinallyBlock | Reports empty finally blocks. Empty blocks of code serve no purpose and should be removed. | Maintainability | https://arturbosch.github.io/detekt/empty-blocks.html#emptyfinallyblock |
EmptyForBlock | Reports empty for loops. Empty blocks of code serve no purpose and should be removed. | Maintainability | https://arturbosch.github.io/detekt/empty-blocks.html#emptyforblock |
EmptyFunctionBlock | Reports empty functions. Empty blocks of code serve no purpose and should be removed. This rule will not report functions overriding others. | Maintainability | https://arturbosch.github.io/detekt/empty-blocks.html#emptyfunctionblock |
EmptyIfBlock | Reports empty if blocks. Empty blocks of code serve no purpose and should be removed. | Maintainability | https://arturbosch.github.io/detekt/empty-blocks.html#emptyifblock |
EmptyInitBlock | Reports empty init expressions. Empty blocks of code serve no purpose and should be removed. | Maintainability | https://arturbosch.github.io/detekt/empty-blocks.html#emptyinitblock |
EmptyKtFile | Reports empty Kotlin (.kt) files. Empty blocks of code serve no purpose and should be removed. | Maintainability | https://arturbosch.github.io/detekt/empty-blocks.html#emptyktfile |
EmptySecondaryConstructor | Reports empty secondary constructors. Empty blocks of code serve no purpose and should be removed. | Maintainability | https://arturbosch.github.io/detekt/empty-blocks.html#emptysecondaryconstructor |
EmptyWhenBlock | Reports empty when expressions. Empty blocks of code serve no purpose and should be removed. | Maintainability | https://arturbosch.github.io/detekt/empty-blocks.html#emptywhenblock |
EmptyWhileBlock | Reports empty while expressions. Empty blocks of code serve no purpose and should be removed. | Maintainability | https://arturbosch.github.io/detekt/empty-blocks.html#emptywhileblock |
EndOfSentenceFormat | This rule validates the end of the first sentence of a KDoc comment. It should end with proper punctuation or with a correct URL. | https://arturbosch.github.io/detekt/comments.html#endofsentenceformat | |
EnumNaming | Reports when enum names which do not follow the specified naming convention are used. | https://arturbosch.github.io/detekt/naming.html#enumnaming | |
EqualsAlwaysReturnsTrueOrFalse | Reports equals() methods which will always return true or false. Equals methods should always report if some other object is equal to the current object. See the Kotlin documentation for Any.equals(other: Any?): https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/equals.html | Accuracy | https://arturbosch.github.io/detekt/potential-bugs.html#equalsalwaysreturnstrueorfalse |
EqualsNullCall | To compare an object with null prefer using ==. This rule detects and reports instances in the code where the equals() method is used to compare a value with null. | Robustness | https://arturbosch.github.io/detekt/style.html#equalsnullcall |
EqualsWithHashCodeExist | When a class overrides the equals() method it should also override the hashCode() method. All hash-based collections depend on objects meeting the equals-contract. Two equal objects must produce the same hashcode. When inheriting equals or hashcode, override the inherited and call the super method for Clarification. | Accuracy | https://arturbosch.github.io/detekt/potential-bugs.html#equalswithhashcodeexist |
ExceptionRaisedInUnexpectedLocation | This rule allows to define functions which should never throw an exception. If a function exists that does throw an exception it will be reported. By default this rule is checking for toString, hashCode, equals and finalize. This rule is configurable via the methodNames configuration to change the list of functions which should not throw any exceptions. | Robustness | https://arturbosch.github.io/detekt/exceptions.html#exceptionraisedinunexpectedlocation |
ExplicitGarbageCollectionCall | Reports all calls to explicitly trigger the Garbage Collector. Code should work independently of the garbage collector and should not require the GC to be triggered in certain points in time. | Resource Utilization | https://arturbosch.github.io/detekt/potential-bugs.html#explicitgarbagecollectioncall |
ExpressionBodySyntax | Functions which only contain a return statement can be collapsed to an expression body. This shortens and cleans up the code. | https://arturbosch.github.io/detekt/style.html#expressionbodysyntax | |
ForbiddenClassName | Reports class names which are forbidden per configuration. By default this rule does not report any classes. Examples for forbidden names might be too generic class names like …Manager. | https://arturbosch.github.io/detekt/naming.html#forbiddenclassname | |
ForbiddenComment | This rule allows to set a list of comments which are forbidden in the codebase and should only be used during development. Offending code comments will then be reported. | https://arturbosch.github.io/detekt/style.html#forbiddencomment | |
ForbiddenImport | This rule allows to set a list of forbidden imports. This can be used to discourage the use of unstable, experimental or deprecated APIs. Detekt will then report all imports that are forbidden. | https://arturbosch.github.io/detekt/style.html#forbiddenimport | |
ForEachOnRange | Using the forEach method on ranges has a heavy performance cost. Prefer using simple for loops. Benchmarks have shown that using forEach on a range can have a huge performance cost in comparison to simple for loops. Hence in most contexts a simple for loop should be used instead. See more details here: https://sites.google.com/a/athaydes.com/renato-athaydes/posts/kotlinshiddencosts-benchmarks To solve this CodeSmell, the forEach usage should be replaced by a for loop. | Efficiency | https://arturbosch.github.io/detekt/performance.html#foreachonrange |
FunctionMaxLength | Reports when very long function names are used. | https://arturbosch.github.io/detekt/naming.html#functionmaxlength | |
FunctionMinLength | Reports when very short function names are used. | https://arturbosch.github.io/detekt/naming.html#functionminlength | |
FunctionNaming | Reports when function names which do not follow the specified naming convention are used. | https://arturbosch.github.io/detekt/naming.html#functionnaming | |
FunctionOnlyReturningConstant | A function that only returns a single constant can be misleading. Instead prefer to define the constant directly as a const val. | Understandability | https://arturbosch.github.io/detekt/style.html#functiononlyreturningconstant |
InvalidRange | Reports ranges which are empty. This might be a bug if it is used for instance as a loop condition. This loop will never be triggered then. This might be due to invalid ranges like (10..9) which will cause the loop to never be entered. | Robustness | https://arturbosch.github.io/detekt/potential-bugs.html#invalidrange |
IteratorNotThrowingNoSuchElementException | Reports implementations of the Iterator interface which do not throw a NoSuchElementException in the implementation of the next() method. When there are no more elements to return an Iterator should throw a NoSuchElementException.
See: https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html#next() |
Robustness | https://arturbosch.github.io/detekt/potential-bugs.html#iteratornotthrowingnosuchelementexception |
LabeledExpression | This rule reports labeled expressions. Expressions with labels generally increase complexity and worsen the maintainability of the code. Refactor the violating code to not use labels instead. | Understandability | https://arturbosch.github.io/detekt/complexity.html#labeledexpression |
LargeClass | This rule reports large classes. Classes should generally have one responsibility. Large classes can indicate that the class does instead handle multiple responsibilities. Instead of doing many things at once prefer to split up large classes into smaller classes. These smaller classes are then easier to understand and handle less Things. | https://arturbosch.github.io/detekt/complexity.html#largeclass | |
LateinitUsage | Turn on this rule to flag usages of the lateinit modifier. Using lateinit for property initialization can be error prone and the actual initialization is not guaranteed. Try using constructor injection or delegation to initialize properties. | Accuracy | https://arturbosch.github.io/detekt/potential-bugs.html#lateinitusage |
LongMethod | Methods should have one responsibility. Long methods can indicate that a method handles too many cases at once. Prefer smaller methods with clear names that describe their functionality clearly. Extract parts of the functionality of long methods into separate, smaller methods. | https://arturbosch.github.io/detekt/complexity.html#longmethod | |
LongParameterList | Reports functions which have more parameters than a certain threshold (default: 6). | https://arturbosch.github.io/detekt/complexity.html#longparameterlist | |
LoopWithTooManyJumpStatements | Loops which contain multiple break or continue statements are hard to read and understand. To increase readability they should be refactored into simpler loops. | https://arturbosch.github.io/detekt/style.html#loopwithtoomanyjumpstatements | |
MagicNumber | This rule detects and reports usages of magic numbers in the code. Prefer defining constants with clear names describing what the magic number means. | https://arturbosch.github.io/detekt/style.html#magicnumber | |
MandatoryBracesIfStatements | This rule detects multi-line if statements which do not have braces. Adding braces would improve readability and avoid possible errors. | https://arturbosch.github.io/detekt/style.html#mandatorybracesifstatements | |
MatchingDeclarationName | If a Kotlin file contains a single non-private class (potentially with related top-level declarations), its name should be the same as the name of the class, with the .kt extension appended. If a file contains multiple classes, or only top-level declarations, choose a name describing what the file contains, and name the file accordingly. Use camel humps with an uppercase first letter (e.g. ProcessDeclarations.kt).
The name of the file should describe what the code in the file does. Therefore, you should avoid using meaningless words such as “Util” in file names.” – Official Kotlin Style Guide More information at: http://kotlinlang.org/docs/reference/coding-conventions.html |
https://arturbosch.github.io/detekt/naming.html#matchingdeclarationname | |
MaxLineLength | This rule reports lines of code which exceed a defined maximum line length. Long lines might be hard to read on smaller screens or printouts. Additionally having a maximum line length in the codebase will help make the code more uniform. | https://arturbosch.github.io/detekt/style.html#maxlinelength | |
MayBeConst | This rule identifies and reports properties (val) that may be const val instead. Using const val can lead to better performance of the resulting bytecode as well as better interoperability with Java. | https://arturbosch.github.io/detekt/style.html#maybeconst | |
MemberNameEqualsClassName | This rule reports a member that has the same as the containing class or object. This might result in confusion. The member should either be renamed or changed to a constructor. Factory functions that create an instance of the class are exempt from this rule. | https://arturbosch.github.io/detekt/naming.html#membernameequalsclassname | |
MethodOverloading | This rule reports methods which have many versions of the same method with different parameter overloading. Method overloading tightly couples these methods together which might make the code harder to understand.
Refactor these methods and try to use optional parameters instead to prevent some of the overloading. |
https://arturbosch.github.io/detekt/complexity.html#methodoverloading | |
ModifierOrder | This rule reports cases in the code where modifiers are not in the correct order. The default modifier order is taken from: http://kotlinlang.org/docs/reference/coding-conventions.html#modifiers | https://arturbosch.github.io/detekt/style.html#modifierorder | |
NestedBlockDepth | This rule reports excessive nesting depth in functions. Excessively nested code becomes harder to read and increases its hidden complexity. It might become harder to understand edge-cases of the function. Prefer extracting the nested code into well-named functions to make it easier to understand. | https://arturbosch.github.io/detekt/complexity.html#nestedblockdepth | |
NewLineAtEndOfFile | This rule reports files which do not end with a line separator. | https://arturbosch.github.io/detekt/style.html#newlineatendoffile | |
NoTabs | This rule reports if tabs are used in Kotlin files. According to Google’s Kotlin style guide the only whitespace chars that are allowed in a source file are the line terminator sequence and the ASCII horizontal space character (0x20). | https://arturbosch.github.io/detekt/style.html#notabs | |
NotImplementedDeclaration | This rule reports all exceptions of the type NotImplementedError that are thrown. It also reports all TODO(..) functions. These indicate that functionality is still under development and will not work properly. Both of these should only serve as temporary declarations and should not be put into production environments. | https://arturbosch.github.io/detekt/exceptions.html#notimplementeddeclaration | |
ObjectPropertyNaming | Reports when property names inside objects which do not follow the specified naming convention are used. | https://arturbosch.github.io/detekt/naming.html#objectpropertynaming | |
OptionalAbstractKeyword | This rule reports abstract modifiers which are unnecessary and can be removed. | Understandability | https://arturbosch.github.io/detekt/style.html#optionalabstractkeyword |
OptionalUnit | It is not necessary to define a return type of Unit on functions. This rule detects and reports instances where the Unit return type is specified on functions. | Maintainability | https://arturbosch.github.io/detekt/style.html#optionalunit |
OptionalWhenBraces | This rule reports unnecessary braces in when expressions. These optional braces should be removed. | https://arturbosch.github.io/detekt/style.html#optionalwhenbraces | |
PackageNaming | Reports when package names which do not follow the specified naming convention are used. | https://arturbosch.github.io/detekt/naming.html#packagenaming | |
PreferToOverPairSyntax | This rule detects the usage of the Pair constructor to create pairs of values. Using to is preferred. | Understandability | https://arturbosch.github.io/detekt/style.html#prefertooverpairsyntax |
ProtectedMemberInFinalClass | Kotlin classes are final by default. Thus classes which are not marked as open should not contain any protected members. Consider using private or internal modifiers instead. | Understandability | https://arturbosch.github.io/detekt/style.html#protectedmemberinfinalclass |
RedundantVisibilityModifierRule | This rule checks for redundant visibility modifiers. | https://arturbosch.github.io/detekt/style.html#redundantvisibilitymodifierrule | |
ReturnCount | Restrict the number of return methods allowed in methods. Having many exit points in a function can be confusing and impacts readability of the Code. | https://arturbosch.github.io/detekt/style.html#returncount | |
ReturnFromFinally | Reports all return statements in finally blocks. Using return statements in finally blocks can discard and hide exceptions that are thrown in the try block. | Robustness | https://arturbosch.github.io/detekt/exceptions.html#returnfromfinally |
SafeCast | This rule inspects casts and reports casts which could be replaced with safe casts instead. | https://arturbosch.github.io/detekt/style.html#safecast | |
SerialVersionUIDInSerializableClass | Classes which implement the Serializable interface should also correctly declare a serialVersionUID. This rule verifies that a serialVersionUID was correctly defined. | Understandability | https://arturbosch.github.io/detekt/style.html#serialversionuidinserializableclass |
SpacingBetweenPackageAndImports | This rule verifies spacing between package and import statements as well as between import statements and class Declarations. | https://arturbosch.github.io/detekt/style.html#spacingbetweenpackageandimports | |
StringLiteralDuplication | This rule detects and reports duplicated String literals. Repeatedly typing out the same String literal across the codebase makes it harder to change and maintain. Instead, prefer extracting the String literal into a property or constant. | Maintainability | https://arturbosch.github.io/detekt/complexity.html#stringliteralduplication |
ThrowingExceptionsWithoutMessageOrCause | This rule reports all exceptions which are thrown without arguments or further description. Exceptions should always call one of the constructor overloads to provide a message or a cause. Exceptions should be meaningful and contain as much detail about the error case as possible. This will help to track down an underlying issue in a better way. | Maintainability | https://arturbosch.github.io/detekt/exceptions.html#throwingexceptionswithoutmessageorcause |
ThrowingNewInstanceOfSameException | Exceptions should not be wrapped inside the same exception type and then rethrown. Prefer wrapping exceptions in more meaningful exception types. | Analyzability | https://arturbosch.github.io/detekt/exceptions.html#throwingnewinstanceofsameexception |
ThrowsCount | Functions should have clear throw statements. Functions with many throw statements can be harder to read and lead to confusion. Instead prefer to limit the amount of throw statements in a function. | https://arturbosch.github.io/detekt/style.html#throwscount | |
TooGenericExceptionCaught | This rule reports catch blocks for exceptions that have a type that is too generic. It should be preferred to catch specific exceptions to the case that is currently handled. If the scope of the caught exception is too broad it can lead to unintended exceptions being caught. | Robustness | https://arturbosch.github.io/detekt/exceptions.html#toogenericexceptioncaught |
TooManyFunctions | This rule reports files, classes, interfaces, objects and enums which contain too many functions. Each element can be configured with different thresholds. Too many functions indicate a violation of the single responsibility principle. Prefer extracting functionality which clearly belongs together in separate parts of the code. | https://arturbosch.github.io/detekt/complexity.html#toomanyfunctions | |
TopLevelPropertyNaming | Reports when top level constant names which do not follow the specified naming convention are used. | https://arturbosch.github.io/detekt/naming.html#toplevelpropertynaming | |
TrailingWhitespace | This rule reports lines that end with a whitespace. | https://arturbosch.github.io/detekt/style.html#trailingwhitespace | |
UnconditionalJumpStatementInLoop | Reports loops which contain jump statements that jump regardless of any conditions. This implies that the loop is only executed once and thus could be rewritten without a loop altogether. | https://arturbosch.github.io/detekt/potential-bugs.html#unconditionaljumpstatementinloop | |
UndocumentedPublicClass | This rule reports public classes, objects and interfaces which do not have the required documentation. Enable this rule if the codebase should have documentation on every public class, interface and object. By default this rule also searches for nested and inner classes and objects. This default behavior can be changed with the configuration options of this rule. | https://arturbosch.github.io/detekt/comments.html#undocumentedpublicclass | |
UndocumentedPublicFunction | This rule will report any public function which does not have the required documentation. If the codebase should have documentation on all public functions enable this rule to enforce this. |
https://arturbosch.github.io/detekt/comments.html#undocumentedpublicfunction | |
UnnecessaryAbstractClass | This rule inspects abstract classes. In case an abstract class does not have any concrete members it should be refactored into an interfacse. Abstract classes which do not define any abstract members should instead be refactored into concrete classes. | Understandability | https://arturbosch.github.io/detekt/style.html#unnecessaryabstractclass |
UnnecessaryInheritance | This rule reports unnecessary super types. Inheriting from Any or Object is unnecessary and should simply be removed. | Maintainability | https://arturbosch.github.io/detekt/style.html#unnecessaryinheritance |
UnnecessaryParentheses | This rule reports unnecessary parentheses around expressions. These unnecessary parentheses can safely be removed. Added in v1.0.0.RC4 | https://arturbosch.github.io/detekt/style.html#unnecessaryparentheses | |
UnnecessaryTemporaryInstantiation | Avoid temporary objects when converting primitive types to String. This has a performance penalty when compared to using primitive types directly. To solve this issue, remove the wrapping type. | Efficiency | https://arturbosch.github.io/detekt/performance.html#unnecessarytemporaryinstantiation |
UnsafeCallOnNullableType | Reports unsafe calls on nullable types. These calls will throw a NullPointerException in case the nullable value is null. Kotlin provides many ways to work with nullable types to increase null safety. Guard the code appropriately to prevent NullPointerExceptions. | Robustness | https://arturbosch.github.io/detekt/potential-bugs.html#unsafecallonnullabletype |
UnsafeCast | Reports casts which are unsafe. In case the cast is not possible it will throw an exception. | Robustness | https://arturbosch.github.io/detekt/potential-bugs.html#unsafecast |
UntilInsteadOfRangeTo | Reports calls to ‘…’ operator instead of calls to ‘until’. ‘unti’ is applicable in cases where the upper range value is described as some value subtracted by 1. ‘until’ helps to prevent off-by-one errors. | https://arturbosch.github.io/detekt/style.html#untilinsteadofrangeto | |
UnusedImports | This rule reports unused imports. Unused imports are dead code and should be removed. | https://arturbosch.github.io/detekt/style.html#unusedimports | |
UnusedPrivateMember | Reports unused private properties, function parameters and functions. If private properties are unused they should be removed. Otherwise this dead code can lead to confusion and potential bugs. | https://arturbosch.github.io/detekt/style.html#unusedprivatemember | |
UseDataClass | Classes that simply hold data should be refactored into a data class. Data classes are specialized to hold data and generate hashCode, equals and toString implementations as well.
Read more about data class: https://kotlinlang.org/docs/reference/data-classes.html |
https://arturbosch.github.io/detekt/style.html#usedataclass | |
UselessPostfixExpression | This rule reports postfix expressions (++, -) which are unused and thus unnecessary. This leads to confusion as a reader of the code might think the value will be incremented/decremented. However the value is replaced with the original value which might lead to bugs. | Understandability | https://arturbosch.github.io/detekt/potential-bugs.html#uselesspostfixexpression |
UtilityClassWithPublicConstructor | A class which only contains utility functions and no concrete implementation can be refactored into an object. | https://arturbosch.github.io/detekt/style.html#utilityclasswithpublicconstructor | |
VariableMaxLength | Reports when very long variable names are used. | https://arturbosch.github.io/detekt/naming.html#variablemaxlength | |
VariableMinLength | Reports when very short variable names are used. | https://arturbosch.github.io/detekt/naming.html#variableminlength | |
VariableNaming | Reports when variable names which do not follow the specified naming convention are used. | https://arturbosch.github.io/detekt/naming.html#variablenaming | |
WildcardImport | Wildcard imports should be replaced with imports using fully qualified class names. This helps increase clarity of which classes are imported and helps prevent naming conflicts. Library updates can introduce naming clashes with your own classes which might result in compilation errors. | https://arturbosch.github.io/detekt/style.html#wildcardimport | |
WrongEqualsTypeParameter | Reports equals() methods which take in a wrongly typed parameter. Correct implementations of the equals() method should only take in a parameter of type Any?
See: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/equals.html |
Robustness | https://arturbosch.github.io/detekt/potential-bugs.html#wrongequalstypeparameter |
Solidity
The section below covers the Solium Code Checker.
Solium Code Checker
Solium is an open source linter to identify and fix style & security issues in Ethereum’s Solidity. Visit their website for more detailed information on Solium and the ruleset found below.
High level issues
Rule | Description | KPI |
---|---|---|
no-throw | Discourage use of “throw” statement for error flagging | security |
no-tx-origin | Discourage use of “tx.origin” global variable | security |
enforce-explicit-visibility | Encourage user to explicitly specify visibility of function | security |
no-block-members | Discourage use of members “blockhash” & “timestamp” (and alias “now”) of “block” global variable List of members to warn against [“blockhash”, “timestamp”] | security |
no-call-value | Discourage use of .call.value()() | security |
no-assign-params | Disallow assigning to function parameters | security |
no-fixed | Disallow fixed point types | security |
no-inline-assembly | Discourage use of inline assembly | security |
no-low-level-calls | Discourage the use of low-level functions – call(), callcode() & delegatecall() List of functions to warn against [“call”, “callcode”, “delegatecall”] | security |
no-modify-for-iter-var | Discourage user to modify a for loop iteration counting variable in the loop body | security |
no-send | Discourage the use of unsafe method “send” | security |
no-sha3 | Encourage use of “keccak256()” over “sha3()” function | security |
no-unreachable-code | Disallow unreachable code | security |
Medium level issues
Rule | Description | KPI |
---|---|---|
pragma-on-top | Ensure a) A PRAGMA directive exists and b) its on top of the file | Understandability |
no-constant | Ensure that view is used over deprecated constant in function declarations | Portability |
no-experimental | Ensure that experimental features are not used in production | Robustness |
Low level issues
Rule | Description | KPI |
---|---|---|
imports-on-top | Ensure that all import statements are on top of the file | Understandability |
variable-declarations | Ensure that names “l”, “O” & “I” are not used for variables | Understandability |
array-declarations | Ensure that array declarations do not have space between the type and brackets | style |
operator-whitespace | Ensure that operators are surrounded by a single space on either side | style |
conditionals-whitespace | Ensure that there is exactly one space between conditional operators and parenthetic blocks | style |
comma-whitespace | Ensure that there is no whitespace or comments between comma delimited elements and commas | style |
semicolon-whitespace | Ensure that there is no whitespace or comments before semicolons | style |
function-whitespace | Ensure function calls and declaration have (or do not have) whitespace in appropriate locations | style |
lbrace | Ensure that every if, for, while and do statement is followed by an opening curly brace “{“on the same line | style |
mixedcase | Ensure that all variable, function and parameter names follow the mixedCase naming convention | Understandability |
camelcase | Ensure that contract, library, modifier and struct names follow CamelCase notation | Understandability |
uppercase | Ensure that all constants (and only constants) contain only upper case letters and underscore | Understandability |
no-empty-blocks | Ensure that no empty blocks {} exist | Understandability |
no-unused-vars | Flag all the variables that were declared but never used | Understandability |
quotes | Ensure that all strings use only 1 style – either double quotes or single quotes | style |
blank-lines | Ensure that there is exactly a 2-line gap between Contract and Funtion declarations | style |
indentation | Ensure consistent indentation of 4 spaces per level | style |
arg-overflow | In the case of 4+ elements in the same line require they are instead put on a single line each | style |
whitespace | Specify where whitespace is suitable and where it is not | stylfy |
function-order | Ensure order of functions in a contract: constructor, fallback, external, public, internal, private | Understandability |
emit | Ensure that emit statement is used to trigger a solidity event | style |
value-in-payable | Ensure “msg.value” is only used in functions with the “payable” modifier | Accuracy |
max-len | Ensure that a line of code does not exceed the specified number of characters | style |
error-reason | Ensure that error message is provided for revert and require statements | Understandability |
visibility-first | Ensure that the visibility modifier for a function should come before any custom modifiers | Understandability |
linebreak-style | Ensure consistent linebreak style | style |
Ruby
The section below covers the Brakeman code checker issues.
Brakeman Code Issues
Brakeman is a static code analyzer that helps to detect vulnerability security code issues for Ruby language. Visit their website for more detailed information on Brakeman and the ruleset found below.
Brakeman critical level issues
Rules | Description | Example | KPI | config__rules__severity |
---|---|---|---|---|
Command Injection | Command injection occurs when shell commands unsafely include user-manipulatable values. | Security | critical | |
Cross-Site Request Forgery | CSRF allows an attacker to perform actions on a website as if they are an authenticated user. | Security | critical | |
Cross Site Scripting | XSS occurs when a user-manipulatable value is displayed on a web page without escaping it, allowing someone to inject Javascript or HTML into the page. | Security | critical | |
Cross Site Scripting (Content Tag) | Content Tag is a view helper which generates an HTML tag with some content | Security | critical | |
Cross Site Scripting (JSON) | XSS occurs when a user-manipulatable value is displayed on a web page without escaping it, allowing someone to inject Javascript or HTML into the page. | Security | critical | |
Dangerous Evaluation | User input in an eval statement is VERY dangerous | Security | critical | |
Dangerous Send | Using unfiltered user data to select a Class or Method to be dynamically sent is dangerous. | Security | critical | |
Denial of Service | Denial of Service (DoS) is any attack which causes a service to become unavailable for legitimate clients. | Security | critical | |
Divide By Zero | Finds potential division by zero with integers. Dividing a float by zero or 0.0 in Ruby results in Infinity, not an exception. | Security | critical | |
Dynamic Render Paths | When a call to render uses a dynamically generated path, template name, file name, or action, there is the possibility that a user can access templates that should be restricted. The issue may be worse if those templates execute code or modify the database. | Security | critical | |
File Access | Vulnerability can be used to access arbitrary files on a server (including /etc/passwd. | Security | critical | |
Information Disclosure | Vulnerability refers to system or internal information (such as debugging output, stack traces, error messages, etc.) | Security | critical | |
Remote Code Execution | Uses of send, constantize, and other methods which allow creation of arbitrary objects or calling of arbitrary methods. | Security | critical | |
SQL Injection | SQL injection is when a user is able to manipulate a value which is used unsafely inside a SQL query. This can lead to data leaks, data loss, elevation of privilege, and other unpleasant outcomes. | Security | critical | |
SSL Verification Bypass | These attacks rely on the client to establish a connection that doesn’t check the validity of the SSL certificate presented by the server. | Security | critical | |
Unsafe Deserialization | The YAML, JSON, and CSV libraries also have methods for dumping Ruby objects into strings, and then creating objects from those strings. | Security | critical | |
Unsafe Redirects | User-supplied values can be used to “spoof†websites or hide malicious links in otherwise harmless-looking URLs. They can also allow access to restricted areas of a site if the destination is not validated. | Security | critical |
Brakeman high level issues
Rules | Description | Example | KPI | |
---|---|---|---|---|
Authentication | Warn about constants with literal string values that appear to be passwords. | Security | high | |
Basic Authentication | Warning will be raised if http_basic_authenticate_with is used and the password is found to be a string (i.e., stored somewhere in the code). | Security | high | |
Mass Assignment | Allows an application to create a record from the values of a hash. | Security | high | |
Remote Execution in YAML.load | Upgrading Rails, disabling XML parsing, or disabling YAML types in XML request parsing will fix the Rails vulnerability, manually passing user input to YAML.load remains unsafe. | Security | high | |
Session Manipulation | Sessions are typically considered a source of truth (e.g. to check the logged-in user or to match CSRF tokens), allowing an attacker to manipulate the session may lead to unintended behavior. | Security | high | |
Session Settings | If the key length for the session cookies is less than 30 characters. | Security | high | |
Weak Hash | uses of hashing algorithms that should not be used for security-sensitive contexts such as hashing passwords or generating signatures. | Security | high | |
UUIDs as Safe Attributes | #uuid will be treated as a safe value, particular in SQL. | Security | high | |
Tempfile Paths in Shell Commands | Tempfile#path will be considered as safe value for command injection. | Security | high | |
Ignore Development Environment | Brakeman will ignore code that is guarded | Security | high | |
Collapse __send__ Calls | Collapse __send__ Calls | Security | high | |
Redirect | Unvalidated redirects and forwards | Security | high |
Brakeman medium level issues
Rules | Description | Example | KPI | |
---|---|---|---|---|
Attribute Restriction | Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been permitted. | Security | medium | |
HTTP Verb Confusion | Brakeman will warn when an 'if' expression checks request.get? but has an else clause instead of elseif ..... | Security | medium |
Brakeman low level issues
Rules | Description | Example | KPI | |
---|---|---|---|---|
Default Routes | Route to that controller containing :action. | Security | low | |
Format Validation | Calls to validates_format_of ..., :with => // which do not use \A and \z as anchors will cause this warning | Security | low | |
Mail Link | Vulnerable to a cross-site scripting vulnerability mail_to. | Security | low | |
Unscoped Find | Models which belong to another model should typically be accessed via a scoped query. | Security | low |
Apex
The section below covers the Apex PMD code checker issues.
Critical level issues
rule | Description | url | kpi | example |
---|---|---|---|---|
ApexCSRF | Having DML operations in Apex class constructor or initializers can have unexpected side effects:_x000D_ By just accessing a page, the DML statements would be executed and the database would be modified._x000D_ Just querying the database is permitted._x000D_ _x000D_ In addition to constructors and initializers, any method called `init` is checked as well._x000D_ _x000D_ Salesforce Apex already protects against this scenario and raises a runtime exception._x000D_ _x000D_ Note: This rule has been moved from category "Security" to "Error Prone" with PMD 6.21.0, since_x000D_ using DML in constructors is not a security problem, but crashes the application. | https://pmd.github.io/latest/pmd_rules_apex_errorprone.html#apexcsrf | Maintainability | |
ApexBadCrypto | The rule makes sure you are using randomly generated IVs and keys for `Crypto` calls._x000D_ Hard-wiring these values greatly compromises the security of encrypted data. | https://pmd.github.io/latest/pmd_rules_apex_security.html#apexbadcrypto | Maintainability | |
ApexCRUDViolation | The rule validates you are checking for access permissions before a SOQL/SOSL/DML operation._x000D_ Since Apex runs in system mode not having proper permissions checks results in escalation of_x000D_ privilege and may produce runtime errors. This check forces you to handle such scenarios._x000D_ _x000D_ Note: This rule will produce false positives for VF getter methods. In VF getters the access permission_x000D_ check happens automatically and is not needed explicitly. However, the rule can't reliably determine_x000D_ whether a getter is a VF getter or not and reports a violation in any case. In such cases, the violation_x000D_ should be [suppressed](pmd_userdocs_suppressing_warnings.html). | https://pmd.github.io/latest/pmd_rules_apex_security.html#apexcrudviolation | Maintainability | |
ApexDangerousMethods | Checks against calling dangerous methods._x000D_ _x000D_ For the time being, it reports:_x000D_ _x000D_ * Against `FinancialForce`'s `Configuration.disableTriggerCRUDSecurity()`. Disabling CRUD security_x000D_ opens the door to several attacks and requires manual validation, which is unreliable._x000D_ * Calling `System.debug` passing sensitive data as parameter, which could lead to exposure_x000D_ of private data. | https://pmd.github.io/latest/pmd_rules_apex_security.html#apexdangerousmethods | Maintainability | |
ApexInsecureEndpoint | Checks against accessing endpoints under plain **http**. You should always use_x000D_ **https** for security. | https://pmd.github.io/latest/pmd_rules_apex_security.html#apexinsecureendpoint | Maintainability | |
ApexOpenRedirect | Checks against redirects to user-controlled locations. This prevents attackers from_x000D_ redirecting users to phishing sites. | https://pmd.github.io/latest/pmd_rules_apex_security.html#apexopenredirect | Maintainability | |
ApexSOQLInjection | Detects the usage of untrusted / unescaped variables in DML queries. | https://pmd.github.io/latest/pmd_rules_apex_security.html#apexsoqlinjection | Maintainability | |
ApexSuggestUsingNamedCred | Detects hardcoded credentials used in requests to an endpoint._x000D_ _x000D_ You should refrain from hardcoding credentials:_x000D_ * They are hard to mantain by being mixed in application code_x000D_ * Particularly hard to update them when used from different classes_x000D_ * Granting a developer access to the codebase means granting knowledge_x000D_ of credentials, keeping a two-level access is not possible._x000D_ * Using different credentials for different environments is troublesome_x000D_ and error-prone._x000D_ _x000D_ Instead, you should use *Named Credentials* and a callout endpoint._x000D_ _x000D_ For more information, you can check [this](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_named_credentials.htm) | https://pmd.github.io/latest/pmd_rules_apex_security.html#apexsuggestusingnamedcred | Maintainability | |
ApexXSSFromEscapeFalse | Reports on calls to `addError` with disabled escaping. The message passed to `addError`_x000D_ will be displayed directly to the user in the UI, making it prime ground for XSS_x000D_ attacks if unescaped. | https://pmd.github.io/latest/pmd_rules_apex_security.html#apexxssfromescapefalse | Maintainability | |
ApexXSSFromURLParam | Makes sure that all values obtained from URL parameters are properly escaped / sanitized_x000D_ to avoid XSS attacks. | https://pmd.github.io/latest/pmd_rules_apex_security.html#apexxssfromurlparam | Maintainability |
High level issues
rule | Description | url | kpi | example |
---|---|---|---|---|
CyclomaticComplexity | The complexity of methods directly affects maintenance costs and readability. Concentrating too much decisional logic_x000D_ in a single method makes its behaviour hard to read and change._x000D_ _x000D_ Cyclomatic complexity assesses the complexity of a method by counting the number of decision points in a method,_x000D_ plus one for the method entry. Decision points are places where the control flow jumps to another place in the_x000D_ program. As such, they include all control flow statements, such as 'if', 'while', 'for', and 'case'._x000D_ _x000D_ Generally, numbers ranging from 1-4 denote low complexity, 5-7 denote moderate complexity, 8-10 denote_x000D_ high complexity, and 11+ is very high complexity. By default, this rule reports methods with a complexity >= 10._x000D_ Additionally, classes with many methods of moderate complexity get reported as well once the total of their_x000D_ methods' complexities reaches 40, even if none of the methods was directly reported._x000D_ _x000D_ Reported methods should be broken down into several smaller methods. Reported classes should probably be broken down_x000D_ into subcomponents. | https://pmd.github.io/latest/pmd_rules_apex_design.html#cyclomaticcomplexity | Maintainability | public class Complicated { public void example() { // This method has a cyclomatic complexity of 12 int x = 0, y = 1, z = 2, t = 2; boolean a = false, b = true, c = false, d = true; if (a && b || b && d) { if (y == z) { x = 2; } else if (y == t && !d) { x = 2; } else { x = 2; } } else if (c && d) { while (z < y) { x = 2; } } else { for (int n = 0; n < t; n++) { x = 2; } } } } |
CognitiveComplexity | Methods that are highly complex are difficult to read and more costly to maintain. If you include too much decisional logic within a single method, you make its behavior hard to understand and more difficult to modify. Cognitive complexity is a measure of how difficult it is for humans to read and understand a method. Code that contains a break in the control flow is more complex, whereas the use of language shorthands doesn't increase the level of complexity. Nested control flows can make a method more difficult to understand, with each additional nesting of the control flow leading to an increase in cognitive complexity. Information about Cognitive complexity can be found in the original paper here: https://www.sonarsource.com/docs/CognitiveComplexity.pdf By default, this rule reports methods with a complexity of 15 or more. Reported methods should be broken down into less complex components. | https://pmd.github.io/latest/pmd_rules_apex_design.html#cognitivecomplexity | Maintainability | public class Foo { // Has a cognitive complexity of 0 public void createAccount() { Account account = new Account(Name = 'PMD'); insert account; } // Has a cognitive complexity of 1 public Boolean setPhoneNumberIfNotExisting(Account a, String phone) { if (a.Phone == null) { // +1 a.Phone = phone; update a; return true; } return false; } // Has a cognitive complexity of 5 public void updateContacts(List List for (Contact contact : contacts) { // +1 if (contact.Department == 'Finance') { // +2 contact.Title = 'Finance Specialist'; contactsToUpdate.add(contact); } else if (contact.Department == 'Sales') { // +2 contact.Title = 'Sales Specialist'; contactsToUpdate.add(contact); } } update contactsToUpdate; } } |
StdCyclomaticComplexity | Complexity directly affects maintenance costs is determined by the number of decision points in a method_x000D_ plus one for the method entry. The decision points include 'if', 'while', 'for', and 'case labels' calls._x000D_ Generally, numbers ranging from 1-4 denote low complexity, 5-7 denote moderate complexity, 8-10 denote_x000D_ high complexity, and 11+ is very high complexity. | https://pmd.github.io/latest/pmd_rules_apex_design.html#stdcyclomaticcomplexity | Maintainability | _x000D_ // This has a Cyclomatic Complexity = 12_x000D_ public class Foo {_x000D_ 1 public void example() {_x000D_ 2 if (a == b || (c == d && e == f)) {_x000D_ 3 if (a1 == b1) {_x000D_ fiddle();_x000D_ 4 } else if a2 == b2) {_x000D_ fiddle();_x000D_ } else {_x000D_ fiddle();_x000D_ }_x000D_ 5 } else if (c == d) {_x000D_ 6 while (c == d) {_x000D_ fiddle();_x000D_ }_x000D_ 7 } else if (e == f) {_x000D_ 8 for (int n = 0; n < h; n++) {_x000D_ fiddle();_x000D_ }_x000D_ } else {_x000D_ switch (z) {_x000D_ 9 case 1:_x000D_ fiddle();_x000D_ break;_x000D_ 10 case 2:_x000D_ fiddle();_x000D_ break;_x000D_ 11 case 3:_x000D_ fiddle();_x000D_ break;_x000D_ 12 default:_x000D_ fiddle();_x000D_ break;_x000D_ }_x000D_ }_x000D_ }_x000D_ |
AvoidHardcodingId | When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail. | https://pmd.github.io/latest/pmd_rules_apex_errorprone.html#avoidhardcodingid | Maintainability | |
EmptyTryOrFinallyBlock | Avoid empty try or finally blocks - what's the point? | https://pmd.github.io/latest/pmd_rules_apex_errorprone.html#emptytryorfinallyblock | Maintainability | |
OverrideBothEqualsAndHashcode | Override both `public Boolean equals(Object obj)`, and `public Integer hashCode()`, or override neither._x000D_ Even if you are inheriting a hashCode() from a parent class, consider implementing hashCode and explicitly_x000D_ delegating to your superclass._x000D_ _x000D_ This is especially important when [Using Custom Types in Map Keys and Sets](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_maps_keys_userdefined.htm). | https://pmd.github.io/latest/pmd_rules_apex_errorprone.html#overridebothequalsandhashcode | Maintainability | |
OperationWithLimitsInLoop | Database class methods, DML operations, SOQL queries, or SOSL queries within loops can cause governor limit exceptions. Instead, try to batch up the data into a list and invoke the operation once on that list of data outside the loop. | https://pmd.github.io/latest/pmd_rules_apex_performance.html#operationwithlimitsinloop | Maintainability | _x000D_ public class Something {_x000D_ public void databaseMethodInsideOfLoop(List for (Account a : accounts) {_x000D_ Database.insert(a);_x000D_ }_x000D_ }_x000D_ public void dmlInsideOfLoop() {_x000D_ for (Integer i = 0; i < 151; i++) {_x000D_ Account account;_x000D_ // ..._x000D_ insert account;_x000D_ }_x000D_ }_x000D_ public void soqlInsideOfLoop() {_x000D_ for (Integer i = 0; i < 10; i++) {_x000D_ List }_x000D_ }_x000D_ public void soslInsideOfLoop() {_x000D_ for (Integer i = 0; i < 10; i++) {_x000D_ List
}_x000D_ }_x000D_ }_x000D_ |
ApexSharingViolations | Detect classes declared without explicit sharing mode if DML methods are used. This_x000D_ forces the developer to take access restrictions into account before modifying objects. | https://pmd.github.io/latest/pmd_rules_apex_security.html#apexsharingviolations | Maintainability |
Medium level issues
rule | Description | url | kpi | example |
---|---|---|---|---|
ApexUnitTestClassShouldHaveAsserts | Apex unit tests should System.assert() or assertEquals() or assertNotEquals() | https://pmd.github.io/latest/pmd_rules_apex_bestpractices.html#apexunittestclassshouldhaveasserts | Maintainability | |
ApexUnitTestMethodShouldHaveIsTestAnnotation | Apex test methods should have @isTest annotation. | https://pmd.github.io/latest/pmd_rules_apex_bestpractices.html#apexunittestmethodshouldhaveistestannotation | Maintainability | |
ApexUnitTestShouldNotUseSeeAllDataTrue | Apex unit tests should not use @isTest(seeAllData = true) | https://pmd.github.io/latest/pmd_rules_apex_bestpractices.html#apexunittestshouldnotuseseealldatatrue | Maintainability | |
AvoidGlobalModifier | Avoid using global modifier | https://pmd.github.io/latest/pmd_rules_apex_bestpractices.html#avoidglobalmodifier | Maintainability | |
AvoidLogicInTrigger | Avoid logic in triggers | https://pmd.github.io/latest/pmd_rules_apex_bestpractices.html#avoidlogicintrigger | Maintainability | |
DebugsShouldUseLoggingLevel | Calls to System.debug should specify a logging level. | https://pmd.github.io/latest/pmd_rules_apex_bestpractices.html#debugsshoulduselogginglevel | Maintainability | |
UnusedLocalVariable | Variable ''{0}'' defined but not used | https://pmd.github.io/latest/pmd_rules_apex_bestpractices.html#unusedlocalvariable | Maintainability | |
AvoidDeeplyNestedIfStmts | Avoid creating deeply nested if-then statements since they are harder to read and error-prone to maintain. | https://pmd.github.io/latest/pmd_rules_apex_design.html#avoiddeeplynestedifstmts | Maintainability | _x000D_ public class Foo {_x000D_ public void bar(Integer x, Integer y, Integer z) {_x000D_ if (x>y) {_x000D_ if (y>z) {_x000D_ if (z==x) {_x000D_ // !! too deep_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ |
AvoidDirectAccessTriggerMap | Avoid directly accessing Trigger.old and Trigger.new as it can lead to a bug. Triggers should be bulkified and iterate through the map to handle the actions for each item separately. | https://pmd.github.io/latest/pmd_rules_apex_errorprone.html#avoiddirectaccesstriggermap | Maintainability | |
AvoidNonExistentAnnotations | Apex supported non existent annotations for legacy reasons._x000D_ In the future, use of such non-existent annotations could result in broken apex code that will not compile._x000D_ This will prevent users of garbage annotations from being able to use legitimate annotations added to Apex in the future._x000D_ A full list of supported annotations can be found at https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation.htm | https://pmd.github.io/latest/pmd_rules_apex_errorprone.html#avoidnonexistentannotations | Maintainability | |
EmptyCatchBlock | Empty Catch Block finds instances where an exception is caught, but nothing is done._x000D_ In most circumstances, this swallows an exception which should either be acted on_x000D_ or reported. | https://pmd.github.io/latest/pmd_rules_apex_errorprone.html#emptycatchblock | Maintainability | |
EmptyIfStmt | Empty If Statement finds instances where a condition is checked but nothing is done about it. | https://pmd.github.io/latest/pmd_rules_apex_errorprone.html#emptyifstmt | Maintainability | |
EmptyStatementBlock | Empty block statements serve no purpose and should be removed. | https://pmd.github.io/latest/pmd_rules_apex_errorprone.html#emptystatementblock | Maintainability | |
EmptyWhileStmt | Empty While Statement finds all instances where a while statement does nothing._x000D_ If it is a timing loop, then you should use Thread.sleep() for it; if it is_x000D_ a while loop that does a lot in the exit expression, rewrite it to make it clearer. | https://pmd.github.io/latest/pmd_rules_apex_errorprone.html#emptywhilestmt | Maintainability | |
MethodWithSameNameAsEnclosingClass | Non-constructor methods should not have the same name as the enclosing class. | https://pmd.github.io/latest/pmd_rules_apex_errorprone.html#methodwithsamenameasenclosingclass | Maintainability | |
TestMethodsMustBeInTestClasses | Test methods marked as a testMethod or annotated with @IsTest,_x000D_ but not residing in a test class should be moved to a proper_x000D_ class or have the @IsTest annotation added to the class._x000D_ _x000D_ Support for tests inside functional classes was removed in Spring-13 (API Version 27.0),_x000D_ making classes that violate this rule fail compile-time. This rule is mostly usable when_x000D_ dealing with legacy code. | https://pmd.github.io/latest/pmd_rules_apex_errorprone.html#testmethodsmustbeintestclasses | Maintainability |
Low level issues
rule | Description | url | kpi | example |
---|---|---|---|---|
ApexAssertionsShouldIncludeMessage | Apex test assert statement should make use of the message parameter. | https://pmd.github.io/latest/pmd_rules_apex_bestpractices.html#apexassertionsshouldincludemessage | Maintainability | |
ClassNamingConventions | Configurable naming conventions for type declarations. This rule reports_x000D_ type declarations which do not match the regex that applies to their_x000D_ specific kind (e.g. enum or interface). Each regex can be configured through_x000D_ properties._x000D_ _x000D_ By default this rule uses the standard Apex naming convention (Pascal case). | https://pmd.github.io/latest/pmd_rules_apex_codestyle.html#classnamingconventions | Maintainability | _x000D_ public class FooClass { } // This is in pascal case, so it's ok_x000D_ public class fooClass { } // This will be reported unless you change the regex_x000D_ |
IfElseStmtsMustUseBraces | Avoid using if..else statements without using surrounding braces. If the code formatting_x000D_ or indentation is lost then it becomes difficult to separate the code being controlled_x000D_ from the rest. | https://pmd.github.io/latest/pmd_rules_apex_codestyle.html#ifelsestmtsmustusebraces | Maintainability | _x000D_ // this is OK_x000D_ if (foo) x++;_x000D_ // but this is not_x000D_ if (foo)_x000D_ x = x+1;_x000D_ else_x000D_ x = x-1;_x000D_ |
IfStmtsMustUseBraces | Avoid using if statements without using braces to surround the code block. If the code_x000D_ formatting or indentation is lost then it becomes difficult to separate the code being_x000D_ controlled from the rest. | https://pmd.github.io/latest/pmd_rules_apex_codestyle.html#ifstmtsmustusebraces | Maintainability | _x000D_ if (foo) // not recommended_x000D_ x++;_x000D_ if (foo) { // preferred approach_x000D_ x++;_x000D_ }_x000D_ |
FieldNamingConventions | Configurable naming conventions for field declarations. This rule reports variable declarations_x000D_ which do not match the regex that applies to their specific kind ---e.g. constants (static final),_x000D_ static field, final field. Each regex can be configured through properties._x000D_ _x000D_ By default this rule uses the standard Apex naming convention (Camel case). | https://pmd.github.io/latest/pmd_rules_apex_codestyle.html#fieldnamingconventions | Maintainability | _x000D_ public class Foo {_x000D_ Integer instanceField; // This is in camel case, so it's ok_x000D_ Integer INSTANCE_FIELD; // This will be reported unless you change the regex_x000D_ }_x000D_ |
ForLoopsMustUseBraces | Avoid using 'for' statements without using surrounding braces. If the code formatting or_x000D_ indentation is lost then it becomes difficult to separate the code being controlled_x000D_ from the rest. | https://pmd.github.io/latest/pmd_rules_apex_codestyle.html#forloopsmustusebraces | Maintainability | _x000D_ for (int i = 0; i < 42; i++) // not recommended_x000D_ foo();_x000D_ for (int i = 0; i < 42; i++) { // preferred approach_x000D_ foo();_x000D_ }_x000D_ |
FormalParameterNamingConventions | Configurable naming conventions for formal parameters of methods._x000D_ This rule reports formal parameters which do not match the regex that applies to their_x000D_ specific kind (e.g. method parameter, or final method parameter). Each regex can be_x000D_ configured through properties._x000D_ _x000D_ By default this rule uses the standard Apex naming convention (Camel case). | https://pmd.github.io/latest/pmd_rules_apex_codestyle.html#formalparameternamingconventions | Maintainability | _x000D_ public class Foo {_x000D_ public bar(Integer methodParameter) { } // This is in camel case, so it's ok_x000D_ public baz(Integer METHOD_PARAMETER) { } // This will be reported unless you change the regex_x000D_ }_x000D_ |
MethodNamingConventions | Configurable naming conventions for method declarations. This rule reports_x000D_ method declarations which do not match the regex that applies to their_x000D_ specific kind (e.g. static method, or test method). Each regex can be_x000D_ configured through properties._x000D_ _x000D_ By default this rule uses the standard Apex naming convention (Camel case). | https://pmd.github.io/latest/pmd_rules_apex_codestyle.html#methodnamingconventions | Maintainability | _x000D_ public class Foo {_x000D_ public void instanceMethod() { } // This is in camel case, so it's ok_x000D_ public void INSTANCE_METHOD() { } // This will be reported unless you change the regex_x000D_ |
OneDeclarationPerLine | Apex allows the use of several variables declaration of the same type on one line. However, it_x000D_ can lead to quite messy code. This rule looks for several declarations on the same line. | https://pmd.github.io/latest/pmd_rules_apex_codestyle.html#onedeclarationperline | Maintainability | _x000D_ Integer a, b; // not recommended_x000D_ Integer a,_x000D_ b; // ok by default, can be flagged setting the strictMode property_x000D_ Integer a; // preferred approach_x000D_ Integer b;_x000D_ |
PropertyNamingConventions | Configurable naming conventions for property declarations. This rule reports_x000D_ property declarations which do not match the regex that applies to their_x000D_ specific kind (e.g. static property, or instance property). Each regex can be_x000D_ configured through properties._x000D_ _x000D_ By default this rule uses the standard Apex naming convention (Camel case). | https://pmd.github.io/latest/pmd_rules_apex_codestyle.html#propertynamingconventions | Maintainability | _x000D_ public class Foo {_x000D_ public Integer instanceProperty { get; set; } // This is in camel case, so it's ok_x000D_ public Integer INSTANCE_PROPERTY { get; set; } // This will be reported unless you change the regex_x000D_ }_x000D_ |
WhileLoopsMustUseBraces | Avoid using 'while' statements without using braces to surround the code block. If the code_x000D_ formatting or indentation is lost then it becomes difficult to separate the code being_x000D_ controlled from the rest. | https://pmd.github.io/latest/pmd_rules_apex_codestyle.html#whileloopsmustusebraces | Maintainability | _x000D_ while (true) // not recommended_x000D_ x++;_x000D_ while (true) { // preferred approach_x000D_ x++;_x000D_ }_x000D_ |
ApexDoc | This rule validates that:_x000D_ _x000D_ * ApexDoc comments are present for classes, methods, and properties that are public or global, excluding_x000D_ overrides and test classes (as well as the contents of test classes)._x000D_ * ApexDoc comments are present for classes, methods, and properties that are protected or private, depending_x000D_ on the properties `reportPrivate` and `reportProtected`._x000D_ * ApexDoc comments should contain @description._x000D_ * ApexDoc comments on non-void, non-constructor methods should contain @return._x000D_ * ApexDoc comments on void or constructor methods should not contain @return._x000D_ * ApexDoc comments on methods with parameters should contain @param for each parameter, in the same_x000D_ order as the method signature._x000D_ _x000D_ Method overrides and tests are both exempted from having ApexDoc. | https://pmd.github.io/latest/pmd_rules_apex_documentation.html#apexdoc | Maintainability | /** * @description Hello World */ public class HelloWorld { /** * @description Bar * @return Bar */ public Object bar() { return null; } } |
Apex PMD info level issues
rule | Description | example | kpi |
---|---|---|---|
LocalVariableNamingConventions | Configurable naming conventions for local variable declarations._x000D_ This rule reports variable declarations which do not match the regex that applies to their_x000D_ specific kind (e.g. local variable, or final local variable). Each regex can be configured through_x000D_ properties._x000D_ _x000D_ By default this rule uses the standard Apex naming convention (Camel case). | _x000D_ public class Foo {_x000D_ public Foo() {_x000D_ Integer localVariable; // This is in camel case, so it's ok_x000D_ Integer LOCAL_VARIABLE; // This will be reported unless you change the regex_x000D_ }_x000D_ }_x000D_ | Maintainability |