Skip to main content

Code reviews rule: Unused variable

Written by David Martin

Unused variable

Why is this an issue?

A local variable that is declared and then never read is dead code. It makes the method harder to follow, and it is often the leftover of a half-finished edit where a value was meant to be used and never was.

If the declaration has an initializer, that work still runs at execution time, including a SOQL query whose result is thrown away.

Examples

Example of incorrect code:

public Integer compute() {
Integer a = 1; // never read
Integer b = 2;
return b;
}

Example of correct code:

public Integer compute() {
Integer b = 2;
return b;
}

How can I fix violations?

Delete the declaration. If the initializer has a side effect you need to keep, such as a DML statement or a method call that changes state, keep the call and drop the assignment.

Configuration options

You can configure whether variables whose name starts with an underscore (for example _unused) are allowed. This is enabled by default.

When should I disable this rule?

Only declarations inside a method body, a constructor body or a trigger body are considered, so fields, constants, catch variables and managed package classes are never reported.

Dismiss individual issues where a variable is consumed somewhere the analyzer cannot see. The most common case is a dynamic SOQL bind (:variableName) whose query text is assembled in another class.

Resources

Did this answer your question?