blog dds

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".

Here is the C code from the NetBSD ifconfig implementation.
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 },
};
An here is the annotated Java implementation of the corresponding contruct in Apache's Tomcat Jasper code.
Replacing multi-way branching using the Strategy pattern

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, or share through   


Creative Commons License 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-Share Alike 3.0 Greece License.