Uploaded image for project: 'Kogito'

  • KOGITO-7947

Sonarcloud - (Java) Unused assignments should be removed (28)

Icon: Task

  • Resolution: Done
  • Fix Version/s: None
  • Affects Version/s: None
  • Component/s: None
  • Labels: None
  • Epic Link: Fix SonarCloud reported issues in kogito-runtimes
  • Blocked: False
  • Blocked Reason: None
  • Ready: False
  • Original Estimate: 7h
  • Git Pull Request: https://github.com/kiegroup/kogito-runtimes/pull/2510
  • [QE] How to address?: ---
  • [QE] Why QE missed?: ---
  • SFDC Cases Counter:
  • SFDC Cases Open:
  • SFDC Cases Links:

Description

https://sonarcloud.io/project/issues?resolved=false&rules=java%3AS1854&id=org.kie.kogito%3Akogito-runtimes

A dead store happens when a local variable is assigned a value that is not read by any subsequent instruction. Calculating or retrieving a value only to then overwrite it or throw it away, could indicate a serious error in the code. Even if it’s not an error, it is at best a waste of resources. Therefore all calculated values should be used.

Attachments

kbowers@redhat.com

Time Tracking

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

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

Why unused variables is such an issue?

I was cleaning unused variables warnings one day, and I started to ponder, what exactly is the problem about them?

In fact, some of them even help in debugging (e.g. inspect exception details, or check the return-value before returned).

I couldn't find real actual risk in having them..

I do not mean lines that takes time of other programmers' attention, such as:

That is an obvious redundancy and distraction. I mean stuff like:

  • programming-practices
  • coding-style
  • patterns-and-practices

Community's user avatar

  • 35 You mean other than the fact that the programmer coming after you is going to have to spend time trying to figure out why they are there? –  Robert Harvey Commented Jan 18, 2017 at 15:59
  • 1 stackoverflow.com/questions/6088983/… –  Phil Commented Jan 18, 2017 at 16:01
  • 1 Your examples are harmless, but I've never seen cases like that referred to as "unused variables". Where are your warnings coming from? –  Jacob is on Codidact Commented Jan 18, 2017 at 16:19
  • 9 Well, ret is not unused. –  Robert Harvey Commented Jan 18, 2017 at 16:22
  • 4 You wrote " I mean stuff like catch (SomeException e) " - you are pretending there are other, similar cases. Enlighten me, which ones? I ask because in C# or C++, I have trouble to find a different situation for your case. –  Doc Brown Commented Jan 18, 2017 at 21:23

7 Answers 7

According to the frame you have given, it is hard to argue against those variables per se:

Take this for example. You are catching an exception and (perhaps) have code which deals with the exception in a proper way. The fact that you aren't using the actual instance of the exception does no harm, neither to the code flow nor to the understandability.

But what makes me think is when you write about the legitimation of »unused variables«

In fact, some of them even help in debugging

That is not the purpose of writing code: having to debug it later. In order to prevent misunderstandings, I have to say, that I am well aware, that oftentimes you have to fix your code; and sometimes debugging is the solution. But it should not be the first, what comes to your mind, when writing code, that you leave "anchor points", whose only purpose it is to make debugging easier.

Here it depends how complex stuff is and how that is related to the value, which is returned.

As a "Golden Rule", I would say the following:

If it helps understanding the purpose of the code, it is okay to incease redundancy in your code

or to put it otherwise:

Write your code as redundancy free as is necessary to understand later easily, what the code is doing

That results in: Most of the time, you should remove "debug"-variables .

Thomas Junk's user avatar

The biggest issue is clarity . If your code has a bunch of extraneous junk in it, and I am maintaining your code, I have to figure out what everything does.

Is that variable ever used for anything? Perhaps you do perform operations on it, but never use its value for something. Simply incrementing a variable doesn't mean the variable serves a purpose if you never read it (return, input into another expression, et al).

However: if a variable has a purpose and is named appropriately it does not detract from the code as a whole.

Given the examples in your updated question and some others I thought of:

Having a function that calls another function, stores the result, logs it, then returns it is a pretty short and clear.

Splitting a statement with multiple expressions into multiple statements (e.g. splitting a long, complex calculation into multiple statements with multiple intermediate variables) can make the code more clear despite being more verbose. With less information to process at a time, the brain can more easily grok what is going on.

Not using exceptions is perfectly fine: most languages require specifying the exception being caught including providing a variable name to be used in the catch block. There is no way around this in many popular languages and programmers are used to it.

If I need to spend time figuring out what code elements have a purpose and which are only wasting my time, my productivity decreases. However, if the code is fairly concise and variables are well-named even when they appear to be extraneous at first, this mitigates the risk of wasting unnecessary time reviewing the code to understand it.

Bad code with extraneous variables, empty blocks, and dead code is one way developers get a bad reputation around the office: "I was fixing a bug in Snowman's code. I spent two hours figuring out what that function was doing, and thirty seconds fixing the bug! Snowman is terrible at programming!" But if the code serves a purpose and is written in a clear manner, it is perfectly fine.

  • 9 +1 for "Snowman is terrible at programming." I always suspected. How can you be a good programmer when your fingers are always melting? –  Robert Harvey Commented Jan 18, 2017 at 16:18
  • See my edit - I don't mean mere variables created out of the blue for no purpose, just those that may assist here and there during debug, or just generated by one of those automatic tools like catch blocks. –  Tar Commented Jan 18, 2017 at 16:22
  • 1 @Tar that changes the entire question - edit incoming. –  user22815 Commented Jan 18, 2017 at 16:24
  • Note that in your bulleted list of when you do this, the first two tend to not actually result in warning (I've never seen a language that produced a warning in such a case). For the third case, any language that requires the exception be given an identifier doesn't have a warning for it, and any that produce a warning for it don't require it to have an identifier (again, that I'm familiar with anyway). –  Servy Commented Jan 18, 2017 at 18:06
  • 2 Looking at the revision history I don't see any indication of the question fundamentally changing. As far as the OP's code goes, the first two will result in a warning in C# (which looks to be the language used). The third example would not result in a warning. The comments on the question also indicate that they're specifically indicated in compiler warnings, and when Robert pointed out that the third example doesn't produce a warning, the author conceded that it was a bad example for their question. –  Servy Commented Jan 18, 2017 at 19:17

Unused variables that serve no obvious purpose are a code smell in my view. At best, they can be a distraction - they add to the general noise in the module.

The worst case is that subsequent coders spend time figuring out what it was supposed to do and wondering if the code is complete. Do yourself (and everyone else) a favour and get rid.

Robbie Dee's user avatar

  • 1 What is a "bug" in your view? Unused variables do not produce unexpected, erroneous outcomes per se, which is what most people would qualify as a bug. –  Harris Commented Jan 18, 2017 at 16:14
  • 5 Why is the variable unused? Very likely because it should have been used, but another variable was used instead by mistake. You get a compiler warning, and you fix it and fix the bug at the same time. Problem is if you have an undisciplined programmer who leaves a mess around, you can't find where that kind of warning indicates a bug and where it just indicates a messy programmer. –  gnasher729 Commented Jan 18, 2017 at 19:38
  • @HarrisWeinstein Given testers and devs can't even agree what is a bug most of the time, I'm going to park that for now. Suffice to say it is a deficiency in the code - and possibly the executable as it will take up space. Admittedly, not the biggest problem in the world but up there with comment box spelling mistakes and commented out code. It is cruft that adds nothing so should be removed. Code that looks good inspires confidence. I think this quotation is also apt and covers the refactoring process well. –  Robbie Dee Commented Jan 18, 2017 at 19:52
  • If you're using a dynamic language, assigning a value to some_var when the rest of the code uses someVar is almost guaranteed to be a bug. This might not be problem in Java or C but it can easily break some Python. –  Sean McSomething Commented Jan 18, 2017 at 22:13
  • 1 @ThomasJunk That is probably a better term for it - thank you. I shall adjust my answer accordingly. –  Robbie Dee Commented Jan 19, 2017 at 10:39

Unused variables make the intent of your code unclear. This is bad because despite appearances, code is predominantly written for people to read, not for computers .

Others have already pointed out that constructing a value and not using it confuses other people who have to read and work with your code. However, in my view the greater danger is to yourself .

An unused variable might be intentional, or it might be an oversight pointing to a defect. For instance, you might have mistyped a name and stored a value in one place when you thought you'd stored it in another. The resulting program could run fine but silently give the wrong result.

Analysing data flow can help you find such errors and many others. Therefore it pays to write your code in such a way that everything a data flow analyser points out as an anomaly is, in fact, a bug. Automatic assistance in preventing bugs is invaluable; many people think "Oh, I don't need assistance, I would never be that careless", but so far everyone I've met who thought that was wrong.

Kilian Foth's user avatar

There is a coding style that involves deliberately assigning anything that was (or might become) of interest to a variable for the specific purpose of easily looking at it in a debugger. This is especially useful for code which looks like:

Even with somewhat better names for the functions, it can be easier to work out what's going wrong in the call to foo when written as:

I'm yet to work with people who practice this as the default configuration, but rewriting a piece of code which is stubbornly refusing to make any sense in single assignment form can make it easier to work out what's going on under the debugger. We always reverted the code back to compact, "pretty" format afterwards but I wonder whether that was a mistake.

The alternative is walking up and down the stack and hoping you don't step too far, or using (the distressingly rare) reversible debuggers.

It's not a popular strategy, but as it's helped me work through some absurd bugs I don't think it should be written off as intrinsically bad.

Pete Kirkham's user avatar

  • While I probably wouldn't go as far as you did I find your first "pretty" form too compact. –  Loren Pechtel Commented Jan 19, 2017 at 2:45
  • 1 Except that there isn't a single unused variable in your code. –  Florian F Commented Jan 19, 2017 at 21:10
  • 1 On the positive side, if you were to get a warning about unused variables, you would know that somewhere in that transformation you committed some major blunder. Which would be easy to fix. –  gnasher729 Commented Jan 19, 2017 at 21:45

For people who include their unit test code in the same projects or modules as their "real" code, an unused field , like an object method, is a strong signal that your unit tests aren't testing everything. This increases the chance that a developer will try to use that currently unused field or method, and run into a bug that wasn't being caught until then.

An unused variable in a somewhat nontrivial subroutine or method may indicate that the programmer meant to use it, but is using another variable by mistake (say, after cleaning up after a copy-paste operation).

An unused variable in a more trivial subroutine is probably either unnecessary dross, as other people have answered. Occasionally, it's used in a breadcrumb statement that's currently commented out:

...it's clear to the eyeball that it's used there, and only there (i.e. someMethod has an important side effect), but the IDE doesn't know that, and removing that variable is more trouble than it's worth. I tentatively use warning suppressors in such cases.

Paul Brinkley's user avatar

  • 1 I'm wondering under what circumstances you'd want to have commented-out code committed to your repository. But a similar situation arises when using conditional compilation (such as when using the assert macro in C or C++). Unused variable warnings can indeed be an annoyance there and suppressing them is the most reasonable response, if you ask me. –  5gon12eder Commented Jan 18, 2017 at 20:42
  • 1 I've edited my answer, adding a very rough example of what I've seen in the past. The block might be run many times, and something's collecting all the debug info in a log for analysis when tracing a problem, but printing is slow and so it's usually turned off. I could replace the first line with someMethod and lose info on where tmp came from. Or I could commit a clean version and forget that some past version had that useful breadcrumb (and lacked necessary code added in later versions). ...I've sought an ideal tradeoff on this for a long time now. –  Paul Brinkley Commented Jan 18, 2017 at 21:01
  • I see. Apparently, your language of choice does not have a pre-processor. ;-) –  5gon12eder Commented Jan 18, 2017 at 21:08
  • Currently, aye. :-) Although to be fair, I've seen this same sort of stuff in C and C++, and it likewise wasn't easy to get rid of unused variables in those cases, either (quasi-appendices?). ...The fact that my last big C/C++ project was done at a time when IDEs didn't exist (compiler warnings required running "gcc -pedantic") also didn't help. –  Paul Brinkley Commented Jan 18, 2017 at 21:18

It is easy when you write code to mix up two variables. You compute a variable B but then use instead some variable A created earlier.

So a possible reason for an unused variable is that there is a mistake in your code. That is why the compiler warns you. If you "don't do" unused variables, it is even a dead giveaway.

When you see such a warning, you should verify your code and either fix it or remove the offending variable. If you don't remove it, you will stop paying attention to these warnings, and you might just as well disable them completely. But then you will eventually loose an afternoon debugging the code because of one silly mistake.

Florian F's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Software Engineering Stack Exchange. 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 programming-practices coding-style patterns-and-practices warnings or ask your own question .

  • The Overflow Blog
  • Where developers feel AI coding tools are working—and where they’re missing...
  • He sold his first company for billions. Now he’s building a better developer...
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network

Hot Network Questions

  • How is the universe able to run physics so smoothly?
  • Double 6x6 Beam
  • A scrambled word which can't be guessed without all of its letters
  • Image localisation and georeference
  • Is there a faster way to find the positions of specific elements in a very large list?
  • Why does Voyager use consumable hydrazine instead of reaction wheels that only rotate when moving the spacecraft?
  • How do I link a heading containing spaces in Markdown?
  • cURL in bash script reads $HOME as /root/
  • Could you compress chocolate such that it has the same density and shape as a real copper coin?
  • What does mean by "offer accepted" in Mathjobs portal?
  • Is there any reason _not_ to add a flyback diode?
  • Can a floppy disk be wiped securely using the Windows format command with the passes-parameter?
  • Does the Rogue's Evasion cost a reaction?
  • Soldering a thermal fuse. 92°C
  • How can moving observer explain non-simultaneity?
  • Short story about a space traveller on a planet of people, each immensely talented
  • Does a ball fit in a pipe if they are exactly the same diameter?
  • What is the meaning of "I apply my personality in a paste"?
  • Could a Project like Orion be built today with non nuclear weapons?
  • Tic-tac-toe encode them all
  • What is the mechanical equivalent of an electronic AND gate?
  • Why would an escrow/title company not accept ACH payments?
  • I want a smooth orthogonalization process
  • Could you suffocate someone to death with a big enough standing wave?

unused assignments should be removed java

no-useless-assignment

Disallow variable assignments when the value is not used

Wikipedia describes a “dead store” as follows:

In computer programming, a local variable that is assigned a value but is not read by any subsequent instruction is referred to as a dead store .

“Dead stores” waste processing and memory, so it is better to remove unnecessary assignments to variables.

Also, if the author intended the variable to be used, there is likely a mistake around the dead store. For example,

  • you should have used a stored value but forgot to do so.
  • you made a mistake in the name of the variable to be stored.

Rule Details

This rule aims to report variable assignments when the value is not used.

Examples of incorrect code for this rule:

Examples of correct code for this rule:

This rule will not report variables that are never read. Because it’s clearly an unused variable. If you want it reported, please enable the no-unused-vars rule.

When Not To Use It

If you don’t want to be notified about values that are never read, you can safely disable this rule.

Related Rules

  • no-unused-vars

This rule was introduced in ESLint v9.0.0-alpha.1.

Further Reading

Avatar image for en.wikipedia.org

  • Rule source
  • Tests source

ReSharper 2024.2 Help

Code inspection: unused local variable.

Category : Redundancies in Symbol Declarations

ID : UnusedVariable

EditorConfig : resharper_unused_variable_highlighting=[error|warning|suggestion|hint|none]

Default severity : Warning

Language : C#, VB.NET

Requires SWA : No

This inspection detects local variables in a method that are declared and may be assigned, but are never used. Such a variable might act only once as the recipient in an assignment statement, without read usages, for example:

Unused variables impair readability of the code, especially in longer functions. Anyone who reads this code will take some time to understand what is the purpose of a variable and why it was assigned a specific value, only to find out that the variable is never read and does not affect the program in any way. Therefore, you should either actually use variables or remove them. ReSharper suggests removing all detected unused variables with a quick-fix.

ReSharper also offers an additional quick-fix — Indicate unused variable with name . You can select a meaningful name for it ( _ , dummy , or unused ), to indicate that the variable is unused deliberately. With these names, ReSharper will not highlight the variable as unused.

IDE extension that lets you fix coding issues before they exist!

Setup is effortless and analysis is automatic for most languages

Self-Hosted

Fast, accurate analysis; enterprise scalability

Unused assignments should be removed.

Why is this an issue?

What is the potential impact, how can i fix it.

Computing or retrieving a value only to then immediately overwrite it or throw it away indicates a serious logic error in the code.

Assigning a value to a local variable that is not read by any subsequent instruction is called a dead store . The following code snippet depicts a few dead stores.

Even if the unnecessary operations do not do any harm in terms of the program’s correctness, they are—​at best—​a waste of computing resources. In most cases, these operations have their intended use but it is not expressed correctly in the code. Therefore, unused values and superfluous code should be removed to prevent logic errors.

  • Artificial Intelligence
  • Generative AI
  • Cloud Computing
  • Data Management
  • Emerging Technology
  • Technology Industry
  • Software Development
  • Microsoft .NET
  • Development Tools
  • Open Source
  • Programming Languages
  • Enterprise Buyer’s Guides
  • Newsletters
  • Foundry Careers
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Copyright Notice
  • Member Preferences
  • About AdChoices
  • E-commerce Affiliate Relationships
  • Your California Privacy Rights

Our Network

  • Computerworld
  • Network World

dustin_marx

NetBeans 7.1’s Unused Assignment and Dead Branch Hints

One of the new code hints provided by NetBeans 7.1 is the Unused Assignment hint. A simple code sample that will cause this hint to be displayed in NetBeans 7.1 is shown next.

Demonstrating Unused Assignment

In the code above, the local variable “i” is initialized to 2, but is never used and then is initialized again, making the first initialization unnecessary. The next image is a screen snapshot that shows NetBeans 7.1 displaying a warning code hint for the unused assignment.

As the above image indicates, NetBeans 7.1 warns of “The assigned value is never used.”

The New And Noteworthy in NetBeans IDE 7.1 page mentions this hint among others and states:

Unused Assignment A new pair of hints, Unused Assignment and Dead Branch, was introduced. The Unused Assignment finds values that are computed and assigned to a variable, but never used by reading the variable. The Dead Branch hint searches for branches of code that can never be executed.

Oh Dead Branch Hint, Where Art Thou?

The Unused Assignment Hint seems to work as suggested based on the example shown above. However, I have not been able to generate code that demonstrates the “Dead Branch” hint. I wonder if the Dead Branch hint is not yet supported and text related to it is not supposed to be under the “Unused Assignment” heading.

The following code contains a listing with several methods that I would expect might potentially lead to a warning about a dead code branch. None of these cause this code hint to appear in any form (warning or error) in my installation of NetBeans 7.1.

Methods With Compilable Dead Code Branches

Although none of the methods in the directly previous code listing lead to the Dead Branch code hint, NetBeans 7.1 does include configuration options for the Dead Branch hint. This is shown in the next screen snapshot (selecting Tools->Options followed by the “Editor” tab and then selecting “Hints”).

The NetBeans 7.1 News and Noteworthy page shows examples of other new hints , but does not show an example of the Dead Branch hint. Also, the text talking about Dead Branch is mixed with the section on Unused Assignment and under a heading that only talks about Unused Assignment. As my previous code listing demonstrates, I attempted to come up with a code sample to demonstrate the Dead Branch hint, but have not been able to do so. The purpose of this hint (“search[ing] for branches of code that can never be executed”) sounds like a nice complement to compiler errors such as “ unreachable statement ” and “ exception already caught ” and other NetBeans “green” warnings such as “variable such-and-such is not used.”

I have blogged about NetBeans hints before and the addition of new hints in NetBeans 7.1 is welcome. If anyone knows of a code sample that will demonstrate the Dead Branch hint in NetBeans 7.1, please share!

Original posting available at https://marxsoftware.blogspot.com/ (Inspired by Actual Events)

unused assignments should be removed java

Related content

Packages and static imports in java, how to describe java code with annotations, thread behavior in the jvm, what is the jdk introduction to the java development kit.

dustin_marx

Dustin Marx is a principal software engineer and architect at Raytheon Company. His previous published work for JavaWorld includes Java and Flex articles and " More JSP best practices " (July 2003) and " JSP Best Practices" (November 2001).

More from this author

Javascript objects from a java developer’s perspective, codehaus: the once great house of code has fallen, manipulating jars, wars, and ears on the command line, java extension mechanism loads all jars, choiceformat: numeric range formatting, big java news in late summer 2014, autoboxing, unboxing, and nosuchmethoderror, books that have most influenced my software development career, show me more, eclipse working group to address cybersecurity, ai regulations.

Image

Intro to Node's built-in SQLite module

Image

Google suite leverages conversational AI for customer support

Image

How to implement "modes" in software, with a game as an example

Image

Powerful Python source code processing with "ast"

Image

The power of Python enums

Image

Sponsored Links

  • Visibility, monitoring, analytics. See Cisco SD-WAN in a live demo.
  • OpenText Financial Services Summit 2024 in New York City!

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:

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.

Is critical SonarLint issue S1166 in my Java code a false positive or not?

SonarLint 1.0.0 for Eclipse flags a critical issue in my code and I can't see why and how to fix it. It really looks like a false positive to me—or am I missing something? Here's an excerpt of t...

sonarqube giving false positive with the rule "Unknown type selectors should be removed" when trying to style a custom HTML tag

We have used angular custom directive to generate a custom html tag called .The corresponding style sheet file for this tag is student.scss and its content is Can anybody suggest any way to resolve th...

False Positive eslint(no-unused-vars)

Here you can see I have a very simple react component, but the eslint rule is giving me a false positive. Config Details package.json .eslintrc.js ESLint doesn't know React semantics for variable usag...

pylint false positive for unused argument

I'm in the process of cleaning up code with pylint in order to be able to use it for pre-commit validation. I have a lot of "unused-argument" warning when in fact they are used. Here is an e...

False positive "Missing include" xslt error in eclipse

I have an xslt file in my eclipse project. The xslt is run using a custom processor, which contains some xslt files as an in-jar resource. The xslt linter does not see those resources, and signals an ...

Eclipse indexer shows false-positive semantic errors

I've recently updated to Eclipse Mars.2 (version 4.5.2) and switched my project to C++11 development (yeah, it's about time!). I've managed to configure all my Makefiles to build correctly (ie. no obv...

Rails Best Practices false positive unused methods

I'm using Rails best practices to validate my own code. The actions here are mostly unused methods. The only problem is that those actions aren't even defined... I tried to use remove_method without a...

Using SonarLint in eclipse

I am trying to learn how to use SonarLint plugin in Eclipse. I downloaded the plugin and I have 4 views in my Eclipse now - SonarLint on the Fly, SonarLint Report, SonarLint Rule Description, SonarQub...

Sonarlint Eclipse StackOverflowError

SonarLint for Eclipse crashes with the following scenario: Create a couple of files in the same package: Menu.java SomeClass.java When SonarLint analyzes the SomeClass.java, a crash occurs with Eclips...

Eclipse formatter with checkstyle and sonarlint

I have this plugins installed and it seems that the Eclipse Formatter is not taken into consideration. For instance, I have my chain funtions to look like the below code in Formatter: But when I ask e...

Python Efficiency / Optimization Project Euler #5 example

I wrote this solution to Project Euler #5. Takes my system about 8.5 seconds. Then I decided to compare with other peoples solutions. I found this Project Euler 5 in Python - How can I optimize my sol...

how to update value of Qsetting while changing value in inputbox with connect statement in QT

I just want to update the value in Qsettings while changing in Qlineedit using connect statement only means I dont want to make any function for update value in Qsettings. The simplest way to achieve ...

handling to onchange event of AutoCompleteTextField in wicket

I'm writing an autocomplete component for a webapp using Java and Wicket. Is there a way to handle the onchange event to run some code when the user selects one of the options of the autocomplete list...

Change textfield to textareafield

I need to change xtype from textfield to textareafield basing on a condition. I need to do something like this, but I cant update xtype or i can use the viewmodel, but xtype is not bindable Exactly: y...

SQL: How To Find The Top String Column Value in a Grouped Query

When grouping is there a simple way to get the first or top value out of a column. In the following example I want the last value in [Text] if sorted by [Date] descending. Thanks in advance. If you wa...

  • SonarQube false-positive "unused private methods should be removed" in static method
  • Unused method parameters should be removed (squid:S1172) false positive using lambda
  • MAJOR: Unused private method should be removed - postConstruct Annotation - false positive
  • SonarLint - RedundantThrowsDeclarationCheck - false positive?
  • SonarLint Rule S1172 "Unused method parameters should be removed" and EventHandlers
  • Java method with @Inject annotation: False-positive for the rule "Unused "private" methods should be removed"?
  • False Unused "private" methods should be removed
  • False positives against flex:S1172 - Unused function parameters should be removed
  • False Positives on S1172 - "Unused method parameters should be removed"
  • SonarLint connected to SonarQube not using "won't fix" or "false positive" from server
  • How to add certificates to SonarLint in Eclipse
  • Sonarlint installed on eclipse Kepler but not found
  • SonarLint hint hiding Eclipse tooltip
  • Setting source files for Sonarlint in Eclipse
  • Install sonarlint plugin in eclipse offline
  • SonarLint plugin not working in Eclipse Oxygen
  • Update SonarQube rules in SonarLint eclipse
  • Connecting sonarlint with eclipse and sonarqube error
  • Where is the Sonarlint Ruleset file in eclipse?
  • Spring boot test: Test passes, but should not (false positive)
  • Mutable members should not be stored or returned directly - com.google.common.collect.ImmutableList - "false positive"
  • Methods and field names should not differ only by capitalization (squid:S1845) false positive
  • Sonar false-positive on rule: Null pointers should not be dereferenced
  • @typescript-eslint/no-unused-vars false positive in type declarations
  • Eclipse null analysis raises false positive NullPointerException warning
  • Eclipse - Sonar S2629 possible false positive with new String
  • SonarLint on eclipse : Unable to start standalone SonarLint engine
  • How to use SonarLint in Eclipse
  • Unable to install Sonarlint on Eclipse
  • How to show SonarLint in Eclipse?
  • How to choose what code to put in a View vs. a ViewController?
  • Use macs alias folders in R
  • How to read a file containing numbers in Octave using textscan
  • Aspose DataSet.readXml producing more complicated structure
  • Quadtree and division into equal subquadrants
  • mule remove json elements from json array
  • Inconsistent behavior of SVN Info with externals
  • user isn't authenticated in custom authorize attribute
  • Node JS - No such file?
  • Javascript - graph traversal - return shortest path

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

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

@pavel-mikula-sonarsource

volgunin commented Feb 17, 2020

When a variable is used inside local function, is raised.

No warning.

warning : Remove this useless assignment to local variable 'buffer'.

  • 👍 8 reactions

@pavel-mikula-sonarsource

andrei-epure-sonarsource commented Feb 28, 2020 • edited Loading

We see this in our own project as well ( )
putting a screenshot for the reference, as sonarcloud link will become onbsolete once we fix this

Sorry, something went wrong.

@paulhickman-a365

paulhickman-a365 commented Apr 3, 2020

I have encountered a similar case, but rather than calling the local function that uses the variable, I'm passing it as a delegate to another function to be called:

Sonar Analzyer Version: 8.4.0.15306

@sarahelsaig

pavel-mikula-sonarsource commented Oct 9, 2020

Another example on

@costin-zaharia-sonarsource

costin-zaharia-sonarsource commented Apr 21, 2021

And another one:

@github-actions

Successfully merging a pull request may close this issue.

@volgunin

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

SonarLint Rule S1172 "Unused method parameters should be removed" and EventHandlers

How should I fix SonarLint Rule S1172 "Unused method parameters should be removed" when I create EventHandler methods.

You could rewrite the code with Reactive Extensions and making 'Observables' but that is quite complex solution for simple event handlers. Another option could be to rewrite the code like:

But the question then is how do you do the UnSubscribe() ? By my opinion the unused parameters is not applicable to event handler methods. But it might be difficult to make detection for that in SonarLint.

  • visual-studio-2015

Niek Jannink's user avatar

  • As mentioned below, storing the delegate in a field is an option. But I think we should handle this issue properly in SonarLint if this is a common scenario. My feeling is that if you don't need the sender and the EventArgs at all, then you could use a custom delegate which doesn't have those. But this only works if you control the type of the event. Is this the case? Do you have subscribers that need those two parameters? Do you think this goes against event handling best practices? –  Tamas Commented Aug 19, 2015 at 6:32
  • I think its a design guideline that events always should be (derived) of the type EventHandler . So that means you will always get the sender and EventArgs . So even tho the subscribers don't use those parameters all events in the .Net framework are build using this paradigm and so SonarLint should be able to handle this. I think resharper correctly recognises event handling methods and ignores the unused parameters of these. –  Niek Jannink Commented Aug 19, 2015 at 9:23
  • Thanks, let's continue the discussion on github.com/SonarSource/sonarlint-vs/issues/211 –  Tamas Commented Aug 19, 2015 at 15:14
  • This seems a C# or VisualStudio feature , but indeed raises other questions, see my question: stackoverflow.com/q/41162335/1845672 . btw the discussion link at github is dead –  Roland Commented Dec 15, 2016 at 11:22

If you need to unsubscribe, you'll need to store the delegate (remove static for proper code, this is pasted from a hacked console app project):

Or use a mass-unsubscribe :

Or if you own the event, you could also use this to unsubscribe all:

Or just use the syntax you've always used and create a non-anonymous method, like you show above. There's nothing wrong with that syntax. You could do the obligatory

to get rid of the warning ;)

Community's user avatar

  • PS: I think this should be treated as a bug in S1172. –  jessehouwing Commented Aug 18, 2015 at 17:47
  • This doesn't solve my issue. Having to store the EventHandler in a field to resolve the Rule warning S1172 doesn't seem the correct way to resolve the warning. So yea I would also say its a bug in S1172 –  Niek Jannink Commented Aug 18, 2015 at 18:52
  • Just add the ArgumentNullChecks ;). If you do start to use the parameters, it's the next SonarLint error you'll run into ;). –  jessehouwing Commented Aug 18, 2015 at 18:54
  • Raised over at the SonarLint issues on GitHub: github.com/SonarSource/sonarlint-vs/issues/211 –  jessehouwing Commented Aug 19, 2015 at 8:02

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 c# visual-studio-2015 sonarlint or ask your own question .

  • The Overflow Blog
  • Where developers feel AI coding tools are working—and where they’re missing...
  • He sold his first company for billions. Now he’s building a better developer...
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Should low-scoring meta questions no longer be hidden on the Meta.SO home...
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Let's say Kant was right about Transcendental Idealism, what further conclusions would you come to about reality and our existence?
  • How old was Abraham when Rebecca (Isaac's wife) was born?
  • Better way to share JavaScript code
  • Thunderbird will not create profile in chosen folder on a different partition
  • When can I book German train tickets for January 2025?
  • I want a smooth orthogonalization process
  • Neil Tyson: gravity is the same every where on the geoid
  • What is the actual relationship between partition coefficient (logP or clog P) and Retention factor (Rf) value?
  • What is the mechanical equivalent of an electronic AND gate?
  • A scrambled word which can't be guessed without all of its letters
  • Purpose of sleeve on sledge hammer handle
  • Tic-tac-toe encode them all
  • Can I breed fish in Minecraft?
  • What exactly do I buy when I buy an index-following ETF?
  • Is a private third party allowed to take things to court?
  • What evidence exists for the historical name of Kuwohi Mountain (formerly Clingmans Dome)?
  • Is the Earth still capable of massive volcanism, like the kind that caused the formation of the Siberian Traps?
  • Is there an AGPL 3.0 ONLY license?
  • Will a car seat fit into a standard economy class seat on a plane?
  • Short story about a space traveller on a planet of people, each immensely talented
  • Prevent push upgrades (auto and manual) entirely for version X.X
  • How can I draw a wedge of a cylinder?
  • Is "into" a verb in this sentence?
  • How do you tell someone to offer something to everyone in a room by taking it physically to everyone in the room so everyone can have it?

unused assignments should be removed java

IMAGES

  1. java

    unused assignments should be removed java

  2. Please remove unused versions of Java

    unused assignments should be removed java

  3. How to Remove all Unused Imports in a Java File

    unused assignments should be removed java

  4. java的unused import statement解决方法-CSDN博客

    unused assignments should be removed java

  5. Java Basics: Looping (UNEDITED AND UNCENSORED) Homework Assignment for

    unused assignments should be removed java

  6. How To Do Assignments In Java?

    unused assignments should be removed java

VIDEO

  1. Pattern matching with unnamed pattern in action #JEPCafe #Java #Java21

  2. Management and Organizational Behaviour, (MBAZ 503): Assignment Tips

  3. Java || CSE110 || sequences a & b || Task 01 || Assignment-04 || CW-01

  4. Recover Deleted Course Content (e.g., Assignment, Discussion, Page, File etc.) in Canvas LMS

  5. Java 17 Sealed Classes introduction

  6. Understanding Java Garbage Collection and what you can do about it

COMMENTS

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

  2. Sonarcloud

    Sonarcloud - (Java) Unused assignments should be removed (28) Log In. Closed. Export. null View workflow XML Word Printable. Details. Type: Task Resolution: Done Priority: Minor . Fix Version/s: None Affects Version/s: None Component/s: None ...

  3. Rule Request: AvoidUnusedAsignments #220

    Sonar rule - java:S1854 - Unused assignments should be removed leads to a lot of false positives which makes the rule unusable. Create a rule which detects unused assignments. example: String doodle = "init"; // bad, assigned value overw...

  4. S1854 ignore increments and decrements when value is used #3290

    S1854 - Unused assignments should be removed: FP Example * Array index * Function argument * Null example * Another null example: Explanation. This rule raises issues for increment and decrements operators, even when the result of the expression is used.

  5. Java static code analysis

    Unused assignments should be removed Code SmellSections of code should not be commented out Code SmellUnused method parameters should be removed Code SmellUnused "private" methods should be removed Code SmellUnused "private" fields should be removed Code SmellUnused labels should be removed Code SmellPackages containing only "package-info.java ...

  6. programming practices

    So a possible reason for an unused variable is that there is a mistake in your code. That is why the compiler warns you. If you "don't do" unused variables, it is even a dead giveaway. When you see such a warning, you should verify your code and either fix it or remove the offending variable. If you don't remove it, you will stop paying ...

  7. Unused assignments should be removed #63

    Going to close this for now. While we could hack something together now, a more thorough treatment requires support for dataflow analysis that we haven't yet begun to design.

  8. no-useless-assignment

    "Dead stores" waste processing and memory, so it is better to remove unnecessary assignments to variables. Also, if the author intended the variable to be used, there is likely a mistake around the dead store. For example, you should have used a stored value but forgot to do so. you made a mistake in the name of the variable to be stored.

  9. Unused assignment

    Reports assignment values that are not used after assignment. If the assignment value is unused, it's better to remove the assignment to shorten the code and avoid redundant allocations. The following cases are reported: variables that are never read after assignment. variables that are always overwritten with a new value before being read.

  10. [java] UnusedAssignment should be able to ignore unused ...

    When you keep the defaults of the rule, you don't see reports of unused formal parameters so you cannot remove the parameter. What the violations of this rule mean is A named value is unused. Either 1. use it, 2. remove the assignment (or parameter), or 3. rename the variable to unused or so to make it clear this is intended.

  11. Code inspection: Unused local variable

    Therefore, you should either actually use variables or remove them. ReSharper suggests removing all detected unused variables with a quick-fix. ReSharper also offers an additional quick-fix — Indicate unused variable with name. You can select a meaningful name for it (_, dummy, or unused), to indicate that the variable is unused deliberately ...

  12. Unused assignments should be removed

    Assigning a value to a local variable that is not read by any subsequent instruction is called a dead store. The following code snippet depicts a few dead stores. int x = 0; // Noncompliant: dead store, next line overwrites x. x = 100; // Noncompliant: dead store, next line overwrites x. x = 200; int y = 0; y += 9001; // Noncompliant: dead ...

  13. 'Unused local variables and functions should be removed' reported for

    Remove the declaration of the unused 'ButtonIcon' variable. And... Unused local variables and functions should be removed. Expected behavior Whilst I appreciate the code could be rewritten to cast the variable name in the function declaration: const IconLabelButton = ({ icon: ButtonIcon, label, clickHandler }) => { ...

  14. NetBeans 7.1's Unused Assignment and Dead Branch Hints

    One of the new code hints provided by NetBeans 7.1 is the Unused Assignment hint. A simple code sample that will cause this hint to be displayed in NetBeans 7.1 is shown next.

  15. javascript

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

  16. [Sornalint]

    myMeritArr = emptyArr; 같이 사용자가 특성을 아무것도 지정하지 않고 저장 버튼을 눌렀을 경우 null 값이 들어와 에러가 발생해서 넣은 코드였는데 이런 에러가 떠버렸다... The text was updated successfully, but these errors were encountered: Assignees. No one assigned. Labels. None yet. Projects ...

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

    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.

  18. 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. Actual b...

  19. c#

    So even tho the subscribers don't use those parameters all events in the .Net framework are build using this paradigm and so SonarLint should be able to handle this. I think resharper correctly recognises event handling methods and ignores the unused parameters of these. -