I'm using this code to initialize an action handler and I'm getting a Sonar Alert with a severity blocker:
Refactor this method to not always return the same value
for the following code:
private static boolean initialized = false;
public static boolean initialize() {
if (!initialized) {
//TODO
initialized = true ;
return initialized ;
}
// TODO
return initialized;
}
How can I improve this code ?
Without knowing what is hidden under the // TODO
it is impossible to propose something useful. The following code:
public static boolean initialize() {
if (!initialized) {
// TODO
initialized = true;
return initialized;
}
// TODO
return initialized;
}
is equivalent to:
public static boolean initialize() {
if (!initialized) {
initialized = true;
return initialized;
}
return initialized;
}
which is also equivalent to:
public static boolean initialize() {
if (!initialized) {
initialized = true;
}
return true;
}
The returned boolean value is always the same, so there is no sense to return it. The final code:
public static void initialize() {
if (!initialized) {
initialized = true;
}
}