It seems that avoiding premature initialization is a good programming practice.
I'm using PMD add-on for Eclipse, and I have had some "Found 'DD'-anomaly for variable 'var'". I know what this anomaly means. It means that a variable is prematurely initialized (the initialized value is never used).
However, I'm stuck with the following problem.
This is an general example of what I want to do.
String var = null;
if (someCondition()) {
Object a;
//some treatment on a
var = "some value" + a.toString();
}
else {
Object b;
//some treatment on b
var = "some other value" + b.toString();
}
return var;
And this would be the specific example of what I want to do :
String token = null;
String authorization = getAuthorization(token);
if (authorization != null) {
String[] parts = authorization.split(" ");
if (parts.length == 2 && "Bearer".equals(part[0])) {
token = parts[1];
}
}
return token;
.
The problem is that the variable is only used inside of a scope (in this case inside of the if
block or the else
block), but it is also the value to return. So if I declare it inside the if
block or the else
block to avoid premature initialization, then the variable won't exist outside of those blocks and I won't be able to return it.
I also want to avoid using multiple return statement, because that would cause another anomaly from PMD.
Is there a way to solve my problem while avoiding premature initialization?
Use a single LoC for this:
The code in here:
In this case, you should initialize the variable with a default value, then initialize it wherever you need to:
Also, I would move
"Bearer"
into anstatic final String
variable in order to avoid using literal strings directly in the code.