This is the 16th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge

What is table driven?

A programming model that looks for information from a table without using logical statements (if and case). In fact, anything that can be selected by a logical statement can be selected by looking up a table. For simple cases, using logical statements is easier and more straightforward, but the more complex the logical chain becomes, the more attractive the look-up table method becomes.

Use the general

When appropriate, the resulting code is simpler, easier to modify, and more efficient than complex logical code.

Here’s an example:

Suppose you need to divide characters into letters, punctuation marks, and numbers.

Use complex logic to classify characters

if ((( 'a' <= inputChar ) && ( inputChar <= 'z' )) || (( 'A' <= inputChar ) && ( inputChar <= 'Z' ))){ charType = CharacterType.Letter; } else if (( inputChar = '' ) || ( inputChar = ',' ) || ( inputChar = '.' ) || ( inputChar = '! ' ) || ( inputChar = '(' ) || ( inputChar = ')' ) || ( inputChar = ':' ) || ( inputChar = '; ' ) || ( inputChar = '? ') || ( inputChar = '-' )) { charType = CharacterType.Punctuation; } else if (( '0' <= inputChar && inputChar <= '9' )) { charType = CharacterType.Digit; }Copy the code

Use query tables to sort characters

charType = charTypeTable[inputChar];
Copy the code

Two problems with using a table-driven approach

1) How to look up data from a table?

  • Direct access to the

  • Index access

  • Ladder access

2) What to put in the watch?

  • data

  • Action – The code that describes the action/a reference to the action’s subroutine.

1. Direct access

As with all direct lookup tables, direct access replaces a more complex logical control structure. They are “direct access” because you don’t have to go through a lot of complicated circles to find the information you want.

Example:

Suppose you need to count the number of days in each month.

The conventional dumb method is as follows:

if(month == 1) {
    days = 31;
} else if (month = 2){
    days = 28;
} else if (month = 3){
    days = 31;
} else if (month = 4){
    days = 30;
} else if (month = 5){
    days = 31;
} else if (month = 6){
    days = 30;
} else if (month = 7){
    days = 31;
} else if (month = 8){
    days = 31;
} else if (month = 9){
    days = 30;
} else if (month = 10){
    days = 31;
} else if (month = 11){
    days = 30;
} else if (month = 12){
    days = 31;
}
Copy the code

Save the data in a table and create this table:

[31, 28, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 31, 31, 31]Copy the code

A simple array access statement is all that is needed:

charType = charTypeTable[inputChar];
Copy the code

Of course, we’d like to be able to access the table directly with the data as key values, which is easy and fast, but the problem or the data is often not so friendly. The method of constructing the query key value is introduced:

1) Copy information so you can use keys directly

One way to enable age to be used as a key in the rate table is to make a copy of the under-18 rate for all ages between 1-17 and then access the table directly with the age key. The same thing can be done for people over 66.

The advantage of this is that the structure of the table itself is very simple and the logic of accessing the table is very simple;

The disadvantage is that the redundant information generated by replication will waste space, that is, the use of space exchange efficiency.

2) Convert key values so that they can be used directly

A second way to enable AGE to be used in rate table queries like a key value is to use a function to convert age to another value. In this case, the function must convert all ages between 1 and 17 directly to a key value, such as 17, and convert all ages over 66 to another key value, such as 66.

This allows the min() and Max () functions to do the conversion before retrieval.

For example, you can use the expression Max (min(66, age), 17) to generate a table key between 17 and 66.

3) The key value conversion extraction city independent subroutine

If you must construct some data to be used like table keys, extract the data-to-key conversion operations into a separate subroutine. This avoids different transformations being performed in different locations and makes the transformation operations easier to modify.

For example, it’s OK to write the logical function KeyFromAge() in your programming language, and even use HashMap to define a logical key-value mapping.

2. Index access

Sometimes it is not possible to convert data such as age into table keys with a simple mathematical operation. This can be solved by using index access.

Index application: first use a basic type of data from an index table to find a key value, and then use this key value to find the required master data.

For example:

There are more than 100 items, shop item number (range 0000-9999)

Create two tables: index table (0-9999), item (query) table (0-100)

Index tables and queries

Index access has two advantages:

  • If each record of the primary query table is large, it takes much less space to create a space-wasting array than it does to create the primary query table.

  • Manipulating records in indexes is more convenient than manipulating records in primary query tables, and data written into tables is easier to maintain than data embedded in code.

For example, if you have a table of employee names, times of employment, and salaries, you can generate an index that accesses the table by employee name. Generate another index table to access the table by time of employment; And generate a third index to access the table by salary.

3. Step access

This access method is not as direct as the index structure, but it saves space than the index access method.

The basic idea of the ladder structure: the records in the table are valid for different data ranges, not different data points.

Classification is determined by the level of the ladder hit

For example:

A rating application where a “B” record corresponds to a range of 75.0% to 90.0%

A > = 90.0%

< 90.0% B

< 75.0% C

< 65.0% D

< 50.0% F

This partitioning is not appropriate for query tables, because you cannot use simple data conversion functions to convert table keys to the a-F letter hierarchy. Indexing is also not appropriate because you’re using floating-point numbers.

When applying the ladder approach, the end points of the range must be treated with care.

Dim rangeLimit() As Double ={50.0, 65.0, 75.0, 90.0, 100.0} Dim grade() As String={"F", "D", "C", "B", "A"} maxGradeLevel = grade.Length - 1 // assign a grad to a student based on the student's score GradeLevel= 1 StudentGrade = "A" while(StudentGrade = "A" and GradeLevel < MaxGradeLevel) if(StudentScore < RangeLimit(GradeLevel) ) ) then StudentGrade = Grade ( GradeLevel) end if GradeLevel = GradeLevel + 1 WendCopy the code

The advantage of this approach over other table-driven approaches is that it is well suited to dealing with irregular data.

Some details to note when using stair access:

1) Pay attention to boundary endpoints

Note the boundaries: < and <= to ensure that the loop terminates properly after finding the highest level interval.

2) Consider binary search instead of sequential search

If the list is large, you can replace it with a quasi-binary search, which is performance intensive

3) Consider index access instead of ladder access

Lookup operations in ladder access can be time-consuming, and if speed is important, consider replacing ladder lookup with index access, sacrificing storage for speed.

conclusion

  1. The table-driven approach provides an alternative to the complex logic and inheritance structure. If you find yourself confused about the logic or inheritance of an application, can you simplify it with a query table?

  2. The key decision to make with a table is how to access the table. Can it be direct access, index access, or ladder access

  3. Another key decision for using tables is deciding how to put what into the table

  4. When you need to save floating-point and range numbers, use the form of step access.

– END –

Author: Architecture improvement road, ten years of research and development wind and rain road, dacang architect, CSDN blog expert, focus on architecture technology precipitation learning and sharing, career and cognitive upgrading, adhere to the sharing of grounding gas dry articles, look forward to growing with you. Follow and private message I reply “01”, send you a programmer growth advance gift package, welcome to hook up.

Thanks for reading!