Patterns for Handling Changing Property Sets in C++

Posted by Bhargav Bhat on Programmers See other posts from Programmers or by Bhargav Bhat
Published on 2012-04-18T06:07:21Z Indexed on 2012/06/17 15:23 UTC
Read the original article Hit count: 336

Filed under:
|
|

I have a bunch "Property Sets" (which are simple structs containing POD members). I'd like to modify these property sets (eg: add a new member) at run time so that the definition of the property sets can be externalized and the code itself can be re-used with multiple versions/types of property sets with minimal/no changes.

For example, a property set could look like this:

struct PropSetA
{
    bool activeFlag;
    int processingCount;
    /* snip few other such fields*/
};

But instead of setting its definition in stone at compile time, I'd like to create it dynamically at run time. Something like:

class PropSet propSetA;
propSetA("activeFlag",true);  //overloading the function call operator
propSetA("processingCount",0); 

And the code dependent on the property sets (possibly in some other library) will use the data like so:

 bool actvFlag = propSet["activeFlag"];
 if(actvFlag  == true)
 {
   //Do Stuff
 }

The current implementation behind all of this is as follows:

class PropValue
{
 public:
    // Variant like class for holding multiple data-types
    // overloaded Conversion operator. Eg:
    operator bool()
    {
      return (baseType == BOOLEAN) ? this->ToBoolean() : false;
    }
    // And a method to create PropValues various base datatypes
    static FromBool(bool baseValue);
};

class PropSet
{

 public:
  // overloaded[] operator for adding properties
  void operator()(std::string propName, bool propVal)
  {
    propMap.insert(std::make_pair(propName, PropVal::FromBool(propVal)));
  }

 protected:
   // the property map
   std::map<std::string, PropValue> propMap;
};

This problem at hand is similar to this question on SO and the current approach (described above) is based on this answer. But as noted over at SO this is more of a hack than a proper solution. The fundamental issues that I have with this approach are as follows:

  • Extending this for supporting new types will require significant code change. At the bare minimum overloaded operators need to be extended to support the new type.
  • Supporting complex properties (eg: struct containing struct) is tricky.
  • Supporting a reference mechanism (needed for an optimization of not duplicating identical property sets) is tricky. This also applies to supporting pointers and multi-dimensional arrays in general.

Are there any known patterns for dealing with this scenario? Essentially, I'm looking for the equivalent of the visitor pattern, but for extending class properties rather than methods.

Edit: Modified problem statement for clarity and added some more code from current implementation.

© Programmers or respective owner

Related posts about design

Related posts about c++