Sujet : Against bool
De : malcolm.arthur.mclean (at) *nospam* gmail.com (Malcolm McLean)
Groupes : comp.lang.cDate : 30. May 2024, 17:16:40
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v3a8p9$1osnv$1@dont-email.me>
User-Agent : Mozilla Thunderbird
So here is a little function I just wrote as part of my work with the XML parser.
int xmltojson(FILE *fp, XMLNODE *node, int useattributes)
{
if (is_array(node, useattributes))
{
fprintf(fp, "[\n");
xmltojson_r(fp, node->child, useattributes, 1, 0, 1);
fprintf(fp, "]\n");
}
else if (is_object(node, useattributes))
{
fprintf(fp, "{\n");
xmltojson_r(fp, node->child, useattributes, 1, 1, 1);
fprintf(fp, "}\n");
}
else if (is_field(node, useattributes))
{
fprintf(fp, "{");
xmltojson_r(fp, node->child, useattributes, 1, 1, 0);
fprintf(fp, "}\n");
}
return 0;
}
And it's completely hopeless isn't it? You can work out exactly what the first flag means. But the last three paramters? And of course I've just used int, and bool will not help much, except parmater 3 is actually an integer (it's the depth parameter). Actually it obfuscates. Because bool is avialable, but breaks on old compilers, it it less obvious that useattributes is a flag - someone who is a bit naive might think that because I didn't use "bool" it must take more than two values. So it has made code harder rather than easier to understand.
And every boolean means something. It doesn't mean "true" or "false" in some sort of philosphical abstract, it means that attributs=es are to be used or not to be used, and so on.
And what we want is this
int xmltojson(FILE *fp, XMLNODE *node, bool_useattributes useattributes)
{
if (is_array(node, useattributes))
{
fprintf(fp, "[\n");
xmltojson_r(fp, node->child, useattributes, 1, NO_WRITETAG, YES_NEWLINE);
fprintf(fp, "]\n");
}
else if (is_object(node, useattributes))
{
fprintf(fp, "{\n");
xmltojson_r(fp, node->child, useattributes, 1, YES_WRITETAG, YES_NEWLINE);
fprintf(fp, "}\n");
}
else if (is_field(node, useattributes))
{
fprintf(fp, "{");
xmltojson_r(fp, node->child, useattributes, 1, YES_WRITETAG, NO_NEWLINE);
fprintf(fp, "}\n");
}
return 0;
}
And now anyone can see exactly what this function is doing.
And so we want to abolish bool and replace it with a bool enum. bool enums would be special enums constrained to have two values, and you'd have an easy way of recognising them - prefixing by NO_ and YES_ is a tentative proposal. And the constants "true" and "false" just never appear. They are disallowed for passing to functions.
-- Check out Basic Algorithms and my other books:https://www.lulu.com/spotlight/bgy1mm