c++ Warning: Clang-Tidy: Repeated branch in conditional chain

Viewed 8295

Can you help me how to avoid the warning in this code ...

Warning: Clang-Tidy: Repeated branch in conditional chain

HubInterface *getFreeHub() {
        HubInterface *freeHub = nullptr;
        while (freeHub == nullptr) {
            for (auto hub : this->getHubList()) {
                if (freeHub == nullptr) {
                    freeHub = hub;
                } else if (hub->getStatus() == STATUS_READY &&
                           hub->getBusyNodes().size() < freeHub->getBusyNodes().size()) {
                    freeHub = hub;
                }
            }
            sleep(5);
        }
        return freeHub;
    }

Warning provided by CLion IDE

1 Answers

The warning is about the fact that you are doing the same thing in your if and else if branches, which is freeHub = hub;

if (freeHub == nullptr) {
    freeHub = hub;
} else if (hub->getStatus() == STATUS_READY &&
           hub->getBusyNodes().size() < freeHub->getBusyNodes().size()) {
    freeHub = hub; // same as above, what is the point?
}

I suppose you could rewrite it as a single condition but it's getting a bit scary:

if (freeHub == nullptr ||
    (hub->getStatus() == STATUS_READY &&
     hub->getBusyNodes().size() < freeHub->getBusyNodes().size())) {
    freeHub = hub;
}
Related