49 lines
1010 B
Plaintext
49 lines
1010 B
Plaintext
== Why is this an issue?
|
|
|
|
For the sake of clarity, variables should be declared as close to where they're used as possible. This is particularly true when considering methods that contain early returns and the potential to throw exceptions. In these cases, it is not only pointless, but also confusing to declare a variable that may never be used because conditions for an early return are met first.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,text]
|
|
----
|
|
public boolean isConditionMet(int a, int b) {
|
|
int difference = a - b;
|
|
MyClass foo = new MyClass(a); // Noncompliant; not used before early return
|
|
|
|
if (difference < 0) {
|
|
return false;
|
|
}
|
|
|
|
// ...
|
|
|
|
if (foo.doTheThing()) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,text]
|
|
----
|
|
public boolean isConditionMet(int a, int b) {
|
|
int difference = a - b;
|
|
|
|
if (difference < 0) {
|
|
return false;
|
|
}
|
|
|
|
// ...
|
|
|
|
MyClass foo = new MyClass(a);
|
|
if (foo.doTheThing()) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
----
|
|
|