Compare commits

...

3 Commits

Author SHA1 Message Date
Ilia Kebets
9f69b9efc0 format and add noncompliatn code comments 2024-09-03 08:40:40 +02:00
Ilia Kebets
87db8f4148 Implement rule 2024-09-02 17:20:10 +02:00
ilia-kebets-sonarsource
e8fb884af9 Create rule S7056 2024-09-02 14:51:34 +00:00
3 changed files with 101 additions and 0 deletions

View File

@ -0,0 +1,25 @@
{
"title": "Modules should not export mutable variables",
"type": "CODE_SMELL",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"architecture"
],
"defaultSeverity": "Minor",
"ruleSpecification": "RSPEC-7056",
"sqKey": "S7056",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "infeasible",
"code": {
"impacts": {
"MAINTAINABILITY": "MEDIUM",
"RELIABILITY": "MEDIUM"
},
"attribute": "MODULAR"
}
}

View File

@ -0,0 +1,74 @@
== Why is this an issue?
Using `var` or `let` to export mutable variables in JavaScript can lead to unpredictable behavior and bugs, as any module that imports them can change their values.
This complicates debugging and reduces code readability, as it's difficult to understand the flow and state of the application.
Avoiding mutable exports helps maintain data integrity and makes your code more reliable.
== How to fix it
When you need to export a variable, use `const` to ensure it remains immutable. This prevents other modules from altering its value.
If you need to export data that might change, consider exporting functions that return the data instead of exporting the data directly. This way, you can control how and when the data is modified.
Consider using immutable data structures, such as those provided by libraries like https://www.npmjs.com/package/immutable[Immutable.js], to manage data that should not change. This can help you maintain data integrity and avoid unintended side effects.
=== Code examples
==== Noncompliant code example
[source,javascript,diff-id=1,diff-type=noncompliant]
----
let port = 8080
export { port }; // Noncompliant
----
==== Compliant solution
[source,javascript,diff-id=1,diff-type=compliant]
----
const port = 8080
export { port };
----
==== Noncompliant code example
[source,javascript,diff-id=2,diff-type=noncompliant]
----
let counter = 0;
export { counter }; // Noncompliant
----
==== Compliant solution
[source,javascript,diff-id=2,diff-type=compliant]
----
let counter = 0;
const getCounter = () => counter;
const incrementCounter = () => { counter += 1; };
export { getCounter, incrementCounter };
----
==== Noncompliant code example
[source,javascript,diff-id=3,diff-type=noncompliant]
----
let settings = {
theme: "dark",
language: "en"
};
export { settings }; // Noncompliant
----
==== Compliant solution
[source,javascript,diff-id=3,diff-type=compliant]
----
import { Map } from 'immutable';
const settings = Map({
theme: "dark",
language: "en"
});
export { settings };
----

View File

@ -0,0 +1,2 @@
{
}