Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions rules/S8315/groovy/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"title": "Empty strings should not be used for type conversion",
"type": "CODE_SMELL",
"status": "beta",
"remediation": {
"func": "Constant/Issue",
"constantCost": "5 min"
},
"tags": [
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-8315",
"sqKey": "S8315",
"scope": "Main",
"defaultQualityProfiles": [
"Sonar way"
],
"quickfix": "unknown",
"code": {
"impacts": {
"MAINTAINABILITY": "HIGH"
},
"attribute": "EFFICIENT"
}
}
44 changes: 44 additions & 0 deletions rules/S8315/groovy/rule.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
This rule raises an issue when an empty string literal is concatenated with another value using the `+` operator.

== Why is this an issue?

Concatenating an empty string with another value is an inefficient way to convert that value to a string. This pattern creates unnecessary string objects and obscures the developer's intent.

In Groovy, when you use `'' + someValue`, the runtime must:

* Create a new empty string object
* Convert `someValue` to a string representation
* Concatenate the empty string with the converted value
* Return the result

This approach is less efficient than direct string conversion methods and makes the code less readable. The intent (converting a value to a string) is not immediately clear to other developers reading the code.

Moreover, this pattern can lead to unexpected behavior with null values, as `'' + null` results in the string `"null"` rather than an empty string or a null pointer exception that might be more appropriate depending on the context.

== How to fix it

Replace empty string concatenation with explicit `toString()` calls. For potentially null values, use safe navigation with null coalescing to handle null cases appropriately.

=== Code examples

==== Noncompliant code example

[source,groovy,diff-id=1,diff-type=noncompliant]
----
def variable = method('' + property)
----

==== Compliant solution

[source,groovy,diff-id=1,diff-type=compliant]
----
def variable = method(property?.toString() ?: "")
----

== Resources

=== Documentation

* Groovy documentation - https://groovy-lang.org/syntax.html#_string_summary_table[String handling and conversion methods]

* Groovy documentation - https://groovy-lang.org/operators.html#_safe_navigation_operator[Safe navigation operator]
2 changes: 2 additions & 0 deletions rules/S8315/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{
}
Loading