2005.05.13
Warum einfach, wenns auch kompliziert geht?
(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 },
};
As they say, the code speaks for itself. I believe the implementation is way too complicated for what it is trying to achieve. On the other hand, the programmer was just trying to overcome a limitation of the Java programming language: in Java methods are not first (or even second) class citizens.
(My thanks to my colleagues Panagiotis Louridas and Spyros Oikonomopoulos for a fruitful discussion on this topic.) Read and post comments