I have two proposals for parsing arguments:
Method A
const char *
cmp_skip (const char *key, const char *str)
{
int len = strlen (key);
return strncmp (key, str, len) ? NULL : str + len;
}
void
parser (int argc, const char **argv)
{
for (int i = 0; i < argc; i++) {
const char *str, *arg = argv[i];
if ((str = cmp_skip ("db=", arg)))
db_field = str;
else if ((str = cmp_skip ("table=", arg)))
table_field = str;
else if ((str = cmp_skip ("pass=", arg)))
pass_field = str;
else if ((str = cmp_skip ("type=", arg)))
type_field = str;
else if ((str = cmp_skip ("priv=", arg)))
priv_field = str;
}
}
Method B
void
parser (int argc, const char **argv)
{
for (int i = 0; i < argc; i++) {
const char *key = argv[i];
if (!strncmp (key, "db=", 3))
db_field = key + 3;
else if (!strncmp (key, "table=", 6))
table_field = key + 6;
else if (!strncmp (key, "pass=", 5))
pass_field = key + 5;
else if (!strncmp (key, "type=", 5))
type_field = key + 5;
else if (!strncmp (key, "priv=", 5))
priv_field = key + 5;
}
}
Anyway we have some hardcoded strings. I think this is inevitable. Our project is limited to specific fields: db
, table
, pass
, type
and priv
. What is the best choice for assigning their values to our pointers?
I think that B is better because:
- It hasn't any extra abstraction.
- Anyway we hardcoded some strings. Why we can't hardcode their length? Trying to find a known length of a hardcoded string sucks. Doesn't it?
- Anyway in
cmp_skip()
we implement what we see in this code. - This code is very smaller than the first code.
- This code doesn't call any functions and doesn't waste resources.
- This code is very simple, readable and optimizable.
- We don't need to extend this structure. But if we to need to, we can refactor this easily.
- YAGNI.
But my friends say that second code is horrible and first code is very good and extensible. But I think actually we don't need flexibility and extendibility for now! Cause YAGNI!
Anyway what is your opinion? I'm really confused ...