Reassigned local variable java что такое
Перейти к содержимому

Reassigned local variable java что такое

  • автор:

IDEA сплошное подчеркивание серым — что это? [дубликат]

введите сюда описание изображения

Что означает такое вот подчеркивание?

Отслеживать
задан 10 янв 2019 в 15:44
user224616 user224616

По поводу вашей правки: нет, не «могут изменяться», а именно что изменяются. В показанном вами коде requestLocale тоже «может изменяться», но не подчёркивается, потому что не изменяется

12 янв 2019 в 15:05

Я имел в виду, если if -ы не сработают, то locale не изменится, т.е. именно МОГУТ изменяться, а не изменяются

– user224616
12 янв 2019 в 15:12

Ваша интерпретация интересена, но, подозреваю, для анализатора кода не применима: с его точки зрения, если есть locale = — значит считаем за изменение, даже если завернуть в if (false) и реального изменения никогда не произойдёт — всё равно подчеркнётся (я не проверял, но подозреваю, что так и будет, проверьте на всякий случай)

Reassign parameter to local variable

Is this just some cargo-cult practice that some programming teachers pass on, or are there coding style guidelines that actually recommend it? The only justification I can think of for this would be in languages that pass parameters by reference, if the function needs to reassign the variable without affecting the caller’s variable. Is this a legacy of instructors who grew up learning Fortran, which passes all parameters by reference? Most other languages with by-reference parameters require them to be declared explictly, as in C++’s type &parameter declaration, and in these cases it’s usually desirable to modify the caller’s variable. This style of coding for variables that are reassigned is discussed in Is there a reason to not modify values of parameters passed by value?. But I also see this in functions that only read the variable. For instance, this question has a function like this:

function say(messages = []) < let alphabets = []; let textLines = messages console.log(textLines.length) textLines.forEach((line, i) =>< if (i < textLines.length - 1) line.text += " "; // more code >); >); 

It could just as easily be written with textLines as the parameter name.
asked Oct 5, 2022 at 18:46
324 2 2 silver badges 5 5 bronze badges

2 Answers 2

It will happen if you want a different name for the parameter at the caller side and for the argument on the callee side. The developer making the call and the developer implementing the function can have different views of things.

Another situation are parameters being references and you don’t want to unintentionally modify the original, or read-only, or you want both a modified value and the original value.

So there are cases where it makes sense and cases where it doesn’t. If you see it, probably not worth changing.

answered Oct 6, 2022 at 10:27
gnasher729 gnasher729
43.6k 4 4 gold badges 61 61 silver badges 124 124 bronze badges

But we’re talking about exercise code, not code implementing an API with pre-ordained parameter names. The programmer gets to decide what the variables are named.

Oct 6, 2022 at 13:41

Is this just some cargo-cult practice that some programming teachers pass on,

There are millions of teachers all over the world, so how shall we know?

or are there coding style guidelines that actually recommend it?

I have never seen one, but the situation is not different than the former: there are too many coding standards all over the world to answer this.

Hence I think it is impossible to answer this generically «for all questions on SO which use this style» in a sensible manner. One has to look at each individual case, review the code or ask the authors for their reasons. So please do yourself a favor and stop asking questions which wrongly assume the existence of some overgeneralizated answer.

In your specific example, however, I guess the two different names simply reflect the different points of view of the interface vs. implementation:

  • on the caller’s side, the function signature is just say(messages) . The name messages just gives the caller a hint what the parameter should contain.
  • from the implementors’s point of view, those messages may be interpreted as text lines, so they will be given a different name. The primary context is here the internal agorithm. This is hidden from the caller, since it is an implementation detail.

So introducing a alias name can make sense in certain situations. However, for other situations there might be different reasons, or it is quite unneccessary — one has to look at each individual case.

Notification saying «Reassigned local variable» in Android Studio

My string is getting underlined, with a notification saying «Reassigned local variable» . I have worked out that this happens any time that the string is modified, but I am not sure why this notification is coming up. It doesn’t appear do be causing any errors, and nothing is showing under the «problems» tab, so I’m not sure if it is something I should change or if I should just ignore it. Below is a simplified version of the code.

Canvas canvas; Paint p = new Paint(); String value = "a"; //'value' here becomes underlined if(someCondition()) value += "bcdefghijklmnop"; //'value' here becomes underlined canvas.drawText(value, 50, 50, p); 

asked Dec 22, 2022 at 22:24
29 1 1 silver badge 7 7 bronze badges
Whats the question? Do you want to avoid re-assigning the local variable or remove the notification?
Dec 22, 2022 at 22:29

1 Answer 1

It is just a notification, probably because sometimes reassigned local variables can cause problems for later operations. In your case it is totally legit to reassign, just be aware that it will create several new objects.

If you would like to prevent this, you could work with a StringBuilder here that you convert to a String whenever necessary, but this also creates a new String object, so if you don’t use this in a loop usually it is not necessary to change anything (and for the string manipulation in a loop you probably will get a warning, a stronger sign for a potential problem in your code than this actual notification).

Reassigned local variable java что такое

Most local variables are declared and initialized on the same line, at the point in the method where both its initial value is available and the variable itself is immediately useful.

Declaring local variables without using them immediately may unnecessarily increase their scope. This decreases legibility, and increases the likelihood of error.

There are two common cases where a local variable is assigned some default initial value (typically null, 0, false, or an empty String ):

  • variables which need to be visible outside of a try block, and are thus declared and initialized just before the try block (in modern code using try-with-resources, this is now relatively rare)
  • some loop variables, which are initialized to some default value just before the loop

Here, input and output are examples of local variables being initialized to null , since they need to be visible in both the try and finally blocks.

As well, line is an example of a loop variable declared and initialized outside the loop.

Note that this example uses JDK 6, simply to illustrate the point. In JDK 7, try-with-resources would be used to automatically close streams, and the issue of stream references being initialized to null would not occur.

import java.io.*; /** JDK 6 or before. */ public final class ReadWriteTextFile < /** * Fetch the entire contents of a text file, and return it in a String. * This style of implementation does not throw Exceptions to the caller. * * @param file is a file which already exists and can be read. */ static public String getContents(File file) < //. checks on aFile are elided StringBuilder contents = new StringBuilder(); try < //use buffering, reading one line at a time //FileReader always assumes default encoding is OK! BufferedReader input = new BufferedReader(new FileReader(file)); try < String line = null; //not declared within while loop /* * readLine is a bit quirky : * it returns the content of a line MINUS the newline. * it returns null only for the END of the stream. * it returns an empty String if two newlines appear in a row. */ while (( line = input.readLine()) != null)< contents.append(line); contents.append(System.getProperty("line.separator")); > > finally < input.close(); >> catch (IOException ex) < ex.printStackTrace(); >return contents.toString(); > /** * Change the contents of text file in its entirety, overwriting any * existing text. * * This style of implementation throws all exceptions to the caller. * * @param file is an existing file which can be written to. * @throws IllegalArgumentException if param does not comply. * @throws FileNotFoundException if the file does not exist. * @throws IOException if problem encountered during write. */ static public void setContents( File file, String contents ) throws FileNotFoundException, IOException < if (file == null) < throw new IllegalArgumentException("File should not be null."); > if (!file.exists()) < throw new FileNotFoundException ("File does not exist: " + file); > if (!file.isFile()) < throw new IllegalArgumentException("Should not be a directory: " + file); > if (!file.canWrite()) < throw new IllegalArgumentException("File cannot be written: " + file); > //use buffering Writer output = new BufferedWriter(new FileWriter(file)); try < //FileWriter always assumes default encoding is OK! output.write( contents ); > finally < output.close(); >> /** Simple test harness. */ public static void main (String. arguments) throws IOException < File testFile = new File("C:\\Temp\\blah.txt"); System.out.println("Original file contents: " + getContents(testFile)); setContents(testFile, "The content of this file has been overwritten. "); System.out.println("New file contents: " + getContents(testFile)); > >

Java Practices 3.012
© 2023 John O’Hanley
Source Code | Contact | License | RSS
Individual code snippets have a BSD license
Over 1,000,000 unique IPs last year
Last updated 2023-01-03
— In Memoriam : Bill Dirani —

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *