Remove this useless assignment to variable

I am using SimpleDataTables JS Library and their minimal suggested implementation: const dataTable = new DataTable("#myTable");

In SC this throws me an Remove this useless assignment to variable "dataTable". and an Remove the declaration of the unused 'dataTable' variable.

If I remove the assignement SC tells me to Either remove this useless object instantiation of "DataTable" or use it.

In SC, the FIRST approach is considered a code-smell, the second approach is considered a bug. So I prefer to use first approach, but still SC is not fully happy.

With my rather limited knowledge of JS, I would say simply doing new DataTable("#myTable"); is the right approach. Of course, strictly speaking, that library should probably not have sideffects when instantiating the object but rather provide a method (like DataTable->run()), but that is not the case.

Is there some other approach to do it “correctly” other than marking this as a false alarm?

Indeed you are using some lib probably having side-effects on constructor execution. I don’t think we will support this lib (I see from npm downloads it’s not very popular), so it’s up to you to ignore the issues.

I would keep the variable (it seems the recommended way as you might hook some events on it later). So either you could “won’t fix” the issues, or you can set in SC settings to ignore particular files for these rules (Administration → General Settings → Analysis Scope → Ignore Issues on Multiple Criteria).

Understood, I will maybe switch to the official data tables lib by jQuery. I had chosen the current one because it is much lighter, but in the end with modern computers and servers etc this doesn’t matter that much anyway.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

Sonar's Useless Assignment Error in Swift

Solving Sonar's 'Remove Useless Assignment of Local Variable' Error in Swift

Abstract: Learn how to resolve SonarQube's 'Remove Useless Assignment of Local Variable' error in Swift by understanding its cause and using different workarounds.

Solving Sonar's "Remove Useless Assignment to Local Variable" Error in Swift

Sonar is a popular tool used for code analysis and review. It helps developers identify and fix issues in their code, making it more readable, maintainable, and secure. One common issue that Sonar flags is the "Remove Useless Assignment to Local Variable" error in Swift. This error occurs when a local variable is assigned a value that is not used in the code. In this article, we will discuss how to solve this error in Swift.

Understanding the Error

To understand the error, let's consider an example:

In this example, we declare two local variables, x and y. We assign the value 5 to x and then calculate the value of y by multiplying x by 2. However, we never use the value of x again in the code. Therefore, Sonar flags the assignment of x as a useless assignment.

Solving the Error

To solve the error, we need to ensure that every local variable is used in the code. We can do this by either using the variable or removing its declaration. In the above example, we can remove the declaration of x, as it is not used in the code:

Alternatively, we can use the value of x in the code:

In this example, we print the value of x to the console, ensuring that it is used in the code.

Using Sonar to Identify Useless Assignments

Sonar can help us identify useless assignments in our code. To do this, we need to configure Sonar to analyze our Swift code. We can do this by installing the SonarSwift plugin and configuring it to analyze our project. Once we have done this, Sonar will flag any useless assignments in our code, allowing us to fix them.

The "Remove Useless Assignment to Local Variable" error in Swift is a common issue that Sonar flags. To solve this error, we need to ensure that every local variable is used in the code. We can do this by either using the variable or removing its declaration. Sonar can help us identify useless assignments in our code, allowing us to fix them and improve the quality of our code.

Remove Useless Assignment to Local Variable

Supported Languages

Tags: :  Swift SonarQube Software Development

Latest news

  • Gradle: Sharing Build Logic and Subprojects in Multi-Module Spring Projects
  • Resolving Build Gradle Failure in Android Project
  • Calling Python Scripts with Matplotlib in Laravel: A Controller Approach
  • Access Request User in Django REST Framework Serializer for TokenRefreshSerializer
  • Automating Flutter App: Finding Elements with Appium Locator
  • Using Nokia SDK 1.1 Java with Asha 300/303: Compatibility with Windows 10
  • Unable to Configure ODBC with MongoDB Driver on Windows 11
  • Filter List Given Attribute Value: Group Read-Only Access App Dev Env
  • Session Overwritten using Node.js Express Passport Authentication OAuth2 Session: Google
  • Running AZ VM Extensions with System-Assigned Managed Identity: Permission Required
  • Java: Creating an Average Hashmap with String Keys
  • Simplifying JWT Token Verification with hashlib in Python
  • Fixing Error: Test-NetConnection - Positional Parameter Not Found - Active Directory File Share Mount
  • Deploying Micro-services in an ECS Cluster on AWS: A Basic Guide
  • Getting Started with PyFlink and Apache Iceberg on Amazon S3 Table API
  • Configuring Log4J2: Directing INFO and WARN Level Messages to Console and ERROR Level Messages to a File
  • Debugging SQL Server on Ubuntu 22 with Visual Studio 2022: A Step-by-Step Guide
  • Troubleshooting SIGSEGV Error in GitHub Data Download Task
  • Modifying Middleware in CakePHP4: Get Request Controller Name Application.php
  • Data Flow in Oracle SQL Server: Moving Data with OPENQUERY
  • Next.js: Getting Started with Google Interfont - A Gentle Guide
  • Understanding the Scope of outerScopeVar in FileReader onload event
  • Implementing a Temperature Controller: Simulating IEEE Std Logic without Inputs
  • Implementing Autoscale Y-axis in Line Chart Generators: A Class Act
  • SwiftUI: onAppear not called on iPad NavigationStack selecting new item
  • WebApplicationFactory: Failing Registrations of Background Services in RabbitMQ Integration Tests
  • Next.js 14: Long Redirect Process
  • Resolving 'ObservableHQ Python not found; run without arguments install Microsoft Store' error in Python 3.5.2 on Windows 7
  • Understanding the WHTG Spec: Script Execution in HTML Elements
  • Extending the Character Limit of SSMSSP Debugger's 'Watch' Variable to 255
  • Understanding Scipy's Newton-Secant Method Condition: abs(q1) < abs(q0) Loop
  • VSCode: Resolved 'Ruby get message: press Enter to confirm input, Esc to cancel' and Ran Debug File
  • Disabling Existing Conditional Access Policies using CLI: A Step-by-Step Guide
  • Fixing SQL Highlighting Issues in VSCode for BigQuery SQL Files
  • Handling Dynamic protobuf Messages in Rust with Tonic

java - Sonar "useless assignment to local variable"解决方法?

标签 java null sonarqube sonar-runner

我正在努力改进我的代码,我从 Sonar 遇到了这个问题:

事实是,它并非毫无用处,因为我在代码之后就使用了它:

Sonar 仍然告诉我“uiRequest”没用,为什么?它不是,因为如果它为空,我不希望它到达代码。我尝试初始化它 ( uiRequest = new UiRequest() ),但它一直告诉我它没用。

有人知道为什么 Sonar 会这样/如何纠正吗?

这段代码有两条可能的路径:

  • a() 返回 true 。 x 被分配 b() 然后 c(x) 被调用。
  • a() 返回 false 。抛出异常, c(x) 没有被调用。

这些路径都没有使用 null 的初始赋值调用 c(x) 。因此,无论您最初分配什么,都是多余的。

请注意,如果初始分配不是 null,这也会是一个问题。除非赋值的右侧有 副作用 ,否则任何赋值都会被浪费。 ( Sonar 分析副作用)

这对 Sonar 来说是可疑的:

  • 也许程序员期望第一个赋值会产生效果——它没有,所以这可能是一个错误。
  • 这还与代码的清晰度有关—— future 代码的人类读者可能会浪费时间思考初始值的用途。
  • 如果右侧涉及计算,但没有副作用,那将是浪费计算。

您可以通过两种方式解决此问题:

首先只是删除 = null ,留下 Foo x; - Java 足够聪明,可以实现所有到 c(x) 的路由涉及赋值,所以这仍然可以编译。

更好的是,将 c(x) 移到 block 中:

这在逻辑上是等价的,更简洁,并且减少了 x 的范围。缩小范围是一件好事。当然,如果你 需要 更大范围的 x ,你就不能这样做了。

还有一个变体,逻辑上也是等价的:

...对“提取方法”和“内联”重构 react 良好:

使用最能传达您意图的那个。

关于java - Sonar "useless assignment to local variable"解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44115011/

上一篇: Java - 我是否应该在 Setters 中使用 new() ?

下一篇: java - testng 在组中运行时跳过@beforesuite 和@beforeclass.

Java:父类(super class)中的同步方法与子类中的同步方法获取相同的锁,对吗?

java - Gradle 传递依赖项不起作用?

java - 您会在 App Engine 中使用 "Future"做什么?

php - MySQL PDO WHERE 语句中的 NULL

c++ - 从可能为 NULL 的字符指针初始化 std::string

Java : static fields behaviour in different executions

php - 在设置值之前检查请求输入是否不为空

eclipse-plugin - SonarQube P2 存储库已经一去不复返了

maven - 将 sonarqube 与 Jenkins 集成

java - 使用 SonarLint 插件和 SonarQube 服务器未检测到 HTTP 请求重定向漏洞

©2024 IT工具网   联系我们

SonarQube displaying to 'remove this useless assignment to local variable'

Why is SonarQube giving this error? How should I fix it? Their rule page does not specify the solution,

Remove this useless assignment to local variable validateAddressRequest.

enter

 Answers

This site says that the error occurs when:

A value is assigned to a variable or property, but either that location is never read later on, or its value is always overwritten before being read. This means that the original assignment has no effect, and could indicate a logic error or incomplete code.

On the first line of the if block, you assign to validateAddressRequest , but then on the third line of the if block, you overwrite validateAddressRequest without having read the previously assigned variable. So the first line is useless.

Declare validateAddressRequest only when calling convertToValidateRequest instead.

Note that you almost certainly don't need the type annotation - if Typescript knows that convertToValidateRequest returns a ValidateAddressRequest already, there's no need to do so again with the new variable. You can do so if you think it's unclear otherwise, or if you don't have type Intellisense, but it may just be noise.

If you were declaring the variable with let so as to enable assignment to it in the future, keep in mind that it's best to avoid reassignment whenever possible, and it's almost always possible to avoid reassignment. If you need another variable that contains a ValidateAddressRequest , give it a different variable name so that you can use const to declare both variables; that makes the code more understandable at a glance, when a reader can be sure that a particular variable reference isn't ever going to be reassigned.

caylasarinag

freddiejarretk

remove this useless assignment to local variable sonar

"Remove this useless assignment to local variable", but the assignment is not useless

petr.h...@iongroup.com's profile photo

[email protected]

Michael Gumowski's profile photo

Michael Gumowski

-- You received this message because you are subscribed to the Google Groups "SonarQube" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected] . To view this discussion on the web visit https://groups.google.com/d/msgid/sonarqube/0d998b34-fedc-4c60-82b6-171e9a4a1914%40googlegroups.com . For more options, visit https://groups.google.com/d/optout .

404 Not found

remove this useless assignment to local variable sonar

Sonar issue - Remove this useless assignment to local variable

I am using below mentioned piece of code:

Here sonar is saying "Remove this useless assignment to local variable". How can I add to the list without initializing it with new keyword?

Sonar comment is "Remove this useless assignment to local variable "listComments". "

I went through below links but not getting my answer.

Sonar complaining about useless assignment of local variable

remove this useless assignment to local variable c#

  • sonarqube-scan

What about this:

If these are of same type. Otherwise project the required fields after where:

I guess that ForEach loop is unnecessary.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove unused assignments and methods from Major Sonar issues #2059

@abhishek-hedera

abhishek-hedera commented Aug 23, 2021

@nathanklick

Successfully merging a pull request may close this issue.

@abhishek-hedera

IMAGES

  1. Remove this useless assignment to local variable Sonarqube

    remove this useless assignment to local variable sonar

  2. Remove this useless assignment to local variable Sonarqube

    remove this useless assignment to local variable sonar

  3. javascript

    remove this useless assignment to local variable sonar

  4. S1481 False Positive "Remove this useless assignment to local variable

    remove this useless assignment to local variable sonar

  5. javascript

    remove this useless assignment to local variable sonar

  6. Sonar: Remove this useless assignment to variable "locale" · Issue

    remove this useless assignment to local variable sonar

VIDEO

  1. LEGO Useless Machine II Mk. II

  2. Enable HyperOS new feature "Remove useless apps and make device smooth" #shorts

  3. Serious Sam Fusion 2017

  4. how to remove useless part from a book

  5. You are useless for this world

  6. EN-210 final video assignment Local Thanksgiving drive

COMMENTS

  1. SonarQube displaying to 'remove this useless assignment to local variable'

    It's best to avoid reassignment whenever possible, and it's almost always possible to avoid reassignment. If you need another variable that contains a ValidateAddressRequest, give it a different variable name so that you can use const to declare both variables; that makes the code more understandable at a glance, when a reader can be sure that a particular variable reference isn't ever going ...

  2. Sonar "useless assignment to local variable" workaround?

    Note that this would also be an issue if the initial assignment was something other than null. Unless the right-hand-side of the assignment has a side effect, any assignment is wasted. (Sonar analyses for side-effects) This is suspicious to Sonar: Maybe the programmer expected the first assignment to have an effect -- it doesn't, so perhaps it ...

  3. Sonarlint wrong "useless assignment to local variables"

    java, intellij. Philippe_Cade (Philippe Cadé) May 7, 2020, 8:45am 1. Since the last update of Sonarlint, we now have some obviously wrong issues reported about useless assignments to local variables: I think this only happens in standalone mode, when connected to Sonar those issues are not shown. Is this known already and is there a ticket to ...

  4. S1854 Remove this useless assignment to a local variable, when used in

    A false positive is generated when the variable is only used in a range operator. versions used : Sonarlint 4.23.0.19399 Visual Studio 2019 Community Edition 16.6.4 c# minimal code sample to reproduce: var prepTexts = "From here"; var test = prepTexts.IndexOf(" ", StringComparison.Ordinal)+1; //hits S1854 Remove this useless assignment to local variable var res= prepTexts[test..9]; //when the ...

  5. Remove this useless assignment to variable

    I am using SimpleDataTables JS Library and their minimal suggested implementation: const dataTable = new DataTable("#myTable"); In SC this throws me an Remove this useless assignment to variable "dataTable". and an Remove the declaration of the unused 'dataTable' variable. If I remove the assignement SC tells me to Either remove this useless object instantiation of "DataTable" or use it. In SC ...

  6. S1481 False Positive "Remove this useless assignment to local variable

    carldebilly changed the title S1481 False Positive S1481 False Positive "Remove this useless assignment to local variable 'x'" Feb 28, 2020. andrei-epure-sonarsource added this to background tasks (investigate, clarify) ... Remove this useless assignment to local variable S1854. We have Sonar Version 8.3.1 (build 34397) and C# plugin 8.6.1 ...

  7. "Remove this useless assignment to local variable" doesn't ...

    The original idea of the plugin was to use external tools for static code analysis. In the past there found some 'internal' checks their way into the plugin. In my opinion we should remove them (not fix it). guwirth self-assigned this Apr 21, 2018. guwirth added this to the 0.9.9 milestone Apr 21, 2018.

  8. Solving Sonar's 'Remove Useless Assignment of Local Variable' Error in

    Using Sonar to Identify Useless Assignments. Sonar can help us identify useless assignments in our code. To do this, we need to configure Sonar to analyze our Swift code. We can do this by installing the SonarSwift plugin and configuring it to analyze our project. Once we have done this, Sonar will flag any useless assignments in our code ...

  9. False Positive useless assignment to local variable #3115

    SonarSource / sonar-dotnet Public. Notifications Fork 221; Star 658. Code; Issues 498; Pull requests 39; ... False Positive useless assignment to local variable #3115. Closed Dixtosa opened this issue Feb 12, 2020 · 1 comment ... The warning is "remove this useless assignment to local variable". Known workarounds.

  10. Sonar "useless assignment to local variable"解决方法?

    Remove this useless assignment to local variable "uiRequest" 事实是,它并非毫无用处,因为我在代码之后就使用了它: ... Sonar "useless assignment to local variable"解决方法?,我们在Stack Overflow上找到一个类似的问题: https: ...

  11. SonarQube displaying to 'remove this useless assignment to local variable'

    On the first line of the if block, you assign to validateAddressRequest, but then on the third line of the if block, you overwrite validateAddressRequest without having read the previously assigned variable. So the first line is useless.

  12. "Remove this useless assignment to local variable", but the assignment

    Hello. In the following code: attemptNumber++; } catch (IOException e) {. System. exit ( 1 ); Sonar warns me that the line "attemptNumber++" is a useless assignment. However, the value is being read -- in the reachable catch block. Best regards, Petr.

  13. Fix S1854 FP: When a variable is used inside local function #3126

    Description When a variable is used inside local function, S1854 is raised. Repro steps public string Test() { string buffer = new string('a', 1); return Local(); string Local() { return buffer; } } Expected behavior No warning. ... Remove this useless assignment to local variable 'buffer'. Known workarounds ... Sonar Analzyer Version: 8.4.0.15306.

  14. Sonarlint wrong "useless assignment to local variables"

    Since one last update off Sonarlint, our now possess some obviously wrong issues reported about impractical assignments to local variables: I think the only happens in standalone mode, when network to Sonar those issues are not shown. Is this known already furthermore is there a ticket to follow? Version: SonarLint for Eclipse 5.1.0.17086 org.sonarlint.eclipse.feature.feature.group SonarSource

  15. S1854 False Positive useless assignment to local variable #2760

    The warning S1854 should not be thrown in the case that a variable is set a value, and might be updated in a try/catch block. Repro steps. See the following code. The warning is raised about the variable ports.

  16. Sonar issue

    Here sonar is saying "Remove this useless assignment to local variable". How can I add to the list without initializing it with new keyword? Sonar comment is "Remove this useless assignment to local variable "listComments". "I went through below links but not getting my answer. Sonar complaining about useless assignment of local variable

  17. How to ignore "Remove this useless assignment to local variable " error

    Hmm, ok.. than maybe this can help turning-sonar-off-for-certain-code or this one ignoring-a-line-with-sonar or this sonarqube-javascript-disable-a-part-of-code If you didn't read this questions already xD

  18. Sonar: Remove this useless assignment to variable "locale" #12472

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.

  19. Remove unused assignments and methods from Major Sonar issues

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.