How do I refactor code into a subroutine but allow for early exit?

Posted by deworde on Stack Overflow See other posts from Stack Overflow or by deworde
Published on 2010-06-10T09:58:54Z Indexed on 2010/06/10 10:02 UTC
Read the original article Hit count: 281

Filed under:
|

There's a really obvious refactoring opportunity in this (working) code.

bool Translations::compatibleNICodes(const Rule& rule, 
                                     const std::vector<std::string>& nicodes)
{
    bool included = false;

    // Loop through the ni codes.
    for(std::vector<std::string> iter = nicodes.begin();
        iter != nicodes.end();
        ++iter)
    {
        // Match against the ni codes of the rule
        if(rule.get_ni1() == *iter)
        {
            // If there's a match, check if the rule is include or exclude
            const std::string flag = rule.get_op1();
            // If include, code is included unless a later rule excludes it
            if(flag == "INCLUDE"){ included = true; }
            // If exclude, code is specifically excluded
            else if(flag == "EXCLUDE"){ return false; }
        }
        if(rule.get_ni2() == *iter)
        {
            const std::string flag = rule.get_op2();
            if(flag == "INCLUDE"){ included = true; }
            else if(flag == "EXCLUDE"){ return false; }
        }
        if(rule.get_ni3() == *iter)
        {
            const std::string flag = rule.get_op3();
            if(flag == "INCLUDE"){ included = true; }
            else if(flag == "EXCLUDE"){ return false; }
        }
        if(rule.get_ni4() == *iter)
        {
            const std::string flag = rule.get_op4();
            if(flag == "INCLUDE"){ included = true; }
            else if(flag == "EXCLUDE"){ return false; }
        }
        if(rule.get_ni5() == *iter)
        {
            const std::string flag = rule.get_op5();
            if(flag == "INCLUDE"){ included = true; }
            else if(flag == "EXCLUDE"){ return false; }
        }
    }
    return included;
}

The problem is that I can't get around the problem that I want to exit early if it's an exclude statement.

Note that I can't change the structure of the Rule class.

Any advice?

© Stack Overflow or respective owner

Related posts about c++

Related posts about refactor