...
Code Block |
---|
|
class Vector {
private int val = 1;
public boolean isEmpty() {
if(val == 1) //compares with 1 instead of 0
return true;
else
return false;
}
//other functionality is same as java.util.Vector
}
import java.util.Vector;
public class VectorUser {
public static void main(String[] args) {
Vector v = new Vector();
if(v.isEmpty())
System.out.println("Vector is empty");
}
}
|
Compliant Solution
This compliant solution declares the class Vector
with a different name:
Code Block |
---|
|
class MyVector {
//other code
}
|
As a tenet, do not:
- Reuse the name of a superclass
- Reuse the name of an interface
- Reuse the name of a field defined in a superclass
- Reuse the name of a field that appears in the same method (in different scope)
Noncompliant Code Example
This noncompliant specimen reuses the name of the val instance field in the scope of an instance method.
Code Block |
---|
|
class Vector {
private int val = 1;
private void doLogic() {
int val;
//...
}
}
|
Compliant Solution
This solution ameliorates the issue by using a different name for the variable defined in the method scope. This compliant solution declares the class Vector
with a different name:
Code Block |
---|
|
class MyVectorprivate void doLogic() {
int newValue;
//other... code
}
|
Risk Assessment
Reusing names leads to code that is harder to read and maintain and may result in security weaknesses.
...