Re: overloading vs. default argument question
perkins45@gmail.com schrieb:
So lets say I have this pretend function that compares a given serial
number against the one true serial VALID_SERIAL:
bool validateSerial(string serialNum)
{
if(serialNum == VALID_SERIAL)
return true;
else
return false;
}
Is it by design that you provide the string argument by value?
I see no need for that, because it is not modified. Why not
inline bool validateSerial(const std::string& serialNum)
{
return (serialNum == VALID_SERIAL);
}
for clarity?
I want to add a function that does the same thing, but will also pad
the given serialNum with a prefix of "0" if the original serialNum
does not check out. I was thinking I could change the original
function to something like:
bool validateSerial(string serialNum, bool padFlag = false)
{
if(!padFlag)
{
if(serialNum == VALID_SERIAL)
return true;
else
return false;
}
else
{
// padding functionality...unimportant for now
}
}
I don't see how this function could modify any of it's arguments
in a way that has any effect. It should probably use a reference
to the string.
but that would seems ugly to have one function that should be really
be two. I could also overload it with a new function like
bool validateSerial(string serialNum, bool padFlag)
{
//padding functionality
}
but that function would not even use the padFlag variable.
That is correct.
Any suggestions on how I should organize these public functions from
an OO perspective?
I don't see any reason, why you should use overloading here.
It would probably clearer, if the function name would clarify it's
intend. Why not handling it in the following way
if (!validateSerial(s)) {
markSerial(s);
}
where markSerial performs the modification of the test serial
number? If the double step (test-and-modify) is the usual case,
why not something like
inline bool validateSerialAndMark(std::string& s) {
const bool result = validateSerial(s);
if (!result) {
markSerial(s);
}
return result;
}
or with a tagging flag where overloading can not be
misunderstood:
enum MarkingTag { MarkInvalid };
inline bool validateSerial(std::string& s, MarkingTag) {
const bool result = validateSerial(s);
if (!result) {
markSerial(s);
}
return result;
}
which is called in a signalling way:
if (validateSerial(s, MarkInvalid)) {
..
}
Greetings from Bremen,
Daniel Kr|gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]