Re: How to make iterating through list of variables more elegant
On 7/12/2010 12:56 PM, Angus wrote:
I have the following string variables in my class:
m_PrimaryID, m_SecondaryID and m_TertiaryID.
Apparently, those are pointers to char or something convertible to a
pointer to char... It would be nice if you spelled it out for us,
instead of making us deduce this. Like so:
class CTool // or does it inherit from something?
{
char* m_PrimaryID;
char* m_SecondaryID;
char* m_TertiaryID;
// other stuff irrelevant
public:
const char* getID(int) const;
CTool* findTool(const char*); // or is it inherited?
CTool* FindTool();
bool Exists();
// other interface not important
};
I have a search function, FindTool(), which goes through each of these
ID's to search for something.
I have a getID() function like this:
const char* CTool::getID(int index) const
{
switch(index)
{
case 0: return m_PrimaryID&& *m_PrimaryID ? m_PrimaryID : 0;
case 1: return m_SecondaryID&& *m_SecondaryID ?
m_SecondaryID : 0;
case 2: return m_TertiaryID&& *m_TertiaryID ? m_TertiaryID :
0;
default: return 0;
}
}
which returns the requisite variable if not null.
I do the search like this:
CTool* CTool::FindTool()
{
CTool* tool = 0;
//try all available gcid's
for(int it = 0; it != 3; ++it)
{
if(getID(it))
tool = findTool(getID(it)); //this is using library I need
to use
"Need" as in "must"? Or "need" as in "has the functionality I don't
want to reinvent"? Is that a member of the base class? Is that a
global function? Consider supplying 'this->' in the former case and the
namespace prefix '::' in the latter.
You can declare a local variable instead of calling 'getID' twice:
if (const char *cid = getID(it))
tool = findTool(cid);
Is that more elegant? I think so.
if(tool&& tool->Exists())
return tool;
}
return 0;
}
But I am concerned the code looks obscure. How can I make it more
elegant?
Naming functions better might help (you have both 'getID' and
'FindTool', which are mixing different case conventions - bad). Adding
comments would certainly make the code more readable (and thus less
obscure)... Prefixes to the function to avoid misinterpreting global
functions as members (when read by a human, apparently the compiler has
no problem). Better control of the whitespace and indentation would help...
Anyway, what's your definition of "elegant"? Is that "I know one when I
see it"?
V
--
I do not respond to top-posted replies, please don't ask