Deactivate a variable after use

Is there some kind of annotation that allows me to tell the java compiler that the variable should not be used after the annotation? Thanks to the autocomplete and copy functions in modern IDEs, it is too simple introduction of errors, erroneous variable names. Such annotations will help to detect some of these errors during compilation (or when entering time if you use smart IDEs such as netbeans / eclipse). As an example, I have the following string pipeline:

String input = .... String pass1 = op1 (input); ... String pass2 = op2 (pass1); ... String pass3 = op3 (pass1); // typo: pass1 should be pass2 ... return pass3; 

If I could say something like disable pass1 right after the line where op2 is called op2 typo in the line where op3 is op3 will be detected as pass1 being out of scope as a result of the hypothetical disable annotation.

+5
source share
2 answers

No, you cannot deactivate variables in Java. Alternatively, reuse variables instead of creating new ones:

 String input = .... String currentPass = op1 (input); ... currentPass = op2 (currentPass); ... currentPass = op3 (currentPass); ... return currentPass; 

In theory, a smart enough IDE could use java annotations to throw a warning. However, this is a bad idea. The syntax would be ugly and bind you to a specific IDE. In addition, there are no Java IDEs that implement this feature.

+3
source

You cannot "deactivate" variables as you describe / wish.

However, if you construct the block structure correctly, you can arrange for certain variables to be unavailable; eg.

 String input = .... { String pass1 = op1 (input); ... } String pass2 = op2 (pass1); // compilation error ... pass1 is out of scope. 

It is unclear whether this gives you sufficient control to achieve what you are really trying to do. But if I don't think about any alternatives that will work at compile time ...


Reusing the variables described in @Joshua is a different approach. This avoids the problem, rather than solving it directly.

+2
source

Source: https://habr.com/ru/post/1204999/


All Articles