O'Reilly logo

Beautiful Code by Andy Oram, Greg Wilson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A Little Polymorphism Can Go a Long Way

Inside most programs of any flexibility, there is likely to be a polymorphic object of some sort. The table that takes up most of the main page of the Gene Sorter is composed of a series of polymorphic column objects.

Making polymorphic objects in C is not as easy as it is in more modern object-oriented languages, but it can be done in a relatively straightforward manner using a struct in place of an object, and function pointers in place of polymorphic methods. Example 13-1 shows a somewhat abbreviated version of the C code for the column object.

Example 13-1. The column structure, a polymorphic object in C

struct column
/* A column in the big table. The central data structure for
 * hgNear. */
   {
   /* Data set guaranteed to be in each column. */
   struct column *next;   /* Next column in list. */
   char *name;            /* Column name, not seen by user. */
   char *shortLabel;      /* Column label. */
   char *longLabel;       /* Column description. */

   /* -- Methods -- */
   void (*cellPrint)(struct column *col, struct genePos *gp,
        struct sqlConnection *conn);
   /* Print one cell of this column in HTML. */

   void (*labelPrint)(struct column *col);
   /* Print the label in the label row. */
   void (*filterControls)(struct column *col,
        struct sqlConnection *conn);
   /* Printout controls for advanced filter. */

   struct genePos *(*advFilter)(struct column *col, struct sqlConnection *conn, /* Return list of positions for advanced filter. */ /* Lookup tables use the next few fields. */ char *table; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required