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

  • Customizing Context Menus in EditableText using Flutter
  • Understanding Check Object Property Optional in JavaScript (Agnostic to Strict Mode)
  • CSS initial-letter property: Differences in Inheritance between Chrome and Safari
  • Refreshing UI Issues with ElectronReact and SQLite IPC Database Operations
  • Node.js/NPM Setup in Docker Container Fails: Wrong Version/NPM Not Found
  • Storing C# Class Methods in Memory: An Example with Voxel Classes
  • React App: Token Not Persisting after Refresh in Azure Static Web App using MSAL
  • Handling Missing Tabs with SKUs in Pricing Lists: A Common Account TPL Issue
  • Faster Way to Write and Draw Many Random Samples in R: An Alternative Approach
  • Extracting Bitmap Information from Online Videos for Android Development
  • Troubleshooting Navbar Links in addapp.jsx and Mixed Homepage in TryAddUSPage
  • Firebase Auth Integration with Ktor Backend: Verifying ID Tokens
  • Flexbox Image Design in Edge Firefox and IE11: A Comparison
  • JPackage via Maven: Missing desktop file icon for JLink Project
  • Solving MS Access Select Query Issue: Data Not Retrieved Unless Refresh
  • NanoTime vs currentTimeMillis: A Three-Minute Divergence in Time Measurements
  • Unable to Find Crystal Reports Assemblies in Visual Studio 2019: A Solution
  • PHP vs Python: Rrule Function Equivalent for Recurring Events
  • Reducing Redundant Logging in Selenium Wire with Django and Celery
  • Unpacking Iterators Inside *args Type Hinting: Merging Two Iterators
  • Restoring MassTransit Sagas to a Not-Finished State: A Simple Approach
  • Taking a Screenshot of the Browser's Actual Display with JavaScript
  • Delphi 12 Upgrade Issues: App Crashes Starting Foreground Service
  • Can't Void Parameter Generic Lookup in TypeScript?
  • Resolving Gateway[SCR] Error while Binding References in WSO2 GitRepo
  • Animate.css File Not Recognized on GitHub Pages: A Solution
  • Getting Stuck on Initial Connect: CppZMQ Router-to-Router Communication
  • Opening a Microsoft Word File on a Web Application with Local IIS Server
  • Displaying DataFrame Table with FilterOptions using reactable Package in R ShinyDashboard
  • React-Native: Status Bar Not Responding to Style Changes in Login/Register Screens
  • Preventing User Closure of Picamera2 Preview Window in Python/tkinter App
  • Understanding Microservices: A New Approach with Spring Boot
  • Catching SocketException with Nice Error Messages: No Internet Connection
  • Resolving Keras Datasets Import Issue in Python
  • Troubleshooting Internal Test Case Failure with mtcars Dataset and Dplyr Package

remove this useless assignment to local variable sonar fix java

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

Sonar "useless assignment to local variable" workaround?

I am working towards improving my code, and I came across this issue from Sonar:

Fact is, it is not useless, as I am using it just after in the code:

Sonar still tells me that "uiRequest" is useless, why ? It is not, as I don't want it to reach the code if it is null. I tried initializing it ( uiRequest = new UiRequest() ) but it keeps telling me that it is useless.

Anyone got an idea about why Sonar behaves like this / how to correct this ?

Your issue simplifies to:

There are two potential paths through this code:

  • a() returns true . x is assigned b() then c(x) is called.
  • a() returns false . An exception is thrown and c(x) is not called.

Neither of these paths calls c(x) using the initial assignment of null . So whatever you assigned at first, is redundant.

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's a bug.
  • It's also about code clarity -- a future human reader of the code might waste time wondering what the initial value is for.
  • If the right-hand-side had involved computation, but had no side effect, it would be wasted computation.

You can fix this in two ways:

Firstly just removing the = null , leaving Foo x; - Java is clever enough to realise that all routes to c(x) involve an assignment, so this will still compile.

Better yet, move c(x) into the block:

This is logically equivalent, neater, and reduces the scope of x . Reducing scope is a good thing. Of course, if you need x in the wider scope, you can't do this.

One more variation, also logically equivalent:

... which responds well to "extract-method" and "inline" refactorings:

Use whichever communicates your intent best.

You can avoid the warning and perhaps have slightly more readable code by:

What about moving it into the if statement?

Or throw exception in the if statement and just have no else clause. i.e let the normal case be the "happy path".

The assignment is useless because no code can possibly see that assigned value.

How to detect file name exist on upload in Angular file manager

2019-03-20 1

How to set ng-model variable from custom validation directive

2022-12-02 1

Jquery asynchronous ajax variable not changing synchronously

2020-04-16 1

I wrote a program to calculate pi but something went wrong

2020-10-17 2

SQL injection when single quotes are escaped with two single quotes

2022-02-22 2

Go to list of users who liked

More than 3 years have passed since last update.

remove this useless assignment to local variable sonar fix java

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

Remove this useless assignment to local variable - sonarqube - using try catch

In the following code, sonarqube is complaining for the mentioned error in the question:

How can I re-write this code to resolve this complain from sonarqube?

teenup's user avatar

  • 1 Does your catch block rethrow? Can you provide a minimal reproducible example example rather then just commented bits? –  Jon Skeet Commented Nov 25, 2020 at 11:15
  • @Jon I have provided the exact code. –  teenup Commented Nov 25, 2020 at 11:17
  • 1 Have you tried not having a result at all and doing a return await func() / return default(T) instead? –  Caius Jard Commented Nov 25, 2020 at 11:18
  • 2 I could assume that it's complaining about T result = default; but why are you making me guess? –  Damien_The_Unbeliever Commented Nov 25, 2020 at 11:19
  • 1 @TimSchmelter: How is it redundant? If func() throws an exception or the task it returns throws an exception, there'd be no value in result . Without the initial assignment, the variable isn't definitely assigned at the return statement. –  Jon Skeet Commented Nov 25, 2020 at 11:19

Know someone who can answer? Share a link to this question via email , Twitter , or Facebook .

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 .

Browse other questions tagged c# sonarqube or ask your own question .

  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • Can I use "Member, IEEE" as my affiliation for publishing papers?
  • What makes a new chain jump other than a worn cassette?
  • Is supremum of a continuous function continuous either?
  • How can I cover all my skin (face+neck+body) while swimming outside (sea or outdoor pool) to avoid UV radiations?
  • Implications of the statement: "Note that it is very difficult to remove Rosetta 2 once it is installed"
  • What can cause a 24 volt solar panel to output 40 volt?
  • chess game: loading images for the rooks
  • Garage door not closing when sunlight is bright
  • Is there a way to say "wink wink" or "nudge nudge" in German?
  • ~1980 UK TV: very intelligent children recruited for secret project
  • Can one repair an "Amen Chatufa"?
  • 'best poster' and 'best talk' prizes - can we do better?
  • Why is deontological ethics the opposite of teleological ethics and not "ontological" ethics
  • What is the number ways to count tuples whose sum is zero?
  • set of words w such that M halts on w is decidable
  • Can police offer an “immune interview”?
  • In compound nouns is there a way to distinguish which is the subject or the object?
  • Unreachable statement when upgrading APEX class version
  • Kyoto is a famous tourist destination/area/site/spot in Japan
  • Solve an integral analytically
  • Extrude Individual Faces function is not working
  • Is my encryption format secure?
  • The complement of a properly embedded annulus in a handlebody is a handlebody
  • Guitar amplifier placement for live band

remove this useless assignment to local variable sonar fix java

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

False Positive useless assignment to local variable #3115

@Dixtosa

Dixtosa commented Feb 12, 2020 • edited Loading

fails on tuples.

This generates warning:

This does not:

I expect the warning to not show up.

The warning is "remove this useless assignment to local variable".

@andrei-epure-sonarsource

andrei-epure-sonarsource commented Feb 12, 2020

thanks , this looks like a duplicate of

this fix for is on master and will be in the next release

Sorry, something went wrong.

@andrei-epure-sonarsource

No branches or pull requests

@Dixtosa

IMAGES

  1. Solución (FIX): Sonar

    remove this useless assignment to local variable sonar fix java

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

    remove this useless assignment to local variable sonar fix java

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

    remove this useless assignment to local variable sonar fix java

  4. Sonarlint wrong "useless assignment to local variables"

    remove this useless assignment to local variable sonar fix java

  5. javascript

    remove this useless assignment to local variable sonar fix java

  6. How to convert JSON String to java object

    remove this useless assignment to local variable sonar fix java

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

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

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

    StructA a = aFunctionThatReturnsStructA(args); // Remove this useless assignment to local variable a StructB b = {.field1 = a.field1}; The text was updated successfully, but these errors were encountered:

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

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

    Sonar: Remove this useless assignment to variable "locale" #12472. Closed 1 task done. qmonmert opened this issue Sep 10, 2020 · 3 comments · Fixed by #12504. ... Launch analysis ./mvnw -Pprod clean verify sonar:sonar; Related issues Suggest a Fix. Delete the line locale = TranslatorContext.context.locale; JHipster Version(s) Current version.

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

  9. Remove Assignments to Parameters

    The reasons for this refactoring are the same as for Split Temporary Variable, but in this case we're dealing with a parameter, not a local variable. First, if a parameter is passed via reference, then after the parameter value is changed inside the method, this value is passed to the argument that requested calling this method.

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

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

    Find and fix vulnerabilities Codespaces. Instant dev environments ... carldebilly changed the title S1481 False Positive S1481 False Positive "Remove this useless assignment to local variable 'x'" Feb 28, 2020. ... 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)

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

    All groups and messages ... ...

  13. remove this useless assignment to local variable sonar fix java

    CodeQL overview; Writing CodeQL queries; CodeQL query help documentation » CodeQL query help for C# » Useless assignment to local variable ¶ Click to see the query in the CodeQ

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

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

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

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

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

  18. c#

    SONAR Issue "Method parameters, caught exceptions and foreach variables should not be reassigned" ... remove this useless assignment to local variable c#. 0 ... Sonar issue - Remove this useless assignment to local variable. 3 SonarQube null pointers should not be dereferenced on try/catch. 1 Sonarqube - Catches should be combined ...

  19. False Positive useless assignment to local variable #3115

    Find and fix vulnerabilities Codespaces. Instant dev environments ... SonarSource / sonar-dotnet Public. Notifications You must be signed in to change notification settings; Fork 226; ... The warning is "remove this useless assignment to local variable". Known workarounds. Related information.