Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should C++ class "helper functions" be members, free, or anon-namespace free?

Tags:

So, I have a class. It's a useful class. I like a lot. Let's call it MyUsefulClass. MyUsefulClass has a public method. Let's call it processUsefulData(std::vector<int>&).

Now suppose processUsefulData really does two things and I want to refactor it from this:

std::vector<int> MyUsefulClass::processUsefulData(std::vector<int>& data)
{
    for (/*...*/)
    {
        for (/*...*/)
        {
            // a bunch of statements...
        }
    }

    for (/*...*/)
    {
        for (/*...*/)
        {
            // a bunch of other statements...
        }
    }
    return data;
}

Now, I want to split these responsibilities and rewrite the code as

std::vector<int> MyUsefulClass::processUsefulData(std::vector<int>& data)
{
    doProcessA(data, dataMember_);
    doProcessB(data, otherDataMember_);
    return data;
}

So, I don't know if I should make the two helper functions free functions or member functions, and when each would be appropriate. I also don't know if it's better to make them in an anonymous namespace or not. Does anyone know good times to do this?

like image 854
rlbond Avatar asked Jul 17 '09 20:07

rlbond


1 Answers

I generally make helper routines "free" routines in an anonomous namespace if possible. That way I don't complicate the interface (off in the *.h file) with stuff clients don't need to worry about.

However, you have to be careful that you don't introduce non-reentrancy by doing that. For instance, by modifying global data objects or static locals rather than class members. If you need to do that, you are better off making it a proper class member.

like image 76
T.E.D. Avatar answered Oct 18 '22 11:10

T.E.D.