CodeAnt AI home pagelight logodark logo
  • Support
  • Dashboard
  • Dashboard
  • Join Community
Start Here
  • What is CodeAnt?
Setup
  • Github
  • Bitbucket
  • Gitlab
  • Azure Devops
Pull Request Review
  • Features
  • Customize Review
  • Quality Gates
  • Integrations
Scan center
  • Code Security
  • Code Quality
  • Cloud Security
  • Engineering Productivity
Integrations
  • Jira
  • Test Coverage
  • CI/CD
IDE
  • Setup
  • Review
  • Enhancements
Rule Reference
  • Compliance
  • Anti-Patterns
    • Pyspark
    • Python
    • Java
    • C / CPP
    • C #
    • JavaScript
    • Jcl
    • Kotlin
    • Kubernetes
    • Abap
    • Apex
    • Azure Source Manager
    • Php
    • Pli
    • Plsql
    • Secrets
    • Swift
    • Terraform
    • Text
    • Tsql
    • Rpg
    • Ruby
    • Scala
    • Vb6
    • Vbnet
    • Xml
    • Flex
    • Go
    • Html
    • Docker
    • Css
    • Cobol
    • Common
  • Code Governance
  • Infrastructure Security Database
  • Application Security Database
Resources
  • Open Source
  • Blogs
Anti-Patterns

Scala

Expressions should not be too complex

The complexity of an expression is defined by the number of && and || operators it contains.

A single expression’s complexity should not become too high to keep the code readable.

Copy
if (((condition1 && condition2) || (condition3 && condition4)) && condition5) { ... }

Related if/else if statements and case in a match should not have the same condition

A `match and a chain of if/else if statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.

Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it’s simply dead code and at worst, it’s a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior.

For a match, the second case` will never be executed, rendering it dead code. Worse there is the risk in this situation that future maintenance will be done on the dead case, rather than on the one that’s actually used.

Copy
if (param == 1) {
openWindow
} else if (param == 2) {
closeWindow
} else if (param == 1) { // Noncompliant
moveWindowToTheBackground
}

param match {
case 1 =>
// ...
case 3 =>
// ...
case 1 => // Noncompliant
// ...
case _ =>
//...
}

All code should be reachable

Jump statements (return) move control flow out of the current code block. So any statements that come after a jump are dead code.

Copy
def foo(a: Int) {
val i = 10;
return a + i;       // Noncompliant 
bar;                // dead code
}

if ... else if constructs should end with else clauses

This rule applies whenever an `if statement is followed by one or more else if statements; the final else if should be followed by an else statement.

The requirement for a final else statement is defensive programming.

The else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final case _ clause in a match`.

Copy
if (x == 0) {
doSomething
} else if (x == 1) {
doSomethingElse
}

Function names should comply with a naming convention

For example, with the default provided regular expression ^([a-z][a-zA-Z0-9]*+(_[^a-zA-Z0-9])?+|)$, the function:

Copy
def DoSomething( ) : Unit = { // Noncompliant
// ...
}

match case clauses should not have too many lines of code

The match statement should be used only to clearly define some new branches in the control flow. As soon as a case clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case clause should be extracted into a dedicated method.

Copy
myVariable match {
case 0 => // Noncompliant: 6 lines till next case
methodCall1()
methodCall2()
methodCall3()
methodCall4()
methodCall5()
case 1 =>
// ...
}

All branches in a conditional structure should not have exactly the same implementation

Having all branches of a match or if chain with the same implementation indicates a problem.

In the following code:

Copy
if (b == 0) { // Noncompliant
doSomething
} else {
doSomething
}

i match { // Noncompliant
case 1 => doSomething
case 2 => doSomething
case 3 => doSomething
case _ => doSomething
}

match statements should have case _ clauses

The requirement for a final case _ clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken.

Copy
param match {
case 1 => doSomething
case 2 => doSomethingElse
}

match statements should not be nested

Nested `match structures are difficult to understand because you can easily confuse the cases of an inner match as belonging to an outer statement. Therefore nested match statements should be avoided.

Specifically, you should structure your code to avoid the need for nested match statements, but if you cannot, then consider moving the inner match` to another function.

Copy
def foo(n: Int, m: Int): Unit = {
n match {
case 0 => m match {
    case 0 =>
    // ...
  }
case 1 =>
// ...
}
}

Boolean checks should not be inverted

It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead.

Copy
if (!(a == 2)) { ...}  // Noncompliant
val b = !(i < 10)  // Noncompliant

Statements should be on separate lines

Putting multiple statements on a single line lowers the code readability and makes debugging the code more complex.

Unresolved directive in <stdin> - include::{noncompliant}[]

Write one statement per line to improve readability.

Unresolved directive in <stdin> - include::{compliant}[]

Copy
println("Hello"); println("world!") // Noncompliant

Boolean literals should not be redundant

A boolean literal can be represented in two different ways: {true} or {false}. They can be combined with logical operators ({ops}) to produce logical expressions that represent truth values. However, comparing a boolean literal to a variable or expression that evaluates to a boolean value is unnecessary and can make the code harder to read and understand. The more complex a boolean expression is, the harder it will be for developers to understand its meaning and expected behavior, and it will favour the introduction of new bugs.

Copy
if (booleanMethod() || false) { /* ... */ }
doSomething(!false)

booleanVariable = if (booleanMethod()) true else false
booleanVariable = if (booleanMethod()) true else exp
booleanVariable = if (booleanMethod()) false else exp
booleanVariable = if (booleanMethod()) exp else true
booleanVariable = if (booleanMethod()) exp else false

Mergeable if statements should be combined

Nested code - blocks of code inside blocks of code - is eventually necessary, but increases complexity. This is why keeping the code as flat as possible, by avoiding unnecessary nesting, is considered a good practice.

Merging if statements when possible will decrease the nesting of the code and improve its readability.

Copy
if (condition1) {
if (condition2) {             // Noncompliant
/* ... */
}
}

Methods should not be empty

An empty {operationName} is generally considered bad practice and can lead to confusion, readability, and maintenance issues. Empty {operationName}s bring no functionality and are misleading to others as they might think the {operationName} implementation fulfills a specific and identified requirement.

There are several reasons for a {operationName} not to have a 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 exception should be thrown.

  • The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.

Copy
def shouldNotBeEmpty() = {  // Noncompliant - method is empty
}

def notImplementedYet() = {  // Noncompliant - method is empty
}

def willNeverBeImplemented() = {  // Noncompliant - method is empty
}

def emptyOnPurpose() = {  // Noncompliant - method is empty
}

Redundant pairs of parentheses should be removed

The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. However, redundant pairs of parentheses could be misleading and should be removed.

Copy
val x = ((y / 2 + 1))  // Noncompliant

if (a && ((x + y > 0))) {  // Noncompliant
return ((x + 1))  // Noncompliant
}

Variables should not be self-assigned

There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead.

Copy
def doSomething() = {
var name = ""
// ...
name = name
}

String literals should not be duplicated

Duplicated string literals make the process of refactoring complex and error-prone, as any change would need to be propagated on all occurrences.

Copy
public def run() {
prepare("action random1")    // Noncompliant - "action random1" is duplicated 3 times
execute("action random1")
release("action random1")
}

Methods should not have identical implementations

Two {func_name}s having the same implementation are suspicious. It might be that something else was intended. Or the duplication is intentional, which becomes a maintenance burden.

Copy
class Circle(var radius: Int) {
def width_=(size: Int) {
radius = size / 2
updateShape()
}

def height_=(size: Int) { // Noncompliant: duplicates width_
radius = size / 2
updateShape()
}

def updateShape() = {...}
}

Using hardcoded IP addresses is security-sensitive

Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities:

  • CVE-2006-5901

  • CVE-2005-3725

Today’s services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery, and deployment:

  • The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.

  • It misleads to use the same address in every environment (dev, sys, qa, prod).

Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service, try to get access to the system, or try to spoof the IP address to bypass security checks. Such attacks can always be possible, but in the case of a hardcoded IP address solving the issue will take more time, which will increase an attack’s impact.

Copy
val ips = Source.fromFile(configuration_file).getLines.toList // Compliant
val socket = new Socket(ips(0), 6667)

Unused private methods should be removed

This rule raises an issue when a {visibility} {operationName} is never referenced in the code.

Copy
class Foo extends Serializable {
private def unusedMethod(): Unit = {...} // Noncompliant
private def writeObject(s: ObjectOutputStream): Unit = {...} // Compliant, relates to the serialization mechanism
private def readObject(s: ObjectInputStream): Unit = {...} // Compliant, relates to the serialization mechanism
}

Useless if(true) {...} and if(false){...} blocks should be removed

`if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.

There are three possible causes for the presence of such code:

  • An if statement was changed during debugging and that debug code has been committed.

  • Some value was left unset.

  • Some logic is not doing what the programmer thought it did.

In any of these cases, unconditional if` statements should be removed.

Copy
if (true) {
doSomething
}
// ...
if (false) {
doSomethingElse
}

Unused local variables should be removed

An unused local variable is a variable that has been declared but is not used anywhere in the block of code where it is defined. It is dead code, contributing to unnecessary complexity and leading to confusion when reading the code. Therefore, it should be removed from your code to maintain clarity and efficiency.

Copy
def numberOfMinutes(hours: Int): Int = {
var seconds = 0 // Noncompliant - seconds is unused
val result = hours * 60
result
}

Local variable and function parameter names should comply with a naming convention

A naming convention in software development is a set of guidelines for naming code elements like variables, functions, and classes. {identifier_capital_plural} hold the meaning of the written code. Their names should be meaningful and follow a consistent and easily recognizable pattern. Adhering to a consistent naming convention helps to make the code more readable and understandable, which makes it easier to maintain and debug. It also ensures consistency in the code, especially when multiple developers are working on the same project.

This rule checks that {identifier} names match a provided regular expression.

Copy
def printSomething(text_param: String): Unit = { // Noncompliant
var _1LOCAL = "" // Noncompliant
println(text_param + _1LOCAL)
}
RubyVb6
twitterlinkedin
Powered by Mintlify
Assistant
Responses are generated using AI and may contain mistakes.