I would say that this is a prime example of when you should use inheritance. Take for example the following:
Abstract Class Item { // This class will never be instantiated, but it can hold // things that are common to all Items, such as sale price. private int price; public int getPrice() { return price; } // etc. } Class VendorOneItem : Item { // This class gets 'price' and 'getPrice' by default, // since it inherits from Item private String color; private String model; // etc. } Class VendorTwoItem : Item { // This class also gets 'price' and 'getPrice' private Double width; private Double height; // etc. }
I know that this does not go the way of dynamically reading data, but it is a clearer way in my mind. Even if you can somehow read all the data dynamically, how can this data be processed? As Reed noted, you might have a dictionary or map of some kind, which is reasonable. You will have data that might look like this:
{"key": value} {"Color": "blue"} {"Price": 9.99} {"Model": 1234-567-890}
or
{"Price": 129.99} {"Height": 12.750} {"Width": 8.55}
But then you just shift your problem by computing attributes at compile time to figure out the attributes at runtime. To handle these two, part of the code will know what to do with "Width" and "Height" , and he also needs to know what to do with "Model" and "Color" . Reflection is one of the possibilities, but what is described by these elements is fundamentally different, and it may be almost impossible to generalize the algorithm that concerns their details.
It is much easier for me to start with a base class and inherit classes that know the details. You can even create Item collections in your code along the way without knowing the exact type of each object.
In C ++:
std::vector<*Item> items; items.push_back(new VendorOneItem()); items.push_back(new VendorTwoItem());
Now say you added this to the Item class:
virtual public void ProcessItem()=0;
So now that the items vector is defined, you can do this:
items[0].ProcessItem(); items[1].ProcessItem();
And it does not matter that both objects are instances of different classes. Both of them must implement ProcessItem, so there is no problem figuring out which functions to call.