Data hiding in C, an object-oriented technique
This is my OLD blog. I've copied this post over to my NEW blog at:
http://www.saltycrane.com/blog/2007/04/data-hiding-in-c-object-oriented/
You should be redirected in 2 seconds.
I am working on some legacy code which uses almost entirely global variables. My task is to change the scope of the variables that don't need to be global. I have changed many of the variables to function scope because they are not used elsewhere, however there is a lot of data that is shared among functions.
My first idea was to create data structures of the shared data and pass pointers to those structures through the parameter list of the functions. However I had some multi-layer function calls. I.e., function1 calls function2 which calls function3. Only the last function called needed the shared data, but the parameter needed to be passed among many functions.
After looking over some other code, I got the idea for using "get" and "set" functions as used in object-oriented programming to access the data structures. The data structures are defined as static at the file scope. The file is like an object with functions that operate on the static data. External (outside the file) access to the data is only allowed through external interface functions declared in a header file which get and set the data. Here is a simple example with an accessor "get" function which passes a pointer to the static structure. It is declared as a pointer to a pointer because I need to pass the pointer by reference so it can be modified. However the structure itself is declared const so that the accessor won't change the data by mistake. To summarize, it is a pointer to a const structure passed by reference.
main.c:
#includealgorithm.c:#include "algorithm.h" int main(void) { const ALGORITHM_DATA *alg_ptr; Algorithm(); GetAlgorithmData(&alg_ptr); /*alg_ptr->data1 = 99.9;*/ /* This is illegal */ printf("%f\n", alg_ptr->data1); printf("%f\n", alg_ptr->data2); printf("%f\n", alg_ptr->data3); return 0; }
#include "algorithm.h" static ALGORITHM_DATA alg; void GetAlgorithmData(const ALGORITHM_DATA **out) { *out = &alg; } void Algorithm(void) { alg.data1 = 1.0; alg.data2 = 2.0; alg.data2 = 3.0; }algorithm.h:
#ifndef ALGORITHM_H_ #define ALGORITHM_H_ typedef struct { double data1; double data2; double data3; } ALGORITHM_DATA; void GetAlgorithmData(const ALGORITHM_DATA **out); void Algorithm(void); #endif /*ALGORITHM_H_*/
No comments:
Post a Comment