Memni Akram
Memni Akram

Reputation: 37

Sonar Alert : Refactor this method to not always return the same value

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 ?

Upvotes: 3

Views: 8793

Answers (1)

agabrys
agabrys

Reputation: 9136

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;
    }
}

Upvotes: 4

Related Questions