In the process of writing an application server in C language, the server usually needs to deal with multiple peripheral systems, accept requests from multiple clients, or call services of other applications, which may involve multiple communication formats, therefore, it is necessary to maintain a set of data formats unrelated to the outside world on the server. In general business development, it is often necessary to change fields and it is difficult to determine all required fields in the early stage. Therefore, the flexibility and scalability of the internal structure are also very important, in addition, the length, type, or the upper layer should not be modified when a new field is added.
The simplest Internal interface in C language may be to use a struct. This method is the simplest, but it is actually a built-in language without implementation, and the access efficiency is very high; the disadvantage is that the structure is statically compiled. Once modified, it involves re-Compilation of the program. In the packet conversion process, only a large number of repeated codes can be used to copy data, the data correspondence is also static. The flexible data storage method may be similar to the Map interface in java. The get and put methods are used, and the data is stored in key-> value methods. This provides high flexibility and scalability, the upper-layer application code is comfortable. The data is not statically coupled with the specific data retrieval method, but it may involve some dynamic memory allocation and high internal implementation requirements, in addition, there are some efficiency problems. The idea of this article is to use a simple idea to implement an internal structure to ensure the upper-layer application code is comfortable.
In the general development process, the data required for a single development can be determined (what data is required for the next requirement change ), therefore, you only need to add fields, and the data structure of upper-layer applications adopts the key-> value method such as get and put. The core of this idea is actually very simple. You only need to maintain a configuration file, store the key names of all required fields in the bucket, and load the file after the program runs, allocate the storage location of each field according to the configuration, and maintain a key in the memory and the ing relationship between the storage address of the expected data, in get, find the corresponding address based on the key and read the data. In put, it is similar to Map in usage, the main difference is that the corresponding key must be configured in the file in advance, otherwise an error will be reported during access. Of course, on this basis, some extensions must be combined with the actual situation to make it easier to use.
Author: "OneThin blog"