Basic Question:
If I’m storying/modifying data, should I access elements of a file by index hard-coded index, i.e. targetFile.getElement(5); via a hardcoded identifier (internally translated into index), i.e. target.getElementWithID("Desired Element"), or with some intermediate DESIRED_ELEMENT = 5; ... target.getElement(DESIRED_ELEMENT), etc.
Edit: Or something using an enum ??
Background:
My program (c++) stores data in lots of different ‘dataFile’s. I also keep a list of all of the data-files in another file—a ‘listFile’—which also stores some of each one’s properties (see below, but i.e. what it’s name is, how many lines of information it has etc.). There is an object which manages the data files and the list file, call it a ‘fileKeeper’.
The entries of a listFile look something like:
filename , contents name , number of lines , some more numbers ...
Its definitely possible that I may add / remove fields from this list — but in general, they’ll stay static.
Right now, I have a constant string array which holds the identification of each element in each entry, something like:
const string fileKeeper::idKeys[] = { "FileName" , "Contents" , "NumLines" ... };
const int fileKeeper::idKeysNum = 6; // 6 - for example
I’m trying to manage this stuff in ‘good’ programatic form. Thus, when I want to retrieve the number of lines in a file (for example), instead of having a method which just retrieves the ‘3’rd element… Instead I do something like:
string desiredID = "NumLines";
int desiredIndex = indexForID(desiredID);
string desiredElement = elementForIndex(desiredIndex);
where the function indexForID() goes through the entries of idKeys until it finds desiredID then returns the index it corresponds to. And elementForIndex(index) actually goes into the listFile to retrieve the index’th element of the comma-delimited string.
Problem:
This still seems pretty ugly / poor-form. Is there a way I should be doing this? If not, what are some general ways in which this is usually done?
Thanks!
My solution is using a combination of a std::map, and an enum:
This way I can easily access the indices and iterate through the keys easily (in the proper order — which a
map<string,int>wouldn’t do) using the enum, and still retrieve the mapping from index to string using the map. Using aget()method prevents adding elements to the map, and keeping the actualmapprivate keeps me from accessing it lazily using integers (even though it is technically of int-index type).No where in the code do I need to access elements using the actual string idenitified, i.e. get___(“Num Lines”); — which is kind of ugly, and seems to be a faux pas.