If we have several data structures, like:
typedef struct {
int par1;
//...
int parn1;
} struct1;
typedef struct {
int par1;
//...
int parn2;
} struct2;
(consider in general the fields types could differ) does make any sense to abstract the iterator for the field of such structures?
Is this something actually used in practice?
What I had in mind was something like (more or less pseudocode):
typedef struct {
int par1;
//...
int parn1;
} struct1;
typedef struct {
int par1;
//...
int parn2;
} struct2;
typedef struct {
int* iterator_ptr;
int curr_pos;
int n_field;
} struct_iterator;
typedef union {
struct1 s1;
struct2 s2;
} generic_struct;
typedef enum {
label_struct_1,
label_struct_2,
n_struct
} struct_label;
struct_iterator get_iterator(generic_struct* s,struct_label label) {
struct_iterator it;
if(label == label_struct_1) {
it.iterator_ptr = s->par1;
it.curr_pos = 0;
it.n_fields = n1;
} else if(label == label_struct_2) {
it.iterator_ptr = s->par1;
it.curr_pos = 0;
it.n_fields = n2;
} else {
//something else, maybe other structures to handle
}
return it;
}
The purpose is for a code refactoring basically, I have a terrible code in C, i want to make more readable and easier to understand. I have structures like those I showed above, and different algorithms that operates on such structures, the high level algorithm is actually the same, but instead of writing a general version with spots to be specialized it has been preferred to write straight away specialized version of such algorithm. Among the steps of such algorithm there's an iteration through the structs parameters, since these structures could differs in the number of fields, but in some cases the type is the same, what I had in mind was to abstract the concept trying to implement an iterator.
I understand that probably this could sound unnecessary, however what I'm trying to achieve is the easiest way of code reuse. Something like "if u want to extend the code just implement this structures with these operations, you don't need to worry about the other things".
The examples I came up with are for sake of clarity, it's not actual code, I want to understand if the idea make sense or not.
The code is written in C, most of the concepts I'm talking about are implemented in C++, but I'm forced to use C.
Aucun commentaire:
Enregistrer un commentaire