Showing 392 of 393 total issues
Method convertCarriage
has a Cognitive Complexity of 18 (exceeds 15 allowed). Consider refactoring. Open
private static NmbsTrainType convertCarriage(String parentType, String subType, String orientation, int firstClassSeats, int position) {
String newParentType = parentType;
String newSubType = subType;
String newOrientation = orientation;
switch (parentType) {
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Consider simplifying this complex logical expression. Open
if ((stop.isDepartureCanceled() && position == 0) || (stop.isDepartureCanceled() && stop.isArrivalCanceled()) || (stop.isArrivalCanceled() && position == train.getStops().length - 1)) {
vPlatform.setText("");
vPlatformContainer.setBackground(ContextCompat.getDrawable(context, R.drawable.platform_train_canceled));
vStatusText.setText(R.string.status_cancelled);
vStatusContainer.setVisibility(View.VISIBLE);
Consider simplifying this complex logical expression. Open
if (mInfiniteNextScrolling // Check if enabled
&& !mIsLoadingNext // Only when we're not loading already
&& !mLoadNextError // Only when "tap to retry" isn't enabled
&& mInfiniteScrollingDataSource != null // Only when we have a data source linked
&& dy >= 0 // Only when scrolling downwards
Avoid too many return
statements within this method. Open
return VIEW_TYPE_LOADING;
Avoid too many return
statements within this method. Open
return super.onOptionsItemSelected(item);
Avoid too many return
statements within this method. Open
return results;
This block of commented-out lines of code should be removed. Open
{
- Read upRead up
- Exclude checks
Programmers should not comment out code as it bloats programs and reduces readability.
Unused code should be deleted and can be retrieved from source control history if required.
Remove this "String" constructor Open
cache = new JSONObject(new String(requestQueue.getCache().get(jsObjRequest.getCacheKey()).data));
- Read upRead up
- Exclude checks
Constructors for String
, BigInteger
, BigDecimal
and the objects used to wrap primitives should never be
used. Doing so is less clear and uses more memory than simply using the desired value in the case of strings, and using valueOf
for
everything else.
Noncompliant Code Example
String empty = new String(); // Noncompliant; yields essentially "", so just use that. String nonempty = new String("Hello world"); // Noncompliant Double myDouble = new Double(1.1); // Noncompliant; use valueOf Integer integer = new Integer(1); // Noncompliant Boolean bool = new Boolean(true); // Noncompliant BigInteger bigInteger1 = new BigInteger("3"); // Noncompliant BigInteger bigInteger2 = new BigInteger("9223372036854775807"); // Noncompliant BigInteger bigInteger3 = new BigInteger("111222333444555666777888999"); // Compliant, greater than Long.MAX_VALUE
Compliant Solution
String empty = ""; String nonempty = "Hello world"; Double myDouble = Double.valueOf(1.1); Integer integer = Integer.valueOf(1); Boolean bool = Boolean.valueOf(true); BigInteger bigInteger1 = BigInteger.valueOf(3); BigInteger bigInteger2 = BigInteger.valueOf(9223372036854775807L); BigInteger bigInteger3 = new BigInteger("111222333444555666777888999");
Exceptions
BigDecimal
constructor with double
argument is ignored as using valueOf
instead might change resulting
value. See {rule:java:S2111} .
Remove this unused private "isInternetAvailable" method. Open
private boolean isInternetAvailable() {
- Read upRead up
- Exclude checks
private
methods that are never executed are dead code: unnecessary, inoperative code that should be removed. Cleaning out dead code
decreases the size of the maintained codebase, making it easier to understand the program and preventing bugs from being introduced.
Note that this rule does not take reflection into account, which means that issues will be raised on private
methods that are only
accessed using the reflection API.
Noncompliant Code Example
public class Foo implements Serializable { private Foo(){} //Compliant, private empty constructor intentionally used to prevent any direct instantiation of a class. public static void doSomething(){ Foo foo = new Foo(); ... } private void unusedPrivateMethod(){...} private void writeObject(ObjectOutputStream s){...} //Compliant, relates to the java serialization mechanism private void readObject(ObjectInputStream in){...} //Compliant, relates to the java serialization mechanism }
Compliant Solution
public class Foo implements Serializable { private Foo(){} //Compliant, private empty constructor intentionally used to prevent any direct instantiation of a class. public static void doSomething(){ Foo foo = new Foo(); ... } private void writeObject(ObjectOutputStream s){...} //Compliant, relates to the java serialization mechanism private void readObject(ObjectInputStream in){...} //Compliant, relates to the java serialization mechanism }
Exceptions
This rule doesn't raise any issue on annotated methods.
This block of commented-out lines of code should be removed. Open
// Log::info("[{connection->getId()}] Updating S: New: Reach destination from departureStop departing at {quad[self::KEY_DEPARTURE_TIME]} arriving at {quad[self::KEY_ARRIVAL_TIME]}");
- Read upRead up
- Exclude checks
Programmers should not comment out code as it bloats programs and reduces readability.
Unused code should be deleted and can be retrieved from source control history if required.
A "NullPointerException" could be thrown; "lastConnection" is nullable here. Open
arrival = mStationProvider.getStoplocationBySemanticId(lastConnection.getArrivalStationUri());
- Read upRead up
- Exclude checks
A reference to null
should never be dereferenced/accessed. Doing so will cause a NullPointerException
to be thrown. At
best, such an exception will cause abrupt program termination. At worst, it could expose debugging information that would be useful to an attacker, or
it could allow an attacker to bypass security measures.
Note that when they are present, this rule takes advantage of @CheckForNull
and @Nonnull
annotations defined in JSR-305 to understand which values are and are not nullable except when @Nonnull
is used
on the parameter to equals
, which by contract should always work with null.
Noncompliant Code Example
@CheckForNull String getName(){...} public boolean isNameEmpty() { return getName().length() == 0; // Noncompliant; the result of getName() could be null, but isn't null-checked }
Connection conn = null; Statement stmt = null; try{ conn = DriverManager.getConnection(DB_URL,USER,PASS); stmt = conn.createStatement(); // ... }catch(Exception e){ e.printStackTrace(); }finally{ stmt.close(); // Noncompliant; stmt could be null if an exception was thrown in the try{} block conn.close(); // Noncompliant; conn could be null if an exception was thrown }
private void merge(@Nonnull Color firstColor, @Nonnull Color secondColor){...} public void append(@CheckForNull Color color) { merge(currentColor, color); // Noncompliant; color should be null-checked because merge(...) doesn't accept nullable parameters }
void paint(Color color) { if(color == null) { System.out.println("Unable to apply color " + color.toString()); // Noncompliant; NullPointerException will be thrown return; } ... }
See
- MITRE, CWE-476 - NULL Pointer Dereference
- CERT, EXP34-C. - Do not dereference null pointers
- CERT, EXP01-J. - Do not use a null in a case where an object is required
Define a constant instead of duplicating this literal "LCProvider" 8 times. Open
Log.i("LCProvider", "Loading " + url);
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
public void run() { prepare("action1"); // Noncompliant - "action1" is duplicated 3 times execute("action1"); release("action1"); } @SuppressWarning("all") // Compliant - annotations are excluded private void method1() { /* ... */ } @SuppressWarning("all") private void method2() { /* ... */ } public String method3(String a) { System.out.println("'" + a + "'"); // Compliant - literal "'" has less than 5 characters and is excluded return ""; // Compliant - literal "" has less than 5 characters and is excluded }
Compliant Solution
private static final String ACTION_1 = "action1"; // Compliant public void run() { prepare(ACTION_1); // Compliant execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Provide the parametrized type for this generic. Open
public static OpenTransportLog getLogger(Class c) {
- Read upRead up
- Exclude checks
Generic types shouldn't be used raw (without type parameters) in variable declarations or return values. Doing so bypasses generic type checking, and defers the catch of unsafe code to runtime.
Noncompliant Code Example
List myList; // Noncompliant Set mySet; // Noncompliant
Compliant Solution
List<String> myList; Set<? extends Number> mySet;
Define a constant instead of duplicating this literal "departureDelay" 3 times. Open
departureDelay = json.getInt("departureDelay");
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
public void run() { prepare("action1"); // Noncompliant - "action1" is duplicated 3 times execute("action1"); release("action1"); } @SuppressWarning("all") // Compliant - annotations are excluded private void method1() { /* ... */ } @SuppressWarning("all") private void method2() { /* ... */ } public String method3(String a) { System.out.println("'" + a + "'"); // Compliant - literal "'" has less than 5 characters and is excluded return ""; // Compliant - literal "" has less than 5 characters and is excluded }
Compliant Solution
private static final String ACTION_1 = "action1"; // Compliant public void run() { prepare(ACTION_1); // Compliant execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation. Open
public void abortQueries(RequestType type) {
- Read upRead up
- Exclude checks
There are several reasons for a method not to have a method body:
- It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.
- It is not yet, or never will be, supported. In this case an
UnsupportedOperationException
should be thrown. - The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.
Noncompliant Code Example
public void doSomething() { } public void doSomethingElse() { }
Compliant Solution
@Override public void doSomething() { // Do nothing because of X and Y. } @Override public void doSomethingElse() { throw new UnsupportedOperationException(); }
Exceptions
Default (no-argument) constructors are ignored when there are other constructors in the class, as are empty methods in abstract classes.
public abstract class Animal { void speak() { // default implementation ignored } }
Remove this useless assignment to local variable "jsObjRequest". Open
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, successListener, errorListener) {
@Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
- Read upRead up
- Exclude checks
A dead store happens when a local variable is assigned a value that is not read by any subsequent instruction. Calculating or retrieving a value only to then overwrite it or throw it away, could indicate a serious error in the code. Even if it's not an error, it is at best a waste of resources. Therefore all calculated values should be used.
Noncompliant Code Example
i = a + b; // Noncompliant; calculation result not used before value is overwritten i = compute();
Compliant Solution
i = a + b; i += compute();
Exceptions
This rule ignores initializations to -1, 0, 1, null
, true
, false
and ""
.
See
- MITRE, CWE-563 - Assignment to Variable without Use ('Unused Variable')
- CERT, MSC13-C. - Detect and remove unused values
- CERT, MSC56-J. - Detect and remove superfluous code and values
This block of commented-out lines of code should be removed. Open
// exit = (new Station(exitTrainConnection->getArrivalStopUri()))->getDefaultName();
- Read upRead up
- Exclude checks
Programmers should not comment out code as it bloats programs and reduces readability.
Unused code should be deleted and can be retrieved from source control history if required.
This block of commented-out lines of code should be removed. Open
// // Log::info("[{connection->getId()}] Updating S: Reach destination from departureStop departing at {quad[self::KEY_DEPARTURE_TIME]} arriving at {quad[self::KEY_ARRIVAL_TIME]}");
- Read upRead up
- Exclude checks
Programmers should not comment out code as it bloats programs and reduces readability.
Unused code should be deleted and can be retrieved from source control history if required.
A "NullPointerException" could be thrown; "lastConnection" is nullable here. Open
connection.getDepartureTime(), lastConnection.getArrivalTime(),
- Read upRead up
- Exclude checks
A reference to null
should never be dereferenced/accessed. Doing so will cause a NullPointerException
to be thrown. At
best, such an exception will cause abrupt program termination. At worst, it could expose debugging information that would be useful to an attacker, or
it could allow an attacker to bypass security measures.
Note that when they are present, this rule takes advantage of @CheckForNull
and @Nonnull
annotations defined in JSR-305 to understand which values are and are not nullable except when @Nonnull
is used
on the parameter to equals
, which by contract should always work with null.
Noncompliant Code Example
@CheckForNull String getName(){...} public boolean isNameEmpty() { return getName().length() == 0; // Noncompliant; the result of getName() could be null, but isn't null-checked }
Connection conn = null; Statement stmt = null; try{ conn = DriverManager.getConnection(DB_URL,USER,PASS); stmt = conn.createStatement(); // ... }catch(Exception e){ e.printStackTrace(); }finally{ stmt.close(); // Noncompliant; stmt could be null if an exception was thrown in the try{} block conn.close(); // Noncompliant; conn could be null if an exception was thrown }
private void merge(@Nonnull Color firstColor, @Nonnull Color secondColor){...} public void append(@CheckForNull Color color) { merge(currentColor, color); // Noncompliant; color should be null-checked because merge(...) doesn't accept nullable parameters }
void paint(Color color) { if(color == null) { System.out.println("Unable to apply color " + color.toString()); // Noncompliant; NullPointerException will be thrown return; } ... }
See
- MITRE, CWE-476 - NULL Pointer Dereference
- CERT, EXP34-C. - Do not dereference null pointers
- CERT, EXP01-J. - Do not use a null in a case where an object is required
Define a constant instead of duplicating this literal "isDepartureCanceled" 3 times. Open
departureCanceled = parseBooleanIfPresent(json, false, "isDepartureCanceled");
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
public void run() { prepare("action1"); // Noncompliant - "action1" is duplicated 3 times execute("action1"); release("action1"); } @SuppressWarning("all") // Compliant - annotations are excluded private void method1() { /* ... */ } @SuppressWarning("all") private void method2() { /* ... */ } public String method3(String a) { System.out.println("'" + a + "'"); // Compliant - literal "'" has less than 5 characters and is excluded return ""; // Compliant - literal "" has less than 5 characters and is excluded }
Compliant Solution
private static final String ACTION_1 = "action1"; // Compliant public void run() { prepare(ACTION_1); // Compliant execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.