(Why make it simple, when you can also make it complicated?)
Consider the task of associating code with specific data
values.
Using a multi-way conditional can be error-prone, because
the data values become separated by the code.
It can also be inefficient in the cases where we have to use cascading
else if
statements, instead of a switch
,
which the compiler can optimize into a hash table.
In C I would use an array containing values and function pointers.
My understanding is that the Java approach involves using the
Strategy pattern: a separate class for each case,
and an interface "to rule them all".
void setifflags (char *, int);
void notrailers (char *, int);
/* [...] */
void setifdstaddr (char *, int);
struct cmd {
char *c_name;
int c_parameter;
void (*c_func) (char *, int);
} cmds[] = {
{ "up", IFF_UP, setifflags } ,
{ "down", -IFF_UP, setifflags },
{ "trailers", -1, notrailers },
{ "-trailers", 1, notrailers },
/* [...] */
{ 0, 0, setifdstaddr },
};
Last modified: Friday, May 13, 2005 9:54 am
Unless otherwise expressly stated, all original material on this page created by Diomidis Spinellis is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.