What are table-driven methods?

最后都变了- 提交于 2019-11-27 04:41:30

问题


What is a "table-driven method"?

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


回答1:


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.




回答2:


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.




回答3:


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, investiagethe Fitnesse testing framework at http://fitnesse.org/.



来源:https://stackoverflow.com/questions/105311/what-are-table-driven-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!