Inspectopedia Help

Scope of variable is too broad

Reports any variable declarations that can be moved to a smaller scope.

This inspection is especially useful for Pascal style declarations at the beginning of a method. Additionally variables with too broad a scope are also often left behind after refactorings.

Example:

StringBuilder sb = new StringBuilder(); System.out.println(); sb.append(1);

After the quick-fix is applied:

System.out.println(); StringBuilder sb = new StringBuilder(); sb.append(1);

Locating this inspection

By ID

Can be used to locate inspection in e.g. Qodana configuration files, where you can quickly enable or disable it, or adjust its settings.

TooBroadScope
Via Settings dialog

Path to the inspection settings via IntelliJ Platform IDE Settings dialog, when you need to adjust inspection settings directly from your IDE.

Settings or Preferences | Editor | Inspections | Java | Data flow

Configure the inspection:

  • Use the Only report variables that can be moved into inner blocks option to report only those variables that can be moved inside deeper code blocks. For example, when the option is enabled, the movement will not be suggested for the sb variable above. However, it will be suggested for the following code:

    StringBuilder sb = new StringBuilder(a); if (flag) { sb.append(1); }
  • Use the Report variables with a new expression as initializer (potentially unsafe) option to report variables that are initialized with a new expression. This makes the inspection potentially unsafe when the constructor has non-local side effects. For example, when the option is enabled, the movement will be suggested for the foo variable:

    class Foo { static List<Foo> fooList = new ArrayList<>(); String bar; Foo(String bar) { this.bar = bar; fooList.add(this); } public static void main(String[] args) { // movement is possible even though is unsafe Foo foo = new Foo("bar"); System.out.println(fooList.size()); System.out.println(foo.bar); } }

Inspection options

Here you can find the description of settings available for the Scope of variable is too broad inspection, and the reference of their default values.

Only report variables that can be moved into inner blocks

Not selected

Report variables with a new expression as initializer<br>(potentially unsafe)

Not selected

Inspection Details

By default bundled with:

IntelliJ IDEA 2024.2, Qodana for JVM 2024.2,

Can be installed with plugin:

Java, 242.22892

Last modified: 11 September 2024