hello, everyone, I'm Zhang Zhang, the public name author of "the road to structural excellence".
Recently, many students talked about some idea s of designing table structure in the development process. In order to avoid detours, we plan to talk about table driven method today~
1. Concept introduction
Table driven method is a programming mode that looks up information from tables without using logical statements (if/else)
In fact, everything that can be selected by logical statements can be selected by looking up tables.
For simple cases, it is easier and straightforward to use logical statements, but as the logical chain becomes more and more complex, the look-up table method becomes more and more attractive.
Application principle
When appropriate, using table driven method, the generated code will be simpler, easier to modify and more efficient than complex logic code.
2. Application practice
2.1 direct access
2.1.1 what day is it today?
Traditional writing:
String today = "Sunday";Switch( dayForMonth % 7 ){ case 0 : today = "Sunday"; case 1 : today = "Monday"; case 2 : today = "Tuesday"; case 3 : today = "Wednesday"; case 4 : today = "Thursday"; case 5 : today = "Friday"; default: today = "Saturday"; }
Table driven method:
String [] weekday = new String[]{"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
String today = weekday [ dayForMonth % 7 ];
2.1.2 how many days per month?
Traditional writing:
if(1 == iMonth) { iDays = 31;} else if(2 == iMonth) { iDays = 28;} else if(3 == iMonth) { iDays = 31;} else if(4 == iMonth) { iDays = 30;} else if(5 == iMonth) { iDays = 31;} else if(6 == iMonth) { iDays = 30;} else if(7 == iMonth) { iDays = 31;} else if(8 == iMonth) { iDays = 31;} else if(9 == iMonth) { iDays = 30;} else if(10 == iMonth) { iDays = 31;} else if(11 == iMonth) { iDays = 30;} else if(12 == iMonth) { iDays = 31;}
Table driven method:
Write the logic as a map or list. It is clear at a glance. You can make a 2-dimensional group and add the logic of leap year.
const monthDays = [ [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]]
function getMonthDays(month, year) { let isLeapYear = (year % 4 === 0) && (year % 100 !== 0 || year % 400 === 0) ? 1 : 0 return monthDays[isLeapYear][(month - 1)];}
console.log(getMonthDays(2, 2000))
2.2 index access
Sometimes only a simple mathematical operation can not convert data such as age into table key values, which can be solved by index access.
Index application: first use a basic type of data to find a key value from an index table, and then use this key value to find the required master data.
give an example:
There are 100 items, store item number (range 0000-9999)
Create two tables: index table (0-9999) and item (query) table (0-100)
Index access has two advantages:
If each record of the main query table is large, the space used to create an array that wastes a lot of space is much smaller than that used to create the main query table.
Operating the records in the index is more convenient than operating the records in the main query table. The data written in the table is easier to maintain than the data embedded in the code.
2.3 ladder 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 ladder structure: the records in the table are valid for different data ranges, not for different data points.
give an example:
A rating application in which the "B" record corresponds to a range of 75.0% - 90.0%
>= 90.0% A
<90.0% B
<75.0% C
<65.0% D
<50.0% F
This kind of range division is not suitable for query tables, because you can't use a simple data conversion function to convert table key values to the level represented by A-F letters. It's not appropriate to use indexes, because floating-point numbers are used here.
When applying the ladder method, the endpoint of the range must be handled carefully.
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 scoregradeLevel= 0 studentGrade = "A" while( studentGrade = "A" and gradeLevel < maxGradeLevel ) if( studentScore < rangeLimit( gradeLevel ) ) then studentGrade = grade ( gradeLevel) end if gradeLevel = gradeLevel + 1 wend
Compared with other table driven methods, the advantage of this method is that it is very suitable for dealing with irregular data.
Some details to pay attention to when using ladder access:
1) Pay attention to the end of the boundary
Note the boundary: < and < =, and confirm that the cycle can be properly terminated after finding the highest level interval.
2) Consider replacing sequential lookup with binary lookup
If the list is large, you can replace it with a quasi binary search method, which is very performance-consuming
3) Consider using index access instead of ladder access
The search operation in ladder access may be time-consuming. If the execution speed is very important, you can consider using index access to replace ladder search, that is, sacrificing storage space for speed.
2.4 construct query key values
As in the above example, we hope to be able to directly access the table with data as key values, which is simple and fast.
However, problems or data are usually not so friendly, so it is necessary to introduce the method of constructing query key values.
The rate varies with age, sex, marriage and years of payment.
1) Copy information so that key values can be used directly
age supplement: copy a 50 year old rate for all ages over 50.
The advantage of this is that the structure of the table itself is very simple, and the logic of accessing the table is also very simple;
The disadvantage is that copying the generated redundant information will waste space, that is, using space for efficiency.
2) Convert key values so that they can be used directly
When querying the rate table, use one function to convert age to another value.
In this example, the function must convert all ages between 0-5 directly into a key value, such as 5, and all ages over 50 into another key value, such as 50.
In this way, the min() and max() functions can be used to do this conversion before retrieval.
For example, you can use the following expression: max(min(50, age), 17) to generate a table key value between 17-50.
3) Key value conversion extraction City independent subroutine
If you have to construct some data to use them like table keys, extract the data to key conversion operation into a separate subroutine. This avoids performing different transformations in different locations and makes the transformation operation easier to modify.
The task is a method, not a value. Here, we can use the language feature of Dart that supports high-order functions to store the method as an object in the table.var data = <String, Map>{ "A": { "name": "AA", "action": (name) => print(name + "/AA"), }, "B": { "name": "BB", "action": (name) => print(name + "/BB"), }, }; var action = data["A"]["action"]; action("kk");
3. Summary
1) How to query data from a table?
List item
Direct access
Index access
Stair-step access
2) What do you keep in your watch?
data
Action - code describing the action / reference to the subroutine of the action.
Table driven method provides an alternative to complex logic and inheritance structure. If you find yourself confused about the logic or inheritance relationship of an application, can you simplify it through a query table.
The key decision to use a table is to decide how to access the table, which can take direct access, index access or ladder access
Another key decision to use a table is to decide how to put what into the table
When you need to save floating-point numbers and range numbers, use ladder access.
Thanks for reading!
Pay attention to official account and free access to learning materials.
If you think it's good, welcome to follow and forward ~
This article shares the WeChat official account - jiagou_jingjin.
In case of infringement, please contact support@oschina.cn Delete.
Article participation“ OSC source creation program ”, you who are reading are welcome to join us and share with us.