I have seen in mainly high level languages, but also in lower level languages, the use of option names as strings to specify one of several fixed options, or as flags, or more generally, code using strings to communicate with other code.
In GTK, for example,
g_signal_connect()
uses a string as a signal name to specify which signal to listen for. Each GTK widget type has a fixed list of signals.In C,
fopen()
uses a string to specify the open mode (read, write, etc).
Strings are human readable text, and as such are used for human communication to and from code, such as converting objects to and from strings to be printed or read from a command line. A string takes more space and time to handle and parse. If the only communication is between code and other code, I see using strings as bloat, being analogous to:
char my_boolean[6];
if (condition) {
strcpy(my_boolean, "true");
} else {
strcpy(my_boolean, "false");
}
// Later
if (!strcmp(my_boolean, "true")) {
code();
} else if (!strcmp(my_boolean, "false")) {
other_code();
}
Enums already exist for the purpose of choosing between one of several fixed options. The question is what are the reasons to use a string instead of an enum in these cases?
Why this:
g_signal_connect(button, "clicked", G_CALLBACK(button_action), NULL);
Instead of this:
g_signal_connect(button, SIGNAL_CLICKED, G_CALLBACK(button_action), NULL);
2 Answers 2
Some APIs are directly addressed by the user and require a format and data type that is available on the user level. A good example would be URLs.
This is also flexible and easily extendable (if pages/services are added you can, as a user, just type that new URL) and it is multiplatform without a hassle (every system knows strings, every system knows ASCII).
So I would not say it is always just laziness and/or tradition. Performance will hardly ever be an issue, interoperability is generally way more important. The more open the system is, the more sense it could make to use strings for identifiers.
-
1"every system knows ASCII" - citation needed.Toby Speight– Toby Speight10/11/2022 10:35:51Commented Oct 11, 2022 at 10:35
Enum types are final by design. You can’t extend their values. That means they work great in switch statements that need to staticly know every possible value.
Strings don’t care about any of that. You can add new string keys to a map whenever you like.
Which means if you don’t know what every possible signal might ever be then reaching for an enum isn’t what you do. Not if you care about The Open Closed Principle.
Sure, strings don’t offer type safety. And hash lookups are a tiny bit slower. But sometimes you can’t predict the future and want a solution that allows for that.
fopen
it is probably because C supportedfopen
before it supported enums.