vendredi 13 mai 2016

Does this saving/loading pattern have a name?

There's a variable persistence concept I have integrated multiple times:

// Standard initialiation
boolean save = true;
Map<String, Object> dataHolder;

// variables to persist
int number = 10;
String text = "I'm saved";

// Use the variables in various ways in the project
void useVariables() { ... number ... text ...}


// Function to save the variables into a datastructure and for example write them to a file
public Map<String, Object> getVariables()
{
  Map<String, Object> data = new LinkedHashMap<String, Object>();
  persist(data);
  return(data);
}

// Function to load the variables from the datastructure
public void setVariables(Map<String, Object> data)
{
  persist(data);
}


void persist(Map<String, Object> data)
{
  // If the given datastructure is empty, it means data should be saved
  save = (data.isEmpty());
  dataHolder = data;

  number = handleVariable("theNumber", number);
  text = handleVariable("theText", text);
  ...
}

private Object handleVariable(String name, Object value)
{
  // If currently saving
  if(save)
    dataHolder.put(name, value); // Just add to the datastructure
  else // If currently writing
    return(dataHolder.get(name)); // Read and return from the datastruct

  return(value); // Return the given variable (no change)
}

The main benefit of this principle is that you only have a single script where you have to mention new variables you add during the development and it's one simple line per variable. Of course you can move the handleVariable() function to a different class which also contains the "save" and "dataHolder" variables so they wont be in the main application. Additionally you could pass meta-information, etc. for each variable required for persisting the datastructure to a file or similar by saving a custom class which contains this information plus the variable instead of the object itself.

Performance could be improved by keeping track of the order (in another datastructure when first time running through the persist() function) and using a "dataHolder" based on an array instead of a search-based map (-> use an index instead of a name-string).

However, for the first time, I have to document this and so I wondered whether this function-reuse principle has a name. Does someone recognize this idea?

Thank you very much!

Aucun commentaire:

Enregistrer un commentaire