Sonarlint wrong "useless assignment to local variables"

Since the last update of Sonarlint, we now have some obviously wrong issues reported about useless assignments to local variables:

image

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 follow?

Version: SonarLint for Eclipse 5.1.0.17086 org.sonarlint.eclipse.feature.feature.group SonarSource

I can still see it with the version SonarLint for Eclipse 5.2.1.18852 org.sonarlint.eclipse.feature.feature.group SonarSource

Nobody else is affected?

The noise that this is creating is quite annoying.

Hi Phlippe,

Can you share a reproducer? Like a sample project on GitHub having the issue.

Unfortunately I haven’t found a good way to reproduce the issue but now I know a little bit more about it. I have uploaded the example code I used above here: https://github.com/philippecade/sonarlint.bug

  • When I only have this project in Eclipse, the issue doesn’t appear. I can only see it when this project is in a workspace with ~30 other projects, some connected to Sonar and some not.
  • The issue only happens if the project in question is not connected to a Sonar server.
  • It is a regression from version 4.3.0.
  • I don’t think that it depends on a particular code construct, the issue is also reported in a simple for loop for example: for (Foo f: list) { f.foo(); } <-- Remove this unused “f” local variable

Not sure if this is enough information for you. I’m willing to help further if you have a debug build or something like that.

Thanks Philippe

I’m still unable to reproduce.

  • enable analysis + verbose logs
  • clear the SonarLint console
  • close/reopen the file LdapUtils
  • share the logs

For the record, this is what I get:

This is what I get in the Eclipse that shows the error:

I see your project is configured to use a JRE, not a JDK. Could it be the reason of the difference? Could you try to configure a JDK instead? I will try to reproduce on my side.

I was able to reproduce. This is because you run Eclipse with a JDK 8, but your project is configured to use a Java 11 runtime. We have a ticket on our side to track this issue: https://jira.sonarsource.com/browse/SLE-348 I will update it and try to make its resolution prioritized.

In the meantime, a workaround is to configure Eclipse to run with a more recent JDK.

Great, I’m glad you found it.

I can also confirm that using Java 11 for Eclipse solves the issue.

Thanks for your help!

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

  • Making ggplot: Understanding Relative Value Depth for Phosphate Concentrations in Mapped Sites
  • Three.js: Efficiently Building 'Boxy' Terrain in Three Steps
  • Summing Rows: Value Across Multiple Distinct Columns
  • Updating Multi-Tenant OpenEdge Database Using ODBC: A Step-by-Step Guide
  • Creating Grid Image Section: Aligning Layout Issues
  • Object Mapper: Get JSON and Convert List<Map<String, Object>>
  • Setting up Kamailio SIP Server to Playback Message Instead of Replying with Busy
  • User Registration with Country Code: A Step-by-Step Guide for Software Development
  • The Best Way to Create Functions with Variable Types Arrays in .NET (C# and VB.NET)
  • Scheduling Jobs in Apex: Creating and Modifying Contact-Related Scheduled Jobs
  • Gh-pages Not Finding JsCSS File: A 404 Error and White Screen
  • Property Setter Absence in Abstract Base Classes: Impact on Class Instantiation
  • Troubleshooting Fluent-bit Sidecar Container Exit Code 139 in AWS ECS Fargate
  • Understanding Managed Identity and Access to Confusing Concepts: Different Private Endpoints
  • C Program Outputs Differently on Linux and Windows
  • Authenticating and Pulling Subscriptions with Azure App Registration and Certificate-Based Authentication
  • Sharing Weights between Nested Torch nn.Module Objects: An Example of SharedBlock Class
  • PowerPoint: Deleting Slides with One-Row Tables
  • NRFconnect Board: Single Connection Peripheral in NRF5340 Application
  • El.scrollIntoView() Causes Whole Container to Move? Understanding Nested Overflow-Y: Auto Elements and Full Page Scrollability
  • Deploying Jakarta EE Application with Jetty 12: Resolving ClassNotFoundException with CDI Providers using jetty-ee10-maven-plugin
  • Selenium Driver Gets Wrong Page: Handling Link Issues in Python
  • ARIMA Time Series Modeling: Significance Testing of ARMA(2,1) Process
  • Mastering FontForge: A Deep Dive into Glyph Alignment
  • Adding a Legend to ggplot not as Aesthetic
  • Isolating Barcodes from Images using Barcode ISMLKit and OpenCV in Android
  • Checking Value of Optional Header in Nginx using Map Function
  • React Native Build Error: Execution failed task: expo:compileDebugKotlin
  • VSCodium Not Detecting Modules: A Look at the Giraffe Academy Inheritance Tutorial Issue
  • Speech Bubble Not Appearing Every 30 Seconds: A Fix
  • Sorting Excel File Columns: Getting List of Filenames in Python
  • Properly Using Flask-JWT-Extended Refresh Tokens with HTTP Cookies in Software Development
  • Applying Fixed Pixel Width to an HTML Email Button in Outlook
  • Error during Angular 16 to 17 Upgrade: '@angular/build' not found
  • Troubleshooting Divi Custom Post Type: Slug Deletion Not Working

s1854 remove this useless assignment to local variable

"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 .

sonarlint-visualstudio sonarlint-visualstudio copied to clipboard

False positive with s1854.

Product: SolarLint 6.8.0.53188 IDE: VS 2022 CE 17.0.4 Preview 2 Language: C# Rule: S1854 - "Remove this useless assignment to local variable"

I am using the prefix increment operator in code that sends an integer to a method. Here's a MRE:

If there are hundreds of calls to MyMethod2(int i) , making the last and only last " i+1 " is a code smell in itself:

image

(this would be difficult to spot visually, and adding another line to the end with the prefix operator would introduce a bug).

cdanek avatar

Go to list of users who liked

More than 3 years have passed since last update.

s1854 remove this useless assignment to local variable

Rubocopエラー「Useless assignment to variable」の解決例

上記エラーを調べると、「使っていないローカル変数の定義がある」というエラーのようで 削除すれば解決するとの事でした。

しかし、今回はちゃんと使っている内容で、書き方の問題のようでした。 以下のように、if文などの後に 明示的に使用している記載が必要 とのことでした。

Go to list of comments

Register as a new user and use Qiita more conveniently

  • You get articles that match your needs
  • You can efficiently read back useful information
  • You can use dark theme
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL query help documentation »
  • CodeQL query help for Go »

Useless assignment to local variable ¶

Click to see the query in the CodeQL repository

A value is assigned to a variable, but either it is never read, 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.

Recommendation ¶

Remove assignments to variables that are immediately overwritten, or use the blank identifier _ as a placeholder for return values that are never used.

In the following example, a value is assigned to a , but then immediately overwritten, a value is assigned to b and never used, and finally, the results of a call to fmt.Println are assigned to two temporary variables, which are then immediately overwritten by a call to function .

The result of calculateValue is never used, and if calculateValue is a side-effect free function, those assignments can be removed. To ignore all the return values of fmt.Println , you can simply not assign it to any variables. To ignore only certain return values, use _ .

References ¶

Wikipedia: Dead store .

The Go Programming Language Specification: Blank identifier .

Common Weakness Enumeration: CWE-563 .

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Eclipse SonarLint false positive "Unused assignments should be removed (java:S1854)"

I'm using Eclipse 2020-03 (4.15.0) with Sonarlint for Eclipse 5.1.0.17086 and I get , IMO, false positive S1854 warnings in the following code (taken from the book "Java 8 In Action"). Working with Java OpenJDK 13.0.2. This is not a showstopper since I am merely studying Java 8 techniques. I just want to understand why these lines are flagged...

Did I miss something here? Both "length", "leftTask" and "rightTask" are used several times in the code...

Above class is tested with the following class:

  • sonarlint-eclipse

PaulN's user avatar

  • What are end , start and THRESHOLD ? Please provide a minimal reproducible example . –  howlger Commented May 13, 2020 at 14:37
  • Edited to add more code info. –  PaulN Commented May 14, 2020 at 8:51

2 Answers 2

I did a brief survey about Warning S1854 on Sonar and saw several issues created on Github and on the Sonar website itself, apparently it was fixed in February/2020. Check if your Sonar is up to date, and if it is, the error probably hasn't been fixed :(

https://jira.sonarsource.com/browse/SONARJAVA-3281

Alan Ensina's user avatar

  • Thanks for your survey. I checked in Eclipse for SonarLint updates. There were none. I also checked your link. It handles false positives in lambda code, which is not the case in my code. We'll see... –  PaulN Commented May 13, 2020 at 11:52

I finally solved the problem, I was set on the right track by a post on the sonarlint forum ( https://community.sonarsource.com/t/java-s2166-rule-not-working/22943/15 ). My projects were working with Java 13 while my Windows cmd "Java -version" returned Java 1.8 as the running Java version. This mismatch (Eclipse starting up with Java 1.8 and the project working with Java 13) caused the SonarLint FP's.

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged java eclipse sonarlint-eclipse or ask your own question .

  • The Overflow Blog
  • At scale, anything that could fail definitely will
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Is it possible to recover from a graveyard spiral?
  • How to add a third argument to a popup_menu() callback function?
  • Is this schematic ready to be made into a circuit?
  • Maximizing the common value of both sides of an equation (part 2)
  • Why am I having problems starting my service in Red Hat Enterprise Linux 8?
  • When did graduate student teaching assistants become common in universities?
  • Are all citizens of Saudi Arabia "considered Muslims by the state"?
  • Does it make sense for the governments of my world to genetically engineer soldiers?
  • Can Christian Saudi Nationals Visit Mecca?
  • How would you slow the speed of a rogue solar system?
  • What is Zion's depth in the Matrix?
  • A novel (and a movie) about a village in southern France where a strange succession of events happens
  • Can I Use A Server In International Waters To Provide Illegal Content Without Getting Arrested?
  • How do I apologize to a lecturer
  • figuring out the speed controller of a cassette tape motor
  • Whats the safest way to store a password in database?
  • Geometry optimization of two or more different interacting molecules
  • Homeomorphism between topological subspaces
  • Fetch grapghQl response in next js
  • Does proficiency with an ability check that uses a tool but not with the tool itself give any advantages for D&D 5.24?
  • What other marketable uses are there for Starship if Mars colonization falls through?
  • quantulum abest, quo minus .
  • Uniqueness of Neumann series
  • Find the number of distinct cubes that can be made by painting each face of a given cube in one of the 5 given colors

s1854 remove this useless assignment to local variable

IMAGES

  1. Remove this useless assignment to local variable "strideDistance

    s1854 remove this useless assignment to local variable

  2. Local variable referenced before assignment in Python

    s1854 remove this useless assignment to local variable

  3. Sonarlint wrong "useless assignment to local variables"

    s1854 remove this useless assignment to local variable

  4. UnboundLocalError: Local Variable Referenced Before Assignment

    s1854 remove this useless assignment to local variable

  5. "Fixing UnboundLocalError: Local Variable Referenced Before Assignment"

    s1854 remove this useless assignment to local variable

  6. C++ : Is it useless to declare a local variable as rvalue-reference, e

    s1854 remove this useless assignment to local variable

VIDEO

  1. EN-210 final video assignment Local Thanksgiving drive

  2. IMS458 GROUP ASSIGNMENT LOCAL COMMUNITY WEBSITE: DISCOVER LENGGONG BY GROUP 5

  3. Serious Sam Fusion 2017

  4. when you remove useless line from your code 😅 agree or not comment it #programmers #codememes

  5. Novak 69 HR Explains How Ambiguous Policy is Used Against Employees

  6. Are There Any Useless Local SEO Metrics? 📊🤔

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. S1854 FP

    Hey again. Indeed, it looks like you're running the SonarScanner CLI, which isn't the recommended way (unless your normal build tool is an ant, in which case it's the only way).. This is because the SonarScanner CLI requires a lot of manual configuration to perform an accurate analysis of Java, specifically the bytecode (the "semantic" I was referring to earlier)

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

    Description 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. ... S1854 False Positive useless assignment to local variable #2760. jcurl opened this issue Nov 1, 2019 · 2 comments Labels. Area: C# C# rules related issues.

  5. 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 Related information.

  6. Sonarlint wrong "useless assignment to local variables"

    intellij, java. 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: 990×328 25 KB. I think this only happens in standalone mode, when connected to Sonar those issues are not shown.

  7. Fix S1854 FP with usage inside tuples · Issue #3094 · SonarSource/sonar

    In the following code, SonarAnalyzer.CSharp 8.3.0.14607 flags S1854: Remove this useless assignment to local variable 'r'. Is this a false positive? Version 8.2 didn't flag this code. namespace S18...

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

    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. References. Remove Useless Assignment to Local Variable. Supported ...

  9. "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.

  10. Fix S1854 FP: ref keyword on a local variable #3304

    Description When a local variable with ref keyword is used, S1854 is raised. Repro steps private void Test(int[] values) { ref int value = ref values[0]; value = default; } Expected behavior No warning. ... warning S1854: Remove this useless assignment to local variable 'value'. Known workarounds Related information. SonarAnalyzer.CSharp.8.6. ...

  11. Useless assignment to local variable

    In IsDouble, the out argument of the call to int.TryParse is assigned to the unread local variable i. In ParseDouble, the exception thrown by the call to double.Parse in case of parse failure is assigned to the unread local variable e. In Count, the elements of ss are assigned to the unread local foreach variable s.

  12. sonarlint-visualstudio False positive with S1854

    Product: SolarLint 6.8.0.53188 IDE: VS 2022 CE 17.0.4 Preview 2 Language: C# Rule: S1854 - "Remove this useless assignment to local variable" I am using the prefix increment operator in code that sends an integer to a method. Here's a MRE:

  13. Rubocopエラー「Useless assignment to variable」の解決例

    Rubocopエラー「Useless assignment to variable」の解決例. 上記エラーを調べると、「使っていないローカル変数の定義がある」というエラーのようで 削除すれば解決するとの事でした。 しかし、今回はちゃんと使っている内容で、書き方の問題のようでした。

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

    S1481 False Positive "Remove this useless assignment to local variable 'x'" #3169. Closed carldebilly opened this issue Feb 28, 2020 · 4 comments ... Remove this useless assignment to local variable S1854. We have Sonar Version 8.3.1 (build 34397) and C# plugin 8.6.1 (build 17183)

  15. switch statement not supporting "when"

    The problem lies in the fact that the "When" code is not being considered when checking if a method parameter is in use or not. I can't see how a ruleset changes that?

  16. Fix S1854 FP: `try` block not connected to `catch` when ...

    andrei-epure-sonarsource changed the title S1854 "Remove this useless assignment to local variable" is not aware of exception filters S1854 FP: try actions are not reflected in catch block Jul 22, 2019

  17. Useless assignment to local variable

    Useless assignment to local variable¶ ID: go/useless-assignment-to-local Kind: problem Security severity: Severity: warning Precision: very-high Tags: - maintainability - external/cwe/cwe-563 Query suites: - go-security-and-quality.qls ... Remove assignments to variables that are immediately overwritten, or use the blank identifier _ as a ...

  18. Eclipse SonarLint false positive "Unused assignments should be removed

    I'm using Eclipse 2020-03 (4.15.0) with Sonarlint for Eclipse 5.1.0.17086 and I get , IMO, false positive S1854 warnings in the following code (taken from the book "Java 8 In Action"). Working with Java OpenJDK 13.0.2. This is not a showstopper since I am merely studying Java 8 techniques. I just want to understand why these lines are flagged...

  19. False positive with S1854 #6154

    Product: SolarLint 6.8.0.53188 IDE: VS 2022 CE 17.0.4 Preview 2 Language: C# Rule: S1854 - "Remove this useless assignment to local variable" I am using the prefix increment operator in code that s...