Sonar Alert :将此方法重构为不总是 return 相同的值

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

我正在使用此代码来初始化操作处理程序,并且我收到了带有严重性阻止程序的声纳警报:

Refactor this method to not always return the same value

对于以下代码:

private static boolean initialized = false;
public static boolean initialize() {
    if (!initialized) {
        //TODO
        initialized = true ;
        return initialized ;
    }
    // TODO
    return initialized;
}

如何改进此代码?

如果不知道 // TODO 下隐藏的是什么,就不可能提出有用的建议。以下代码:

public static boolean initialize() {
    if (!initialized) {
        // TODO
        initialized = true;
        return initialized;
    }
    // TODO
    return initialized;
}

相当于:

public static boolean initialize() {
    if (!initialized) {
        initialized = true;
        return initialized;
    }
    return initialized;
}

也等同于:

public static boolean initialize() {
    if (!initialized) {
        initialized = true;
    }
    return true;
}

returned 布尔值始终相同,因此 return 没有任何意义。最终代码:

public static void initialize() {
    if (!initialized) {
        initialized = true;
    }
}