What are table-driven methods?

后端 未结 3 673
失恋的感觉
失恋的感觉 2020-12-06 11:07

What is a \"table-driven method\"?

As mentioned by Bill Gates in the second Windows Vista commercial at 1:05.

3条回答
  •  醉梦人生
    2020-12-06 11:50

    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.

提交回复
热议问题