What are table-driven methods?

Table-driven methods are schemes that allow you to look up information in a table rather than using logic statements (i.e. case, if). In simple cases, it's quicker and easier to use logic statements, but as the logic chain becomes more complex, table-driven code is simpler than complicated logic, easier to modify and more efficient.

Reference: McConnell, Steve. Code Complete, Second Edition. Redmond (Washington): Microsoft, 2004. Print. Page 411, Paragraph 1.


The referenced video has Bill Gates reading from the book Code Complete by Steve McConnell. Jeff Atwood mentioned this in his blog (the YouTube links match up).

From Code Complete, 2nd edition:

A table-driven method is a scheme that allows you to look up information in a table rather than using logic statements (if and case) to figure it out.

McConnell uses an array as his "table" in his examples, but I think the concept can be applied to database tables or anything else that is table-like.

The concept is really best explained through an example.

Let's say you're running a restaurant and have a different number of seats for each table number.

Your logic to get the number of seats for a particular table might look something like

if table number == 1
    table has 4 seats
else if table number == 2
    table has 8 seats
. . .

so if you have 50 tables you would have 100 lines of code just to determine the number of seats.

Using table-driven methods, you could make an array with the index representing the table number and the value representing the number of seats, so your logic would instead look something like

tables [] = {4, 8, 2, 4, ...}
table seats = tables[table number]

which is simpler, shorter, and easier to maintain.


A table-driven method is quite simple. Use data structures instead of if-then statements to drive program logic. For example, if you are processing two types of records (tv versus cable) you might do this:

hash[tv] = process_tv_records
hash[cable] = process_cable_records

In some languages, like Ruby or Perl, this technique is straightforward. In Java, you'd need to use Reflection to find method handles.

If you want to learn about decision tables, investigate the Fitnesse testing framework at http://fitnesse.org/.